Core¶
sanic.handlers¶
- class sanic.handlers.ContentRangeHandler(request, stats)¶
Bases:
object
A mechanism to parse and process the incoming request headers to extract the content range information.
- Parameters:
request (
sanic.request.Request
) – Incoming api requeststats (
posix.stat_result
) – Stats related to the content
- Variables:
start – Content Range start
end – Content Range end
size – Length of the content
total – Total size identified by the
posix.stat_result
instanceContentRangeHandler.headers – Content range header
dict
- class sanic.handlers.ErrorHandler(base=<class 'sanic.errorpages.TextRenderer'>)¶
Bases:
object
Provide
sanic.app.Sanic
application with a mechanism to handle and process any and all uncaught exceptions in a way the application developer will set fit.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.
- Parameters:
base (Type[BaseRenderer]) –
- add(exception, handler, route_names=None)¶
Add a new exception handler to an already existing handler object.
- Parameters:
exception (
sanic.exceptions.SanicException
orException
) – Type of exception that need to be handledhandler (
function
) – Reference to the method that will handle the exceptionroute_names (List[str] | None) –
- Returns:
None
- default(request, exception)¶
Provide a default behavior for the objects of
ErrorHandler
. If a developer chooses to extent theErrorHandler
they can provide a custom implementation for this method to behave in a way they see fit.- Parameters:
request (
sanic.request.Request
) – Incoming requestexception (
sanic.exceptions.SanicException
orException
) – Exception object
- Returns:
- 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.
- Parameters:
exception (
sanic.exceptions.SanicException
orException
) – Type of exceptionroute_name (str | None) –
- Returns:
Registered function if found
None
otherwise
- response(request, exception)¶
Fetches and executes an exception handler and returns a response object
- Parameters:
request (
sanic.request.Request
) – Instance ofsanic.request.Request
exception (
sanic.exceptions.SanicException
orException
) – Exception to handle
- Returns:
Wrap the return value obtained from
default()
or registered handler for that type of exception.
sanic.headers¶
- class sanic.headers.Accept(value, *args, **kwargs)¶
Bases:
str
- Parameters:
value (str) –
- class sanic.headers.AcceptContainer(iterable=(), /)¶
Bases:
list
- class sanic.headers.MediaType(value)¶
Bases:
str
- Parameters:
value (str) –
- sanic.headers.format_http1_response(status, headers)¶
Format a HTTP/1.1 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.
- Parameters:
fwd (Iterable[Tuple[str, str]]) –
- Return type:
Dict[str, int | str]
- sanic.headers.fwd_normalize_address(addr)¶
Normalize address fields of proxy headers.
- Parameters:
addr (str) –
- Return type:
str
- sanic.headers.parse_accept(accept)¶
Parse an Accept header and order the acceptable media types in accorsing to RFC 7231, s. 5.3.2 https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2
- Parameters:
accept (str) –
- 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 quotes.
- 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.
- 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. :return: None in place of missing elements
- 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.- Parameters:
type (str) – The mimetype, defaults to text/plain
body (bytes) – Bytes of the file
name (str) – The filename
- 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:
object
Properties of an HTTP request such as URL, headers, etc.
- Parameters:
- get_args(keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')¶
Method to parse
query_string
usingurllib.parse.parse_qs
. This methods is used byargs
property. Can be used directly if you need to change default parameters.- Parameters:
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
- Return type:
- classmethod get_current()¶
Retrieve the current request object
This implements Context Variables to allow for accessing the current request from anywhere.
Raises
sanic.exceptions.ServerError
if it is outside of a request lifecycle.from sanic import Request current_request = Request.get_current()
- Returns:
the current
sanic.request.Request
- Return type:
- get_form(keep_blank_values=False)¶
Method to extract and parse the form data from a request.
- Parameters:
keep_blank_values (bool) – Whether to discard blank values from the form data
- Returns:
the parsed form data
- Return type:
Optional[RequestParameters]
- get_query_args(keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')¶
Method to parse query_string using urllib.parse.parse_qsl. This methods is used by query_args property. Can be used directly if you need to change default parameters.
- Parameters:
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
- Return type:
list
- 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.
- 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:
@app.get("/") async def handler(request: Request): data = ... # Process something json_response = json({"data": data}) await request.respond(json_response) # You are now free to continue executing other code ... @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:
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()
- Parameters:
response (BaseHTTPResponse | None) – response instance to send
status (int) – status code to return in the response
headers (Header | Dict[str, str] | None) – headers to return in the response
content_type (str | None) – Content-Type header of the response
- Returns:
final response being sent (may be different from the
response
parameter because of middlewares) which can be used to manually send data
- url_for(view_name, **kwargs)¶
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.- Parameters:
kwargs – takes same parameters as in
sanic.Sanic.url_for()
view_name (str) –
- Returns:
an absolute url to the given view
- Return type:
str
- property accept: AcceptContainer¶
- Returns:
The
Accept
header parsed- Return type:
- property args: RequestParameters¶
Convenience property to access
Request.get_args()
with default values.
- property content_type: str¶
- Returns:
Content-Type header form the request
- Return type:
str
- property cookies: Dict[str, str]¶
- Returns:
Incoming cookies on the request
- Return type:
Dict[str, str]
- property credentials: Credentials | None¶
Attempt to return the auth header value.
Covers NoAuth, Basic Auth, Bearer Token, Api Token authentication schemas.
- Returns:
A Credentials object with token, or username and password related to the request
- property endpoint: str | None¶
- Returns:
Alias of
sanic.request.Request.name
- Return type:
Optional[str]
- property files¶
- Returns:
The request body parsed as uploaded files
- property form¶
- Returns:
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:
forwarded address info
- Return type:
Dict[str, str]
- property host: str¶
The currently effective server ‘host’ (hostname or hostname:port). 1. config.SERVER_NAME overrides any client headers 2. proxied host of original request 3. request host header hostname and port may be separated by sanic.headers.parse_host(request.host).
- Returns:
the first matching host found, or empty string
- Return type:
str
- 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 toX-Request-ID
. Sanic will try to cast the ID into aUUID
or anint
. If there is not a UUID from the client, then Sanic will try to generate an ID by callingRequest.generate_id()
. The default behavior is to generate aUUID
. You can customize this behavior by subclassingRequest
.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)
- property ip: str¶
- Returns:
peer ip of the socket
- Return type:
str
- property is_cacheable: bool¶
- Returns:
Whether the HTTP method is cacheable. See https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.3
- Return type:
bool
- property is_idempotent: bool¶
- Returns:
Whether the HTTP method is iempotent. See https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.2
- Return type:
bool
- property is_safe: bool¶
- Returns:
Whether the HTTP method is safe. See https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.1
- Return type:
bool
- property json: Any¶
- Returns:
The request body parsed as JSON
- Return type:
Any
- property match_info¶
- Returns:
matched info after resolving route
- property name: str | None¶
The route name
In the following pattern:
<AppName>.[<BlueprintName>.]<HandlerName>
- Returns:
Route name
- Return type:
Optional[str]
- property network_paths¶
Access the network paths if available
- property path: str¶
- Returns:
path of the local HTTP request
- Return type:
str
- property port: int¶
- Returns:
peer port of the socket
- Return type:
int
- property protocol¶
- Returns:
The HTTP protocol instance
- property query_args: list¶
Convenience property to access
Request.get_query_args()
with default values.
- property query_string: str¶
- Returns:
representation of the requested query
- Return type:
str
- property raw_headers: bytes¶
- Returns:
The unparsed HTTP headers
- Return type:
bytes
- property remote_addr: str¶
Client IP address, if available. 1. proxied remote address self.forwarded[‘for’] 2. local remote address self.ip
- Returns:
IPv4, bracketed IPv6, UNIX socket name or arbitrary string
- Return type:
str
- property request_line: bytes¶
- Returns:
The first line of a HTTP request
- Return type:
bytes
- property scheme: str¶
Determine request scheme. 1. config.SERVER_NAME if in full URL format 2. proxied proto/scheme 3. local connection protocol
- Returns:
http|https|ws|wss or arbitrary value given by the headers.
- Return type:
str
- property scope: MutableMapping[str, Any]¶
- Returns:
The ASGI scope of the request. If the app isn’t an ASGI app, then raises an exception.
- Return type:
Optional[ASGIScope]
- property server_name: str¶
- Returns:
hostname the client connected to, by
request.host
- Return type:
str
- property server_path: str¶
- Returns:
full path of current URL; uses proxied or local path
- Return type:
str
- property server_port: int¶
The port the client connected to, by forwarded
port
orrequest.host
.Default port is returned as 80 and 443 based on
request.scheme
.- Returns:
port number
- Return type:
int
- property socket¶
- Returns:
Information about the connected socket if available
- property stream_id¶
Access the HTTP/3 stream ID.
Raises
sanic.exceptions.ServerError
if it is not an HTTP/3 request.
- property token: str | None¶
Attempt to return the auth header token.
- Returns:
token related to request
- property uri_template: str | None¶
- Returns:
The defined URI template
- Return type:
Optional[str]
- property url: str¶
- Returns:
the URL
- Return type:
str
- 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
- Parameters:
name (str) –
default (Any | None) –
- Return type:
Any | None
- getlist(name, default=None)¶
Return 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
- Parameters:
body – bytes request body
boundary – bytes multipart boundary
- Returns:
fields (RequestParameters), files (RequestParameters)
sanic.response¶
- class sanic.response.BaseHTTPResponse¶
Bases:
object
The base class for all HTTP Responses
- async send(data=None, end_stream=None)¶
Send any pending response headers and the given data as body.
- Parameters:
data (AnyStr | None) – str or bytes to be written
end_stream (bool | None) – whether to close the stream after this block
- Return type:
None
- property cookies: CookieJar¶
The response cookies. Cookies should be set and written as follows:
response.cookies["test"] = "It worked!" response.cookies["test"]["domain"] = ".yummy-yummy-cookie.com" response.cookies["test"]["httponly"] = True
See user guide re: cookies <https://sanic.dev/en/guide/basics/cookies.html>
- Returns:
the cookie jar
- Return type:
- 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:
response headers
- Return type:
Tuple[Tuple[bytes, bytes], …]
- class sanic.response.HTTPResponse(body=None, status=200, headers=None, content_type=None)¶
Bases:
BaseHTTPResponse
HTTP response to be sent back to the client.
- Parameters:
body (Optional[bytes]) – the body content to be returned
status (int) – HTTP response number. Default=200
headers (Optional;) – headers to be returned
content_type (Optional[str]) – content type to be returned (as a header)
- class sanic.response.JSONResponse(body=None, status=200, headers=None, content_type=None, dumps=None, **kwargs)¶
Bases:
HTTPResponse
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
status (int) – HTTP response number. Default=200
headers (Optional) – headers to be returned
content_type (Optional[str]) – content type to be returned (as a header)
dumps (Optional[Callable]) – json.dumps function to use
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.
- 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.
- Parameters:
value (Any) –
- Return type:
None
- pop(key, default=<sanic.helpers.Default object>)¶
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.
- Parameters:
key (Any) –
default (Any) –
- Return type:
Any
- set_body(body, dumps=None, **dumps_kwargs)¶
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) –
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.
- Return type:
None
- 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.
- class sanic.response.ResponseStream(streaming_fn, status=200, headers=None, content_type=None)¶
Bases:
object
ResponseStream is 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.
:param status Response code. :param headers Custom Headers.
- 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=<sanic.helpers.Default object>, max_age=None, no_store=None, _range=None)¶
Return a response object with file data. :param status: 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).
- Parameters:
request_headers (Header | None) – The request headers.
validate_when_requested (bool) – If True, will validate the file when requested.
location (str | PurePath) – Location of file on system.
mime_type (str | None) – Specific mime_type.
headers (Dict[str, str] | None) – Custom Headers.
filename (str | None) – Override filename.
last_modified (datetime | float | int | Default | None) – The last modified date and time of the file.
max_age (float | int | None) – Max age for cache control.
no_store (bool | None) – Any cache should not store this response.
_range (Range | None) –
status (int) –
- 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:
- sanic.response.html(body, status=200, headers=None)¶
Returns response object with body in html format.
- Parameters:
body (str | bytes | HTMLProtocol) – str or bytes-ish, or an object with __html__ or _repr_html_.
status (int) – Response code.
headers (Dict[str, str] | None) – Custom Headers.
- 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.
- Parameters:
body (Any) – Response data to be serialized.
status (int) – Response code.
headers (Dict[str, str] | None) – Custom Headers.
kwargs (Any) – Remaining arguments that are passed to the json encoder.
content_type (str) –
dumps (Callable[[...], str] | None) –
- 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.
- Parameters:
body (AnyStr | None) – Response data.
status (int) – Response code.
headers (Dict[str, str] | None) – Custom Headers.
content_type (str) – the content type (string) of the response.
- Return type:
- sanic.response.redirect(to, headers=None, status=302, content_type='text/html; charset=utf-8')¶
Abort execution and cause a 302 redirect (by default) by setting a Location header.
- Parameters:
to (str) – path or fully qualified URL to redirect to
headers (Dict[str, str] | None) – optional dict of headers to include in the new request
status (int) – status code (int) of the new request, defaults to 302
content_type (str) – the content type (string) of the response
- 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.
- Parameters:
body (str) – Response data to be encoded.
status (int) – Response code.
headers (Dict[str, str] | None) – Custom Headers.
content_type (str) – the content type (string) of the response
- Return type:
sanic.views¶
- class sanic.views.HTTPMethodView¶
Bases:
object
Simple class based implementation of view for the sanic. You should implement methods (get, post, put, patch, delete) for the class to every HTTP method you want to support.
For example:
class DummyView(HTTPMethodView): def get(self, request, *args, **kwargs): return text('I am get method') def put(self, request, *args, **kwargs): return text('I am put method')
If someone tries to use a non-implemented method, there will be a 405 response.
If you need any url params just mention them in method definition:
class DummyView(HTTPMethodView): def get(self, request, my_param_here, *args, **kwargs): return text('I am get method with %s' % my_param_here)
To add the view into the routing you could use
app.add_route(DummyView.as_view(), '/')
, ORapp.route('/')(DummyView.as_view())
To add any decorator you could set it into decorators variable
- classmethod as_view(*class_args, **class_kwargs)¶
Return view function for use with the routing system, that dispatches request to appropriate handler method.
- Parameters:
class_args (Any) –
class_kwargs (Any) –
- Return type:
Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]