Wiki Page: fetch_status in Python Concurrency with asyncio

Overview

The fetch_status function is a key component in demonstrating how to perform asynchronous web requests using the aiohttp library in Python. This function is designed to fetch the HTTP status code from a given URL, leveraging Python's asyncio for concurrency. Below, we explore the implementation and usage of fetch_status, along with examples of running multiple requests concurrently.

Implementation of fetch_status

The fetch_status function is defined to make an asynchronous HTTP GET request to a specified URL and return the status code of the response. It uses the aiohttp.ClientSession to manage the HTTP session and ensure efficient resource usage.

Basic Implementation

import asyncio
import aiohttp
from aiohttp import ClientSession
from util import async_timed

@async_timed()
async def fetch_status(session: ClientSession, url: str) -> int:
    async with session.get(url) as result:
        return result.status

In this implementation, the function is decorated with @async_timed to measure the execution time. The async with statement ensures that the session is properly closed after the request is completed.

Extended Implementation with Delay

An extended version of fetch_status includes an optional delay parameter, allowing for simulating network latency or other delays in processing.

async def fetch_status(session: ClientSession, url: str, delay: int = 0) -> int:
    await asyncio.sleep(delay)
    async with session.get(url) as result:
        return result.status

Running Requests Concurrently

The power of fetch_status is best demonstrated when making multiple requests concurrently. This is achieved using asyncio.gather, which allows multiple coroutines to run simultaneously.

Example: Concurrent Requests

Listing 4.6 Running requests concurrently with gather

import asyncio
import aiohttp
from aiohttp import ClientSession
from chapter_04 import fetch_status
from util import async_timed

@async_timed()
async def main():
    async with aiohttp.ClientSession() as session:
        urls = ['https://example.com' for _ in range(1000)]
        requests = [fetch_status(session, url) for url in urls]   #1
        status_codes = await asyncio.gather(*requests)            #2
        print(status_codes)

asyncio.run(main())

In this example, 1,000 requests are made to example.com concurrently. The asyncio.gather function is used to manage these requests, allowing them to run in parallel and significantly reducing the total execution time compared to synchronous execution.

Synchronous vs. Asynchronous Execution

Running the requests synchronously, by awaiting each fetch_status call individually, results in a much longer execution time. This is because each request must complete before the next one begins, as shown in the following synchronous example:

@async_timed()
async def main():
    async with aiohttp.ClientSession() as session:
        urls = ['https://example.com' for _ in range(1000)]
        status_codes = [await fetch_status(session, url) for url in urls]
        print(status_codes)

This synchronous approach can take significantly longer, around 18 seconds, compared to the asynchronous version, which can complete in as little as 600 milliseconds.

Handling Exceptions

When making concurrent requests, it's important to handle potential exceptions, such as invalid URLs. The asyncio.gather function does not cancel other tasks if one fails, which can be both an advantage and a drawback depending on the use case.

Example: Handling Invalid URLs

@async_timed()
async def main():
    async with aiohttp.ClientSession() as session:
        urls = ['https://example.com', 'python://example.com']
        tasks = [fetch_status(session, url) for url in urls]
        status_codes = await asyncio.gather(*tasks)
        print(status_codes)

In this example, an invalid URL ('python://example.com') will cause an AssertionError. Despite this, the other requests will continue to run, demonstrating that asyncio.gather does not cancel ongoing tasks upon encountering an error.

Conclusion

The fetch_status function, when used with asyncio and aiohttp, provides a powerful tool for performing concurrent web requests in Python. By leveraging asynchronous programming, developers can significantly improve the efficiency and speed of network operations, making it an essential technique for modern Python applications.