Practical Examples

Asynchronous HTTP Requests

Asyncio can be used to perform asynchronous HTTP requests, allowing multiple requests to be processed concurrently without blocking the execution flow. This is particularly useful for web scraping, API interactions, and other network-bound tasks.

import asyncio
import aiohttp

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

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, "https://example.com")
        print(html)

asyncio.run(main())

File Handling with Asyncio

Asyncio provides tools for asynchronous file handling, allowing you to read and write files without blocking the execution flow. This is useful for applications that need to process large files or perform frequent file I/O operations.

import asyncio

async def read_file(filename):
    async with aiofiles.open(filename, 'r') as f:
        contents = await f.read()
        print(contents)

async def main():
    await read_file('example.txt')

asyncio.run(main())

Real-World Application Examples

Asyncio is used in various real-world applications, including web servers, chat applications, and data processing systems. These examples demonstrate the power and flexibility of asynchronous programming for building high-performance, scalable applications.

import asyncio
import aiohttp

async def fetch_status(session, url):
    async with session.get(url) as response:
        return response.status

async def main():
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_status(session, f"https://example.com/{i}") for i in range(10)]
        statuses = await asyncio.gather(*tasks)
        print(statuses)

asyncio.run(main())