Skip to content

Instantly share code, notes, and snippets.

@gyli
Created January 8, 2018 22:03
Show Gist options
  • Save gyli/605e6549713b63011c214b73514f4888 to your computer and use it in GitHub Desktop.
Save gyli/605e6549713b63011c214b73514f4888 to your computer and use it in GitHub Desktop.
Making requests with asyncio and aiohttp
import aiohttp
import asyncio
NUMBERS = range(12)
URL = 'http://httpbin.org/get?a={}'
async def fetch_async(a):
async with aiohttp.ClientSession() as session:
async with session.request('GET', URL.format(a)) as response:
data = await response.json()
return data['args']['a']
event_loop = asyncio.get_event_loop()
tasks = [fetch_async(num) for num in NUMBERS]
results = event_loop.run_until_complete(asyncio.gather(*tasks))
for num, result in zip(NUMBERS, results):
print('fetch({}) = {}'.format(num, result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment