base#

class starlite.middleware.session.base.BaseBackendConfig#

Bases: BaseModel

Configuration for Session middleware backends.

key: ConstrainedStrValue#

Key to use for the cookie inside the header, e.g. session=<data> where session is the cookie key and <data> is the session data.

Notes

  • If a session cookie exceeds 4KB in size it is split. In this case the key will be of the format session-{segment number}.

max_age: ConstrainedIntValue#

Maximal age of the cookie before its invalidated.

scopes: WEBSOCKET: 'websocket'>]]#

Scopes for the middleware - options are http and websocket with the default being both

path: str#

Path fragment that must exist in the request url for the cookie to be valid.

Defaults to '/'.

domain: Optional[str]#

Domain for which the cookie is valid.

secure: bool#

Https is required for the cookie.

httponly: bool#

Forbids javascript to access the cookie via ‘Document.cookie’.

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

Controls whether or not a cookie is sent with cross-site requests.

Defaults to lax.

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

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

exclude_opt_key: str#

An identifier to use on routes to disable the session middleware for a particular route.

property middleware: DefineMiddleware#

Use this property to insert the config into a middleware list on one of the application layers.

Examples

Returns:

An instance of DefineMiddleware including self as the config kwarg value.

class starlite.middleware.session.base.ServerSideSessionConfig#

Bases: BaseBackendConfig

Base configuration for server side backends.

session_id_bytes: int#

Number of bytes used to generate a random session-ID.

class starlite.middleware.session.base.BaseSessionBackend#

Bases: ABC, Generic[ConfigT]

Abstract session backend defining the interface between a storage mechanism and the application SessionMiddleware.

This serves as the base class for all client- and server-side backends

__init__(config: ConfigT) None#

Initialize BaseSessionBackend

Parameters:

config – A instance of a subclass of BaseBackendConfig

static serlialize_data(data: ScopeSession, scope: Optional[Scope] = None) bytes#

Serialize data into bytes for storage in the backend.

Parameters:
  • data – Session data of the current scope.

  • scope – A scope, if applicable, from which to extract a serializer.

Notes

  • The serializer will be extracted from scope or fall back to default_serializer

Returns:

data serialized as bytes.

static deserialize_data(data: Any) Dict[str, Any]#

Deserialize data into a dictionary for use in the application scope.

Parameters:

data – Data to be deserialized

Returns:

Deserialized data as a dictionary

abstract async store_in_message(scope_session: ScopeSession, message: Message, connection: ASGIConnection) None#

Store the necessary information in the outgoing Message

Parameters:
  • scope_session – Current session to store

  • message – Outgoing send-message

  • connection – Originating ASGIConnection containing the scope

Returns:

None

abstract async load_from_connection(connection: ASGIConnection) Dict[str, Any]#

Load session data from a connection and return it as a dictionary to be used in the current application scope.

Parameters:

connection – An ASGIConnection instance

Returns:

The session data

Notes

  • This should not modify the connection’s scope. The data returned by this method will be stored in the application scope by the middleware

class starlite.middleware.session.base.ServerSideBackend#

Bases: Generic[ServerConfigT], BaseSessionBackend[ServerConfigT]

Base class for server-side backends.

Implements BaseSessionBackend and defines and interface which subclasses can implement to facilitate the storage of session data.

__init__(config: ServerConfigT) None#

Initialize ServerSideBackend

Parameters:

config – A subclass of ServerSideSessionConfig

abstract async get(session_id: str) Optional[Union[bytes, str, Dict[str, Any]]]#

Retrieve data associated with session_id.

Parameters:

session_id – The session-ID

Returns:

The session data, if existing, otherwise None.

abstract async set(session_id: str, data: bytes) None#

Store data under the session_id for later retrieval.

If there is already data associated with session_id, replace it with data and reset its expiry time

Parameters:
  • session_id – The session-ID

  • data – Serialized session data

Returns:

None

abstract async delete(session_id: str) None#

Delete the data associated with session_id. Fails silently if no such session-ID exists.

Parameters:

session_id – The session-ID

Returns:

None

abstract async delete_all() None#

Delete all session data stored within this backend.

Returns:

None

generate_session_id() str#

Generate a new session-ID, with n=:attr:session_id_bytes <ServerSideSessionConfig.session_id_bytes> random bytes.

Returns:

A session-ID

async store_in_message(scope_session: ScopeSession, message: Message, connection: ASGIConnection) None#

Store the necessary information in the outgoing Message by setting a cookie containing the session-ID.

If the session is empty, a null-cookie will be set. Otherwise, the serialised data will be stored using set, under the current session-id. If no session-ID exists, a new ID will be generated using generate_session_id.

Parameters:
  • scope_session – Current session to store

  • message – Outgoing send-message

  • connection – Originating ASGIConnection containing the scope

Returns:

None

async load_from_connection(connection: ASGIConnection) Dict[str, Any]#

Load session data from a connection and return it as a dictionary to be used in the current application scope.

The session-ID will be gathered from a cookie with the key set in BaseBackendConfig.key. If a cookie is found, its value will be used as the session-ID and data associated with this ID will be loaded using get. If no cookie was found or no data was loaded from the store, this will return an empty dictionary.

Parameters:

connection – An ASGIConnection instance

Returns:

The current session data

class starlite.middleware.session.base.SessionMiddleware#

Bases: AbstractMiddleware, Generic[BaseSessionBackendT]

Starlite session middleware for storing session data.

__init__(app: ASGIApp, backend: BaseSessionBackendT) None#

Initialize SessionMiddleware

Parameters:
  • app – An ASGI application

  • backend – A BaseSessionBackend instance used to store and retrieve session data

create_send_wrapper(connection: ASGIConnection) Callable[[Message], Awaitable[None]]#

Create a wrapper for the ASGI send function, which handles setting the cookies on the outgoing response.

Parameters:

connection – ASGIConnection

Returns:

None