Created
March 3, 2019 21:29
-
-
Save abatilo/66a33bcec190323f7e6d0f0e60baee4e to your computer and use it in GitHub Desktop.
Use a single aiohttp session to make multiple HTTP requests concurrently using asyncio
This file contains 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 asyncio | |
from aiohttp import ClientSession | |
async def fetch(url, session): | |
async with session.get(url) as response: | |
return await response.json() | |
async def main(): | |
url = 'http://localhost:8000' | |
async with ClientSession() as session: | |
tasks = (fetch(f'{url}/{i}', session) for i in range(1000)) | |
responses = await asyncio.gather(*tasks) | |
print(responses) | |
if __name__ == '__main__': | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment