应用 ===

litestar.app.DEFAULT_OPENAPI_CONFIG = OpenAPIConfig(title='Litestar API', version='1.0.0', create_examples=False, random_seed=10, contact=None, description=None, external_docs=None, license=None, security=None, components=Components(schemas={}, responses=None, parameters=None, examples=None, request_bodies=None, headers=None, security_schemes=None, links=None, callbacks=None, path_items=None), servers=[Server(url='/', description=None, variables=None)], summary=None, tags=None, terms_of_service=None, use_handler_docstrings=False, webhooks=None, operation_id_creator=<function default_operation_id_creator>, path=None, render_plugins=[<litestar.openapi.plugins.RapidocRenderPlugin object>, <litestar.openapi.plugins.StoplightRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.SwaggerRenderPlugin object>, <litestar.openapi.plugins.RedocRenderPlugin object>, <litestar.openapi.plugins.JsonRenderPlugin object>], openapi_router=None, openapi_controller=None, root_schema_site='redoc', enabled_endpoints={'rapidoc', 'elements', 'openapi.yml', 'openapi.yaml', 'swagger', 'redoc', 'openapi.json', 'oauth2-redirect.html'})

如果未显式将配置传递给 Litestar 实例构造函数,则使用此默认 OpenAPI 配置。

class litestar.app.HandlerIndex

基类:TypedDict

将路由处理程序名称映射到路径和路由处理程序的映射。 它由 get_handler_index_by_name 工具方法返回。

paths: list[str]

Full route paths to the route handler.

handler: RouteHandlerType

Route handler instance.

identifier: str

Unique identifier of the handler.

Either equal to :attr`__name__ <obj.__name__>` attribute or __str__ value of the handler.

class litestar.app.Litestar

基类:Router

Litestar 应用程序。 Litestar 是应用程序的根级别——它具有基础路径 /,所有根级别的控制器(Controllers)、路由器(Routers)和路由处理器(Route Handlers)都应注册到它上面。

__init__(route_handlers: Sequence[ControllerRouterHandler] | None = None, *, after_exception: Sequence[AfterExceptionHookHandler] | None = None, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, allowed_hosts: Sequence[str] | AllowedHostsConfig | None = None, before_request: BeforeRequestHookHandler | None = None, before_send: Sequence[BeforeMessageSendHookHandler] | None = None, cache_control: CacheControlHeader | None = None, compression_config: CompressionConfig | None = None, cors_config: CORSConfig | None = None, csrf_config: CSRFConfig | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, debug: bool | None = None, dependencies: Dependencies | None = None, etag: ETag | None = None, event_emitter_backend: type[BaseEventEmitterBackend] = <class 'litestar.events.emitter.SimpleEventEmitter'>, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, listeners: Sequence[EventListener] | None = None, logging_config: BaseLoggingConfig | EmptyType | None = _EmptyEnum.EMPTY, middleware: Sequence[Middleware] | None = None, multipart_form_part_limit: int = 1000, on_app_init: Sequence[OnAppInitHandler] | None = None, on_shutdown: Sequence[LifespanHook] | None = None, on_startup: Sequence[LifespanHook] | None = None, openapi_config: OpenAPIConfig | None = OpenAPIConfig(title='Litestar API', version='1.0.0', create_examples=False, random_seed=10, contact=None, description=None, external_docs=None, license=None, security=None, components=Components(schemas={}, responses=None, parameters=None, examples=None, request_bodies=None, headers=None, security_schemes=None, links=None, callbacks=None, path_items=None), servers=[Server(url='/', description=None, variables=None)], summary=None, tags=None, terms_of_service=None, use_handler_docstrings=False, webhooks=None, operation_id_creator=<function default_operation_id_creator>, path=None, render_plugins=[<litestar.openapi.plugins.RapidocRenderPlugin object>, <litestar.openapi.plugins.StoplightRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.SwaggerRenderPlugin object>, <litestar.openapi.plugins.RedocRenderPlugin object>, <litestar.openapi.plugins.JsonRenderPlugin object>], openapi_router=None, openapi_controller=None, root_schema_site='redoc', enabled_endpoints={'rapidoc', 'elements', 'openapi.yml', 'openapi.yaml', 'swagger', 'redoc', 'openapi.json', 'oauth2-redirect.html'}), opt: Mapping[str, Any] | None = None, parameters: ParametersMap | None = None, path: str | None = None, plugins: Sequence[PluginProtocol] | None = None, request_class: type[Request] | None = None, request_max_body_size: int | None = 10000000, response_cache_config: ResponseCacheConfig | None = None, response_class: type[Response] | None = None, response_cookies: ResponseCookies | None = None, response_headers: ResponseHeaders | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, security: Sequence[SecurityRequirement] | None = None, signature_namespace: Mapping[str, Any] | None = None, signature_types: Sequence[Any] | None = None, state: State | None = None, static_files_config: Sequence[StaticFilesConfig] | None = None, stores: StoreRegistry | dict[str, Store] | None = None, tags: Sequence[str] | None = None, template_config: TemplateConfigType | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, websocket_class: type[WebSocket] | None = None, lifespan: Sequence[Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager] | None = None, pdb_on_exception: bool | None = None, debugger_module: Debugger = <module 'pdb' from 'D:\\Programs\\miniforge3\\envs\\litestar\\Lib\\pdb.py'>, experimental_features: Iterable[ExperimentalFeatures] | None = None) None

Initialize a Litestar application.

参数:
  • after_exception -- A sequence of exception hook handlers. 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 -- A sync or async function executed after the route handler function returned and the response object has been resolved. Receives the response object.

  • after_response -- 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 -- A sequence of allowed hosts, or an AllowedHostsConfig instance. Enables the builtin allowed hosts middleware.

  • before_request -- 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 -- A sequence of before send hook handlers. Called when the ASGI send function is called.

  • cache_control -- A cache-control header of type CacheControlHeader to add to route handlers of this app. Can be overridden by route handlers.

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

  • cors_config -- If set, configures CORS handling for the application.

  • csrf_config -- If set, configures CSRFMiddleware.

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

  • dependencies -- A string keyed mapping of dependency Providers.

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

  • etag -- 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.

  • exception_handlers -- A mapping of status codes and/or exception types to handler functions.

  • guards -- A sequence of Guard callables.

  • include_in_schema -- A boolean flag dictating whether the route handler should be documented in the OpenAPI schema.

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

  • listeners -- A sequence of EventListener.

  • logging_config -- A subclass of BaseLoggingConfig.

  • middleware -- A sequence of Middleware.

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

  • on_app_init -- A sequence of OnAppInitHandler instances. Handlers receive an instance of AppConfig that will have been initially populated with the parameters passed to Litestar, and must return an instance of same. If more than one handler is registered they are called in the order they are provided.

  • on_shutdown -- A sequence of LifespanHook called during application shutdown.

  • on_startup -- A sequence of LifespanHook called during application startup.

  • openapi_config -- Defaults to DEFAULT_OPENAPI_CONFIG

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

  • parameters -- A mapping of Parameter definitions available to all application paths.

  • path --

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

    在 2.8.0 版本加入.

  • pdb_on_exception -- Drop into the PDB when an exception occurs.

  • debugger_module -- 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 -- Sequence of plugins.

  • request_class -- An optional subclass of Request to use for http connections.

  • request_max_body_size -- 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 -- A custom subclass of Response to be used as the app's default response.

  • response_cookies -- A sequence of Cookie.

  • response_headers -- A string keyed mapping of ResponseHeader

  • response_cache_config -- Configures caching behavior of the application.

  • return_dto -- AbstractDTO to use for serializing outbound response data.

  • route_handlers -- A sequence of route handlers, which can include instances of Router, subclasses of Controller or any callable decorated by the route handler decorators.

  • security -- A sequence of dicts that will be added to the schema of all route handlers in the application. See SecurityRequirement for details.

  • signature_namespace -- A mapping of names to types for use in forward reference resolution during signature modelling.

  • signature_types -- 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 -- An optional State for application state.

  • static_files_config -- A sequence of StaticFilesConfig

  • stores -- Central registry of Store that will be available throughout the application. If this is a dictionary to it will be passed to a StoreRegistry. If it is a StoreRegistry, this instance will be used directly.

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

  • template_config -- An instance of TemplateConfig

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

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

  • websocket_class -- An optional subclass of WebSocket to use for websocket connections.

  • experimental_features -- An iterable of experimental features to enable

async __call__(scope: Scope | LifeSpanScope, receive: Receive | LifeSpanReceive, send: Send | LifeSpanSend) None

应用程序入口点。 生命周期事件(启动/关闭)会发送给生命周期处理器,否则将使用 ASGI 处理器。 Args: scope: ASGI 连接作用域。 receive: ASGI 接收函数。 send: ASGI 发送函数。 Returns: None

classmethod from_scope(scope: Scope) Litestar

从当前 ASGI 作用域中检索 Litestar 应用程序

lifespan() AsyncGenerator[None, None]

处理 ASGI 生命周期的上下文管理器。 当从服务器接收到 lifespan 消息时进入,在 asgi.shutdown 消息之后退出。在此期间,它负责调用 on_startupon_shutdown 钩子以及自定义生命周期管理器。

property openapi_schema: OpenAPI

获取应用程序的 OpenAPI 模式。 Returns: 应用程序的 OpenAPI <pydantic_openapi_schema.open_api.OpenAPI> 实例。 Raises: ImproperlyConfiguredException: 如果应用程序的 openapi_config 属性为 None

classmethod from_config(config: AppConfig) Self

从配置实例初始化 Litestar 应用程序。 Args: config: AppConfig <.config.AppConfig> 的实例 Returns: Litestar 应用程序的实例。

register(value: ControllerRouterHandler) None

Register a route handler on the app.

This method can be used to dynamically add endpoints to an application.

参数:

value -- An instance of Router, a subclass of Controller or any function decorated by the route handler decorators.

返回:

None

get_handler_index_by_name(name: str) HandlerIndex | None

接收一个路由处理器名称,并返回一个可选字典,其中包含路由处理器实例和按字典序排序的路径列表。 示例: .. code-block:: python from litestar import Litestar, get @get("/", name="my-handler") def handler() -> None: pass app = Litestar(route_handlers=[handler]) handler_index = app.get_handler_index_by_name("my-handler") # { "paths": ["/"], "handler" ... } Args: name: 路由处理器的唯一名称。 Returns: 一个 HandlerIndex 实例或 None

route_reverse(name: str, **path_parameters: Any) str

接收路由处理器名称和路径参数值,并返回填充了路径参数的处理器 URL 路径。 示例: .. code-block:: python from litestar import Litestar, get @get("/group/{group_id:int}") def get_group_members(group_id: int) -> None: pass @get("/group/{group_id:int}/user/{user_id:int}", name="get_membership_details") def get_membership_details(group_id: int, user_id: int) -> None: pass app = Litestar(route_handlers=[get_group_members, get_membership_details]) group_members_path = app.route_reverse(get_group_members, group_id=10) # /group/10 membership_details_path = app.route_reverse( "get_membership_details", user_id=100, group_id=10 ) # /group/10/user/100 Args: name: 路由处理器的 name,或者是路由处理器本身。 **path_parameters: 路由中路径参数的实际值。datetimedatetimetimedeltafloatPathUUID 类型的参数可以以其字符串形式传递。 Raises: NoRouteMatchFoundException: 如果不存在名为 'name' 的路由,或者 **path_parameters 中缺少任何路径参数,或其类型不正确。 Returns: 一个完全格式化后的 URL 路径。

url_for_static_asset(name: str, file_path: str) str

Receives a static files handler name, an asset file path and returns resolved url path to the asset.

示例

from litestar import Litestar
from litestar.static_files.config import StaticFilesConfig

app = Litestar(
    static_files_config=[
        StaticFilesConfig(directories=["css"], path="/static/css", name="css")
    ]
)

path = app.url_for_static_asset("css", "main.css")

# /static/css/main.css
参数:
  • name -- A static handler unique name.

  • file_path -- a string containing path to an asset.

抛出:

NoRouteMatchFoundException -- If static files handler with name does not exist.

返回:

A url path to the asset.

property route_handler_method_view: dict[str, list[str]]

Map route handlers to paths.

返回:

A dictionary of router handlers and lists of paths as strings

update_openapi_schema() None

更新 OpenAPI 模式以反映在应用上注册的路线处理器。 Returns: None

emit(event_id: str, *args: Any, **kwargs: Any) None

向所有附加的监听器发出事件。 Args: event_id: 要发出的事件 ID,例如 my_event。 args: 要传递给监听器的参数。 kwargs: 要传递给监听器的关键字参数。 Returns: None