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)Report a problem with this exampleOpens a pre-filled issue on GitHub.