Not so long ago, I began to learn asyncio. And I ran into a problem. My code is not terminating. I can't figure it out. Help me please!
import signal
import sys
import asyncio
import aiohttp
import json
loop = asyncio.get_event_loop()
client = aiohttp.ClientSession(loop=loop)
async def get_json(client, url):
async with client.get(url) as response:
assert response.status == 200
return await response.read()
async def get_reddit_cont(subreddit, client):
data1 = await get_json(client, 'https://www.reddit.com/r/' + subreddit + '/top.json?sort=top&t=day&limit=50')
jn = json.loads(data1.decode('utf-8'))
print('DONE:', subreddit)
def signal_handler(signal, frame):
loop.stop()
client.close()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
for key in {'python':1, 'programming':2, 'compsci':3}:
asyncio.ensure_future(get_reddit_cont(key, client))
loop.run_forever()
Result:
DONE: compsci
DONE: programming
DONE: python
...
I tried to accomplish something, but the result was not stable.
future = []
for key in {'python':1, 'programming':2, 'compsci':3}:
future=asyncio.ensure_future(get_reddit_cont(key, client))
loop.run_until_complete(future)
Result (1 tasks instead of 3):
DONE: compsci
[Finished in 1.5s]
I solved my question in this way:
Added by:
async with aiohttp.ClientSession () as a client:
AT:
async def get_reddit_cont (subreddit, client):
And:
if __name__ == '__main__':
loop = asyncio.get_event_loop()
futures = [get_reddit_cont(subreddit,client) for subreddit in range(1,6)]
result = loop.run_until_complete(asyncio.gather(*futures))
But when the code is completed, I get the message:
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x034021F0>
[Finished in 1.0s]
I don't understand why this is happening.
But when I try to execute "for key" about 60 or more times, I get an error:
...
aiohttp.client_exceptions.ClientOSError: [WinError 10054] Remote host forcibly terminated an existing connection