1. import time
  2. import threading
  3. class RequestThrottler:
  4. def __init__(self, rate_limit_calls, period):
  5. """
  6. Initializes the throttler.
  7. Args:
  8. rate_limit_calls (int): Maximum number of requests allowed within the period.
  9. period (float): Time period (in seconds) for the rate limit.
  10. """
  11. self.rate_limit_calls = rate_limit_calls
  12. self.period = period
  13. self.request_times = [] # Store timestamps of requests
  14. self.lock = threading.Lock() #For thread safety
  15. def is_allowed(self):
  16. """
  17. Checks if a request is allowed based on the rate limit.
  18. Returns True if allowed, False otherwise.
  19. """
  20. with self.lock:
  21. now = time.time()
  22. # Remove requests older than the period
  23. self.request_times = [t for t in self.request_times if now - t < self.period]
  24. if len(self.request_times) < self.rate_limit_calls:
  25. self.request_times.append(now)
  26. return True
  27. else:
  28. return False
  29. def wait_if_needed(self):
  30. """
  31. Waits if the request is not allowed and then checks again.
  32. """
  33. if not self.is_allowed():
  34. time.sleep(self.period / self.rate_limit_calls) # Calculate wait time
  35. self.is_allowed() # check again after waiting

Add your comment