Advertisement
Guest User

asyncio.py

a guest
Apr 19th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. import time
  2. import asyncio
  3. import aiohttp
  4. import json
  5. from datetime import datetime
  6.  
  7.  
  8. async def fetch_url(url):
  9.     async with aiohttp.ClientSession() as session:
  10.         async with session.get(url['url']) as resp:
  11.             content = await resp.text()
  12.             print('{}: {}'.format(url['title'], resp.status))
  13.             # return {'title': url['title'], 'status': resp.status, 'content': content}
  14.  
  15.  
  16. def chunks(l, n):
  17.     """Yield successive n-sized chunks from l."""
  18.     for i in range(0, len(l), n):
  19.         yield l[i:i + n]
  20.  
  21.  
  22. if __name__ == '__main__':
  23.     loop = asyncio.get_event_loop()
  24.  
  25.     with open('urls.json', 'r') as f:
  26.         urls = json.loads(f.read())
  27.  
  28.     start = int(time.time())
  29.     for chunked_url in chunks(urls, 5):
  30.         tasks = asyncio.gather(*[fetch_url(url) for url in chunked_url])
  31.         for i in loop.run_until_complete(tasks):
  32.             pass
  33.  
  34.     end = int(time.time())
  35.     print('took time: {} seconds'.format(int(end - start)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement