Async Programming with asyncio
Master non-blocking I/O and high-concurrency apps with asyncio.
The Evolution of Concurrency
Python's asyncio module is the modern way to write concurrent code using the async/await syntax. It's particularly powerful for network-bound tasks.
Core Concepts
- Coroutine: A special function that can pause its execution.
- Event Loop: Orchestrates the execution of coroutines.
- Task: A scheduled coroutine.
Simple Coroutine
import asyncio
async def say_hello():
print("Hello...")
await asyncio.sleep(1)
print("...World!")
asyncio.run(say_hello())
async def say_hello():
print("Hello...")
await asyncio.sleep(1)
print("...World!")
asyncio.run(say_hello())
Concurrent Execution
async def main():
# Run multiple coroutines at once
await asyncio.gather(
say_hello(),
say_hello(),
say_hello()
)
asyncio.run(main())
# Run multiple coroutines at once
await asyncio.gather(
say_hello(),
say_hello(),
say_hello()
)
asyncio.run(main())
Async Context Managers
Use async with for resources like database connections and HTTP sessions.
import aiohttp
async def fetch_page(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def fetch_page(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
โ Practice (30 minutes)
- Write an async function that mimics a long-running database query using
asyncio.sleep. - Create a script that fetches data from 10 different URLs concurrently.
- Handle timeouts in your async requests using
asyncio.wait_for. - Understand the difference between
asyncio.create_taskandawait.