Skip to content

Instantly share code, notes, and snippets.

@jonluca
Last active June 13, 2023 09:22
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jonluca/14fe99be6204f34cbd61c950b0faf3b1 to your computer and use it in GitHub Desktop.
Save jonluca/14fe99be6204f34cbd61c950b0faf3b1 to your computer and use it in GitHub Desktop.
Fast asyncio HTTP requests
import sys
import os
import json
import asyncio
import aiohttp
# Initialize connection pool
conn = aiohttp.TCPConnector(limit_per_host=100, limit=0, ttl_dns_cache=300)
PARALLEL_REQUESTS = 100
results = []
urls = ['https://jsonplaceholder.typicode.com/todos/1' for i in range(10)] #array of urls
async def gather_with_concurrency(n):
semaphore = asyncio.Semaphore(n)
session = aiohttp.ClientSession(connector=conn)
# heres the logic for the generator
async def get(url):
async with semaphore:
async with session.get(url, ssl=False) as response:
obj = json.loads(await response.read())
results.append(obj)
await asyncio.gather(*(get(url) for url in urls))
await session.close()
loop = asyncio.get_event_loop()
loop.run_until_complete(gather_with_concurrency(PARALLEL_REQUESTS))
conn.close()
print(f"Completed {len(urls)} requests with {len(results)} results")
@jonluca
Copy link
Author

jonluca commented Aug 21, 2022

Is PARALLEL_REQUESTS set to None in your code?

File "C:\Users\jbard\AppData\Local\Programs\Python\Python39\lib\concurrent\futures\thread.py", line 140, in init
if max_workers <= 0:
TypeError: '<=' not supported between instances of 'NoneType' and 'int'

max_workers is None - you need to pass a valid number to loop.run_until_complete(gather_with_concurrency(PARALLEL_REQUESTS))

@007-JB
Copy link

007-JB commented Aug 21, 2022

Ta- I think I did something funny with one of the threading;/future or some other module - to allow me to increase max threads - because I'm running exact same code on other machine at it works beautifully - I'll get there - thanks so much for swift response. your code is awesome!!! thumbs up - take care, J

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment