Reputation: 963
I know, this has been asked maybe a hundred times, but I still cannot figure out why this always draws an error at the end.
import asyncio
import aiohttp
async def read_index_page():
async with aiohttp.ClientSession() as session:
async with session.get('https://some/api/url') as resp:
print(resp.status)
async def main():
loop = asyncio.get_event_loop()
task = loop.create_task(read_index_page())
await asyncio.gather(task)
if __name__ == '__main__':
asyncio.run(main())
This reports the well known runtime error for the event look is closed. I run this code on a Windows 10 machine.
From my point of view I do things right but I'm a totally beginner in using asyncio. So, please be gentle. :)
Regards, Thomas
Upvotes: 1
Views: 3430
Reputation: 3836
Try to set another loop implementation for your app, on the other hand I should say that I have no error on my Windows 10 Home, tested on Python 3.6 (with Aiohttp 3.4.4) and Python 3.9. (with Aiohttp 3.7.4.post())
import asyncio
from aiohttp import ClientSession
URL = "http://..."
async def send_req(session: ClientSession):
async with session.get(URL) as resp:
if resp.status == 200:
r = await resp.json()
print(r)
else:
print(resp.status)
async def main():
# check what loop is really running in our Main Thread now
loop = asyncio.get_running_loop()
print(loop)
# no need to create ClientSession for all send_req, you need only one ClientSession
async with ClientSession() as session:
# asyncio gather creates tasks itself, no need to create tasks outside
await asyncio.gather(*[send_req(session) for _ in range(8)])
if __name__ == '__main__':
# set another loop implementation:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
Upvotes: 2