You can download this code by clicking the button below.
This code is now available for download.
This function uses the aiohttp library to asynchronously fetch a random quote and return it.
Technology Stack : Python, aiohttp, asyncio
Code Type : Asyncio asynchronous tasks
Code Difficulty : Intermediate
import random
import aiohttp
import asyncio
def fetch_random_quote(session):
async def fetch(session):
async with session.get('https://api.quotable.io/random') as response:
return await response.json()
async def main():
async with session as req:
quote = await fetch(req)
return quote['content']
return asyncio.create_task(main())
async def get_random_quote():
async with aiohttp.ClientSession() as session:
quote_task = fetch_random_quote(session)
quote = await quote_task
return quote