sanic.response.convenience.empty#

Returns an empty response to the client.

def empty(status: int = 204, headers: Optional[Dict[str, str]] = None): -> HTTPResponse

Parameters
status
int

HTTP response code. Defaults to 204.

headers
[type]

Custom HTTP headers. Defaults to None.

Return
HTTPResponse

An empty response to the client.

sanic.response.convenience.file#

Return a response object with file data.

async def file(location: Union[str, PurePath], status: int = 200, request_headers: Optional[Header] = None, validate_when_requested: bool = True, mime_type: Optional[str] = None, headers: Optional[Dict[str, str]] = None, filename: Optional[str] = None, last_modified: Optional[Union[datetime, float, int, Default]] = <Default>, max_age: Optional[Union[float, int]] = None, no_store: Optional[bool] = None, _range: Optional[Range] = None): -> HTTPResponse

Parameters
location
Union[str, PurePath]

Location of file on system.

status
int

HTTP response code. Won't enforce the passed in status if only a part of the content will be sent (206) or file is being validated (304). Defaults to 200.

request_headers
Optional[Header]

The request headers.

validate_when_requested
bool

If True, will validate the file when requested. Defaults to True.

mime_type
Optional[str]

Specific mime_type.

headers
Optional[Dict[str, str]]

Custom Headers.

filename
Optional[str]

Override filename.

last_modified
Optional[Union[datetime, float, int, Default]]

The last modified date and time of the file.

max_age
Optional[Union[float, int]]

Max age for cache control.

no_store
Optional[bool]

Any cache should not store this response. Defaults to None.

_range
Optional[Range]

_range

Return
HTTPResponse

The response object with the file data.

sanic.response.convenience.file_stream#

Return a streaming response object with file data.

async def file_stream(location: Union[str, PurePath], status: int = 200, chunk_size: int = 4096, mime_type: Optional[str] = None, headers: Optional[Dict[str, str]] = None, filename: Optional[str] = None, _range: Optional[Range] = None): -> ResponseStream

:param location: Location of file on system. :param chunk_size: The size of each chunk in the stream (in bytes) :param mime_type: Specific mime_type. :param headers: Custom Headers. :param filename: Override filename. :param _range:

Parameters
location
Union[str, PurePath]

Location of file on system.

status
int

HTTP response code. Won't enforce the passed in status if only a part of the content will be sent (206) or file is being validated (304). Defaults to 200.

chunk_size
int

The size of each chunk in the stream (in bytes). Defaults to 4096.

mime_type
Optional[str]

Specific mime_type.

headers
Optional[Dict[str, str]]

Custom HTTP headers.

filename
Optional[str]

Override filename.

_range
Optional[Range]

The range of bytes to send.

sanic.response.convenience.html#

Returns response object with body in html format.

def html(body: Union[str, bytes, HTMLProtocol], status: int = 200, headers: Optional[Dict[str, str]] = None): -> HTTPResponse

Body should be a str or bytes like object, or an object with __html__ or _repr_html_.

Parameters
body
Union[str, bytes, HTMLProtocol]

Response data.

status
int

HTTP response code. Defaults to 200.

headers
Dict[str, str]

Custom HTTP headers. Defaults to None.

Return
HTTPResponse

A response object with body in html format.

sanic.response.convenience.json#

Returns response object with body in json format.

def json(body: Any, status: int = 200, headers: Optional[Dict[str, str]] = None, content_type: str = "application/json", dumps: Optional[Callable[..., str]] = None, kwargs: Any): -> JSONResponse

Parameters
body
Any

Response data to be serialized.

status
int

HTTP response code. Defaults to 200.

headers
Dict[str, str]

Custom HTTP headers. Defaults to None.

content_type
str

The content type (string) of the response. Defaults to "application/json".

dumps
Callable[..., str]

A custom json dumps function. Defaults to None.

**kwargs
Any

Remaining arguments that are passed to the json encoder.

Return
JSONResponse

A response object with body in json format.

sanic.response.convenience.raw#

Returns response object without encoding the body.

def raw(body: Optional[AnyStr], status: int = 200, headers: Optional[Dict[str, str]] = None, content_type: str = "application/octet-stream"): -> HTTPResponse

Parameters
body
Optional[AnyStr]

Response data.

status
int

HTTP response code. Defaults to 200.

headers
Dict[str, str]

Custom HTTP headers. Defaults to None.

content_type
str

The content type (string) of the response. Defaults to "application/octet-stream".

Return
HTTPResponse

A response object without encoding the body.

sanic.response.convenience.redirect#

Cause a HTTP redirect (302 by default) by setting a Location header.

def redirect(to: str, headers: Optional[Dict[str, str]] = None, status: int = 302, content_type: str = "text/html; charset=utf-8"): -> HTTPResponse

Parameters
to
str

path or fully qualified URL to redirect to

headers
Optional[Dict[str, str]]

optional dict of headers to include in the new request. Defaults to None.

status
int

status code (int) of the new request, defaults to 302. Defaults to 302.

content_type
str

the content type (string) of the response. Defaults to "text/html; charset=utf-8".

Return
HTTPResponse

A response object with the redirect.

sanic.response.convenience.text#

Returns response object with body in text format.

def text(body: str, status: int = 200, headers: Optional[Dict[str, str]] = None, content_type: str = "text/plain; charset=utf-8"): -> HTTPResponse

Parameters
body
str

Response data.

status
int

HTTP response code. Defaults to 200.

headers
Dict[str, str]

Custom HTTP headers. Defaults to None.

content_type
str

The content type (string) of the response. Defaults to "text/plain; charset=utf-8".

Return
HTTPResponse

A response object with body in text format.

Raises
TypeError

If the body is not a string.

sanic.response.convenience.validate_file#

Validate file based on request headers.

async def validate_file(request_headers: Header, last_modified: Union[datetime, float, int]): -> Optional[HTTPResponse]

Parameters
request_headers
Header

The request headers.

last_modified
Union[datetime, float, int]

The last modified date and time of the file.

Return
Optional[HTTPResponse]

A response object with status 304 if the file is not modified.

sanic.response.types.BaseHTTPResponse#

The base class for all HTTP Responses

class BaseHTTPResponse()

add_cookie#

Add a cookie to the CookieJar

def add_cookie(self, key: str, value: str, path: str = "/", domain: Optional[str] = None, secure: bool = True, max_age: Optional[int] = None, expires: Optional[datetime] = None, httponly: bool = False, samesite: Optional[SameSite] = Lax, partitioned: bool = False, comment: Optional[str] = None, host_prefix: bool = False, secure_prefix: bool = False): -> Cookie

See Cookies

Parameters
key
str

The key to be added

value
str

The value to be added

path
str

Path of the cookie. Defaults to "/".

domain
Optional[str]

Domain of the cookie. Defaults to None.

secure
bool

Whether the cookie is secure. Defaults to True.

max_age
Optional[int]

Max age of the cookie. Defaults to None.

expires
Optional[datetime]

Expiry date of the cookie. Defaults to None.

httponly
bool

Whether the cookie is http only. Defaults to False.

samesite
Optional[SameSite]

SameSite policy of the cookie. Defaults to "Lax".

partitioned
bool

Whether the cookie is partitioned. Defaults to False.

comment
Optional[str]

Comment of the cookie. Defaults to None.

host_prefix
bool

Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True. Defaults to False.

secure_prefix
bool

Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

Return
Cookie

The cookie that was added

cookies#

The response cookies.

@property
def cookies(self): -> CookieJar

See Cookies

Return
CookieJar

The response cookies

delete_cookie#

Delete a cookie

def delete_cookie(self, key: str, path: str = "/", domain: Optional[str] = None, host_prefix: bool = False, secure_prefix: bool = False): -> None

This will effectively set it as Max-Age: 0, which a browser should interpret it to mean: "delete the cookie".

Since it is a browser/client implementation, your results may vary depending upon which client is being used.

See Cookies

Parameters
key
str

The key to be deleted

path
str

Path of the cookie. Defaults to "/".

domain
Optional[str]

Domain of the cookie. Defaults to None.

host_prefix
bool

Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True. Defaults to False.

secure_prefix
bool

Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

processed_headers#

Obtain a list of header tuples encoded in bytes for sending.

@property
def processed_headers(self): -> Iterator[Tuple[bytes, bytes]]

Add and remove headers based on status and content_type.

Return
Iterator[Tuple[bytes, bytes]]

A list of header tuples encoded in bytes for sending

send#

Send any pending response headers and the given data as body.

async def send(self, data: Optional[AnyStr] = None, end_stream: Optional[bool] = None): -> None

Parameters
data
Optional[AnyStr]

str or bytes to be written. Defaults to None.

end_stream
Optional[bool]

whether to close the stream after this block. Defaults to None.

sanic.response.types.HTTPResponse#

HTTP response to be sent back to the client.

Inherits from: BaseHTTPResponse

class HTTPResponse(body: Optional[Any] = None, status: int = 200, headers: Optional[Union[Header, Dict[str, str]]] = None, content_type: Optional[str] = None)

Parameters
body
Optional[Any]

The body content to be returned. Defaults to None.

status
int

HTTP response number. Defaults to 200.

headers
Optional[Union[Header, Dict[str, str]]]

Headers to be returned. Defaults to None.

content_type
Optional[str]

Content type to be returned (as a header). Defaults to None.

add_cookie#

Add a cookie to the CookieJar

def add_cookie(self, key: str, value: str, path: str = "/", domain: Optional[str] = None, secure: bool = True, max_age: Optional[int] = None, expires: Optional[datetime] = None, httponly: bool = False, samesite: Optional[SameSite] = Lax, partitioned: bool = False, comment: Optional[str] = None, host_prefix: bool = False, secure_prefix: bool = False): -> Cookie

See Cookies

Parameters
key
str

The key to be added

value
str

The value to be added

path
str

Path of the cookie. Defaults to "/".

domain
Optional[str]

Domain of the cookie. Defaults to None.

secure
bool

Whether the cookie is secure. Defaults to True.

max_age
Optional[int]

Max age of the cookie. Defaults to None.

expires
Optional[datetime]

Expiry date of the cookie. Defaults to None.

httponly
bool

Whether the cookie is http only. Defaults to False.

samesite
Optional[SameSite]

SameSite policy of the cookie. Defaults to "Lax".

partitioned
bool

Whether the cookie is partitioned. Defaults to False.

comment
Optional[str]

Comment of the cookie. Defaults to None.

host_prefix
bool

Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True. Defaults to False.

secure_prefix
bool

Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

Return
Cookie

The cookie that was added

cookies#

The response cookies.

@property
def cookies(self): -> CookieJar

See Cookies

Return
CookieJar

The response cookies

delete_cookie#

Delete a cookie

def delete_cookie(self, key: str, path: str = "/", domain: Optional[str] = None, host_prefix: bool = False, secure_prefix: bool = False): -> None

This will effectively set it as Max-Age: 0, which a browser should interpret it to mean: "delete the cookie".

Since it is a browser/client implementation, your results may vary depending upon which client is being used.

See Cookies

Parameters
key
str

The key to be deleted

path
str

Path of the cookie. Defaults to "/".

domain
Optional[str]

Domain of the cookie. Defaults to None.

host_prefix
bool

Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True. Defaults to False.

secure_prefix
bool

Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

eof#

Send a EOF (End of File) message to the client.

async def eof(self)

processed_headers#

Obtain a list of header tuples encoded in bytes for sending.

@property
def processed_headers(self): -> Iterator[Tuple[bytes, bytes]]

Add and remove headers based on status and content_type.

Return
Iterator[Tuple[bytes, bytes]]

A list of header tuples encoded in bytes for sending

send#

Send any pending response headers and the given data as body.

async def send(self, data: Optional[AnyStr] = None, end_stream: Optional[bool] = None): -> None

Parameters
data
Optional[AnyStr]

str or bytes to be written. Defaults to None.

end_stream
Optional[bool]

whether to close the stream after this block. Defaults to None.

sanic.response.types.JSONResponse#

Convenience class for JSON responses

Inherits from: HTTPResponse, BaseHTTPResponse

class JSONResponse(body: Optional[Any] = None, status: int = 200, headers: Optional[Union[Header, Dict[str, str]]] = None, content_type: str = "application/json", dumps: Optional[Callable[..., str]] = None, kwargs: Any)

HTTP response to be sent back to the client, when the response is of json type. Offers several utilities to manipulate common json data types.

Parameters
body
Optional[Any]

The body content to be returned. Defaults to None.

status
int

HTTP response number. Defaults to 200.

headers
Optional[Union[Header, Dict[str, str]]]

Headers to be returned. Defaults to None.

content_type
str

Content type to be returned (as a header). Defaults to "application/json".

dumps
Optional[Callable[..., str]]

The function to use for json encoding. Defaults to None.

**kwargs
Any

The kwargs to pass to the json encoding function. Defaults to {}.

add_cookie#

Add a cookie to the CookieJar

def add_cookie(self, key: str, value: str, path: str = "/", domain: Optional[str] = None, secure: bool = True, max_age: Optional[int] = None, expires: Optional[datetime] = None, httponly: bool = False, samesite: Optional[SameSite] = Lax, partitioned: bool = False, comment: Optional[str] = None, host_prefix: bool = False, secure_prefix: bool = False): -> Cookie

See Cookies

Parameters
key
str

The key to be added

value
str

The value to be added

path
str

Path of the cookie. Defaults to "/".

domain
Optional[str]

Domain of the cookie. Defaults to None.

secure
bool

Whether the cookie is secure. Defaults to True.

max_age
Optional[int]

Max age of the cookie. Defaults to None.

expires
Optional[datetime]

Expiry date of the cookie. Defaults to None.

httponly
bool

Whether the cookie is http only. Defaults to False.

samesite
Optional[SameSite]

SameSite policy of the cookie. Defaults to "Lax".

partitioned
bool

Whether the cookie is partitioned. Defaults to False.

comment
Optional[str]

Comment of the cookie. Defaults to None.

host_prefix
bool

Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True. Defaults to False.

secure_prefix
bool

Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

Return
Cookie

The cookie that was added

append#

Appends a value to the response raw_body, ensuring that body is kept up to date.

def append(self, value: Any): -> None

This can only be used if raw_body is a list.

Parameters
value
Any

The value to append

Raises
SanicException

If the body is not a list

body#

Returns the response body.

@property
def body(self): -> Optional[bytes]

Return
Optional[bytes]

The response body

cookies#

The response cookies.

@property
def cookies(self): -> CookieJar

See Cookies

Return
CookieJar

The response cookies

delete_cookie#

Delete a cookie

def delete_cookie(self, key: str, path: str = "/", domain: Optional[str] = None, host_prefix: bool = False, secure_prefix: bool = False): -> None

This will effectively set it as Max-Age: 0, which a browser should interpret it to mean: "delete the cookie".

Since it is a browser/client implementation, your results may vary depending upon which client is being used.

See Cookies

Parameters
key
str

The key to be deleted

path
str

Path of the cookie. Defaults to "/".

domain
Optional[str]

Domain of the cookie. Defaults to None.

host_prefix
bool

Whether to add __Host- as a prefix to the key. This requires that path="/", domain=None, and secure=True. Defaults to False.

secure_prefix
bool

Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

eof#

Send a EOF (End of File) message to the client.

async def eof(self)

extend#

Extends the response's raw_body with the given values, ensuring that body is kept up to date.

def extend(self, value: Any): -> None

This can only be used if raw_body is a list.

Parameters
value
Any

The values to extend with

Raises
SanicException

If the body is not a list

pop#

Pops a key from the response's raw_body, ensuring that body is kept up to date.

def pop(self, key: Any, default: Any = <Default>): -> Any

This can only be used if raw_body is a dict or a list.

Parameters
key
Any

The key to pop

default
Any

The default value to return if the key is not found. Defaults to _default.

Return
Any

The value that was popped

Raises
SanicException

If the body is not a dict or a list

TypeError

If the body is a list and a default value is provided

processed_headers#

Obtain a list of header tuples encoded in bytes for sending.

@property
def processed_headers(self): -> Iterator[Tuple[bytes, bytes]]

Add and remove headers based on status and content_type.

Return
Iterator[Tuple[bytes, bytes]]

A list of header tuples encoded in bytes for sending

raw_body#

Returns the raw body, as long as body has not been manually set previously.

@property
def raw_body(self): -> Optional[Any]

NOTE: This object should not be mutated, as it will not be reflected in the response body. If you need to mutate the response body, consider using one of the provided methods in this class or alternatively call set_body() with the mutated object afterwards or set the raw_body property to it.

Return
Optional[Any]

The raw body

send#

Send any pending response headers and the given data as body.

async def send(self, data: Optional[AnyStr] = None, end_stream: Optional[bool] = None): -> None

Parameters
data
Optional[AnyStr]

str or bytes to be written. Defaults to None.

end_stream
Optional[bool]

whether to close the stream after this block. Defaults to None.

set_body#

Set the response body to the given value, using the given dumps function

def set_body(self, body: Any, dumps: Optional[Callable[..., str]] = None, dumps_kwargs: Any): -> None

Sets a new response body using the given dumps function and kwargs, or falling back to the defaults given when creating the object if none are specified.

Parameters
body
Any

The body to set

dumps
Optional[Callable[..., str]]

The function to use for json encoding. Defaults to None.

**dumps_kwargs
Any

The kwargs to pass to the json encoding function. Defaults to {}.

Examples
response = JSONResponse({"foo": "bar"})
response.set_body({"bar": "baz"})
assert response.body == b'{"bar": "baz"}'

update#

Updates the response's raw_body with the given values, ensuring that body is kept up to date.

def update(self, args, kwargs): -> None

This can only be used if raw_body is a dict.

Parameters
*args

The args to update with

**kwargs

The kwargs to update with

Raises
SanicException

If the body is not a dict

sanic.response.types.ResponseStream#

A compat layer to bridge the gap after the deprecation of StreamingHTTPResponse.

class ResponseStream(streaming_fn: Callable[[Union[BaseHTTPResponse, ResponseStream]], Coroutine[Any, Any, None]], status: int = 200, headers: Optional[Union[Header, Dict[str, str]]] = None, content_type: Optional[str] = None)

It will be removed when:

  • file_stream is moved to new style streaming
  • file and file_stream are combined into a single API

body#

@property
def body(self)

cookies#

@property
def cookies(self): -> CookieJar

eof#

async def eof(self): -> None

processed_headers#

@property
def processed_headers(self)

stream#

async def stream(self): -> HTTPResponse

write#

async def write(self, message: str)