Core

sanic.cookies

class sanic.cookies.Cookie(key, value)

Bases: dict

A stripped down version of Morsel from SimpleCookie #gottagofast

encode(encoding)

Encode the cookie content in a specific type of encoding instructed by the developer. Leverages the str.encode() method provided by python.

This method can be used to encode and embed utf-8 content into the cookies.

Parameters

encoding – Encoding to be used with the cookie

Returns

Cookie encoded in a codec of choosing.

Except

UnicodeEncodeError

class sanic.cookies.CookieJar(headers)

Bases: dict

CookieJar dynamically writes headers as cookies are added and removed It gets around the limitation of one header per name by using the MultiHeader class to provide a unique key that encodes to Set-Cookie.

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 request

  • stats (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 instance

  • ContentRangeHandler.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
add(exception, handler, route_names=None)

Add a new exception handler to an already existing handler object.

Parameters
  • exception (sanic.exceptions.SanicException or Exception) – Type of exception that need to be handled

  • handler (function) – Reference to the method that will handle the exception

  • route_names (Optional[List[str]]) –

Returns

None

default(request, exception)

Provide a default behavior for the objects of ErrorHandler. If a developer chooses to extent the ErrorHandler they can provide a custom implementation for this method to behave in a way they see fit.

Parameters
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
Returns

Registered function if found None otherwise

response(request, exception)

Fetches and executes an exception handler and returns a response object

Parameters
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
  • url_bytes (bytes) –

  • headers (Header) –

  • version (str) –

  • method (str) –

  • transport (TransportProtocol) –

  • app (Sanic) –

  • head (bytes) –

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

sanic.request.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.

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 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.

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 or request.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

See user guide re: cookies

Returns

the cookie jar

Return type

CookieJar

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

sanic.response.HTTPResponse

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

sanic.response.HTTPResponse

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.StreamingHTTPResponse

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.HTTPResponse

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.HTTPResponse

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.HTTPResponse

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.HTTPResponse

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.response.HTTPResponse

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

  1. app.add_route(DummyView.as_view(), '/'), OR

  2. app.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]]]

sanic.websocket