Asynchronous HTTP Request Fetcher with aiohttp

  • Share this:

Code introduction


This function uses the aiohttp library to make asynchronous HTTP requests and returns the HTML content of the response.


Technology Stack : aiohttp, asyncio

Code Type : Asynchronous HTTP request function

Code Difficulty : Intermediate


                
                    
import random
import aiohttp
import asyncio

def fetch_random_url(url):
    async def fetch(session):
        async with session.get(url) as response:
            return await response.text()

    async def main():
        async with aiohttp.ClientSession() as session:
            html = await fetch(session)
            return html

    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(main())
    return result

# JSON Explanation