How do you use `ThreadPoolExecutor` for parallel API calls?
BeginnerConceptConcurrency: threads, processes & asyncio
Answer
from concurrent.futures import ThreadPoolExecutor, as_completed
def check(url):
r = session.get(url, timeout=5)
return url, r.status_code
with ThreadPoolExecutor(max_workers=20) as pool:
futures = {pool.submit(check, u): u for u in urls}
for fut in as_completed(futures):
try:
url, code = fut.result()
except requests.RequestException as e:
log.warning("%s failed: %s", futures[fut], e)
as_completed yields results as they finish; pool.map preserves input order but raises the first exception when you reach it. Exceptions inside a worker are only re-raised when you call .result(), so always call it.
More on Concurrency: threads, processes & asyncio
What is the GIL, and what does it mean for DevOps scripts?IntermediateThreads vs processes vs asyncio: how do you choose?IntermediateWhat is a race condition, and how do you prevent one in threaded code?IntermediateHow does a producer/consumer pattern with `queue.Queue` work?AdvancedWhat are coroutines, `async def` and `await`?IntermediateHow do you run many async tasks concurrently with a limit?Intermediate