Warning
These documents are OUTDATED as of 2023-12-31.
Please refer to the latest version of the documentation at sanic.dev.
Coreο
sanic.handlersο
- class sanic.handlers.ContentRangeHandler(request, stats)ο
Bases:
Range
Parse and process the incoming request headers to extract the content range information.
- Args:
request (Request): The incoming request object. stats (os.stat_result): The stats of the file being served.
- class sanic.handlers.DirectoryHandler(uri, directory, directory_view=False, index=None)ο
Bases:
object
Serve files from a directory.
- Args:
uri (str): The URI to serve the files at. directory (Path): The directory to serve files from. directory_view (bool): Whether to show a directory listing or not. index (Optional[Union[str, Sequence[str]]]): The index file(s) to
serve if the directory is requested. Defaults to None.
- Parameters:
uri (str) β
directory (Path) β
directory_view (bool) β
index (Optional[Union[str, Sequence[str]]]) β
- async handle(request, path)ο
Handle the request.
- Args:
request (Request): The incoming request object. path (str): The path to the file to serve.
- Raises:
NotFound: If the file is not found. IsADirectoryError: If the path is a directory and directory_view is False.
- Returns:
Response: The response object.
- Parameters:
request (Request) β
path (str) β
- class sanic.handlers.ErrorHandler(base=<class 'sanic.errorpages.TextRenderer'>)ο
Bases:
object
Process and handle all uncaught exceptions.
This error handling framework is built into the core that can be extended by the developers to perform a wide range of tasks from recording the error stats to reporting them to an external service that can be used for realtime alerting system.
- Args:
base (BaseRenderer): The renderer to use for the error pages.
- Parameters:
base (Type[BaseRenderer]) β
- add(exception, handler, route_names=None)ο
Add a new exception handler to an already existing handler object.
- Args:
- exception (sanic.exceptions.SanicException or Exception): Type
of exception that needs to be handled.
- handler (function): Reference to the function that will
handle the exception.
- Returns:
None
- Parameters:
route_names (List[str] | None) β
- default(request, exception)ο
Provide a default behavior for the objects of ErrorHandler.
If a developer chooses to extend the ErrorHandler, they can provide a custom implementation for this method to behave in a way they see fit.
- Args:
request (sanic.request.Request): Incoming request. exception (sanic.exceptions.SanicException or Exception): Exception object.
- Returns:
HTTPResponse: The response object.
- Examples:
```python class CustomErrorHandler(ErrorHandler):
- def default(self, request: Request, exception: Exception) -> HTTPResponse:
# Custom logic for handling the exception and creating a response custom_response = my_custom_logic(request, exception) return custom_response
app = Sanic(βMyAppβ, error_handler=CustomErrorHandler()) ```
- Parameters:
request (Request) β
exception (Exception) β
- Return type:
- static log(request, exception)ο
Logs information about an incoming request and the associated exception.
- Args:
request (Request): The incoming request to be logged. exception (Exception): The exception that occurred during the handling of the request.
- Returns:
None
- Parameters:
request (Request) β
exception (Exception) β
- Return type:
None
- lookup(exception, route_name=None)ο
Lookup the existing instance of ErrorHandler and fetch the registered handler for a specific type of exception.
This method leverages a dict lookup to speedup the retrieval process.
- Args:
- exception (sanic.exceptions.SanicException or Exception): Type
of exception.
- Returns:
Registered function if found,
None
otherwise.
- Parameters:
route_name (str | None) β
- response(request, exception)ο
Fetch and executes an exception handler and returns a response object.
- Args:
request (sanic.request.Request): Instance of the request. exception (sanic.exceptions.SanicException or Exception): Exception to handle.
- Returns:
Wrap the return value obtained from the default function or the registered handler for that type of exception.
sanic.headersο
- class sanic.headers.AcceptList(iterable=(), /)ο
Bases:
list
A list of media types, as used in the Accept header.
The Accept header entries are listed in order of preference, starting with the most preferred. This class is a list of MediaType objects, that encapsulate also the q value or any other parameters.
Two separate methods are provided for searching the list: - βmatchβ for finding the most preferred match (wildcards supported) - operator βinβ for checking explicit matches (wildcards as literals)
- Args:
*args (MediaType): Any number of MediaType objects.
- match(*mimes, accept_wildcards=True)ο
Find a media type accepted by the client.
This method can be used to find which of the media types requested by the client is most preferred against the ones given as arguments.
The ordering of preference is set by: 1. The order set by RFC 7231, s. 5.3.2, giving a higher priority
to q values and more specific type definitions,
The order of the arguments (first is most preferred), and
The first matching entry on the Accept header.
Wildcards are matched both ways. A match is usually found, as the Accept headers typically include */*, in particular if the header is missing, is not manually set, or if the client is a browser.
Note: the returned object behaves as a string of the mime argument that matched, and is empty/falsy if no match was found. The matched header entry MediaType or None is available as the m attribute.
- Args:
mimes (List[str]): Any MIME types to search for in order of preference. accept_wildcards (bool): Match Accept entries with wildcards in them.
- Returns:
Match: A match object with the mime string and the MediaType object.
- Parameters:
mimes (str) β
- Return type:
- class sanic.headers.Matched(mime, header)ο
Bases:
object
A matching result of a MIME string against a header.
This class is a representation of a matching result of a MIME string against a header. It encapsulates the MIME string, the header, and provides methods for matching against other MIME strings.
- Args:
mime (str): The MIME string to match. header (MediaType): The header to match against, if any.
- Parameters:
mime (str) β
header (Optional[MediaType]) β
- match(other)ο
Match this MIME string against another MIME string.
Check if this MIME string matches the given MIME string. Wildcards are supported both ways on both type and subtype.
- Args:
other (str): A MIME string to match.
- Returns:
Matched: Returns self if the MIME strings are compatible. None: Returns None if the MIME strings are not compatible.
- class sanic.headers.MediaType(type_, subtype, **params)ο
Bases:
object
A media type, as used in the Accept header.
This class is a representation of a media type, as used in the Accept header. It encapsulates the type, subtype and any parameters, and provides methods for matching against other media types.
Two separate methods are provided for searching the list: - βmatchβ for finding the most preferred match (wildcards supported) - operator βinβ for checking explicit matches (wildcards as literals)
- Args:
type_ (str): The type of the media type. subtype (str): The subtype of the media type. **params (str): Any parameters for the media type.
- Parameters:
type_ (str) β
subtype (str) β
params (str) β
- match(mime_with_params)ο
Match this media type against another media type.
Check if this media type matches the given mime type/subtype. Wildcards are supported both ways on both type and subtype. If mime contains a semicolon, optionally followed by parameters, the parameters of the two media types must match exactly.
Note
Use the == operator instead to check for literal matches without expanding wildcards.
- Args:
media_type (str): A type/subtype string to match.
- Returns:
MediaType: Returns self if the media types are compatible. None: Returns None if the media types are not compatible.
- property has_wildcard: boolο
Return True if this media type has a wildcard in it.
- Returns:
bool: True if this media type has a wildcard in it.
- sanic.headers.format_http1_response(status, headers)ο
Format a HTTP/1.1 response header.
- Args:
status (int): The HTTP status code. headers (HeaderBytesIterable): An iterable of header tuples.
- Returns:
bytes: The formatted response header.
- Parameters:
status (int) β
headers (Iterable[Tuple[bytes, bytes]]) β
- Return type:
bytes
- sanic.headers.fwd_normalize(fwd)ο
Normalize and convert values extracted from forwarded headers.
- Args:
fwd (OptionsIterable): An iterable of key-value pairs.
- Returns:
Options: A dict of normalized key-value pairs.
- Parameters:
fwd (Iterable[Tuple[str, str]]) β
- Return type:
Dict[str, int | str]
- sanic.headers.fwd_normalize_address(addr)ο
Normalize address fields of proxy headers.
- Args:
addr (str): An address string.
- Returns:
str: A normalized address string.
- Parameters:
addr (str) β
- Return type:
str
- sanic.headers.parse_accept(accept)ο
Parse an Accept header and order the acceptable media types according to RFC 7231, s. 5.3.2
https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2
- Args:
accept (str): The Accept header value to parse.
- Returns:
AcceptList: A list of MediaType objects, ordered by preference.
- Raises:
InvalidHeader: If the header value is invalid.
- Parameters:
accept (str | None) β
- Return type:
- sanic.headers.parse_content_header(value)ο
Parse content-type and content-disposition header values.
E.g. form-data; name=upload; filename=βfile.txtβ to (βform-dataβ, {βnameβ: βuploadβ, βfilenameβ: βfile.txtβ})
Mostly identical to cgi.parse_header and werkzeug.parse_options_header but runs faster and handles special characters better.
Unescapes %22 to β and %0D%0A to `
` in field values.
- Args:
value (str): The header value to parse.
- Returns:
Tuple[str, Options]: The header value and a dict of options.
- Parameters:
value (str) β
- Return type:
Tuple[str, Dict[str, int | str]]
- sanic.headers.parse_credentials(header, prefixes=None)ο
Parses any header with the aim to retrieve any credentials from it.
- Args:
header (Optional[str]): The header to parse. prefixes (Optional[Union[List, Tuple, Set]], optional): The prefixes to look for. Defaults to None.
- Returns:
Tuple[Optional[str], Optional[str]]: The prefix and the credentials.
- Parameters:
header (str | None) β
prefixes (List | Tuple | Set | None) β
- Return type:
Tuple[str | None, str | None]
- sanic.headers.parse_forwarded(headers, config)ο
Parse RFC 7239 Forwarded headers. The value of by or secret must match config.FORWARDED_SECRET :return: dict with keys and values, or None if nothing matched
- Return type:
Dict[str, int | str] | None
- sanic.headers.parse_host(host)ο
Split host:port into hostname and port.
- Args:
host (str): A host string.
- Returns:
Tuple[Optional[str], Optional[int]]: A tuple of hostname and port.
- Parameters:
host (str) β
- Return type:
Tuple[str | None, int | None]
- sanic.headers.parse_xforwarded(headers, config)ο
Parse traditional proxy headers.
- Return type:
Dict[str, int | str] | None
sanic.requestο
- class sanic.request.File(type, body, name)ο
Bases:
tuple
Model for defining a file.
It is a namedtuple, therefore you can iterate over the object, or access the parameters by name.
- Args:
type (str, optional): The mimetype, defaults to βtext/plainβ. body (bytes): Bytes of the file. name (str): The filename.
- Parameters:
type (str) β
body (bytes) β
name (str) β
- body: bytesο
Alias for field number 1
- name: strο
Alias for field number 2
- type: strο
Alias for field number 0
- class sanic.request.Request(url_bytes, headers, version, method, transport, app, head=b'', stream_id=0)ο
Bases:
Generic
[sanic_type
,ctx_type
]State of HTTP request.
- Args:
url_bytes (bytes): Raw URL bytes. headers (Header): Request headers. version (str): HTTP version. method (str): HTTP method. transport (TransportProtocol): Transport protocol. app (Sanic): Sanic instance. head (bytes, optional): Request head. Defaults to bββ. stream_id (int, optional): HTTP/3 stream ID. Defaults to 0.
- classmethod generate_id(*_)ο
Generate a unique ID for the request.
This method is called to generate a unique ID for each request. By default, it returns a uuid.UUID instance.
- Returns:
Union[uuid.UUID, str, int]: A unique ID for the request.
- Return type:
UUID | str | int
- get_args(keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')ο
Parse query_string using urllib.parse.parse_qs.
This methods is used by the args property, but it also can be used directly if you need to change default parameters.
- Args:
- keep_blank_values (bool): Flag indicating whether blank values in
percent-encoded queries should be treated as blank strings. A True value indicates that blanks should be retained as blank strings. The default False value indicates that blank values are to be ignored and treated as if they were not included.
- strict_parsing (bool): Flag indicating what to do with parsing
errors. If False (the default), errors are silently ignored. If True, errors raise a ValueError exception.
- encoding (str): Specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
- errors (str): Specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
- Returns:
RequestParameters: A dictionary containing the parsed arguments.
- Parameters:
keep_blank_values (bool) β
strict_parsing (bool) β
encoding (str) β
errors (str) β
- Return type:
- classmethod get_current()ο
Retrieve the current request object
This implements [Context Variables](https://docs.python.org/3/library/contextvars.html) to allow for accessing the current request from anywhere.
A typical usecase is when you want to access the current request from a function that is not a handler, such as a logging function:
- class LoggingFormater(logging.Formatter):
- def format(self, record):
request = Request.get_current() record.url = request.url record.ip = request.ip return super().format(record)
- Returns:
Request: The current request object
- Raises:
- sanic.exceptions.ServerError: If it is outside of a request
lifecycle.
- Return type:
- get_form(keep_blank_values=False)ο
Method to extract and parse the form data from a request.
- Args:
keep_blank_values (bool): Whether to discard blank values from the form data.
- Returns:
Optional[RequestParameters]: The parsed form data.
- Parameters:
keep_blank_values (bool) β
- Return type:
RequestParameters | None
- get_query_args(keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')ο
Parse query_string using urllib.parse.parse_qsl.
This methods is used by query_args propertyn but can be used directly if you need to change default parameters.
- Args:
- keep_blank_values (bool): Flag indicating whether blank values in
percent-encoded queries should be treated as blank strings. A True value indicates that blanks should be retained as blank strings. The default False value indicates that blank values are to be ignored and treated as if they were not included.
- strict_parsing (bool): Flag indicating what to do with
parsing errors. If False (the default), errors are silently ignored. If True, errors raise a ValueError exception.
- encoding (str): Specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
- errors (str): Specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
- Returns:
list: A list of tuples containing the parsed arguments.
- Parameters:
keep_blank_values (bool) β
strict_parsing (bool) β
encoding (str) β
errors (str) β
- Return type:
list
- load_json(loads=None)ο
Load the request body as JSON
- Args:
loads (Callable, optional): A custom JSON loader. Defaults to None.
- Raises:
BadRequest: If the request body cannot be parsed as JSON
- Returns:
Any: The request body parsed as JSON
- Return type:
Any
- static make_context()ο
Create a new context object.
This method is called when a new request context is pushed. It is a great candidate for overriding in a subclass if you want to control the type of context object that is created.
By default, it returns a types.SimpleNamespace instance.
- Returns:
ctx_type: A new context object.
- Return type:
ctx_type
- async receive_body()ο
Receive request.body, if not already received.
Streaming handlers may call this to receive the full body. Sanic calls this function before running any handlers of non-streaming routes.
Custom request classes can override this for custom handling of both streaming and non-streaming routes.
- reset_response()ο
Reset the response object.
This clears much of the state of the object. It should generally not be called directly, but is called automatically as part of the request lifecycle.
- Raises:
- sanic.exceptions.ServerError: If the response has already been
sent.
- Return type:
None
- async respond(response=None, *, status=200, headers=None, content_type=None)ο
Respond to the request without returning.
This method can only be called once, as you can only respond once. If no
response
argument is passed, one will be created from thestatus
,headers
andcontent_type
arguments.The first typical usecase is if you wish to respond to the request without returning from the handler:
```python @app.get(β/β) async def handler(request: Request):
data = β¦ # Process something
json_response = json({βdataβ: data}) await request.respond(json_response)
@app.on_response async def add_header(_, response: HTTPResponse):
# Middlewares still get executed as expected response.headers[βoneβ] = βtwoβ
The second possible usecase is for when you want to directly respond to the request:
```python response = await request.respond(content_type=βtext/csvβ) await response.send(βfoo,β) await response.send(βbarβ)
# You can control the completion of the response by calling # the βeof()β method: await response.eof() ```
- Args:
response (ResponseType): Response instance to send. status (int): Status code to return in the response. headers (Optional[Dict[str, str]]): Headers to return in the response, defaults to None. content_type (Optional[str]): Content-Type header of the response, defaults to None.
- Returns:
- FinalResponseType: Final response being sent (may be different from the
βresponseβ parameter because of middlewares), which can be used to manually send data.
- Parameters:
response (BaseHTTPResponse | None) β
status (int) β
headers (Header | Dict[str, str] | None) β
content_type (str | None) β
- url_for(view_name, **kwargs)ο
Retrieve a URL for a given view name.
Same as sanic.Sanic.url_for, but automatically determine scheme and netloc base on the request. Since this method is aiming to generate correct schema & netloc, _external is implied.
- Args:
view_name (str): The view name to generate URL for. **kwargs: Arbitrary keyword arguments to build URL query string.
- Returns:
str: The generated URL.
- Parameters:
view_name (str) β
- Return type:
str
- property accept: AcceptListο
Accepted response content types.
A convenience handler for easier RFC-compliant matching of MIME types, parsed as a list that can match wildcards and includes / by default.
- Returns:
AcceptList: Accepted response content types
- property args: RequestParametersο
Convenience property to access Request.get_args with default values.
- property client_ip: strο
Client IP address. 1. proxied remote address self.forwarded[βforβ] 2. local peer address self.ip
New in Sanic 23.6. Prefer this over remote_addr for determining the client address regardless of whether the service runs behind a proxy or not (proxy deployment needs separate configuration).
- Returns:
str: IPv4, bracketed IPv6, UNIX socket name or arbitrary string
- property content_type: strο
Content-Type header form the request
- Returns:
str: Content-Type header form the request
- property cookies: RequestParametersο
Incoming cookies on the request
- Returns:
RequestParameters: Incoming cookies on the request
- property credentials: Credentials | Noneο
Attempt to return the auth header value.
Covers NoAuth, Basic Auth, Bearer Token, Api Token authentication schemas.
- Returns:
- Optional[Credentials]: A Credentials object with token, or username
and password related to the request
- property ctx: ctx_typeο
The current request context.
This is a context object for the current request. It is created by Request.make_context and is a great place to store data that you want to be accessible during the request lifecycle.
- Returns:
ctx_type: The current request context.
- property endpoint: str | Noneο
Alias of sanic.request.Request.name
- Returns:
Optional[str]: The route name
- property files: RequestParameters | Noneο
The request body parsed as uploaded files
- Returns:
Optional[RequestParameters]: The request body parsed as uploaded files
- property form: RequestParameters | Noneο
The request body parsed as form data
- Returns:
Optional[RequestParameters]: The request body parsed as form data
- property forwarded: Dict[str, int | str]ο
Active proxy information obtained from request headers, as specified in Sanic configuration.
Field names by, for, proto, host, port and path are normalized. - for and by IPv6 addresses are bracketed - port (int) is only set by port headers, not from host. - path is url-unencoded
Additional values may be available from new style Forwarded headers.
- Returns:
Options: proxy information from request headers
- property host: strο
The currently effective server βhostβ (hostname or hostname:port).
config.SERVER_NAME overrides any client headers
proxied host of original request
3. request host header hostname and port may be separated by sanic.headers.parse_host(request.host).
- Returns:
str: the first matching host found, or empty string
- property id: UUID | str | int | Noneο
A request ID passed from the client, or generated from the backend.
By default, this will look in a request header defined at: self.app.config.REQUEST_ID_HEADER. It defaults to X-Request-ID. Sanic will try to cast the ID into a UUID or an int.
If there is not a UUID from the client, then Sanic will try to generate an ID by calling Request.generate_id(). The default behavior is to generate a UUID. You can customize this behavior by subclassing Request and overwriting that method.
```python from sanic import Request, Sanic from itertools import count
- class IntRequest(Request):
counter = count()
- def generate_id(self):
return next(self.counter)
app = Sanic(βMyAppβ, request_class=IntRequest) ```
- Returns:
- Optional[Union[uuid.UUID, str, int]]: A request ID passed from the
client, or generated from the backend.
- property ip: strο
Peer ip of the socket
- Returns:
str: Peer ip of the socket
- property is_cacheable: boolο
Whether the HTTP method is cacheable.
See https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.3
- Returns:
bool: Whether the HTTP method is cacheable.
- property is_idempotent: boolο
Whether the HTTP method is iempotent.
See https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.2
- Returns:
bool: Whether the HTTP method is iempotent.
- property is_safe: boolο
Whether the HTTP method is safe.
See https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.1
- Returns:
bool: Whether the HTTP method is safe.
- property json: Anyο
The request body parsed as JSON
- Returns:
Any: The request body parsed as JSON
- property match_info: Dict[str, Any]ο
Matched path parameters after resolving route
- Returns:
Dict[str, Any]: Matched path parameters after resolving route
- property name: str | Noneο
The route name
In the following pattern:
` <AppName>.[<BlueprintName>.]<HandlerName> `
- Returns:
Optional[str]: The route name
- property network_paths: List[Any] | Noneο
Access the network paths if available
- Returns:
Optional[List[Any]]: Access the network paths if available
- property path: strο
Path of the local HTTP request
- Returns:
str: Path of the local HTTP request
- property port: intο
Peer port of the socket
- Returns:
int: Peer port of the socket
- property protocol: TransportProtocolο
The HTTP protocol instance
- Returns:
Protocol: The HTTP protocol instance
- property query_args: listο
Convenience property to access Request.get_query_args with default values.
- property query_string: strο
Representation of the requested query
- Returns:
str: Representation of the requested query
- property raw_headers: bytesο
The unparsed HTTP headers
- Returns:
bytes: The unparsed HTTP headers
- property remote_addr: strο
Client IP address, if available from proxy.
- Returns:
str: IPv4, bracketed IPv6, UNIX socket name or arbitrary string
- property request_line: bytesο
The first line of a HTTP request
- Returns:
bytes: The first line of a HTTP request
- property scheme: strο
Determine request scheme.
config.SERVER_NAME if in full URL format
proxied proto/scheme
local connection protocol
- Returns:
str: http|https|ws|wss or arbitrary value given by the headers.
- property scope: MutableMapping[str, Any]ο
The ASGI scope of the request.
- Returns:
ASGIScope: The ASGI scope of the request.
- Raises:
NotImplementedError: If the app isnβt an ASGI app.
- property server_name: strο
hostname the client connected to, by request.host
- Returns:
str: hostname the client connected to, by request.host
- property server_path: strο
Full path of current URL; uses proxied or local path
- Returns:
str: Full path of current URL; uses proxied or local path
- property server_port: intο
The port the client connected to, by forwarded port or request.host.
Default port is returned as 80 and 443 based on request.scheme.
- Returns:
int: The port the client connected to, by forwarded port or request.host.
- property socket: Tuple[str, int] | Tuple[None, None]ο
Information about the connected socket if available
- Returns:
- Tuple[Optional[str], Optional[int]]: Information about the
connected socket if available, in the form of a tuple of (ip, port)
- property stream_id: intο
Access the HTTP/3 stream ID.
- Raises:
sanic.exceptions.ServerError: If the request is not HTTP/3.
- Returns:
int: The HTTP/3 stream ID.
- property token: str | Noneο
Attempt to return the auth header token.
- Returns:
Optional[str]: The auth header token
- property uri_template: str | Noneο
The defined URI template
- Returns:
Optional[str]: The defined URI template
- property url: strο
The URL
- Returns:
str: The URL
- class sanic.request.RequestParametersο
Bases:
dict
Hosts a dict with lists as values where get returns the first value of the list and getlist returns the whole shebang
- get(name, default=None)ο
Return the first value, either the default or actual
- Args:
name (str): The name of the parameter default (Optional[Any], optional): The default value. Defaults to None.
- Returns:
Optional[Any]: The first value of the list
- Parameters:
name (str) β
default (Any | None) β
- Return type:
Any | None
- getlist(name, default=None)ο
Return the entire list
- Args:
name (str): The name of the parameter default (Optional[Any], optional): The default value. Defaults to None.
- Returns:
Optional[Any]: The entire list
- Parameters:
name (str) β
default (Any | None) β
- Return type:
Any | None
- sanic.request.parse_multipart_form(body, boundary)ο
Parse a request body and returns fields and files
- Args:
body (bytes): Bytes request body. boundary (bytes): Bytes multipart boundary.
- Returns:
Tuple[RequestParameters, RequestParameters]: A tuple containing fields and files as RequestParameters.
sanic.responseο
- class sanic.response.BaseHTTPResponseο
Bases:
object
The base class for all HTTP Responses
- add_cookie(key, value, *, path='/', domain=None, secure=True, max_age=None, expires=None, httponly=False, samesite='Lax', partitioned=False, comment=None, host_prefix=False, secure_prefix=False)ο
Add a cookie to the CookieJar
See [Cookies](/en/guide/basics/cookies.html)
- Args:
key (str): The key to be added value (str): The value to be added path (str, optional): Path of the cookie. Defaults to β/β. domain (Optional[str], optional): Domain of the cookie. Defaults to None. secure (bool, optional): Whether the cookie is secure. Defaults to True. max_age (Optional[int], optional): Max age of the cookie. Defaults to None. expires (Optional[datetime], optional): Expiry date of the cookie. Defaults to None. httponly (bool, optional): Whether the cookie is http only. Defaults to False. samesite (Optional[SameSite], optional): SameSite policy of the cookie. Defaults to βLaxβ. partitioned (bool, optional): Whether the cookie is partitioned. Defaults to False. comment (Optional[str], optional): Comment of the cookie. Defaults to None. host_prefix (bool, optional): 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, optional): Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.
- Returns:
Cookie: The cookie that was added
- Parameters:
key (str) β
value (str) β
path (str) β
domain (str | None) β
secure (bool) β
max_age (int | None) β
expires (datetime | None) β
httponly (bool) β
samesite (Literal['Strict'] | ~typing.Literal['Lax'] | ~typing.Literal['None'] | ~typing.Literal['strict'] | ~typing.Literal['lax'] | ~typing.Literal['none'] | None) β
partitioned (bool) β
comment (str | None) β
host_prefix (bool) β
secure_prefix (bool) β
- Return type:
- delete_cookie(key, *, path='/', domain=None, host_prefix=False, secure_prefix=False)ο
Delete a cookie
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](/en/guide/basics/cookies.html)
- Args:
key (str): The key to be deleted path (str, optional): Path of the cookie. Defaults to β/β. domain (Optional[str], optional): Domain of the cookie. Defaults to None. host_prefix (bool, optional): 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, optional): Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.
- Parameters:
key (str) β
path (str) β
domain (str | None) β
host_prefix (bool) β
secure_prefix (bool) β
- Return type:
None
- async send(data=None, end_stream=None)ο
Send any pending response headers and the given data as body.
- Args:
data (Optional[AnyStr], optional): str or bytes to be written. Defaults to None. end_stream (Optional[bool], optional): whether to close the stream after this block. Defaults to None.
- Parameters:
data (AnyStr | None) β
end_stream (bool | None) β
- Return type:
None
- property cookies: CookieJarο
The response cookies.
See [Cookies](/en/guide/basics/cookies.html)
- Returns:
CookieJar: The response cookies
- property processed_headers: Iterator[Tuple[bytes, bytes]]ο
Obtain a list of header tuples encoded in bytes for sending.
Add and remove headers based on status and content_type.
- Returns:
Iterator[Tuple[bytes, bytes]]: A list of header tuples encoded in bytes for sending
- class sanic.response.HTTPResponse(body=None, status=200, headers=None, content_type=None)ο
Bases:
BaseHTTPResponse
HTTP response to be sent back to the client.
- Args:
body (Optional[Any], optional): The body content to be returned. Defaults to None. status (int, optional): HTTP response number. Defaults to 200. headers (Optional[Union[Header, Dict[str, str]]], optional): Headers to be returned. Defaults to None. content_type (Optional[str], optional): Content type to be returned (as a header). Defaults to None.
- Parameters:
body (Optional[Any]) β
status (int) β
headers (Optional[Union[Header, Dict[str, str]]]) β
content_type (Optional[str]) β
- async eof()ο
Send a EOF (End of File) message to the client.
- class sanic.response.JSONResponse(body=None, status=200, headers=None, content_type='application/json', dumps=None, **kwargs)ο
Bases:
HTTPResponse
Convenience class for JSON responses
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.
- Args:
body (Optional[Any], optional): The body content to be returned. Defaults to None. status (int, optional): HTTP response number. Defaults to 200. headers (Optional[Union[Header, Dict[str, str]]], optional): Headers to be returned. Defaults to None. content_type (str, optional): Content type to be returned (as a header). Defaults to βapplication/jsonβ. dumps (Optional[Callable[β¦, str]], optional): The function to use for json encoding. Defaults to None. **kwargs (Any, optional): The kwargs to pass to the json encoding function. Defaults to {}.
- Parameters:
body (Optional[Any]) β
status (int) β
headers (Optional[Union[Header, Dict[str, str]]]) β
content_type (str) β
dumps (Optional[Callable[..., str]]) β
kwargs (Any) β
- append(value)ο
Appends a value to the response raw_body, ensuring that body is kept up to date.
This can only be used if raw_body is a list.
- Args:
value (Any): The value to append
- Raises:
SanicException: If the body is not a list
- Parameters:
value (Any) β
- Return type:
None
- extend(value)ο
Extends the responseβs raw_body with the given values, ensuring that body is kept up to date.
This can only be used if raw_body is a list.
- Args:
value (Any): The values to extend with
- Raises:
SanicException: If the body is not a list
- Parameters:
value (Any) β
- Return type:
None
- pop(key, default=<Default>)ο
Pops a key from the responseβs raw_body, ensuring that body is kept up to date.
This can only be used if raw_body is a dict or a list.
- Args:
key (Any): The key to pop default (Any, optional): The default value to return if the key is not found. Defaults to _default.
- 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
- Returns:
Any: The value that was popped
- Parameters:
key (Any) β
default (Any) β
- Return type:
Any
- set_body(body, dumps=None, **dumps_kwargs)ο
Set the response body to the given value, using the given dumps function
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.
- Args:
body (Any): The body to set dumps (Optional[Callable[β¦, str]], optional): The function to use for json encoding. Defaults to None. **dumps_kwargs (Any, optional): The kwargs to pass to the json encoding function. Defaults to {}.
- Examples:
`python response = JSONResponse({"foo": "bar"}) response.set_body({"bar": "baz"}) assert response.body == b'{"bar": "baz"}' `
- Parameters:
body (Any) β
dumps (Callable[[...], str] | None) β
dumps_kwargs (Any) β
- Return type:
None
- update(*args, **kwargs)ο
Updates the responseβs raw_body with the given values, ensuring that body is kept up to date.
This can only be used if raw_body is a dict.
- Args:
*args: The args to update with **kwargs: The kwargs to update with
- Raises:
SanicException: If the body is not a dict
- Return type:
None
- property body: bytes | Noneο
Returns the response body.
- Returns:
Optional[bytes]: The response body
- property raw_body: Any | Noneο
Returns the raw body, as long as body has not been manually set previously.
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.
- Returns:
Optional[Any]: The raw body
- class sanic.response.ResponseStream(streaming_fn, status=200, headers=None, content_type=None)ο
Bases:
object
A compat layer to bridge the gap after the deprecation of StreamingHTTPResponse.
It will be removed when: - file_stream is moved to new style streaming - file and file_stream are combined into a single API
- Parameters:
streaming_fn (Callable[[Union[BaseHTTPResponse, ResponseStream]], Coroutine[Any, Any, None]]) β
status (int) β
headers (Optional[Union[Header, Dict[str, str]]]) β
content_type (Optional[str]) β
- sanic.response.empty(status=204, headers=None)ο
Returns an empty response to the client.
- Args:
status (int, optional): HTTP response code. Defaults to 204. headers ([type], optional): Custom HTTP headers. Defaults to None.
- Returns:
HTTPResponse: An empty response to the client.
- Parameters:
status (int) β
headers (Dict[str, str] | None) β
- Return type:
- async sanic.response.file(location, status=200, request_headers=None, validate_when_requested=True, mime_type=None, headers=None, filename=None, last_modified=<Default>, max_age=None, no_store=None, _range=None)ο
Return a response object with file data.
- Args:
location (Union[str, PurePath]): Location of file on system. status (int, optional): 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], optional): The request headers. validate_when_requested (bool, optional): If True, will validate the file when requested. Defaults to True. mime_type (Optional[str], optional): Specific mime_type. headers (Optional[Dict[str, str]], optional): Custom Headers. filename (Optional[str], optional): Override filename. last_modified (Optional[Union[datetime, float, int, Default]], optional): The last modified date and time of the file. max_age (Optional[Union[float, int]], optional): Max age for cache control. no_store (Optional[bool], optional): Any cache should not store this response. Defaults to None. _range (Optional[Range], optional):
- Returns:
HTTPResponse: The response object with the file data.
- Parameters:
location (str | PurePath) β
status (int) β
request_headers (Header | None) β
validate_when_requested (bool) β
mime_type (str | None) β
headers (Dict[str, str] | None) β
filename (str | None) β
last_modified (datetime | float | int | Default | None) β
max_age (int | float | None) β
no_store (bool | None) β
_range (Range | None) β
- Return type:
- async sanic.response.file_stream(location, status=200, chunk_size=4096, mime_type=None, headers=None, filename=None, _range=None)ο
Return a streaming response object with file data.
- Parameters:
location (str | PurePath) β Location of file on system.
chunk_size (int) β The size of each chunk in the stream (in bytes)
mime_type (str | None) β Specific mime_type.
headers (Dict[str, str] | None) β Custom Headers.
filename (str | None) β Override filename.
_range (Range | None) β
status (int) β
- Return type:
- Args:
location (Union[str, PurePath]): Location of file on system. status (int, optional): 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, optional): The size of each chunk in the stream (in bytes). Defaults to 4096. mime_type (Optional[str], optional): Specific mime_type. headers (Optional[Dict[str, str]], optional): Custom HTTP headers. filename (Optional[str], optional): Override filename. _range (Optional[Range], optional): The range of bytes to send.
- sanic.response.html(body, status=200, headers=None)ο
Returns response object with body in html format.
Body should be a str or bytes like object, or an object with __html__ or _repr_html_.
- Args:
body (Union[str, bytes, HTMLProtocol]): Response data. status (int, optional): HTTP response code. Defaults to 200. headers (Dict[str, str], optional): Custom HTTP headers. Defaults to None.
- Returns:
HTTPResponse: A response object with body in html format.
- Parameters:
body (str | bytes | HTMLProtocol) β
status (int) β
headers (Dict[str, str] | None) β
- Return type:
- sanic.response.json(body, status=200, headers=None, content_type='application/json', dumps=None, **kwargs)ο
Returns response object with body in json format.
- Args:
body (Any): Response data to be serialized. status (int, optional): HTTP response code. Defaults to 200. headers (Dict[str, str], optional): Custom HTTP headers. Defaults to None. content_type (str, optional): The content type (string) of the response. Defaults to βapplication/jsonβ. dumps (Callable[β¦, str], optional): A custom json dumps function. Defaults to None. **kwargs (Any): Remaining arguments that are passed to the json encoder.
- Returns:
JSONResponse: A response object with body in json format.
- Parameters:
body (Any) β
status (int) β
headers (Dict[str, str] | None) β
content_type (str) β
dumps (Callable[[...], str] | None) β
kwargs (Any) β
- Return type:
- sanic.response.json_dumps()ο
Converts arbitrary object recursively into JSON. Use ensure_ascii=false to output UTF-8. Set encode_html_chars=True to encode < > & as unicode escape sequences. Set escape_forward_slashes=False to prevent escaping / characters.Set allow_nan=False to raise an exception when NaN or Infinity would be serialized.Set reject_bytes=True to raise TypeError on bytes.
- sanic.response.raw(body, status=200, headers=None, content_type='application/octet-stream')ο
Returns response object without encoding the body.
- Args:
body (Optional[AnyStr]): Response data. status (int, optional): HTTP response code. Defaults to 200. headers (Dict[str, str], optional): Custom HTTP headers. Defaults to None. content_type (str, optional): The content type (string) of the response. Defaults to βapplication/octet-streamβ.
- Returns:
HTTPResponse: A response object without encoding the body.
- Parameters:
body (AnyStr | None) β
status (int) β
headers (Dict[str, str] | None) β
content_type (str) β
- Return type:
- sanic.response.redirect(to, headers=None, status=302, content_type='text/html; charset=utf-8')ο
Cause a HTTP redirect (302 by default) by setting a Location header.
- Args:
to (str): path or fully qualified URL to redirect to headers (Optional[Dict[str, str]], optional): optional dict of headers to include in the new request. Defaults to None. status (int, optional): status code (int) of the new request, defaults to 302. Defaults to 302. content_type (str, optional): the content type (string) of the response. Defaults to βtext/html; charset=utf-8β.
- Returns:
HTTPResponse: A response object with the redirect.
- Parameters:
to (str) β
headers (Dict[str, str] | None) β
status (int) β
content_type (str) β
- Return type:
- sanic.response.text(body, status=200, headers=None, content_type='text/plain; charset=utf-8')ο
Returns response object with body in text format.
- Args:
body (str): Response data. status (int, optional): HTTP response code. Defaults to 200. headers (Dict[str, str], optional): Custom HTTP headers. Defaults to None. content_type (str, optional): The content type (string) of the response. Defaults to βtext/plain; charset=utf-8β.
- Returns:
HTTPResponse: A response object with body in text format.
- Raises:
TypeError: If the body is not a string.
- Parameters:
body (str) β
status (int) β
headers (Dict[str, str] | None) β
content_type (str) β
- Return type:
- async sanic.response.validate_file(request_headers, last_modified)ο
Validate file based on request headers.
- Args:
request_headers (Header): The request headers. last_modified (Union[datetime, float, int]): The last modified date and time of the file.
- Returns:
Optional[HTTPResponse]: A response object with status 304 if the file is not modified.
- Parameters:
request_headers (Header) β
last_modified (datetime | float | int) β
- Return type:
HTTPResponse | None
sanic.viewsο
- class sanic.views.HTTPMethodViewο
Bases:
object
Class based implementation for creating and grouping handlers
Class-based views (CBVs) are an alternative to function-based views. They allow you to reuse common logic, and group related views, while keeping the flexibility of function-based views.
To use a class-based view, subclass the method handler, and implement methods (get, post, put, patch, delete) for the class to correspond to each HTTP method you want to support.
For example:
```python class DummyView(HTTPMethodView):
- def get(self, request: Request):
return text(βI am get methodβ)
- def put(self, request: Request):
return text(βI am put methodβ)
If someone tries to use a non-implemented method, they will reveive a 405 response.
If you need any url params just include them in method signature, like you would for function-based views.
```python class DummyView(HTTPMethodView):
- def get(self, request: Request, my_param_here: str):
return text(fβI am get method with {my_param_here}β)
Next, you need to attach the view to the app or blueprint. You can do this in the exact same way as you would for a function-based view, except you should you use MyView.as_view() instead of my_view_handler.
`python app.add_route(DummyView.as_view(), "/<my_param_here>") `
Alternatively, you can use the attach method:
`python DummyView.attach(app, "/<my_param_here>") `
Or, at the time of subclassing:
```python class DummyView(HTTPMethodView, attach=app, uri=β/<my_param_here>β):
β¦
To add a decorator, you can either:
- Add it to the decorators list on the class, which will apply it to
all methods on the class; or
Add it to the method directly, which will only apply it to that method.
```python class DummyView(HTTPMethodView):
decorators = [my_decorator] β¦
# or
- class DummyView(HTTPMethodView):
@my_decorator def get(self, request: Request):
β¦
One catch is that you need to be mindful that the call inside the decorator may need to account for the self argument, which is passed to the method as the first argument. Alternatively, you may want to also mark your method as staticmethod to avoid this.
Available attributes at the time of subclassing: - attach (Optional[Union[Sanic, Blueprint]]): The app or blueprint to
attach the view to.
uri (str): The uri to attach the view to.
- methods (Iterable[str]): The HTTP methods to attach the view to.
Defaults to {βGETβ}.
host (Optional[str]): The host to attach the view to.
- strict_slashes (Optional[bool]): Whether to add a redirect rule for
the uri with a trailing slash.
version (Optional[int]): The version to attach the view to.
name (Optional[str]): The name to attach the view to.
stream (bool): Whether the view is a stream handler.
- version_prefix (str): The prefix to use for the version. Defaults
to β/vβ.
- classmethod as_view(*class_args, **class_kwargs)ο
Return view function for use with the routing system, that dispatches request to appropriate handler method.
If you need to pass arguments to the classβs constructor, you can pass the arguments to as_view and they will be passed to the class __init__ method.
- Args:
*class_args: Variable length argument list for the class instantiation. **class_kwargs: Arbitrary keyword arguments for the class instantiation.
- Returns:
RouteHandler: The view function.
- Examples:
```python class DummyView(HTTPMethodView):
- def __init__(self, foo: MyFoo):
self.foo = foo
- async def get(self, request: Request):
return text(self.foo.bar)
- Parameters:
class_args (Any) β
class_kwargs (Any) β
- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- classmethod attach(to, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, stream=False, version_prefix='/v')ο
Attaches the view to a Sanic app or Blueprint at the specified URI.
- Args:
cls: The class that this method is part of. to (Union[Sanic, Blueprint]): The Sanic application or Blueprint to attach to. uri (str): The URI to bind the view to. methods (Iterable[str], optional): A collection of HTTP methods that the view should respond to. Defaults to frozenset({βGETβ}). host (Optional[str], optional): A specific host or hosts to bind the view to. Defaults to None. strict_slashes (Optional[bool], optional): Enforce or not the trailing slash. Defaults to None. version (Optional[int], optional): Version of the API if versioning is used. Defaults to None. name (Optional[str], optional): Unique name for the route. Defaults to None. stream (bool, optional): Enable or disable streaming for the view. Defaults to False. version_prefix (str, optional): The prefix for the version, if versioning is used. Defaults to β/vβ.
- sanic.views.stream(func)ο
Decorator to mark a function as a stream handler.