connection¶
- class litestar.connection.ASGIConnection[source]¶
Bases:
Generic[HandlerT,UserT,AuthT,StateT]The base ASGI connection container.
- __init__(scope: Scope, receive: Receive = <function empty_receive>, send: Send = <function empty_send>) None[source]¶
Initialize
ASGIConnection.
- property app: Litestar¶
Return the
appfor this connection.- Returns:
The
Litestarapplication instance
- property auth: AuthT¶
Return the
authdata of this connection’sScope.- Raises:
ImproperlyConfiguredException – If
authis not set in scope via anAuthMiddleware, raises an exception- Returns:
A type correlating to the generic variable Auth.
- property base_url: URL¶
Return the base URL of this connection’s
Scope.- Returns:
A URL instance constructed from the request’s scope, representing only the base part (host + domain + prefix) of the request.
- clear_session() None[source]¶
Remove the session from the connection’s
Scope.If the
Litestar SessionMiddlewareis enabled, this will cause the session data to be cleared.- Returns:
None.
- property client: Address | None¶
Return the
clientdata of this connection’sScope.- Returns:
A two tuple of the host name and port number.
- property cookies: dict[str, str]¶
Return the
cookiesof this connection’sScope.- Returns:
Returns any cookies stored in the header as a parsed dictionary.
- property headers: Headers¶
Return the headers of this connection’s
Scope.- Returns:
A Headers instance with the request’s scope[“headers”] value.
- property path_params: dict[str, Any]¶
Return the
path_paramsof this connection’sScope.- Returns:
A string keyed dictionary of path parameter values.
- property query_params: MultiDict[Any]¶
Return the query parameters of this connection’s
Scope.- Returns:
A normalized dict of query parameters. Multiple values for the same key are returned as a list.
- property route_handler: HandlerT¶
Return the
route_handlerfor this connection.- Returns:
The target route handler instance.
- property session: dict[str, Any]¶
Return the session for this connection if a session was previously set in the
Scope- Returns:
A dictionary representing the session value - if existing.
- Raises:
ImproperlyConfiguredException – if session is not set in scope.
- set_session(value: dict[str, Any] | DataContainerType | EmptyType) None[source]¶
Set the session in the connection’s
Scope.If the
SessionMiddlewareis enabled, the session will be added to the response as a cookie header.- Parameters:
value¶ – Dictionary or pydantic model instance for the session data.
- Returns:
None
- property state: StateT¶
Return the
Stateof this connection.- Returns:
A State instance constructed from the scope[“state”] value.
- property url: URL¶
Return the URL of this connection’s
Scope.- Returns:
A URL instance constructed from the request’s scope.
- url_for(name: str | BaseRouteHandler, **path_parameters: Any) str[source]¶
Return the url for a given route handler / handler name.
- Parameters:
- Raises:
NoRouteMatchFoundException – If route with
namedoes not exist, path parameters are missing or have a wrong type.- Returns:
A string representing the absolute url of the route handler.
- property user: UserT¶
Return the
userdata of this connection’sScope.- Raises:
ImproperlyConfiguredException – If
useris not set in scope via anAuthMiddleware, raises an exception- Returns:
A type correlating to the generic variable User.
- class litestar.connection.Request[source]¶
Bases:
Generic[UserT,AuthT,StateT],ASGIConnection[HTTPRouteHandler,UserT,AuthT,StateT]The Litestar Request class.
- __init__(scope: Scope, receive: Receive = <function empty_receive>, send: Send = <function empty_send>) None[source]¶
Initialize
Request.
- property accept: Accept¶
Parse the request’s ‘Accept’ header, returning an
Acceptinstance.- Returns:
An
Acceptinstance, representing the list of acceptable media types.
- async body() bytes[source]¶
Return the body of the request.
- Returns:
A byte-string representing the body of the request.
- property content_type: tuple[str, dict[str, str]]¶
Parse the request’s ‘Content-Type’ header, returning the header value and any options as a dictionary.
- Returns:
A tuple with the parsed value and a dictionary containing any options send in it.
- async form() FormMultiDict[source]¶
Retrieve form data from the request. If the request is either a ‘multipart/form-data’ or an ‘application/x-www-form- urlencoded’, return a FormMultiDict instance populated with the values sent in the request, otherwise, an empty instance.
- Returns:
A FormMultiDict instance
- async json() Any[source]¶
Retrieve the json request body from the request.
- Returns:
An arbitrary value
- async msgpack() Any[source]¶
Retrieve the MessagePack request body from the request.
- Returns:
An arbitrary value
- async send_push_promise(path: str, raise_if_unavailable: bool = False) None[source]¶
Send a push promise.
This method requires the http.response.push extension to be sent from the ASGI server.
- async stream() AsyncGenerator[bytes, None][source]¶
Return an async generator that streams chunks of bytes.
- Returns:
An async generator.
- Raises:
RuntimeError – if the stream is already consumed
- class litestar.connection.WebSocket[source]¶
Bases:
Generic[UserT,AuthT,StateT],ASGIConnection[WebsocketRouteHandler,UserT,AuthT,StateT]The Litestar WebSocket class.
- __init__(scope: Scope, receive: Receive = <function empty_receive>, send: Send = <function empty_send>) None[source]¶
Initialize
WebSocket.
- async accept(subprotocols: str | None = None, headers: Headers | dict[str, Any] | list[tuple[bytes, bytes]] | None = None) None[source]¶
Accept the incoming connection. This method should be called before receiving data.
- async close(code: int = 1000, reason: str | None = None) None[source]¶
Send an ‘websocket.close’ event.
- async iter_data(mode: WebSocketMode = 'text') AsyncGenerator[str | bytes, None][source]¶
Continuously receive data and yield it
- Parameters:
mode¶ – Socket mode to use. Either
textorbinary
- async iter_json(mode: WebSocketMode = 'text') AsyncGenerator[Any, None][source]¶
Continuously receive data and yield it, decoding it as JSON in the process.
- Parameters:
mode¶ – Socket mode to use. Either
textorbinary
- async iter_msgpack() AsyncGenerator[Any, None][source]¶
Continuously receive data and yield it, decoding it as MessagePack in the process.
Note that since MessagePack is a binary format, this method will always receive data in
binarymode.
- async receive_data(mode: WebSocketMode) str | bytes[source]¶
Receive an ‘websocket.receive’ event and returns the data stored on it.
- Parameters:
mode¶ – The respective event key to use.
- Returns:
The event’s data.
- async receive_json(mode: WebSocketMode = 'text') Any[source]¶
Receive data and decode it as JSON.
- Parameters:
mode¶ – Either
textorbinary.- Returns:
An arbitrary value
- async receive_msgpack() Any[source]¶
Receive data and decode it as MessagePack.
Note that since MessagePack is a binary format, this method will always receive data in
binarymode.- Returns:
An arbitrary value
- receive_wrapper(receive: Receive) Receive[source]¶
Wrap
receiveto set ‘self.connection_state’ and validate events.- Parameters:
receive¶ – The ASGI receive function.
- Returns:
An ASGI receive function.
- async send_bytes(data: str | bytes, encoding: str = 'utf-8') None[source]¶
Send data using the
byteskey of the send event.
- async send_data(data: str | bytes, mode: WebSocketMode = 'text', encoding: str = 'utf-8') None[source]¶
Send a ‘websocket.send’ event.
- async send_json(data: Any, mode: WebSocketMode = 'text', encoding: str = 'utf-8', serializer: Serializer = <function default_serializer>) None[source]¶
Send data as JSON.
- async send_msgpack(data: Any, encoding: str = 'utf-8', serializer: Serializer = <function default_serializer>) None[source]¶
Send data as MessagePack.
Note that since MessagePack is a binary format, this method will always send data in
binarymode.