starlite.config#

class starlite.config.AppConfig#

Bases: BaseModel

The parameters provided to the Starlite 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: Union[Callable[[Exception, Union[HTTPScope, WebSocketScope], Any], Union[None, Awaitable[None]]], List[Callable[[Exception, Union[HTTPScope, WebSocketScope], Any], Union[None, Awaitable[None]]]]]#

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: Optional[Union[Callable[[Callable[[Union[HTTPScope, WebSocketScope], Callable[[...], Awaitable[Union[HTTPRequestEvent, HTTPDisconnectEvent, WebSocketConnectEvent, WebSocketReceiveEvent, WebSocketDisconnectEvent]]], Callable[[Union[HTTPResponseStartEvent, HTTPResponseBodyEvent, HTTPServerPushEvent, HTTPDisconnectEvent, WebSocketAcceptEvent, WebSocketSendEvent, WebSocketResponseStartEvent, WebSocketResponseBodyEvent, WebSocketCloseEvent]], Awaitable[None]]], Awaitable[None]]], Union[Callable[[Union[HTTPScope, WebSocketScope], Callable[[...], Awaitable[Union[HTTPRequestEvent, HTTPDisconnectEvent, WebSocketConnectEvent, WebSocketReceiveEvent, WebSocketDisconnectEvent]]], Callable[[Union[HTTPResponseStartEvent, HTTPResponseBodyEvent, HTTPServerPushEvent, HTTPDisconnectEvent, WebSocketAcceptEvent, WebSocketSendEvent, WebSocketResponseStartEvent, WebSocketResponseBodyEvent, WebSocketCloseEvent]], Awaitable[None]]], Awaitable[None]], Awaitable[Callable[[Union[HTTPScope, WebSocketScope], Callable[[...], Awaitable[Union[HTTPRequestEvent, HTTPDisconnectEvent, WebSocketConnectEvent, WebSocketReceiveEvent, WebSocketDisconnectEvent]]], Callable[[Union[HTTPResponseStartEvent, HTTPResponseBodyEvent, HTTPServerPushEvent, HTTPDisconnectEvent, WebSocketAcceptEvent, WebSocketSendEvent, WebSocketResponseStartEvent, WebSocketResponseBodyEvent, WebSocketCloseEvent]], Awaitable[None]]], Awaitable[None]]]]], Callable[[Any], Union[Any, Awaitable[Any]]]]]#

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: Optional[Callable[[Any], Union[None, Awaitable[None]]]]#

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: Union[Callable[[Any], Union[None, Awaitable[None]]], List[Callable[[Any], Union[None, Awaitable[None]]]]]#

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: Union[Callable[[Any], Union[None, Awaitable[None]]], List[Callable[[Any], Union[None, Awaitable[None]]]]]#

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: Optional[Union[List[str], AllowedHostsConfig]]#

If set enables the builtin allowed hosts middleware.

before_request: Optional[Callable[[Any], Union[Any, Awaitable[Any]]]]#

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: Union[Callable[[Union[HTTPResponseStartEvent, HTTPResponseBodyEvent, HTTPServerPushEvent, HTTPDisconnectEvent, WebSocketAcceptEvent, WebSocketSendEvent, WebSocketResponseStartEvent, WebSocketResponseBodyEvent, WebSocketCloseEvent], Any, Union[HTTPScope, WebSocketScope]], Union[None, Awaitable[None]]], Callable[[Union[HTTPResponseStartEvent, HTTPResponseBodyEvent, HTTPServerPushEvent, HTTPDisconnectEvent, WebSocketAcceptEvent, WebSocketSendEvent, WebSocketResponseStartEvent, WebSocketResponseBodyEvent, WebSocketCloseEvent], Any], Union[None, Awaitable[None]]], List[Union[Callable[[Union[HTTPResponseStartEvent, HTTPResponseBodyEvent, HTTPServerPushEvent, HTTPDisconnectEvent, WebSocketAcceptEvent, WebSocketSendEvent, WebSocketResponseStartEvent, WebSocketResponseBodyEvent, WebSocketCloseEvent], Any, Union[HTTPScope, WebSocketScope]], Union[None, Awaitable[None]]], Callable[[Union[HTTPResponseStartEvent, HTTPResponseBodyEvent, HTTPServerPushEvent, HTTPDisconnectEvent, WebSocketAcceptEvent, WebSocketSendEvent, WebSocketResponseStartEvent, WebSocketResponseBodyEvent, WebSocketCloseEvent], Any], Union[None, Awaitable[None]]]]]]#

An application level before send hook handler or list thereof.

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

before_shutdown: Union[Callable[[Any], Union[None, Awaitable[None]]], List[Callable[[Any], Union[None, Awaitable[None]]]]]#

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: Union[Callable[[Any], Union[None, Awaitable[None]]], List[Callable[[Any], Union[None, Awaitable[None]]]]]#

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: CacheConfig#

Configures caching behavior of the application.

cache_control: Optional[CacheControlHeader]#

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

Can be overridden by route handlers.

compression_config: Optional[CompressionConfig]#

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

cors_config: Optional[CORSConfig]#

If set this enables the builtin CORS middleware.

csrf_config: Optional[CSRFConfig]#

If set this enables the builtin CSRF middleware.

debug: bool#

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

dependencies: Dict[str, Provide]#

A string keyed dictionary of dependency Provider instances.

etag: Optional[ETag]#

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

Can be overridden by route handlers.

exception_handlers: Dict[Union[int, Type[Exception]], Callable[[Any, _ExceptionT], Any]]#

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

guards: List[Callable[[Any, Any], Union[None, Awaitable[None]]]]#

A list of Guard callables.

initial_state: Union[Any, Dict[str, Any], Iterable[Tuple[str, Any]]]#

An object from which to initialize the app state.

logging_config: Optional[BaseLoggingConfig]#

An instance of BaseLoggingConfig subclass.

middleware: List[Union[Callable[[...], Callable[[Union[HTTPScope, WebSocketScope], Callable[[...], Awaitable[Union[HTTPRequestEvent, HTTPDisconnectEvent, WebSocketConnectEvent, WebSocketReceiveEvent, WebSocketDisconnectEvent]]], Callable[[Union[HTTPResponseStartEvent, HTTPResponseBodyEvent, HTTPServerPushEvent, HTTPDisconnectEvent, WebSocketAcceptEvent, WebSocketSendEvent, WebSocketResponseStartEvent, WebSocketResponseBodyEvent, WebSocketCloseEvent]], Awaitable[None]]], Awaitable[None]]], Any, Iterator[Tuple[Callable[[Union[HTTPScope, WebSocketScope], Callable[[...], Awaitable[Union[HTTPRequestEvent, HTTPDisconnectEvent, WebSocketConnectEvent, WebSocketReceiveEvent, WebSocketDisconnectEvent]]], Callable[[Union[HTTPResponseStartEvent, HTTPResponseBodyEvent, HTTPServerPushEvent, HTTPDisconnectEvent, WebSocketAcceptEvent, WebSocketSendEvent, WebSocketResponseStartEvent, WebSocketResponseBodyEvent, WebSocketCloseEvent]], Awaitable[None]]], Awaitable[None]], Dict[str, Any]]], Type[Any]]]#

A list of Middleware.

on_shutdown: List[Union[Callable[[], Union[Any, Awaitable[Any]]], Callable[[Any], Union[Any, Awaitable[Any]]]]]#

A list of LifeSpanHandler called during application shutdown.

on_startup: List[Union[Callable[[], Union[Any, Awaitable[Any]]], Callable[[Any], Union[Any, Awaitable[Any]]]]]#

A list of LifeSpanHandler called during application startup.

openapi_config: Optional[OpenAPIConfig]#

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: Dict[str, Any]#

A mapping of Parameter definitions available to all application paths.

plugins: List[PluginProtocol]#

List of PluginProtocol.

request_class: Optional[Type[Request]]#

An optional subclass of Request to use for http connections.

response_class: Optional[Type[Any]]#

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

response_cookies: List[Any]#

A list of [Cookie](starlite.datastructures.Cookie] instances.

response_headers: Dict[str, Any]#

A string keyed dictionary mapping ResponseHeader instances.

route_handlers: List[Union[Type[Any], Any, Callable[[...], Any]]]#

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[Dict[str, List[str]]]#

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: Union[StaticFilesConfig, List[StaticFilesConfig]]#

An instance or list of StaticFilesConfig.

tags: List[str]#

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

template_config: Optional[TemplateConfig]#

An instance of TemplateConfig.

type_encoders: Optional[Dict[Any, Callable[[Any], Any]]]#

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

websocket_class: Optional[Type[WebSocket]]#

An optional subclass of WebSocket to use for websocket connections.

multipart_form_part_limit: int#

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

classmethod validate_allowed_hosts(value: Optional[Union[List[str], AllowedHostsConfig]]) Optional[AllowedHostsConfig]#

Normalize the allowed hosts to be a config or None.

Parameters:

value – Optional a list of hosts or allowed hosts config

Returns:

Optional config.

class starlite.config.BaseLoggingConfig#

Bases: ABC

Abstract class that should be extended by logging configs.

abstract configure() GetLogger#

Return logger with the given configuration.

Returns:

A ‘logging.getLogger’ like function.

class starlite.config.CORSConfig#

Bases: BaseModel

Configuration for CORS (Cross-Origin Resource Sharing).

To enable CORS, pass an instance of this class to the Starlite 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[Union[Literal['*'], Literal['GET', 'POST', 'DELETE', 'PATCH', 'PUT', 'HEAD', 'TRACE', 'OPTIONS']]]#

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#

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

allow_origin_regex: Optional[str]#

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#

Response caching TTL in seconds, defaults to 600.

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

classmethod validate_allow_headers(value: List[str]) List[str]#

Ensure that allow headers are all lower cased. :param value: A list of headers.

Returns:

A list of lower-cased headers.

property allowed_origins_regex: Pattern#

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 starlite.config.CSRFConfig#

Bases: BaseModel

Configuration for CSRF (Cross Site Request Forgery) protection.

To enable CSRF protection, pass an instance of this class to the Starlite 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#

The CSRF cookie name.

cookie_path: str#

The CSRF cookie path.

header_name: str#

The header that will be expected in each request.

cookie_secure: bool#

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

cookie_httponly: bool#

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

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

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

cookie_domain: Optional[str]#

Specifies which hosts can receive the cookie.

safe_methods: Set[Literal['GET', 'POST', 'DELETE', 'PATCH', 'PUT', 'HEAD', 'TRACE', 'OPTIONS']]#

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

exclude: Optional[Union[str, List[str]]]#

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

exclude_from_csrf_key: str#

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

class starlite.config.CacheConfig#

Bases: BaseModel

Configuration for response caching.

To enable response caching, pass an instance of this class to the Starlite constructor using the ‘cache_config’ key.

backend: Optional[CacheBackendProtocol]#

Instance conforming to CacheBackendProtocol, default.

SimpleCacheBackend()

expiration: int#

Default cache expiration in seconds.

cache_key_builder: Callable[[Any], str]#

CacheKeyBuilder,

default_cache_key_builder if not provided

to_cache() Cache#

Create a cache wrapper from the config.

Returns:

An instance of Cache

class starlite.config.CompressionConfig#

Bases: BaseModel

Configuration for response compression.

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

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

Literal of “gzip” or “brotli”.

minimum_size: ConstrainedIntValue#

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

gzip_compress_level: ConstrainedIntValue#

//docs.python.org/3/library/gzip.html).

Type:

Range [0-9], see [official docs](https

brotli_quality: ConstrainedIntValue#

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']#

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

brotli_lgwin: ConstrainedIntValue#

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]#

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.

brotli_gzip_fallback: bool#

Use GZIP if Brotli is not supported.

middleware_class: Type[CompressionMiddleware]#

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

exclude: Optional[Union[str, List[str]]]#

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

exclude_opt_key: Optional[str]#

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

class starlite.config.LoggingConfig#

Bases: BaseLoggingConfig, BaseModel

Configuration class for standard logging.

Notes

  • If ‘picologging’ is installed it will be used by default.

version: Literal[1]#

The only valid value at present is 1.

incremental: bool#

Whether the configuration is to be interpreted as incremental to the existing configuration.

Notes

  • This option is ignored for ‘picologging’

disable_existing_loggers: bool#

Whether any existing non-root loggers are to be disabled.

filters: Optional[Dict[str, Dict[str, Any]]]#

A dict in which each key is a filter id and each value is a dict describing how to configure the corresponding Filter instance.

propagate: bool#

If messages must propagate to handlers higher up the logger hierarchy from this logger.

handlers: Dict[str, Dict[str, Any]]#

A dict in which each key is a handler id and each value is a dict describing how to configure the corresponding Handler instance.

loggers: Dict[str, Dict[str, Any]]#

A dict in which each key is a logger name and each value is a dict describing how to configure the corresponding Logger instance.

root: Dict[str, Union[Dict[str, Any], List[Any], str]]#

This will be the configuration for the root logger.

Processing of the configuration will be as for any logger, except that the propagate setting will not be applicable.

classmethod validate_handlers(value: Dict[str, Dict[str, Any]]) Dict[str, Dict[str, Any]]#

Ensure that ‘queue_listener’ is always set.

Parameters:

value – A dict of route handlers.

Returns:

A dict of route handlers.

classmethod validate_loggers(value: Dict[str, Dict[str, Any]]) Dict[str, Dict[str, Any]]#

Ensure that the ‘starlite’ logger is always set.

Parameters:

value – A dict of loggers.

Returns:

A dict of loggers.

configure() GetLogger#

Return logger with the given configuration.

Returns:

A ‘logging.getLogger’ like function.

class starlite.config.OpenAPIConfig#

Bases: BaseModel

Configuration for OpenAPI.

To enable OpenAPI schema generation and serving, pass an instance of this class to the Starlite constructor using the ‘openapi_config’ kwargs.

create_examples: bool#

Generate examples using the pydantic-factories library.

openapi_controller: Type[OpenAPIController]#

Controller for generating OpenAPI routes.

Must be subclass of OpenAPIController.

title: str#

Title of API documentation.

version: str#

API version, e.g. ‘1.0.0’.

contact: Optional[Contact]#

API contact information, should be an Contact instance.

description: Optional[str]#

API description.

external_docs: Optional[ExternalDocumentation]#

Links to external documentation.

Should be an instance of ExternalDocumentation.

license: Optional[License]#

API Licensing information.

Should be an instance of License.

security: Optional[List[Dict[str, List[str]]]]#

API Security requirements information.

Should be an instance of SecurityRequirement.

components: Optional[Union[Components, List[Components]]]#

API Components information.

Should be an instance of Components or a list thereof.

servers: List[Server]#

A list of Server instances.

summary: Optional[str]#

A summary text.

tags: Optional[List[Tag]]#

A list of Tag instances.

terms_of_service: Optional[AnyUrl]#

URL to page that contains terms of service.

use_handler_docstrings: bool#

Draw operation description from route handler docstring if not otherwise provided.

webhooks: Optional[Dict[str, Union[PathItem, Reference]]]#

A mapping of key to either PathItem or.

Reference objects.

root_schema_site: Literal['redoc', 'swagger', 'elements']#

The static schema generator to use for the “root” path of /schema/.

enabled_endpoints: Set[str]#

A set of the enabled documentation sites and schema download endpoints.

by_alias: bool#

Render pydantic model schema using field aliases, if defined.

to_openapi_schema() OpenAPI#

Return an OpenAPI instance from the values stored in self.

Returns:

An instance of OpenAPI.

class starlite.config.StaticFilesConfig#

Bases: BaseModel

Configuration for static file service.

To enable static files, pass an instance of this class to the Starlite constructor using the ‘static_files_config’ key.

path: ConstrainedStrValue#

Path to serve static files from.

Note that the path cannot contain path parameters.

directories: List[DirectoryPath]#

A list of directories to serve files from.

html_mode: bool#

Flag dictating whether serving html.

If true, the default file will be ‘index.html’.

name: Optional[str]#

An optional string identifying the static files handler.

file_system: Any#

The file_system spec to use for serving files.

Notes

opt: Optional[Dict[str, Any]]#

A string key dictionary of arbitrary values that will be added to the static files handler.

guards: Optional[List[Callable[[Any, Any], Union[None, Awaitable[None]]]]]#

A list of Guard callables.

exception_handlers: Optional[Dict[Union[int, Type[Exception]], Callable[[Any, _ExceptionT], Any]]]#

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

send_as_attachment: bool#

Whether to send the file as an attachment.

classmethod validate_path(value: str) str#

Ensure the path has no path parameters.

Parameters:

value – A path string

Returns:

The passed in value

classmethod validate_file_system(value: FileSystemProtocol) FileSystemProtocol#

Ensure the value is a file system spec.

Parameters:

value – A file system spec.

Returns:

A file system spec.

to_static_files_app() ASGIRouteHandler#

Return an ASGI app serving static files based on the config.

Returns:

StaticFiles

class starlite.config.StructLoggingConfig#

Bases: BaseLoggingConfig, BaseModel

Configuration class for structlog.

Notes

  • requires ‘structlog’ to be installed.

processors: Optional[List[Callable[[Any, str, MutableMapping[str, Any]], Union[Mapping[str, Any], str, bytes, bytearray, Tuple[Any, ...]]]]]#

Iterable of structlog logging processors.

wrapper_class: Optional[Type[BindableLogger]]#

Structlog bindable logger.

context_class: Optional[Dict[str, Any]]#

Context class (a ‘contextvar’ context) for the logger.

logger_factory: Optional[Callable[[...], Any]]#

Logger factory to use.

cache_logger_on_first_use: bool#

Whether to cache the logger configuration and reuse.

configure() GetLogger#

Return logger with the given configuration.

Returns:

A ‘logging.getLogger’ like function.

class starlite.config.TemplateConfig#

Bases: Generic[T], GenericModel

Configuration for Templating.

To enable templating, pass an instance of this class to the Starlite constructor using the ‘template_config’ key.

directory: Optional[Union[DirectoryPath, List[DirectoryPath]]]#

A directory or list of directories from which to serve templates.

engine: Union[Type[T], T]#

A template engine adhering to the TemplateEngineProtocol.

engine_callback: Optional[Callable[[T], None]]#

A callback function that allows modifying the instantiated templating protocol.

classmethod validate_config(values: Dict[str, Any]) Dict[str, Any]#

Ensure that directory is set if engine is a class.

Parameters:

values – The dictionary of values to validate

Returns:

The validated dictionary of values.

to_engine() T#

Instantiate the template engine.

property engine_instance: T#

Return the template engine instance.

class starlite.config.AllowedHostsConfig#

Bases: BaseModel

Configuration for allowed hosts protection.

To enable allowed hosts protection, pass an instance of this class to the Starlite 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: Optional[Union[str, List[str]]]#

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

exclude_opt_key: Optional[str]#

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

scopes: WEBSOCKET: 'websocket'>]]]#

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

www_redirect: bool#

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

classmethod validate_allowed_hosts(value: List[str]) List[str]#

Ensure that the trusted hosts have correct domain wildcards.

Parameters:

value – A list of trusted hosts.

Returns:

A list of trusted hosts.