Learning asyncio: “coroutine was never awaited” warning error

前端 未结 2 2088
长发绾君心
长发绾君心 2020-12-30 20:43

I am trying to learn to use asyncio in Python to optimize scripts. My example returns a coroutine was never awaited warning, can you help to understand and find

2条回答
  •  攒了一身酷
    2020-12-30 21:13

    Do not use loop.run_until_complete call inside async function. The purpose for that method is to run an async function inside sync context. Anyway here's how you should change the code:

    async def faire_toutes_les_requetes_sans_bloquer():
        async with aiohttp.ClientSession() as session:
            futures = [requete_sans_bloquer(x, session) for x in range(10)]
            await asyncio.gather(*futures)
        print("Fin de la boucle !")
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(faire_toutes_les_requetes_sans_bloquer())
    

    Note that alone faire_toutes_les_requetes_sans_bloquer() call creates a future that has to be either awaited via explicit await (for that you have to be inside async context) or passed to some event loop. When left alone Python complains about that. In your original code you do none of that.

提交回复
热议问题