xiangqinxiaochengxu/backend/app/utils/rate_limit.py
2026-04-17 10:49:14 +08:00

27 lines
727 B
Python

from fastapi import HTTPException, Request, status
from redis.exceptions import RedisError
from app.utils.redis_client import increment_with_expire
async def enforce_rate_limit(
*,
key: str,
limit: int,
window_seconds: int,
message: str,
) -> None:
try:
current = await increment_with_expire(key, window_seconds)
except RedisError:
return
if current > limit:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail=message)
def client_ip(request: Request) -> str:
forwarded = request.headers.get("x-forwarded-for")
if forwarded:
return forwarded.split(",")[0].strip()
return request.client.host if request.client else "unknown"