middleware¶
- class litestar.middleware.ASGIMiddleware[source]¶
Bases:
ABCAn abstract base class to easily construct ASGI middlewares, providing functionality to dynamically skip the middleware based on ASGI
scope["type"], handleroptkeys or path patterns and a simple way to pass configuration to middlewares.This base class does not implement an
__init__method, so subclasses are free to use it to customize the middleware’s configuration.Important
An instance of the individual middlewares will be created once and used to build up the internal middleware stack. As such, middlewares should not be stateful, as this state will be shared across all requests. Any connection-specific state should be scoped to the handle implementation. Not doing so would typically lead to conflicting variable reads / writes across requests, and - most likely - bugs.
class MyMiddleware(ASGIMiddleware): scopes = (ScopeType.HTTP,) exclude_path_pattern = ("/not/this/path",) exclude_opt_key = "exclude_my_middleware" def __init__(self, my_logger: Logger) -> None: self.logger = my_logger async def handle( self, scope: Scope, receive: Receive, send: Send, next_app: ASGIApp ) -> None: self.logger.debug("Received request for path %s", scope["path"]) await next_app(scope, receive, send) self.logger.debug("Processed request for path %s", scope["path"]) app = Litestar(..., middleware=[MyMiddleware(logger=my_logger)])
Added in version 2.15.
- exclude_opt_key: str | None = None¶
Exclude this middleware for handlers with an opt-key of this name that is truthy
- exclude_path_pattern: str | tuple[str, ...] | None = None¶
A regex pattern (or tuple of patterns) to exclude this middleware from route handlers whose path matches any of the provided patterns.
Important
Pattern matching is performed against the handler’s path (e.g.,
/user/{user_id:int}/), NOT against the actual request path (e.g.,/user/1234/). This is a critical distinction for dynamic routes.If you need to exclude based on paths dynamically, use
should_bypass_for_scopeinstead, matching onscope["path"].Example 1: Static path
Handler path:
/api/healthTo exclude this handler, use a pattern like:
exclude_path_pattern = r"^/api/health$"Example 2: Dynamic path (path parameters)
Handler path:
/user/{user_id:int}/profile └─────┬──────┘ └─ This is what the pattern matches against
Actual request paths that match this handler:
/user/1234/profile /user/5678/profile /user/9999/profile
To exclude this handler, the pattern must match the handler, not the actual request path:
exclude_path_pattern = "/user/{user_id:int}/profile" exclude_path_pattern = "/user/\{.+?\}/"
- abstractmethod async handle(scope: Scope, receive: Receive, send: Send, next_app: ASGIApp) None[source]¶
Handle ASGI call.
- scopes: tuple[ScopeType, ...] = (ScopeType.HTTP, ScopeType.WEBSOCKET, ScopeType.ASGI)¶
Scope types this middleware should be applied to
- should_bypass_for_handler(handler: RouteHandlerType) bool[source]¶
Return
Trueif this middleware should be bypassed forhandler, according toscopes,exclude_path_patternorexclude_opt_key, otherwiseFalse.
- should_bypass_for_scope: Callable[[Scope], bool] | None = None¶
A callable that takes in the
Scopeof the current connection and returns a boolean, indicating if the middleware should be skipped for the current request.This can for example be used to exclude a middleware based on a dynamic path:
should_bypass_for_scope = lambda scope: scope["path"].endswith(".jpg")Applied to a route with a dynamic path like
/static/{file_name:str}, it would be skipped only iffile_namehas a.jpgextension.Note
If it is not required to dynamically match the path of a request,
exclude_path_patternshould be used instead. Since its exclusion is done statically at startup time, it has no performance cost at runtime.Added in version 3.0.
- class litestar.middleware.AbstractAuthenticationMiddleware[source]¶
Bases:
ABCAbstract AuthenticationMiddleware that allows users to create their own AuthenticationMiddleware by extending it and overriding
AbstractAuthenticationMiddleware.authenticate_request().- __init__(app: ASGIApp, exclude: str | list[str] | None = None, exclude_from_auth_key: str = 'exclude_from_auth', exclude_http_methods: Sequence[Method] | None = None, scopes: Scopes | None = None) None[source]¶
Initialize
AbstractAuthenticationMiddleware.- Parameters:
app¶ – An ASGIApp, this value is the next ASGI handler to call in the middleware stack.
exclude¶ – A pattern or list of patterns to skip in the authentication middleware.
exclude_from_auth_key¶ – An identifier to use on routes to disable authentication for a particular route.
exclude_http_methods¶ – A sequence of http methods that do not require authentication.
scopes¶ – ASGI scopes processed by the authentication middleware.
- abstractmethod async authenticate_request(connection: ASGIConnection) AuthenticationResult[source]¶
Receive the http connection and return an
AuthenticationResult.Notes
This method must be overridden by subclasses.
- Parameters:
connection¶ – An
ASGIConnectioninstance.- Raises:
NotAuthorizedException | PermissionDeniedException – if authentication fails.
- Returns:
An instance of
AuthenticationResult.
- class litestar.middleware.AbstractMiddleware[source]¶
Bases:
objectAbstract middleware providing base functionality common to all middlewares, for dynamically engaging/bypassing the middleware based on paths,
opt-keys and scope types.When implementing new middleware, this class should be used as a base.
- abstractmethod async __call__(scope: Scope, receive: Receive, send: Send) None[source]¶
Execute the ASGI middleware.
Called by the previous middleware in the stack if a response is not awaited prior.
Upon completion, middleware should call the next ASGI handler and await it - or await a response created in its closure.
- __init__(app: ASGIApp, exclude: str | list[str] | None = None, exclude_opt_key: str | None = None, scopes: Scopes | None = None) None[source]¶
Initialize the middleware.
- Parameters:
app¶ – The
nextASGI app to call.exclude¶ – A pattern or list of patterns to match against a request’s path. If a match is found, the middleware will be skipped.
exclude_opt_key¶ – An identifier that is set in the route handler
optkey which allows skipping the middleware.scopes¶ – ASGI scope types, should be a set including either or both ‘ScopeType.HTTP’ and ‘ScopeType.WEBSOCKET’.
- class litestar.middleware.AuthenticationResult[source]¶
Bases:
objectDataclass for authentication result.
- class litestar.middleware.DefineMiddleware[source]¶
Bases:
objectContainer enabling passing
*argsand**kwargsto Middleware class constructors and factory functions.- __call__(app: ASGIApp) ASGIApp[source]¶
Call the middleware constructor or factory.
- Parameters:
app¶ – An ASGIApp, this value is the next ASGI handler to call in the middleware stack.
- Returns:
Calls
DefineMiddleware.middlewareand returns the ASGIApp created.
- class litestar.middleware.MiddlewareProtocol[source]¶
Bases:
ProtocolAbstract middleware protocol.
- async __call__(scope: Scope, receive: Receive, send: Send) None[source]¶
Execute the ASGI middleware.
Called by the previous middleware in the stack if a response is not awaited prior.
Upon completion, middleware should call the next ASGI handler and await it - or await a response created in its closure.
- __init__(*args, **kwargs)¶