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.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)
- 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.
@param mimes: Any MIME types to search for in order of preference. @param accept_wildcards: Match Accept entries with wildcards in them. @return 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.
- Parameters:
mime (str) β
header (Optional[MediaType]) β
- class sanic.headers.MediaType(type_, subtype, **params)ο
Bases:
object
A media type, as used in the Accept header.
- Parameters:
type_ (str) β
subtype (str) β
params (str) β
- match(mime_with_params)ο
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. @param media_type: A type/subtype string to match. @return self if the media types are compatible, else None
- property has_wildcard: boolο
Return True if this media type has a wildcard in it.
- 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 according to RFC 7231, s. 5.3.2 https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2
- 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.
- 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: 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:
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: RequestParametersο
- 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
- 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
- Parameters:
key (str) β Key of the cookie
value (str) β Value of the cookie
path (Optional[str], optional) β Path of the cookie, defaults to None
domain (Optional[str], optional) β Domain of the cookie, defaults to None
secure (bool) β Whether to set it as a secure cookie, defaults to True
max_age (Optional[int], optional) β Max age of the cookie in seconds; if set to 0 a browser should delete it, defaults to None
expires (Optional[datetime], optional) β When the cookie expires; if set to None browsers should set it as a session cookie, defaults to None
httponly (bool) β Whether to set it as HTTP only, defaults to False
samesite (Optional[SameSite], optional) β How to set the samesite property, should be strict, lax or none (case insensitive), defaults to Lax
partitioned (bool) β Whether to set it as partitioned, defaults to False
comment (Optional[str], optional) β A cookie comment, 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
- Returns:
The instance of the created cookie
- 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.
- Parameters:
key (str) β The key to be deleted
path (Optional[str], optional) β Path of the cookie, defaults to None
domain (Optional[str], optional) β 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
- Return type:
None
- 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]]