Asyncio Semaphore Throttle API
Throttle API calls with asyncio.Semaphore for bounded concurrency in web scraping.
Code
import asyncio, aiohttp
class ThrottledClient:
def __init__(self, max_concurrent=5, rate_limit=10):
self.sem = asyncio.Semaphore(max_concurrent)
self.rate = rate_limit
self.last_call = 0
async def get(self, session, url):
async with self.sem:
now = asyncio.get_event_loop().time()
wait = max(0, 1/self.rate - (now - self.last_call))
if wait > 0:
await asyncio.sleep(wait)
self.last_call = asyncio.get_event_loop().time()
return await session.get(url)What the code does
Asyncio Semaphore Throttle API keeps everything in the class ThrottledClient and the functions __init__ and get.
Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed.
Caveats
- Plan for an install step:
asynciois a real dependency, resolved by the package manager.
Using it
Entry signature: def get(self, session, url)
The surface worth importing is get; the helpers around it are private to the snippet.
Key statements
def __init__(self, max_concurrent=5, rate_limit=10):
self.sem = asyncio.Semaphore(max_concurrent)
self.rate = rate_limit
self.last_call = 0
async def get(self, session, url):
async with self.sem:
now = asyncio.get_event_loop().time()
wait = max(0, 1/self.rate - (now - self.last_call))
if wait > 0:
await asyncio.sleep(wait)
self.last_call = asyncio.get_event_loop().time()
return await session.get(url)
Interactive Tools for This Topic
FAQ
- What does this need from the package registry?
- These are real dependencies: `asyncio`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.