1

Found a good-looking realisation for making asynchronous HTTP requests in this article: https://www.twilio.com/blog/asynchronous-http-requests-in-python-with-aiohttp Here is the code I tried to use:

import aiohttp
import asyncio
import time

start_time = time.time()

async def get_pokemon(session, url):
    async with session.get(url) as resp:
        pokemon = await resp.json()
        return pokemon['name']

async def main():

    async with aiohttp.ClientSession() as session:
    
        tasks = []
        for number in range(1, 151):
            url = f'https://pokeapi.co/api/v2/pokemon/{number}'
            tasks.append(asyncio.ensure_future(get_pokemon(session, url)))
    
        original_pokemon = await asyncio.gather(*tasks)
        for pokemon in original_pokemon:
            print(pokemon)

asyncio.run(main())
print("--- %s seconds ---" % (time.time() - start_time))

But it gives me this:

...
\--- 0.7400617599487305 seconds ---
Exception ignored in: \<function \_ProactorBasePipeTransport.__del__ at 0x000001DBBDB26200\>
Traceback (most recent call last):
File "C:\\Users\\wdgsy\\AppData\\Local\\Programs\\Python\\Python310\\lib\\asyncio\\proactor_events.py", line 116, in __del__
self.close()
File "C:\\Users\\wdgsy\\AppData\\Local\\Programs\\Python\\Python310\\lib\\asyncio\\proactor_events.py", line 108, in close
self.\_loop.call_soon(self.\_call_connection_lost, None)
File "C:\\Users\\wdgsy\\AppData\\Local\\Programs\\Python\\Python310\\lib\\asyncio\\base_events.py", line 750, in call_soon
self.\_check_closed()
File "C:\\Users\\wdgsy\\AppData\\Local\\Programs\\Python\\Python310\\lib\\asyncio\\base_events.py", line 515, in \_check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: \<function \_ProactorBasePipeTransport.__del__ at 0x000001DBBDB26200\>
Traceback (most recent call last):
...

I also tried closing session manually and using asyncio.create_task for tasks list, both didn't change anything.

Kulasangar
  • 9,046
  • 5
  • 51
  • 82
Valerii
  • 11
  • 2
  • i ran your same snippet on my linux and it worked fine. Are you running on Windows? if so could this be helpful? https://stackoverflow.com/questions/45600579/asyncio-event-loop-is-closed-when-getting-loop – Kulasangar Jan 19 '23 at 12:57
  • yes, I am running on windows. this sollution seems to work, thanks – Valerii Jan 19 '23 at 13:05

0 Answers0