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(fallback='auto', base=<class 'sanic.errorpages.HTMLRenderer'>)ο
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
fallback (str) β
base (Type[sanic.errorpages.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 (Optional[List[str]]) β
- 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 (Optional[str]) β
- 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.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'')ο
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 using urllib.parse.parse_qs. This methods is used by 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
RequestParameters
- Return type
- 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.
- 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 args: sanic.request.RequestParametersο
Method to parse query_string using urllib.parse.parse_qs. This methods is used by 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
RequestParameters
- 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 forwarded: Dict[str, Union[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: Optional[Union[uuid.UUID, str, int]]ο
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 match_infoο
- Returns
matched info after resolving route
- 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 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 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 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 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 tokenο
Attempt to return the auth header token.
- Returns
token related to request
- 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 (Optional[Any]) β
- Return type
Optional[Any]
- getlist(name, default=None)ο
Return the entire list
- Parameters
name (str) β
default (Optional[Any]) β
- Return type
Optional[Any]
- 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 (Optional[AnyStr]) β str or bytes to be written
end_stream (Optional[bool]) β whether to close the stream after this block
- Return type
None
- property cookies: sanic.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
- 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:
sanic.response.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.StreamingHTTPResponse(streaming_fn, status=200, headers=None, content_type='text/plain; charset=utf-8', ignore_deprecation_notice=False)ο
Bases:
sanic.response.BaseHTTPResponse
Old style streaming response where you pass a streaming function:
async def sample_streaming_fn(response): await response.write("foo") await asyncio.sleep(1) await response.write("bar") await asyncio.sleep(1) @app.post("/") async def test(request): return stream(sample_streaming_fn)
Warning
Deprecated and set for removal in v21.12. You can now achieve the same functionality without a callback.
@app.post("/") async def test(request): response = await request.respond() await response.send("foo", False) await asyncio.sleep(1) await response.send("bar", False) await asyncio.sleep(1) await response.send("", True) return response
- Parameters
streaming_fn (Callable[[sanic.response.BaseHTTPResponse], Coroutine[Any, Any, None]]) β
status (int) β
headers (Optional[Union[sanic.compat.Header, Dict[str, str]]]) β
content_type (str) β
ignore_deprecation_notice (bool) β
- async send(*args, **kwargs)ο
Send any pending response headers and the given data as body.
- Parameters
data β str or bytes to be written
end_stream β whether to close the stream after this block
- async write(data)ο
Writes a chunk of data to the streaming response.
- Parameters
data β str or bytes-ish data to be written.
- sanic.response.empty(status=204, headers=None)ο
Returns an empty response to the client.
:param status Response code. :param headers Custom Headers.
- Parameters
headers (Optional[Dict[str, str]]) β
- Return type
- async sanic.response.file(location, status=200, mime_type=None, headers=None, filename=None, _range=None)ο
Return a response object with file data.
- Parameters
location (Union[str, pathlib.PurePath]) β Location of file on system.
mime_type (Optional[str]) β Specific mime_type.
headers (Optional[Dict[str, str]]) β Custom Headers.
filename (Optional[str]) β Override filename.
_range (Optional[sanic.models.protocol_types.Range]) β
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 (Union[str, pathlib.PurePath]) β Location of file on system.
chunk_size (int) β The size of each chunk in the stream (in bytes)
mime_type (Optional[str]) β Specific mime_type.
headers (Optional[Dict[str, str]]) β Custom Headers.
filename (Optional[str]) β Override filename.
chunked β Deprecated
_range (Optional[sanic.models.protocol_types.Range]) β
status (int) β
- Return type
- sanic.response.html(body, status=200, headers=None)ο
Returns response object with body in html format.
- Parameters
body (Union[str, bytes, sanic.models.protocol_types.HTMLProtocol]) β str or bytes-ish, or an object with __html__ or _repr_html_.
status (int) β Response code.
headers (Optional[Dict[str, str]]) β 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 (Optional[Dict[str, str]]) β Custom Headers.
kwargs β Remaining arguments that are passed to the json encoder.
content_type (str) β
dumps (Optional[Callable[[...], str]]) β
- Return type
- sanic.response.raw(body, status=200, headers=None, content_type='application/octet-stream')ο
Returns response object without encoding the body.
- Parameters
body (Optional[AnyStr]) β Response data.
status (int) β Response code.
headers (Optional[Dict[str, str]]) β 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 (Optional[Dict[str, str]]) β 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.stream(streaming_fn, status=200, headers=None, content_type='text/plain; charset=utf-8')ο
Accepts an coroutine streaming_fn which can be used to write chunks to a streaming response. Returns a StreamingHTTPResponse.
Example usage:
@app.route("/") async def index(request): async def streaming_fn(response): await response.write('foo') await response.write('bar') return stream(streaming_fn, content_type='text/plain')
- Parameters
streaming_fn (Callable[[sanic.response.BaseHTTPResponse], Coroutine[Any, Any, None]]) β A coroutine accepts a response and writes content to that response.
mime_type β Specific mime_type.
headers (Optional[Dict[str, str]]) β Custom Headers.
chunked β Deprecated
status (int) β
content_type (str) β
- 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 (Optional[Dict[str, str]]) β Custom Headers.
content_type (str) β the content type (string) of the response
- Return type
sanic.viewsο
- class sanic.views.CompositionViewο
Bases:
object
Simple method-function mapped view for the sanic. You can add handler functions to methods (get, post, put, patch, delete) for every HTTP method you want to support.
For example:
view = CompositionView() view.add(['GET'], lambda request: text('I am get method')) view.add(['POST', 'PUT'], lambda request: text('I am post/put method'))
If someone tries to use a non-implemented method, there will be a 405 response.
- 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, Optional[sanic.response.HTTPResponse]]]