Created
January 8, 2018 22:03
-
-
Save gyli/605e6549713b63011c214b73514f4888 to your computer and use it in GitHub Desktop.
Making requests with asyncio and aiohttp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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