title: Get JSON using Python and AsyncIO
body: <p>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! </p>
  
  <pre><code>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&amp;t=day&amp;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()
  </code></pre>
  
  <p>Result:  </p>
  
  <pre><code>DONE: compsci  
  DONE: programming  
  DONE: python  
  ...
  </code></pre>
  
  <hr>
  
  <p>I tried to accomplish something, but the result was not stable.  </p>
  
  <pre><code>future = []
  for key in {'python':1, 'programming':2, 'compsci':3}:
      future=asyncio.ensure_future(get_reddit_cont(key, client))
  loop.run_until_complete(future)
  </code></pre>
  
  <p>Result (1 tasks instead of 3):  </p>
  
  <pre><code>DONE: compsci  
  [Finished in 1.5s]  
  </code></pre>
  
  <hr>
  
  <p>I solved my question in this way:  </p>
  
  <p>Added by:</p>
  
  <pre><code>async with aiohttp.ClientSession () as a client:
  </code></pre>
  
  <p>AT:</p>
  
  <pre><code>async def get_reddit_cont (subreddit, client):  
  </code></pre>
  
  <p>And:</p>
  
  <pre><code>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))
  </code></pre>
  
  <p>But when the code is completed, I get the message:  </p>
  
  <pre><code>Unclosed client session
  client_session: &lt;aiohttp.client.ClientSession object at 0x034021F0&gt;
  [Finished in 1.0s]
  </code></pre>
  
  <p>I don't understand why this is happening.  </p>
  
  <p>But when I try to execute "for key" about 60 or more times, I get an error:  </p>
  
  <blockquote>
    <p>...<br>
    aiohttp.client_exceptions.ClientOSError: [WinError 10054] Remote host forcibly terminated an existing connection</p>
  </blockquote>