Files
boc/landvex-paket/api/rate_limit.py
T

43 lines
1.1 KiB
Python
Raw Normal View History

"""
Enkel rate limiting för LandveX API
"""
import time
from collections import defaultdict
from fastapi import HTTPException, Header
from typing import Optional
# In-memory lagring (i produktion: Redis)
request_counts = defaultdict(lambda: {"count": 0, "reset_at": 0})
def check_rate_limit(x_api_key: Optional[str] = Header(None)):
"""Kolla rate limit per API-nyckel."""
if not x_api_key:
return # Låt auth-modulen hantera detta
now = time.time()
window = 3600 # 1 timme
# Återställ om fönstret har gått ut
if request_counts[x_api_key]["reset_at"] < now:
request_counts[x_api_key] = {"count": 0, "reset_at": now + window}
# Öka räknaren
request_counts[x_api_key]["count"] += 1
# Kolla limit (demo-värden)
limits = {
"demo-key-2026": 1000,
"pro-key-2026": 10000,
}
limit = limits.get(x_api_key, 100)
if request_counts[x_api_key]["count"] > limit:
raise HTTPException(
status_code=429,
detail=f"Rate limit överskriden. Max {limit} requests per timme."
)
return {"remaining": limit - request_counts[x_api_key]["count"]}