init
This commit is contained in:
35
new-planet-backend/app/middleware/rate_limiter.py
Normal file
35
new-planet-backend/app/middleware/rate_limiter.py
Normal file
@@ -0,0 +1,35 @@
|
||||
from fastapi import Request, HTTPException, status
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from app.core.config import settings
|
||||
from app.services.cache_service import cache_service
|
||||
import time
|
||||
|
||||
|
||||
class RateLimitMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
if not settings.RATE_LIMIT_ENABLED:
|
||||
return await call_next(request)
|
||||
|
||||
# Получаем IP адрес клиента
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
|
||||
# Формируем ключ для кэша
|
||||
cache_key = f"rate_limit:{client_ip}"
|
||||
|
||||
# Проверяем количество запросов
|
||||
current_requests = await cache_service.get(cache_key)
|
||||
|
||||
if current_requests:
|
||||
count = int(current_requests)
|
||||
if count >= settings.RATE_LIMIT_PER_MINUTE:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="Rate limit exceeded"
|
||||
)
|
||||
await cache_service.set(cache_key, str(count + 1), expire=60)
|
||||
else:
|
||||
await cache_service.set(cache_key, "1", expire=60)
|
||||
|
||||
response = await call_next(request)
|
||||
return response
|
||||
|
||||
Reference in New Issue
Block a user