Classes
CSRFConfig
5
▼
CSRF middleware configuration.
CSRFConfig
5
▼
CSRF middleware configuration.
Attributes
| Name | Type | Description |
|---|---|---|
field_name |
str
|
Form field name for the token. |
header_name |
str
|
HTTP header name for AJAX/htmx requests. |
session_key |
str
|
Key used to store the token in the session. |
token_length |
int
|
Length of the random token in bytes (hex-encoded). |
exempt_paths |
frozenset[str]
|
Paths that skip CSRF validation (e.g. API webhooks). |
CSRFMiddleware
3
▼
Token-based CSRF protection middleware.
On every request:
1. Loads or generates a CSRF token in th…
CSRFMiddleware
3
▼
Token-based CSRF protection middleware.
On every request:
- Loads or generates a CSRF token in the session.
- Makes the token available via
get_csrf_token()and template globals. - On unsafe methods (POST, PUT, PATCH, DELETE), validates the token from either the form body or the request header.
- Rejects with 403 if the token is missing or invalid.
RequiresSessionMiddlewareto be registered first.
Attributes
| Name | Type | Description |
|---|---|---|
template_globals |
ClassVar[dict[str, Any]]
|
— |
Methods
Internal Methods 2 ▼
__init__
1
▼
__init__
1
▼
def __init__(self, config: CSRFConfig | None = None) -> None
Parameters
| Name | Type | Description |
|---|---|---|
config |
— |
Default:None
|
__call__
2
AnyResponse
▼
Validate CSRF token on unsafe methods, then dispatch.
async
__call__
2
AnyResponse
▼
async def __call__(self, request: Request, next: Next) -> AnyResponse
Parameters
| Name | Type | Description |
|---|---|---|
request |
— |
|
next |
— |
Returns
AnyResponse
Functions
get_csrf_token
0
str
▼
Return the current CSRF token.
Raises ``LookupError`` if called outside a requ…
get_csrf_token
0
str
▼
def get_csrf_token() -> str
Return the current CSRF token.
RaisesLookupErrorif called outside a request with
CSRFMiddlewareactive.
Returns
str
csrf_field
0
str
▼
Render a hidden input field with the CSRF token.
For use as a template global:…
csrf_field
0
str
▼
def csrf_field() -> str
Render a hidden input field with the CSRF token.
For use as a template global::
<form method="post">
{{ csrf_field() }}
...
</form>
Renders:<input type="hidden" name="_csrf_token" value="...">
Returns
str
csrf_token
0
str
▼
Return the raw CSRF token string.
For use as a template global in meta tags::
…
csrf_token
0
str
▼
def csrf_token() -> str
Return the raw CSRF token string.
For use as a template global in meta tags::
<meta name="csrf-token" content="{{ csrf_token() }}">
Returns
str
_validate_token
3
None
▼
Check the CSRF token from form data or header.
Raises ``HTTPError(403)`` if th…
async
_validate_token
3
None
▼
async def _validate_token(request: Request, expected: str, config: CSRFConfig) -> None
Check the CSRF token from form data or header.
RaisesHTTPError(403)if the token is missing or invalid.
Parameters
| Name | Type | Description |
|---|---|---|
request |
Request |
|
expected |
str |
|
config |
CSRFConfig |