starlite.response#

class starlite.response.Response#

Bases: Generic[T]

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

__init__(content: T, *, status_code: int = 200, media_type: Union[MediaType, OpenAPIMediaType, str] = MediaType.JSON, background: Optional[Union[BackgroundTask, BackgroundTasks]] = None, headers: Optional[Dict[str, Any]] = None, cookies: Optional[ResponseCookies] = None, encoding: str = 'utf-8', is_head_response: bool = False, type_encoders: Optional[TypeEncodersMap] = 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.

  • is_head_response – Whether the response should send only the headers (“head” request) or also the content.

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

classmethod serializer(value: Any) Any#

Transform non-natively supported types into supported types.

Should raise TypeError if a type cannot be transformed into a supported type

classmethod get_serializer(type_encoders: Optional[TypeEncodersMap] = None) Serializer#

Get the serializer for this response class.

If Response.serializer is not overridden in a subclass, use default_serializer and pass type_encoders to it.

set_cookie(key: str, value: Optional[str] = None, max_age: Optional[int] = None, expires: Optional[int] = None, path: str = '/', domain: Optional[str] = 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 – Expiration date as unix MS timestamp.

  • 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: str) None#

Set a header on the response.

Parameters:
  • key – Header key.

  • value – Header value.

Returns:

None.

set_etag(etag: Union[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) bytes#

Handle the rendering of content T into a bytes string.

Parameters:

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

Returns:

An encoded bytes string

property content_length: int#

Content length of the response if applicable.

Returns:

The content length of the body (e.g. for use in a “Content-Length” header). If the response does not have a body, this value is None

encode_headers() List[Tuple[bytes, bytes]]#

Encode the response headers as a list of byte tuples.

Notes

  • A ‘Content-Length’ header will be added if appropriate and not provided by the user.

Returns:

A list of tuples containing the headers and cookies of the request in a format ready for ASGI transmission.

async after_response() None#

Execute after the response is sent.

Returns:

None

async start_response(send: Send) None#

Emit the start event of the response. This event includes the headers and status codes.

Parameters:

send – The ASGI send function.

Returns:

None

async send_body(send: Send, receive: Receive) None#

Emit the response body.

Parameters:
  • send – The ASGI send function.

  • receive – The ASGI receive function.

Notes

  • Response subclasses should customize this method if there is a need to customize sending data.

Returns:

None

async __call__(scope: Scope, receive: Receive, send: Send) None#

ASGI callable of the Response.

Parameters:
  • scope – The ASGI connection scope.

  • receive – The ASGI receive function.

  • send – The ASGI send function.

Returns:

None

class starlite.response.RedirectResponse#

Bases: Response[Any]

A redirect response.

__init__(url: str, *, status_code: Literal[301, 302, 303, 307, 308] = 307, background: Optional[Union[BackgroundTask, BackgroundTasks]] = None, headers: Optional[Dict[str, Any]] = None, cookies: Optional[ResponseCookies] = None, encoding: str = 'utf-8') None#

Initialize the response.

Parameters:
  • url – A url to redirect to.

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

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

Raises:

ImproperlyConfiguredException <starlite.exceptions.ImproperlyConfiguredException> – If status code is not a redirect status code.

class starlite.response.StreamingResponse#

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: Union[Iterable[Union[str, bytes]], Iterator[Union[str, bytes]], AsyncIterable[Union[str, bytes]], AsyncIterator[Union[str, bytes]]], *, status_code: int = 200, media_type: Union[MediaType, OpenAPIMediaType, str] = MediaType.JSON, background: Optional[Union[BackgroundTask, BackgroundTasks]] = None, headers: Optional[Dict[str, Any]] = None, cookies: Optional[ResponseCookies] = None, encoding: str = 'utf-8', is_head_response: bool = False)#

Initialize the response.

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

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

  • is_head_response – Whether the response should send only the headers (“head” request) or also the content.

async send_body(send: Send, receive: Receive) None#

Emit a stream of events correlating with the response body.

Parameters:
  • send – The ASGI send function.

  • receive – The ASGI receive function.

Returns:

None

class starlite.response.TemplateResponse#

Bases: Response[bytes]

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

__init__(template_name: str, *, template_engine: TemplateEngineProtocol, context: Dict[str, Any], status_code: int = 200, background: Optional[Union[BackgroundTask, BackgroundTasks]] = None, headers: Optional[Dict[str, Any]] = None, cookies: Optional[ResponseCookies] = None, encoding: str = 'utf-8', media_type: Union[MediaType, str] = MediaType.HTML) 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_engine – The template engine class to use to render the response.

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

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

  • 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 – Content encoding

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

class starlite.response.FileResponse#

Bases: StreamingResponse

A response, streaming a file as response body.

__init__(path: ~typing.Union[str, PathLike, Path], *, background: ~typing.Optional[~typing.Union[BackgroundTask, BackgroundTasks]] = None, chunk_size: int = 1048576, content_disposition_type: ~typing.Literal['attachment', 'inline'] = 'attachment', cookies: ~typing.Optional[ResponseCookies] = None, encoding: str = 'utf-8', etag: ~typing.Optional[ETag] = None, file_system: ~typing.Optional[FileSystemProtocol] = None, filename: ~typing.Optional[str] = None, file_info: ~typing.Optional[FileInfo] = None, headers: ~typing.Optional[~typing.Dict[str, ~typing.Any]] = None, is_head_response: bool = False, media_type: ~typing.Optional[~typing.Union[~typing.Literal[<MediaType.TEXT: 'text/plain'>], str]] = None, stat_result: ~typing.Optional[stat_result_type] = None, status_code: int = 200) None#

Initialize FileResponse

Notes

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

  • status_code – An HTTP status code.

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

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

  • is_head_response – Whether the response should send only the headers (“head” request) or also the content.

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

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

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

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

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

  • file_info – The output of calling file_system.info(..), equivalent to providing a stat_result.

property content_disposition: str#

Content disposition.

Returns:

A value for the ‘Content-Disposition’ header.

property content_length: int#

Content length of the response if applicable.

Returns:

Returns the value of ‘self.stat_result.st_size’ to populate the ‘Content-Length’ header.

async send_body(send: Send, receive: Receive) None#

Emit a stream of events correlating with the response body.

Parameters:
  • send – The ASGI send function.

  • receive – The ASGI receive function.

Returns:

None

async start_response(send: Send) None#

Emit the start event of the response. This event includes the headers and status codes.

Parameters:

send – The ASGI send function.

Returns:

None