应用 ===
- 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 工具方法返回。
- handler: RouteHandlerType¶
Route handler instance.
- class litestar.app.Litestar¶
基类:
RouterLitestar 应用程序。
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
Litestarapplication.- 参数:
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
Requestobject and should not return any values.allowed_hosts¶ -- A sequence of allowed hosts, or an
AllowedHostsConfiginstance. Enables the builtin allowed hosts middleware.before_request¶ -- A sync or async function called immediately before calling the route handler. Receives the
Requestinstance and any non-Nonereturn 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-controlheader of typeCacheControlHeaderto 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¶ --
AbstractDTOto use for (de)serializing and validation of request data.etag¶ -- An
etagheader of typeETagto 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.
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
OnAppInitHandlerinstances. Handlers receive an instance ofAppConfigthat will have been initially populated with the parameters passed toLitestar, 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
LifespanHookcalled during application shutdown.on_startup¶ -- A sequence of
LifespanHookcalled during application startup.openapi_config¶ -- Defaults to
DEFAULT_OPENAPI_CONFIGopt¶ -- A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.parameters¶ -- A mapping of
Parameterdefinitions 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
Requestto 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
Responseto be used as the app's default response.response_headers¶ -- A string keyed mapping of
ResponseHeaderresponse_cache_config¶ -- Configures caching behavior of the application.
return_dto¶ --
AbstractDTOto use for serializing outbound response data.route_handlers¶ -- A sequence of route handlers, which can include instances of
Router, subclasses ofControlleror 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
SecurityRequirementfor 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.static_files_config¶ -- A sequence of
StaticFilesConfigstores¶ -- Central registry of
Storethat will be available throughout the application. If this is a dictionary to it will be passed to aStoreRegistry. If it is aStoreRegistry, 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
TemplateConfigtype_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
WebSocketto 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
- lifespan() AsyncGenerator[None, None]¶
处理 ASGI 生命周期的上下文管理器。 当从服务器接收到
lifespan消息时进入,在asgi.shutdown消息之后退出。在此期间,它负责调用on_startup、on_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 ofControlleror 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: 路由中路径参数的实际值。datetime、date、time、timedelta、float、Path 和 UUID 类型的参数可以以其字符串形式传递。 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
- 参数:
- 抛出:
NoRouteMatchFoundException -- If static files handler with
namedoes not exist.- 返回:
A url path to the asset.