23 lines
704 B
Python
23 lines
704 B
Python
import time
|
|
from collections import defaultdict
|
|
|
|
|
|
class RateLimiter:
|
|
"""Fixed-window limiter keyed by an arbitrary string (user id or client IP)."""
|
|
|
|
def __init__(self, max_requests: int, window_seconds: float):
|
|
self.max_requests = max_requests
|
|
self.window_seconds = window_seconds
|
|
self._hits: dict[str, list[float]] = defaultdict(list)
|
|
|
|
def allow(self, key: str) -> bool:
|
|
now = time.monotonic()
|
|
window_start = now - self.window_seconds
|
|
hits = self._hits[key]
|
|
while hits and hits[0] < window_start:
|
|
hits.pop(0)
|
|
if len(hits) >= self.max_requests:
|
|
return False
|
|
hits.append(now)
|
|
return True
|