Definição
Concorrência com uma única thread para muitas operações de I/O, com async/await.
Exige bibliotecas assíncronas (httpx, aiohttp, asyncpg); requests não funciona com asyncio.
Exemplos
1. Várias chamadas em paralelo
import asyncio, httpx
async def fetch(client, url):
r = await client.get(url, timeout=30)
r.raise_for_status()
return r.json()
async def main():
async with httpx.AsyncClient() as client:
return await asyncio.gather(*(fetch(client, u) for u in urls))
results = asyncio.run(main())2. Limitar a concorrência
sem = asyncio.Semaphore(10)
async def fetch_limited(client, url):
async with sem:
return await fetch(client, url)3. Executar função bloqueante
df = await asyncio.to_thread(pd.read_csv, "big.csv")