Middleware Classes
Fenrir provides built-in ASGI middleware classes for common tasks like CORS, compression, request IDs, and rate limiting.
CORS Middleware
Full CORS support for HTTP and WebSocket requests.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
Parameters:
allow_origins: List of allowed origins, or"*"for all (default:"*")allow_methods: List of allowed HTTP methods (default:"*")allow_headers: List of allowed headers (default:"*")allow_credentials: Whether to allow credentials (default:False)expose_headers: Headers to expose to the browser (default:"")max_age: Max age for preflight cache in seconds (default:600)
GZip Middleware
Automatic gzip compression for responses above a configurable size threshold.
1 2 3 | |
Parameters:
minimum_size: Minimum response size in bytes to compress (default:500)compresslevel: Gzip compression level 1-9 (default:6)
Compressible content types include: text/*, application/json, application/javascript, application/xml, image/svg+xml, and more.
Request ID Middleware
Auto-generates unique request IDs or forwards client-provided IDs.
1 2 3 4 5 6 | |
Parameters:
header_name: Header name for the request ID (default:"X-Request-ID")generator: Custom ID generator function (default:uuid.uuid4)
Rate Limit Middleware
Sliding-window rate limiter per client IP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
Parameters:
max_requests: Maximum requests per window (default:100)window_seconds: Time window in seconds (default:60)key_func: Custom function to extract client key (default: client IP)redis_client: Redis async client for distributed rate limiting (default:None, uses in-memory)retry_after_header: Include Retry-After header in 429 responses (default:True)
When rate limited, returns HTTP 429 with a JSON body and Retry-After header.
Body Limit Middleware
Rejects requests exceeding a maximum body size, preventing DoS via large payloads.
1 2 3 4 | |
Parameters:
max_content_length: Maximum allowed body size in bytes (default:10_485_760— 10 MB)status_code: HTTP status code returned when body exceeds limit (default:413)
CSRF Middleware
Enforces CSRF token validation for state-changing methods (POST, PUT, DELETE, PATCH). Safe methods (GET, HEAD, OPTIONS) are always allowed.
1 2 3 | |
When auto_generate=True (default), a CSRF token cookie is injected into every safe-method response. The client must read this cookie and send it back in the X-CSRF-Token header for subsequent state-changing requests.
Parameters:
secret_key: Secret key for token generation (default:"")cookie_name: Name of the CSRF cookie (default:"_csrf_token")header_name: Header name for the CSRF token (default:"X-CSRF-Token")auto_generate: Auto-inject CSRF cookie on safe methods (default:True)