Created
January 19, 2022 19:32
-
-
Save plasx/ff9530de503cb82c7b61634c91435fe8 to your computer and use it in GitHub Desktop.
Rate Limiting Async API Requests With AIOHTTP and ASYNCIO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# standard | |
import asyncio | |
import logging | |
# thirdparty | |
import aiohttp | |
import attr | |
from attr.validation import instance_of | |
LOGGER_FORMAT = "%(asctime)s %(messages)s" | |
logging.basicConfig(format=LOGGER_FORMAT, datefmt="[%H:%M:%S]") | |
log = logging.getLogger() | |
log.setLevel(Logging.INFO) | |
@attr.s | |
class Fetch: | |
limit = attr.ib() # batch | |
rate = attr.ib(default=5, converter=int) # speed | |
async def make_request(self, url): | |
async with self.limit: | |
async with aiohttp.ClientSession() as session: | |
async with session.request(method="GET", url=url) as response: | |
json = await response.json() | |
status = response.status | |
log.info(f"Made request: {url}. Status: {status}") | |
await asyncio.sleep(self.rate) | |
async def main(urls, rate, limit): | |
limit = asyncio.Semaphore(limit) | |
f = Fetch( | |
rate=rate, | |
limit=limit, | |
) | |
tasks = [] | |
for url in urls: | |
tasks.append(f.make_request(url=url, limit=limit)) | |
results = await asyncio.gather(*tasks) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment