config#

class litestar.config.allowed_hosts.AllowedHostsConfig#

Bases: object

Configuration for allowed hosts protection.

To enable allowed hosts protection, pass an instance of this class to the Litestar constructor using the allowed_hosts key.

allowed_hosts: list[str]#

A list of trusted hosts.

Use *. to allow all hosts, or prefix domains with *. to allow all sub domains.

exclude: str | list[str] | None = None#

A pattern or list of patterns to skip in the Allowed Hosts middleware.

exclude_opt_key: str | None = None#

An identifier to use on routes to disable hosts check for a particular route.

__init__(allowed_hosts: list[str] = <factory>, exclude: str | list[str] | None = None, exclude_opt_key: str | None = None, scopes: Scopes | None = None, www_redirect: bool = True) None#
scopes: Scopes | None = None#

ASGI scopes processed by the middleware, if None both http and websocket will be processed.

www_redirect: bool = True#

A boolean dictating whether to redirect requests that start with www. and otherwise match a trusted host.

__post_init__() None#

Ensure that the trusted hosts have correct domain wildcards.

class litestar.config.app.AppConfig#

Bases: object

The parameters provided to the Litestar app are used to instantiate an instance, and then the instance is passed to any callbacks registered to on_app_init in the order they are provided.

The final attribute values are used to instantiate the application object.

after_exception: list[AfterExceptionHookHandler]#

An application level exception hook handler or list thereof.

This hook is called after an exception occurs. In difference to exception handlers, it is not meant to return a response - only to process the exception (e.g. log it, send it to Sentry etc.).

after_request: AfterRequestHookHandler | None = None#

A sync or async function executed after the route handler function returned and the response object has been resolved.

Receives the response object which may be any subclass of Response.

after_response: AfterResponseHookHandler | None = None#

A sync or async function called after the response has been awaited. It receives the Request object and should not return any values.

allowed_hosts: list[str] | AllowedHostsConfig | None = None#

If set enables the builtin allowed hosts middleware.

before_request: BeforeRequestHookHandler | None = None#

A sync or async function called immediately before calling the route handler. Receives the Request instance and any non-None return value is used for the response, bypassing the route handler.

before_send: list[BeforeMessageSendHookHandler]#

An application level before send hook handler or list thereof.

This hook is called when the ASGI send function is called.

cache_control: CacheControlHeader | None = None#

A cache-control header of type CacheControlHeader to add to route handlers of this app.

Can be overridden by route handlers.

compression_config: CompressionConfig | None = None#

Configures compression behaviour of the application, this enabled a builtin or user defined Compression middleware.

cors_config: CORSConfig | None = None#

If set this enables the builtin CORS middleware.

csrf_config: CSRFConfig | None = None#

If set this enables the builtin CSRF middleware.

debug: bool = False#

If True, app errors rendered as HTML with a stack trace.

dependencies: dict[str, Provide | AnyCallable]#

A string keyed dictionary of dependency Provider instances.

dto: type[AbstractDTO] | None | EmptyType = 0#

AbstractDTO to use for (de)serializing and validation of request data.

etag: ETag | None = None#

An etag header of type ETag to add to route handlers of this app.

Can be overridden by route handlers.

event_emitter_backend#

A subclass of BaseEventEmitterBackend.

alias of SimpleEventEmitter

exception_handlers: ExceptionHandlersMap#

A dictionary that maps handler functions to status codes and/or exception types.

guards: list[Guard]#

A list of Guard callables.

include_in_schema: bool | EmptyType = 0#

A boolean flag dictating whether the route handler should be documented in the OpenAPI schema

lifespan: list[Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager]#

A list of callables returning async context managers, wrapping the lifespan of the ASGI application

listeners: list[EventListener]#

A list of EventListener.

logging_config: BaseLoggingConfig | None = None#

An instance of BaseLoggingConfig subclass.

middleware: list[Middleware]#

A list of Middleware.

on_shutdown: list[LifespanHook]#

A list of LifespanHook called during application shutdown.

on_startup: list[LifespanHook]#

A list of LifespanHook called during application startup.

openapi_config: OpenAPIConfig | None = None#

Defaults to DEFAULT_OPENAPI_CONFIG

opt: dict[str, Any]#

A string keyed dictionary of arbitrary values that can be accessed in Guards or wherever you have access to Request or ASGI Scope.

Can be overridden by routers and router handlers.

__init__(after_exception: list[AfterExceptionHookHandler] = <factory>, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, allowed_hosts: list[str] | AllowedHostsConfig | None = None, before_request: BeforeRequestHookHandler | None = None, before_send: list[BeforeMessageSendHookHandler] = <factory>, cache_control: CacheControlHeader | None = None, compression_config: CompressionConfig | None = None, cors_config: CORSConfig | None = None, csrf_config: CSRFConfig | None = None, debug: bool = False, dependencies: dict[str, Provide | AnyCallable] = <factory>, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, etag: ETag | None = None, event_emitter_backend: type[BaseEventEmitterBackend] = <class 'litestar.events.emitter.SimpleEventEmitter'>, exception_handlers: ExceptionHandlersMap = <factory>, guards: list[Guard] = <factory>, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, lifespan: list[Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager] = <factory>, listeners: list[EventListener] = <factory>, logging_config: BaseLoggingConfig | None = None, middleware: list[Middleware] = <factory>, on_shutdown: list[LifespanHook] = <factory>, on_startup: list[LifespanHook] = <factory>, openapi_config: OpenAPIConfig | None = None, opt: dict[str, Any] = <factory>, parameters: ParametersMap = <factory>, path: str = '', pdb_on_exception: bool = False, plugins: list[PluginProtocol] = <factory>, request_class: type[Request] | None = None, response_class: type[Response] | None = None, response_cookies: ResponseCookies = <factory>, response_headers: ResponseHeaders = <factory>, response_cache_config: ResponseCacheConfig = <factory>, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, route_handlers: list[ControllerRouterHandler] = <factory>, security: list[SecurityRequirement] = <factory>, signature_namespace: dict[str, Any] = <factory>, signature_types: list[Any] = <factory>, state: State = <factory>, static_files_config: list[StaticFilesConfig] = <factory>, stores: StoreRegistry | dict[str, Store] | None = None, tags: list[str] = <factory>, template_config: TemplateConfigType | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, websocket_class: type[WebSocket] | None = None, multipart_form_part_limit: int = 1000, experimental_features: list[ExperimentalFeatures] | None = None) None#
parameters: ParametersMap#

A mapping of Parameter definitions available to all application paths.

path: str = ''#

A base path that prefixed to all route handlers, controllers and routers associated with the application instance.

New in version 2.8.0.

pdb_on_exception: bool = False#

Drop into the PDB on an exception

plugins: list[PluginProtocol]#

List of SerializationPluginProtocol.

request_class: type[Request] | None = None#

An optional subclass of Request to use for http connections.

response_class: type[Response] | None = None#

A custom subclass of Response to be used as the app’s default response.

response_cookies: ResponseCookies#

A list of Cookie.

response_headers: ResponseHeaders#

A string keyed dictionary mapping ResponseHeader.

response_cache_config: ResponseCacheConfig#

Configures caching behavior of the application.

return_dto: type[AbstractDTO] | None | EmptyType = 0#

AbstractDTO to use for serializing outbound response data.

route_handlers: list[ControllerRouterHandler]#

A required list of route handlers, which can include instances of Router, subclasses of Controller or any function decorated by the route handler decorators.

security: list[SecurityRequirement]#

A list of dictionaries that will be added to the schema of all route handlers in the application. See SecurityRequirement for details.

signature_namespace: dict[str, Any]#

A mapping of names to types for use in forward reference resolution during signature modeling.

signature_types: list[Any]#

A sequence of types for use in forward reference resolution during signature modeling.

These types will be added to the signature namespace using their __name__ attribute.

state: State#

A State <.datastructures.State>` instance holding application state.

static_files_config: list[StaticFilesConfig]#

An instance or list of StaticFilesConfig.

stores: StoreRegistry | dict[str, Store] | None = None#

Central registry of Store to be made available and be used throughout the application. Can be either a dictionary mapping strings to Store instances, or an instance of StoreRegistry.

tags: list[str]#

A list of string tags that will be appended to the schema of all route handlers under the application.

template_config: TemplateConfigType | None = None#

An instance of TemplateConfig.

type_decoders: TypeDecodersSequence | None = None#

A sequence of tuples, each composed of a predicate testing for type identity and a msgspec hook for deserialization.

type_encoders: TypeEncodersMap | None = None#

A mapping of types to callables that transform them into types supported for serialization.

websocket_class: type[WebSocket] | None = None#

An optional subclass of WebSocket to use for websocket connections.

multipart_form_part_limit: int = 1000#

The maximal number of allowed parts in a multipart/formdata request. This limit is intended to protect from DoS attacks.

__post_init__() None#

Normalize the allowed hosts to be a config or None.

Returns:

Optional config.

class litestar.config.app.ExperimentalFeatures#

Bases: str, Enum

__new__(value)#
class litestar.config.compression.CompressionConfig#

Bases: object

Configuration for response compression.

To enable response compression, pass an instance of this class to the Litestar constructor using the compression_config key.

backend: Literal['gzip', 'brotli'] | str#

The backend to use.

If the value given is gzip or brotli, then the builtin gzip and brotli compression is used.

minimum_size: int = 500#

Minimum response size (bytes) to enable compression, affects all backends.

gzip_compress_level: int = 9#

Range [0-9], see gzip — Support for gzip files.

brotli_quality: int = 5#

Range [0-11], Controls the compression-speed vs compression-density tradeoff.

The higher the quality, the slower the compression.

brotli_mode: Literal['generic', 'text', 'font'] = 'text'#

MODE_GENERIC, MODE_TEXT (for UTF-8 format text input, default) or MODE_FONT (for WOFF 2.0).

brotli_lgwin: int = 22#

Base 2 logarithm of size.

Range is 10 to 24. Defaults to 22.

brotli_lgblock: Literal[0, 16, 17, 18, 19, 20, 21, 22, 23, 24] = 0#

Base 2 logarithm of the maximum input block size.

Range is 16 to 24. If set to 0, the value will be set based on the quality. Defaults to 0.

__init__(backend: Literal['gzip', 'brotli'] | str, minimum_size: int = 500, gzip_compress_level: int = 9, brotli_quality: int = 5, brotli_mode: Literal['generic', 'text', 'font'] = 'text', brotli_lgwin: int = 22, brotli_lgblock: Literal[0, 16, 17, 18, 19, 20, 21, 22, 23, 24] = 0, brotli_gzip_fallback: bool = True, middleware_class: type[CompressionMiddleware] = <class 'litestar.middleware.compression.middleware.CompressionMiddleware'>, exclude: str | list[str] | None = None, exclude_opt_key: str | None = None, compression_facade: type[CompressionFacade] = <class 'litestar.middleware.compression.gzip_facade.GzipCompression'>, backend_config: Any = None, gzip_fallback: bool = True) None#
brotli_gzip_fallback: bool = True#

Use GZIP if Brotli is not supported.

middleware_class#

Middleware class to use, should be a subclass of CompressionMiddleware.

alias of CompressionMiddleware

exclude: str | list[str] | None = None#

A pattern or list of patterns to skip in the compression middleware.

exclude_opt_key: str | None = None#

An identifier to use on routes to disable compression for a particular route.

compression_facade#

The compression facade to use for the actual compression.

alias of GzipCompression

backend_config: Any = None#

Configuration specific to the backend.

gzip_fallback: bool = True#

Use GZIP as a fallback if the provided backend is not supported by the client.

class litestar.config.cors.CORSConfig#

Bases: object

Configuration for CORS (Cross-Origin Resource Sharing).

To enable CORS, pass an instance of this class to the Litestar constructor using the ‘cors_config’ key.

allow_origins: list[str]#

List of origins that are allowed.

Can use ‘*’ in any component of the path, e.g. ‘domain.*’. Sets the ‘Access-Control-Allow-Origin’ header.

allow_methods: list[Literal['*'] | Method]#

List of allowed HTTP methods.

Sets the ‘Access-Control-Allow-Methods’ header.

allow_headers: list[str]#

List of allowed headers.

Sets the ‘Access-Control-Allow-Headers’ header.

allow_credentials: bool = False#

Boolean dictating whether or not to set the ‘Access-Control-Allow-Credentials’ header.

allow_origin_regex: str | None = None#

Regex to match origins against.

expose_headers: list[str]#

List of headers that are exposed via the ‘Access-Control-Expose-Headers’ header.

max_age: int = 600#

Response caching TTL in seconds, defaults to 600.

Sets the ‘Access-Control-Max-Age’ header.

__init__(allow_origins: list[str] = <factory>, allow_methods: list[Literal['*'] | Method] = <factory>, allow_headers: list[str] = <factory>, allow_credentials: bool = False, allow_origin_regex: str | None = None, expose_headers: list[str] = <factory>, max_age: int = 600) None#
property allowed_origins_regex: Pattern[str]#

Get or create a compiled regex for allowed origins.

Returns:

A compiled regex of the allowed path.

property is_allow_all_origins: bool#

Get a cached boolean flag dictating whether all origins are allowed.

Returns:

Boolean dictating whether all origins are allowed.

property is_allow_all_methods: bool#

Get a cached boolean flag dictating whether all methods are allowed.

Returns:

Boolean dictating whether all methods are allowed.

property is_allow_all_headers: bool#

Get a cached boolean flag dictating whether all headers are allowed.

Returns:

Boolean dictating whether all headers are allowed.

property preflight_headers: dict[str, str]#

Get cached pre-flight headers.

Returns:

A dictionary of headers to set on the response object.

property simple_headers: dict[str, str]#

Get cached simple headers.

Returns:

A dictionary of headers to set on the response object.

is_origin_allowed(origin: str) bool#

Check whether a given origin is allowed.

Parameters:

origin – An origin header value.

Returns:

Boolean determining whether an origin is allowed.

class litestar.config.csrf.CSRFConfig#

Bases: object

Configuration for CSRF (Cross Site Request Forgery) protection.

To enable CSRF protection, pass an instance of this class to the Litestar constructor using the ‘csrf_config’ key.

secret: str#

A string that is used to create an HMAC to sign the CSRF token.

cookie_name: str = 'csrftoken'#

The CSRF cookie name.

cookie_path: str = '/'#

The CSRF cookie path.

header_name: str = 'x-csrftoken'#

The header that will be expected in each request.

cookie_secure: bool = False#

A boolean value indicating whether to set the Secure attribute on the cookie.

__init__(secret: str, cookie_name: str = 'csrftoken', cookie_path: str = '/', header_name: str = 'x-csrftoken', cookie_secure: bool = False, cookie_httponly: bool = False, cookie_samesite: Literal['lax', 'strict', 'none'] = 'lax', cookie_domain: str | None = None, safe_methods: set[Method] = <factory>, exclude: str | list[str] | None = None, exclude_from_csrf_key: str = 'exclude_from_csrf') None#
cookie_httponly: bool = False#

A boolean value indicating whether to set the HttpOnly attribute on the cookie.

cookie_samesite: Literal['lax', 'strict', 'none'] = 'lax'#

The value to set in the SameSite attribute of the cookie.

cookie_domain: str | None = None#

Specifies which hosts can receive the cookie.

safe_methods: set[Method]#

A set of “safe methods” that can set the cookie.

exclude: str | list[str] | None = None#

A pattern or list of patterns to skip in the CSRF middleware.

exclude_from_csrf_key: str = 'exclude_from_csrf'#

An identifier to use on routes to disable CSRF for a particular route.

class litestar.config.response_cache.ResponseCacheConfig#

Bases: object

Configuration for response caching.

To enable response caching, pass an instance of this class to Litestar using the response_cache_config key.

default_expiration: int | None = 60#

Default cache expiration in seconds used when a route handler is configured with cache=True.

key_builder() str#

CacheKeyBuilder. Defaults to default_cache_key_builder().

__init__(default_expiration: int | None = 60, key_builder: CacheKeyBuilder = <function default_cache_key_builder>, store: str = 'response_cache', cache_response_filter: Callable[[HTTPScope, int], bool] = <function default_do_cache_predicate>) None#
store: str = 'response_cache'#

Name of the Store to use.

cache_response_filter(status_code: int) bool#

A callable that receives connection scope and a status code, and returns a boolean indicating whether the response should be cached.

get_store_from_app(app: Litestar) Store#

Get the store defined in store from an Litestar instance.

litestar.config.response_cache.default_cache_key_builder(request: Request[Any, Any, Any]) str#

Given a request object, returns a cache key by combining the request method and path with the sorted query params.

Parameters:

request – request used to generate cache key.

Returns:

A combination of url path and query parameters

final class litestar.config.response_cache.CACHE_FOREVER#

Bases: object

Sentinel value indicating that a cached response should be stored without an expiration, explicitly skipping the default expiration