Modelli asincroni Python

Async in Python è un disastro se non sai cosa stai facendo. Ecco le mie esperienze dopo aver eseguito il debug di troppe condizioni di gara.

Problema 1: blocco delle chiamate nel codice asincrono

Questo è un classico errore che fanno tutti:

async def fetch_data():
    # FORKERT - requests blokerer hele event loopen!
    response = requests.get("https://api.example.com")
    return response.json()

Utilizza invece aiohttp o httpx:

async def fetch_data():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.example.com") as resp:
            return await resp.json()

Problema 2: Dimenticare di aspettare

CODICE_BLOCCO_2

Conclusione

L'asincrono è potente ma richiede disciplina. Inizia in modo semplice e costruisci.