Spaces:
Sleeping
Sleeping
File size: 605 Bytes
586dabf | 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 | import time
from fastapi import HTTPException
# Request memory
RATE_LOG = {}
def rate_limiter(key: str, limit: int, window: int = 60):
"""
key = api key
limit = requests allowed
window = time window (seconds)
"""
now = int(time.time())
if key not in RATE_LOG:
RATE_LOG[key] = []
# Remove old requests
RATE_LOG[key] = [t for t in RATE_LOG[key] if now - t < window]
if len(RATE_LOG[key]) >= limit:
raise HTTPException(
status_code=429,
detail="Rate limit exceeded. Upgrade plan."
)
RATE_LOG[key].append(now)
|