response#

class litestar.response.File#

Bases: Response

A response, streaming a file as response body.

__init__(path: str | PathLike | Path, *, background: BackgroundTask | BackgroundTasks | None = None, chunk_size: int = 1048576, content_disposition_type: Literal['attachment', 'inline'] = 'attachment', cookies: ResponseCookies | None = None, encoding: str = 'utf-8', etag: ETag | None = None, file_info: FileInfo | Coroutine[Any, Any, FileInfo] | None = None, file_system: FileSystemProtocol | None = None, filename: str | None = None, headers: ResponseHeaders | None = None, media_type: Literal[MediaType.TEXT] | str | None = None, stat_result: stat_result_type | None = None, status_code: int | None = None) None#

Initialize File

Notes

  • This class extends the Stream class.

Parameters:
  • path – A file path in one of the supported formats.

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • chunk_size – The chunk sizes to use when streaming the file. Defaults to 1MB.

  • content_disposition_type – The type of the Content-Disposition. Either inline or attachment.

  • cookies – A list of Cookie instances to be set under the response Set-Cookie header.

  • encoding – The encoding to be used for the response headers.

  • etag – An optional ETag instance. If not provided, an etag will be generated.

  • file_info – The output of calling file_system.info, equivalent to providing an os.stat_result.

  • file_system – An implementation of the FileSystemProtocol. If provided it will be used to load the file.

  • filename – An optional filename to set in the header.

  • headers – A string keyed dictionary of response headers. Header keys are insensitive.

  • media_type – A value for the response Content-Type header. If not provided, the value will be either derived from the filename if provided and supported by the stdlib, or will default to application/octet-stream.

  • stat_result – An optional result of calling :func:os.stat:. If not provided, this will be done by the response constructor.

  • status_code – An HTTP status code.

to_asgi_response(app: Litestar | None, request: Request, *, background: BackgroundTask | BackgroundTasks | None = None, encoded_headers: Iterable[tuple[bytes, bytes]] | None = None, cookies: Iterable[Cookie] | None = None, headers: dict[str, str] | None = None, is_head_response: bool = False, media_type: MediaType | str | None = None, status_code: int | None = None, type_encoders: TypeEncodersMap | None = None) ASGIFileResponse#

Create an ASGIFileResponse instance.

Parameters:
  • app – The Litestar application instance.

  • background – Background task(s) to be executed after the response is sent.

  • cookies – A list of cookies to be set on the response.

  • encoded_headers – A list of already encoded headers.

  • headers – Additional headers to be merged with the response headers. Response headers take precedence.

  • is_head_response – Whether the response is a HEAD response.

  • media_type – Media type for the response. If media_type is already set on the response, this is ignored.

  • request – The Request instance.

  • status_code – Status code for the response. If status_code is already set on the response, this is

  • type_encoders – A dictionary of type encoders to use for encoding the response content.

Returns:

A low-level ASGI file response.

class litestar.response.Redirect#

Bases: Response[Any]

A redirect response.

__init__(path: str, *, background: BackgroundTask | BackgroundTasks | None = None, cookies: ResponseCookies | None = None, encoding: str = 'utf-8', headers: ResponseHeaders | None = None, media_type: str | MediaType | None = None, status_code: RedirectStatusType | None = None, type_encoders: TypeEncodersMap | None = None) None#

Initialize the response.

Parameters:
  • path – A path to redirect to.

  • background – A background task or tasks to be run after the response is sent.

  • cookies – A list of Cookie instances to be set under the response Set-Cookie header.

  • encoding – The encoding to be used for the response headers.

  • headers – A string keyed dictionary of response headers. Header keys are insensitive.

  • media_type – A value for the response Content-Type header.

  • status_code – An HTTP status code. The status code should be one of 301, 302, 303, 307 or 308, otherwise an exception will be raised.

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

Raises:

ImproperlyConfiguredException – Either if status code is not a redirect status code or media type is not supported.

to_asgi_response(app: Litestar | None, request: Request, *, background: BackgroundTask | BackgroundTasks | None = None, cookies: Iterable[Cookie] | None = None, encoded_headers: Iterable[tuple[bytes, bytes]] | None = None, headers: dict[str, str] | None = None, is_head_response: bool = False, media_type: MediaType | str | None = None, status_code: int | None = None, type_encoders: TypeEncodersMap | None = None) ASGIResponse#

Create an ASGIResponse from a Response instance.

Parameters:
  • app – The Litestar application instance.

  • background – Background task(s) to be executed after the response is sent.

  • cookies – A list of cookies to be set on the response.

  • encoded_headers – A list of already encoded headers.

  • headers – Additional headers to be merged with the response headers. Response headers take precedence.

  • is_head_response – Whether the response is a HEAD response.

  • media_type – Media type for the response. If media_type is already set on the response, this is ignored.

  • request – The Request instance.

  • status_code – Status code for the response. If status_code is already set on the response, this is

  • type_encoders – A dictionary of type encoders to use for encoding the response content.

Returns:

An ASGIResponse instance.

class litestar.response.Response#

Bases: Generic[T]

Base Litestar HTTP response class, used as the basis for all other response classes.

__init__(content: T, *, background: BackgroundTask | BackgroundTasks | None = None, cookies: ResponseCookies | None = None, encoding: str = 'utf-8', headers: ResponseHeaders | None = None, media_type: MediaType | OpenAPIMediaType | str | None = None, status_code: int | None = None, type_encoders: TypeEncodersMap | None = None) None#

Initialize the response.

Parameters:
  • content – A value for the response body that will be rendered into bytes string.

  • status_code – An HTTP status code.

  • media_type – A value for the response Content-Type header.

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • headers – A string keyed dictionary of response headers. Header keys are insensitive.

  • cookies – A list of Cookie instances to be set under the response Set-Cookie header.

  • encoding – The encoding to be used for the response headers.

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

set_cookie(key: str, value: str | None = None, max_age: int | None = None, expires: int | None = None, path: str = '/', domain: str | None = None, secure: bool = False, httponly: bool = False, samesite: Literal['lax', 'strict', 'none'] = 'lax') None

Set a cookie on the response. If passed a Cookie instance, keyword arguments will be ignored.

Parameters:
  • key – Key for the cookie or a Cookie instance.

  • value – Value for the cookie, if none given defaults to empty string.

  • max_age – Maximal age of the cookie before its invalidated.

  • expires – Seconds from now until the cookie expires.

  • path – Path fragment that must exist in the request url for the cookie to be valid. Defaults to /.

  • domain – Domain for which the cookie is valid.

  • secure – Https is required for the cookie.

  • httponly – Forbids javascript to access the cookie via document.cookie.

  • samesite – Controls whether a cookie is sent with cross-site requests. Defaults to lax.

Returns:

None.

set_header(key: str, value: Any) None#

Set a header on the response.

Parameters:
  • key – Header key.

  • value – Header value.

Returns:

None.

set_etag(etag: str | ETag) None#

Set an etag header.

Parameters:

etag – An etag value.

Returns:

None

Delete a cookie.

Parameters:
  • key – Key of the cookie.

  • path – Path of the cookie.

  • domain – Domain of the cookie.

Returns:

None.

render(content: Any, media_type: str, enc_hook: Serializer = <function default_serializer>) bytes#

Handle the rendering of content into a bytes string.

Returns:

An encoded bytes string

to_asgi_response(app: Litestar | None, request: Request, *, background: BackgroundTask | BackgroundTasks | None = None, cookies: Iterable[Cookie] | None = None, encoded_headers: Iterable[tuple[bytes, bytes]] | None = None, headers: dict[str, str] | None = None, is_head_response: bool = False, media_type: MediaType | str | None = None, status_code: int | None = None, type_encoders: TypeEncodersMap | None = None) ASGIResponse#

Create an ASGIResponse from a Response instance.

Parameters:
  • app – The Litestar application instance.

  • background – Background task(s) to be executed after the response is sent.

  • cookies – A list of cookies to be set on the response.

  • encoded_headers – A list of already encoded headers.

  • headers – Additional headers to be merged with the response headers. Response headers take precedence.

  • is_head_response – Whether the response is a HEAD response.

  • media_type – Media type for the response. If media_type is already set on the response, this is ignored.

  • request – The Request instance.

  • status_code – Status code for the response. If status_code is already set on the response, this is

  • type_encoders – A dictionary of type encoders to use for encoding the response content.

Returns:

An ASGIResponse instance.

class litestar.response.ServerSentEvent#

Bases: Stream

__init__(content: str | bytes | StreamType[SSEData], *, background: BackgroundTask | BackgroundTasks | None = None, cookies: ResponseCookies | None = None, encoding: str = 'utf-8', headers: ResponseHeaders | None = None, event_type: str | None = None, event_id: int | str | None = None, retry_duration: int | None = None, comment_message: str | None = None, status_code: int | None = None) None#

Initialize the response.

Parameters:
  • content – Bytes, string or a sync or async iterator or iterable.

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • cookies – A list of Cookie instances to be set under the response Set-Cookie header.

  • encoding – The encoding to be used for the response headers.

  • headers – A string keyed dictionary of response headers. Header keys are insensitive.

  • status_code – The response status code. Defaults to 200.

  • event_type – The type of the SSE event. If given, the browser will sent the event to any ‘event-listener’ declared for it (e.g. via ‘addEventListener’ in JS).

  • event_id – The event ID. This sets the event source’s ‘last event id’.

  • retry_duration – Retry duration in milliseconds.

  • comment_message – A comment message. This value is ignored by clients and is used mostly for pinging.

class litestar.response.ServerSentEventMessage#

Bases: object

ServerSentEventMessage(data: ‘str | int | bytes | None’ = ‘’, event: ‘str | None’ = None, id: ‘int | str | None’ = None, retry: ‘int | None’ = None, comment: ‘str | None’ = None, sep: ‘str’ = ‘rn’)

__init__(data: str | int | bytes | None = '', event: str | None = None, id: int | str | None = None, retry: int | None = None, comment: str | None = None, sep: str = '\r\n') None#
class litestar.response.Stream#

Bases: Response[Union[Iterable[Union[str, bytes]], Iterator[Union[str, bytes]], AsyncIterable[Union[str, bytes]], AsyncIterator[Union[str, bytes]]]]

An HTTP response that streams the response data as a series of ASGI http.response.body events.

__init__(content: StreamType[str | bytes] | Callable[[], StreamType[str | bytes]], *, background: BackgroundTask | BackgroundTasks | None = None, cookies: ResponseCookies | None = None, encoding: str = 'utf-8', headers: ResponseHeaders | None = None, media_type: MediaType | OpenAPIMediaType | str | None = None, status_code: int | None = None) None#

Initialize the response.

Parameters:
  • content – A sync or async iterator or iterable.

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • cookies – A list of Cookie instances to be set under the response Set-Cookie header.

  • encoding – The encoding to be used for the response headers.

  • headers – A string keyed dictionary of response headers. Header keys are insensitive.

  • media_type – A value for the response Content-Type header.

  • status_code – An HTTP status code.

to_asgi_response(app: Litestar | None, request: Request, *, background: BackgroundTask | BackgroundTasks | None = None, cookies: Iterable[Cookie] | None = None, encoded_headers: Iterable[tuple[bytes, bytes]] | None = None, headers: dict[str, str] | None = None, is_head_response: bool = False, media_type: MediaType | str | None = None, status_code: int | None = None, type_encoders: TypeEncodersMap | None = None) ASGIResponse#

Create an ASGIStreamingResponse from a StremaingResponse instance.

Parameters:
  • app – The Litestar application instance.

  • background – Background task(s) to be executed after the response is sent.

  • cookies – A list of cookies to be set on the response.

  • encoded_headers – A list of already encoded headers.

  • headers – Additional headers to be merged with the response headers. Response headers take precedence.

  • is_head_response – Whether the response is a HEAD response.

  • media_type – Media type for the response. If media_type is already set on the response, this is ignored.

  • request – The Request instance.

  • status_code – Status code for the response. If status_code is already set on the response, this is

  • type_encoders – A dictionary of type encoders to use for encoding the response content.

Returns:

An ASGIStreamingResponse instance.

class litestar.response.Template#

Bases: Response[bytes]

Template-based response, rendering a given template into a bytes string.

__init__(template_name: str | None = None, *, template_str: str | None = None, background: BackgroundTask | BackgroundTasks | None = None, context: dict[str, Any] | None = None, cookies: ResponseCookies | None = None, encoding: str = 'utf-8', headers: dict[str, Any] | None = None, media_type: MediaType | str | None = None, status_code: int = 200) None#

Handle the rendering of a given template into a bytes string.

Parameters:
  • template_name – Path-like name for the template to be rendered, e.g. index.html.

  • template_str – A string representing the template, e.g. tmpl = "Hello <strong>World</strong>".

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • context – A dictionary of key/value pairs to be passed to the temple engine’s render method.

  • cookies – A list of Cookie instances to be set under the response Set-Cookie header.

  • encoding – Content encoding

  • headers – A string keyed dictionary of response headers. Header keys are insensitive.

  • media_type – A string or member of the MediaType enum. If not set, try to infer the media type based on the template name. If this fails, fall back to text/plain.

  • status_code – A value for the response HTTP status code.

create_template_context(request: Request) dict[str, Any]#

Create a context object for the template.

Parameters:

request – A Request instance.

Returns:

A dictionary holding the template context

to_asgi_response(app: Litestar | None, request: Request, *, background: BackgroundTask | BackgroundTasks | None = None, cookies: Iterable[Cookie] | None = None, encoded_headers: Iterable[tuple[bytes, bytes]] | None = None, headers: dict[str, str] | None = None, is_head_response: bool = False, media_type: MediaType | str | None = None, status_code: int | None = None, type_encoders: TypeEncodersMap | None = None) ASGIResponse#

Create an ASGIResponse from a Response instance.

Parameters:
  • app – The Litestar application instance.

  • background – Background task(s) to be executed after the response is sent.

  • cookies – A list of cookies to be set on the response.

  • encoded_headers – A list of already encoded headers.

  • headers – Additional headers to be merged with the response headers. Response headers take precedence.

  • is_head_response – Whether the response is a HEAD response.

  • media_type – Media type for the response. If media_type is already set on the response, this is ignored.

  • request – The Request instance.

  • status_code – Status code for the response. If status_code is already set on the response, this is

  • type_encoders – A dictionary of type encoders to use for encoding the response content.

Returns:

An ASGIResponse instance.