Interview Prep/Python for DevOps/Concurrency: threads, processes & asyncio

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.

All Python for DevOps questions Roadmap: Python for automation

More on Concurrency: threads, processes & asyncio