I have the following code which I'm trying to run to get data from an api asynchronously, using asyncio and aiohttp:
import asyncio
import aiohttp
api = "...some api..."
apps = [
...list of api parameters...
]
def getTasks(sess):
tasks = list()
for app in apps:
tasks.append(asyncio.create_task(sess.get(api+app, ssl = False)))
return tasks
async def main():
results = list()
async with aiohttp.ClientSession() as atpSession:
tasks = getTasks(atpSession)
responses = await asyncio.gather(*tasks)
for response in responses:
results.append(await response.json())
print(results[-1])
print("Done!")
if __name__ == "__main__":
asyncio.run(main())
Though I'm getting the response data, but the following error keeps popping up:
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001C5D98F7490>
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Program Files\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
And there are multiple such similar tracebacks shown one by one.
Now another way I tried this was by removing asyncio.run(main()) and just using some different lines of code:
import asyncio
import aiohttp
api = "...some api..."
apps = [
...list of api parameters...
]
def getTasks(sess):
tasks = list()
for app in apps:
tasks.append(asyncio.create_task(sess.get(api+app, ssl = False)))
return tasks
async def main():
results = list()
async with aiohttp.ClientSession() as atpSession:
tasks = getTasks(atpSession)
responses = await asyncio.gather(*tasks)
for response in responses:
results.append(await response.json())
print(results[-1])
print("Done!")
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Using the following did not give me the prior error but gave me:
DeprecationWarning: There is no current event loop
loop = aio.get_event_loop()
Although, it did give me the responses, my question is, why are these differences arising? Being an absolute beginner with asyncio, I had read that as application developers, we should be using the high level apis like asyncio.run() instead of the low level apis, so why is asyncio.run() creating such problems?