-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathratelimiter.py
More file actions
33 lines (26 loc) · 1.06 KB
/
ratelimiter.py
File metadata and controls
33 lines (26 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import time
import threading
from collections import deque
class RateLimiter:
def __init__(self, max_calls_per_minute=60):
self.max_calls = max_calls_per_minute
self.interval = 60 # seconds
self.calls = deque()
self.lock = threading.Lock()
def __call__(self, func):
def wrapped(*args, **kwargs):
with self.lock:
# Clean up old timestamps
now = time.time()
while self.calls and now - self.calls[0] > self.interval:
self.calls.popleft()
# Check if we've reached the limit
if len(self.calls) >= self.max_calls:
wait_time = self.interval - (now - self.calls[0])
if wait_time > 0:
print(f"Rate limit reached. Waiting {wait_time:.2f} seconds...")
time.sleep(wait_time)
# Add current timestamp and execute function
self.calls.append(time.time())
return func(*args, **kwargs)
return wrapped