Skip to content

Instantly share code, notes, and snippets.

@abatilo
Created March 3, 2019 21:29
Show Gist options
  • Save abatilo/66a33bcec190323f7e6d0f0e60baee4e to your computer and use it in GitHub Desktop.
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
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