starlite.app#

class starlite.app.Starlite#

Bases: Router

The Starlite application.

Starlite is the root level of the app - it has the base path of “/” and all root level Controllers, Routers and Route Handlers should be registered on it.

Inherits from the Router class

__init__(route_handlers: ~typing.List[ControllerRouterHandler], *, after_exception: ~typing.Optional[SingleOrList[AfterExceptionHookHandler]] = None, after_request: ~typing.Optional[AfterRequestHookHandler] = None, after_response: ~typing.Optional[AfterResponseHookHandler] = None, after_shutdown: ~typing.Optional[SingleOrList[LifeSpanHookHandler]] = None, after_startup: ~typing.Optional[SingleOrList[LifeSpanHookHandler]] = None, allowed_hosts: ~typing.Optional[~typing.Union[~typing.List[str], AllowedHostsConfig]] = None, before_request: ~typing.Optional[BeforeRequestHookHandler] = None, before_send: ~typing.Optional[SingleOrList[BeforeMessageSendHookHandler]] = None, before_shutdown: ~typing.Optional[SingleOrList[LifeSpanHookHandler]] = None, before_startup: ~typing.Optional[SingleOrList[LifeSpanHookHandler]] = None, cache_config: ~starlite.config.cache.CacheConfig = CacheConfig(backend=None, expiration=60, cache_key_builder=<function default_cache_key_builder>), cache_control: ~typing.Optional[CacheControlHeader] = None, compression_config: ~typing.Optional[CompressionConfig] = None, cors_config: ~typing.Optional[CORSConfig] = None, csrf_config: ~typing.Optional[CSRFConfig] = None, debug: bool = False, dependencies: ~typing.Optional[~typing.Dict[str, Provide]] = None, etag: ~typing.Optional[ETag] = None, exception_handlers: ~typing.Optional[ExceptionHandlersMap] = None, guards: ~typing.Optional[~typing.List[Guard]] = None, initial_state: ~typing.Optional[InitialStateType] = None, logging_config: ~typing.Optional[~typing.Union[BaseLoggingConfig, EmptyType]] = <class 'starlite.types.empty.Empty'>, middleware: ~typing.Optional[~typing.List[Middleware]] = None, multipart_form_part_limit: int = 1000, on_app_init: ~typing.Optional[~typing.List[OnAppInitHandler]] = None, on_shutdown: ~typing.Optional[~typing.List[LifeSpanHandler]] = None, on_startup: ~typing.Optional[~typing.List[LifeSpanHandler]] = None, openapi_config: ~typing.Optional[~starlite.config.openapi.OpenAPIConfig] = OpenAPIConfig(create_examples=False, openapi_controller=<class 'starlite.openapi.controller.OpenAPIController'>, title='Starlite API', version='1.0.0', contact=None, description=None, external_docs=None, license=None, security=None, components=None, servers=[Server(url='/', description=None, variables=None)], summary=None, tags=None, terms_of_service=None, use_handler_docstrings=False, webhooks=None, root_schema_site='redoc', enabled_endpoints={'elements', 'redoc', 'swagger', 'openapi.json', 'openapi.yaml'}, by_alias=True), opt: ~typing.Optional[~typing.Dict[str, ~typing.Any]] = None, parameters: ~typing.Optional[ParametersMap] = None, plugins: ~typing.Optional[~typing.List[PluginProtocol]] = None, request_class: ~typing.Optional[~typing.Type[Request]] = None, response_class: ~typing.Optional[ResponseType] = None, response_cookies: ~typing.Optional[ResponseCookies] = None, response_headers: ~typing.Optional[ResponseHeadersMap] = None, security: ~typing.Optional[~typing.List[SecurityRequirement]] = None, static_files_config: ~typing.Optional[~typing.Union[StaticFilesConfig, ~typing.List[StaticFilesConfig]]] = None, tags: ~typing.Optional[~typing.List[str]] = None, template_config: ~typing.Optional[TemplateConfig] = None, type_encoders: ~typing.Optional[TypeEncodersMap] = None, websocket_class: ~typing.Optional[~typing.Type[WebSocket]] = None) None#

Initialize a Starlite application.

Parameters:
  • after_exception – 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 – 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.

  • after_shutdown – An application level life-span hook handler or list thereof. This hook is called during the ASGI shutdown, after all callables in the ‘on_shutdown’ list have been called.

  • after_startup – An application level life-span hook handler or list thereof. This hook is called during the ASGI startup, after all callables in the ‘on_startup’ list have been called.

  • allowed_hosts – A list of allowed hosts - 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 – An application level before send hook handler or list thereof. This hook is called when the ASGI send function is called.

  • before_shutdown – An application level life-span hook handler or list thereof. This hook is called during the ASGI shutdown, before any callables in the ‘on_shutdown’ list have been called.

  • before_startup – An application level life-span hook handler or list thereof. This hook is called during the ASGI startup, before any callables in the ‘on_startup’ list have been called.

  • cache_config – Configures caching behavior of the application.

  • 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 this enables the builtin CORS middleware.

  • csrf_config – If set this enables the builtin CSRF middleware.

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

  • dependencies – A string keyed dictionary of dependency Provider instances.

  • etag – An etag header of type ETag to add to route handlers of this app. Can be overridden by route handlers.

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

  • guards – A list of Guard callables.

  • initial_state – An object from which to initialize the app state.

  • logging_config – A subclass of BaseLoggingConfig.

  • middleware – A list 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 Starlite, 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 list of LifeSpanHandler called during application shutdown.

  • on_startup – A list of LifeSpanHandler called during application startup.

  • openapi_config – Defaults to DEFAULT_OPENAPI_CONFIG

  • opt – A string keyed dictionary 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.

  • plugins – List of plugins.

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

  • response_class – A custom subclass of [starlite.response.Response] to be used as the app’s default response.

  • response_cookies – A list of [Cookie](starlite.datastructures.Cookie] instances.

  • response_headers – A string keyed dictionary mapping ResponseHeader instances.

  • route_handlers – 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 – A list of dictionaries that will be added to the schema of all route handlers in the application. See SecurityRequirement for details.

  • static_files_config – An instance or list of StaticFilesConfig

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

  • template_config – An instance of TemplateConfig

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

async __call__(scope: Union[Scope, LifeSpanScope], receive: Union[Receive, LifeSpanReceive], send: Union[Send, LifeSpanSend]) None#

Application entry point.

Lifespan events (startup / shutdown) are sent to the lifespan handler, otherwise the ASGI handler is used

Parameters:
  • scope – The ASGI connection scope.

  • receive – The ASGI receive function.

  • send – The ASGI send function.

Returns:

None

register(value: ControllerRouterHandler, add_to_openapi_schema: bool = False) None#

Register a route handler on the app.

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

Parameters:
  • value – an instance of Router, a subclass of Controller or any function decorated by the route handler decorators.

  • add_to_openapi_schema – Whether to add the registered route to the OpenAPI Schema. This affects only HTTP route handlers.

Returns:

None

get_handler_index_by_name(name: str) Optional[HandlerIndex]#

Receives a route handler name and returns an optional dictionary containing the route handler instance and list of paths sorted lexically.

Examples

Parameters:

name – A route handler unique name.

Returns:

A HandlerIndex instance or None.

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

Receives a route handler name, path parameter values and returns url path to the handler with filled path parameters.

Examples

Parameters:
  • name – A route handler unique name.

  • **path_parameters – Actual values for path parameters in the route.

Raises:

NoRouteMatchFoundException – If route with ‘name’ does not exist, path parameters are missing in **path_parameters or have wrong type.

Returns:

A fully formatted url path.

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.

Examples

Parameters:
  • name – A static handler unique name.

  • file_path – a string containing path to an asset.

Raises:

NoRouteMatchFoundException – If static files handler with ‘name’ does not exist.

Returns:

A url path to the asset.

property route_handler_method_view: Dict[str, List[str]]#

Map route handlers to paths.

Returns:

A dictionary of router handlers and lists of paths as strings

update_openapi_schema() None#

Update the OpenAPI schema to reflect the route handlers registered on the app.

Returns:

None

starlite.app.DEFAULT_OPENAPI_CONFIG = OpenAPIConfig(create_examples=False, openapi_controller=<class 'starlite.openapi.controller.OpenAPIController'>, title='Starlite API', version='1.0.0', contact=None, description=None, external_docs=None, license=None, security=None, components=None, servers=[Server(url='/', description=None, variables=None)], summary=None, tags=None, terms_of_service=None, use_handler_docstrings=False, webhooks=None, root_schema_site='redoc', enabled_endpoints={'elements', 'redoc', 'swagger', 'openapi.json', 'openapi.yaml'}, by_alias=True)#

Starlite <starlite.app.Starlite> instance constructor.

Type:

The default OpenAPI config used if not configuration is explicitly passed to the

Type:

class

starlite.app.DEFAULT_CACHE_CONFIG = CacheConfig(backend=None, expiration=60, cache_key_builder=<function default_cache_key_builder>)#

Starlite <starlite.app.Starlite> instance constructor.

Type:

The default cache config used if not configuration is explicitly passed to the

Type:

class

class starlite.app.HandlerIndex#

Bases: TypedDict

Map route handler names to a mapping of paths + route handler.

It’s returned from the ‘get_handler_index_by_name’ utility method.

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 the ‘name’ attribute or the __str__ value of the handler.