Async/Attendre en Python
La programmation asynchrone permet une exécution simultanée sans threads, idéale pour les tâches liées aux E/S.
Concepts de base
import asyncio
async def fetch_data() -> str:
await asyncio.sleep(1) # Simulates I/O
return "data"
async def main():
result = await fetch_data()
print(result)
asyncio.run(main())
Exécuter des tâches simultanément
async def main():
# Sequential - takes 3 seconds
a = await fetch_data()
b = await fetch_data()
c = await fetch_data()
# Concurrent - takes 1 second
a, b, c = await asyncio.gather(
fetch_data(),
fetch_data(),
fetch_data()
)
Exemple concret : requêtes HTTP
import aiohttp
import asyncio
async def fetch_url(session: aiohttp.ClientSession, url: str) -> str:
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
"https://api.example.com/users",
"https://api.example.com/posts",
"https://api.example.com/comments",
]
async with aiohttp.ClientSession() as session:
results = await asyncio.gather(
*[fetch_url(session, url) for url in urls]
)
for result in results:
print(len(result))
asyncio.run(main())
Quand utiliser Async
Convient pour : - Requêtes HTTP - Requêtes de base de données -E/S de fichier -WebSockets
Pas idéal pour :
- Tâches liées au processeur (utilisez multiprocessing)
- Scripts simples avec un minimum d'E/S