Last active
August 8, 2022 11:17
-
-
Save conf8o/eddcb51b110a13f90562ac87c900501c to your computer and use it in GitHub Desktop.
decorator to limit API requests when using Python as API client
This file contains 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
from datetime import datetime, timedelta | |
class ApiLimit: | |
def __init__(self, request_limit, time_limit_second): | |
self.api_count = 0 | |
self.request_limit = request_limit | |
self.time_limit_second = time_limit_second | |
self.start = None | |
def __call__(self, func): | |
def wrapper(*args, **kwargs): | |
if self.start is None: | |
self.start = datetime.now() | |
if self.api_count >= self.request_limit and datetime.now() - self.start < timedelta(seconds=self.time_limit_second): | |
print(f"API制限のため待機({self.time_limit_second}秒間に{self.request_limit}リクエストまで)") | |
while datetime.now() - self.start < timedelta(seconds=self.time_limit_second): | |
pass | |
print("API制限解除。再開") | |
ret = func(*args, **kwargs) | |
self.api_count += 1 | |
if self.api_count > self.request_limit: | |
self.api_count = 1 | |
self.start = datetime.now() | |
return ret | |
return wrapper | |
api_limit = ApiLimit(100, 10) | |
@api_limit | |
def f(): | |
return 1 | |
@api_limit | |
def g(): | |
return 2 | |
while True: | |
print(f()) | |
print(g()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment