配置

class litestar.config.allowed_hosts.AllowedHostsConfig

基类:object

允许主机保护的配置。 要启用允许主机保护,请使用 allowed_hosts 键将此类的一个实例传递给 Litestar 构造函数。

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

确保受信任的主机具有正确的域名通配符。

class litestar.config.app.AppConfig

基类:object

传递给 Litestar 应用的参数用于实例化一个实例,然后该实例会按照提供的顺序传递给注册到 on_app_init 的任何回调函数。 最终的属性值将用于实例化应用对象。

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.

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.

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.

在 2.8.0 版本加入.

__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, debugger_module: Debugger = <module 'pdb' from 'D:\\Programs\\miniforge3\\envs\\litestar\\Lib\\pdb.py'>, plugins: list[PluginProtocol] = <factory>, request_class: type[Request] | None = None, request_max_body_size: int | None | EmptyType = _EmptyEnum.EMPTY, 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
pdb_on_exception: bool = False

Drop into the PDB on an exception

debugger_module: Debugger = <module 'pdb' from 'D:\\Programs\\miniforge3\\envs\\litestar\\Lib\\pdb.py'>

A pdb-like debugger module that supports the post_mortem() protocol. This module will be used when pdb_on_exception is set to True.

plugins: list[PluginProtocol]

List of SerializationPluginProtocol.

request_class: type[Request] | None = None

An optional subclass of Request to use for http connections.

request_max_body_size: int | None | EmptyType = 0

Maximum allowed size of the request body in bytes. If this size is exceeded, a '413 - Request Entity Too Large' error response is returned.

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 modelling.

signature_types: list[Any]

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

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

将允许的主机规范化为配置或 None。 Returns: 可选配置。

class litestar.config.app.ExperimentalFeatures

基类:str, Enum

__new__(value)
DTO_CODEGEN = 'DTO_CODEGEN'

Enable DTO codegen.

FUTURE = 'FUTURE'

Enable future features that may be considered breaking or changing.

class litestar.config.compression.CompressionConfig

基类:object

响应压缩的配置。 要启用响应压缩,请使用 compression_config 键将本类的实例传递给 Litestar 构造函数。

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.

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.

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

基类:object

CORS(跨域资源共享)的配置。 要启用 CORS,请使用 cors_config 键将本类的实例传递给 Litestar 构造函数。

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]

获取或创建一个用于允许来源的已编译正则表达式。 Returns: 允许路径的已编译正则表达式。

property is_allow_all_origins: bool

获取一个缓存的布尔标志,用于指示是否允许所有来源。 Returns: 指示是否允许所有来源的布尔值。

property is_allow_all_methods: bool

获取一个缓存的布尔标志,用于指示是否允许所有方法。 Returns: 指示是否允许所有方法的布尔值。

property is_allow_all_headers: bool

获取一个缓存的布尔标志,用于指示是否允许所有标头。 Returns: 指示是否允许所有标头的布尔值。

property preflight_headers: dict[str, str]

获取缓存的预检请求头。 Returns: 要在响应对象上设置的标头字典。

property simple_headers: dict[str, str]

获取缓存的简单标头。 Returns: 要设置在响应对象上的标头字典。

is_origin_allowed(origin: str) bool

检查给定的源是否被允许。 Args: origin: 源头部的值。 Returns: 布尔值,用于确定源是否被允许。

class litestar.config.csrf.CSRFConfig

基类:object

CSRF(跨站请求伪造)保护的配置。 要启用 CSRF 保护,请使用 csrf_config 键将本类的实例传递给 Litestar 构造函数。

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.

final class litestar.config.response_cache.CACHE_FOREVER

基类:object

表示缓存响应应永久存储(不设置过期时间)的哨兵值,显式跳过默认过期时间。

class litestar.config.response_cache.ResponseCacheConfig

基类:object

响应缓存的配置。 要启用响应缓存,请使用 response_cache_config 键将本类的实例传递给 Litestar

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

Litestar 实例中获取在 store 中定义的存储。

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

给定一个请求对象,通过组合请求方法和路径与排序后的查询参数,返回一个缓存键。 Args: request: 用于生成缓存键的请求。 Returns: URL 路径和查询参数的组合