import time
import threading
class RequestThrottler:
def __init__(self, rate_limit_calls, period):
"""
Initializes the throttler.
Args:
rate_limit_calls (int): Maximum number of requests allowed within the period.
period (float): Time period (in seconds) for the rate limit.
"""
self.rate_limit_calls = rate_limit_calls
self.period = period
self.request_times = [] # Store timestamps of requests
self.lock = threading.Lock() #For thread safety
def is_allowed(self):
"""
Checks if a request is allowed based on the rate limit.
Returns True if allowed, False otherwise.
"""
with self.lock:
now = time.time()
# Remove requests older than the period
self.request_times = [t for t in self.request_times if now - t < self.period]
if len(self.request_times) < self.rate_limit_calls:
self.request_times.append(now)
return True
else:
return False
def wait_if_needed(self):
"""
Waits if the request is not allowed and then checks again.
"""
if not self.is_allowed():
time.sleep(self.period / self.rate_limit_calls) # Calculate wait time
self.is_allowed() # check again after waiting
Add your comment