Async Python je ideální pro I/O-bound operace — HTTP requesty, databáze, file I/O. Jedna thread, tisíce concurrent operací.
Základy asyncio¶
import asyncio async def fetch_data(url: str) -> dict: async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.json() async def main():
Concurrent requests¶
urls = [“https://api.example.com/1”, “https://api.example.com/2”] results = await asyncio.gather(*[fetch_data(u) for u in urls]) return results asyncio.run(main())
Kdy použít async¶
- HTTP requesty (aiohttp, httpx)
- Database queries (asyncpg, databases)
- File I/O
- WebSocket servery
- NE pro CPU-bound operace (použijte multiprocessing)
Klíčový takeaway¶
Async pro I/O-bound, multiprocessing pro CPU-bound. asyncio.gather pro concurrent operace.