113. Throttling API Requests
import asyncio
import aiohttp
import time
# Define the maximum number of concurrent requests
CONCURRENT_REQUESTS = 5
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def throttled_fetch(sem, session, url):
async with sem: # Acquire a semaphore
print(f"Fetching {url}")
return await fetch(session, url)
async def main():
urls = [f"https://jsonplaceholder.typicode.com/posts/{i}" for i in range(1, 21)]
sem = asyncio.Semaphore(CONCURRENT_REQUESTS) # Throttle to 5 concurrent requests
async with aiohttp.ClientSession() as session:
tasks = [throttled_fetch(sem, session, url) for url in urls]
results = await asyncio.gather(*tasks)
print(f"Fetched {len(results)} responses")
start = time.time()
asyncio.run(main())
print(f"Completed in {time.time() - start:.2f} seconds")Last updated