36 lines
1.2 KiB
Python
36 lines
1.2 KiB
Python
# middleware/decorators.py
|
|
"""
|
|
FastAPI decorators for cross-cutting concerns.
|
|
|
|
This module provides classes and functions for:
|
|
- Rate limiting decorators for endpoint protection
|
|
- Request throttling and abuse prevention
|
|
- Consistent error handling for rate limit violations
|
|
"""
|
|
|
|
from functools import wraps
|
|
from app.exceptions.base import RateLimitException # Add this import
|
|
from middleware.rate_limiter import RateLimiter
|
|
|
|
# Initialize rate limiter instance
|
|
rate_limiter = RateLimiter()
|
|
|
|
def rate_limit(max_requests: int = 100, window_seconds: int = 3600):
|
|
"""Rate limiting decorator for FastAPI endpoints."""
|
|
|
|
def decorator(func):
|
|
@wraps(func)
|
|
async def wrapper(*args, **kwargs):
|
|
client_id = "anonymous" # In production, extract from request
|
|
|
|
if not rate_limiter.allow_request(client_id, max_requests, window_seconds):
|
|
# Use custom exception instead of HTTPException
|
|
raise RateLimitException(
|
|
message="Rate limit exceeded",
|
|
retry_after=window_seconds
|
|
)
|
|
|
|
return await func(*args, **kwargs)
|
|
return wrapper
|
|
return decorator
|