📑 API Reference

sanic.app

class sanic.app.Sanic(name=None, router=None, signal_router=None, error_handler=None, load_env=True, request_class=None, strict_slashes=False, log_config=None, configure_logging=True, register=None, dumps=None)

Bases: sanic.base.BaseSanic

The main application instance

add_route(handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, stream=False)

A helper method to register class instance or functions as a handler to the application url routes.

Parameters
  • handler – function or class instance

  • uri (str) – path of the URL

  • methods (Iterable[str]) – list or tuple of methods allowed, these are overridden if using a HTTPMethodView

  • host (Optional[str]) –

  • strict_slashes (Optional[bool]) –

  • version (Optional[int]) –

  • name (Optional[str]) – user defined route name for url_for

  • stream (bool) – boolean specifying if the handler is a stream handler

Returns

function or class instance

add_task(task)

Schedule a task to run later, after the loop has started. Different from asyncio.ensure_future in that it does not also return a future, and the actual ensure_future call is delayed until before server start.

See user guide re: background tasks

Parameters

task – future, couroutine or awaitable

Return type

None

add_websocket_route(handler, uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None)

A helper method to register a function as a websocket route.

Parameters
  • handler – a callable function or instance of a class that can handle the websocket request

  • host (Optional[str]) – Host IP or FQDN details

  • uri (str) – URL path that will be mapped to the websocket handler handler

  • strict_slashes (Optional[bool]) – If the API endpoint needs to terminate with a “/” or not

  • subprotocols – Subprotocols to be used with websocket handshake

  • name (Optional[str]) – A unique name assigned to the URL so that it can be used with url_for()

  • version (Optional[int]) –

Returns

Objected decorated by websocket()

blueprint(blueprint, **options)

Register a blueprint on the application.

Parameters
  • blueprint – Blueprint object or (list, tuple) thereof

  • options – option dictionary with blueprint defaults

Returns

Nothing

async create_server(host=None, port=None, *, debug=False, ssl=None, sock=None, protocol=None, backlog=100, access_log=None, unix=None, return_asyncio_server=False, asyncio_server_kwargs=None)

Asynchronous version of run().

This method will take care of the operations necessary to invoke the before_start events via trigger_events() method invocation before starting the sanic app in Async mode.

Note

This does not support multiprocessing and is not the preferred way to run a Sanic application.

Parameters
  • host (str) – Address to host on

  • port (int) – Port to host on

  • debug (bool) – Enables debug output (slows server)

  • ssl (SSLContext or dict) – SSLContext, or location of certificate and key for SSL encryption of worker(s)

  • sock (socket) – Socket for the server to accept connections from

  • protocol (type[Protocol]) – Subclass of asyncio Protocol class

  • backlog (int) – a number of unaccepted connections that the system will allow before refusing new connections

  • access_log (bool) – Enables writing access logs (slows server)

  • return_asyncio_server (bool) – flag that defines whether there’s a need to return asyncio.Server or start it serving right away

  • asyncio_server_kwargs (dict) – key-value arguments for asyncio/uvloop create_server method

  • unix (Optional[str]) –

Returns

AsyncioServer if return_asyncio_server is true, else Nothing

Return type

Optional[sanic.server.AsyncioServer]

delete(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True)

Add an API URL under the DELETE HTTP method

Parameters
  • uri (str) – URL to be tagged to DELETE method of HTTP

  • host (Optional[str]) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool]) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[int]) – API Version

  • name (Optional[str]) – Unique name that can be used to identify the Route

  • ignore_body (bool) –

Returns

Object decorated with route() method

enable_websocket(enable=True)

Enable or disable the support for websocket.

Websocket is enabled automatically if websocket routes are added to the application.

exception(*exceptions, apply=True)

This method enables the process of creating a global exception handler for the current blueprint under question.

Parameters
  • args – List of Python exceptions to be caught by the handler

  • kwargs – Additional optional arguments to be passed to the exception handler

:return a decorated method to handle global exceptions for any

route registered under this blueprint.

get(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True)

Add an API URL under the GET HTTP method

Parameters
  • uri (str) – URL to be tagged to GET method of HTTP

  • host (Optional[str]) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool]) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[int]) – API Version

  • name (Optional[str]) – Unique name that can be used to identify the Route

  • ignore_body (bool) –

Returns

Object decorated with route() method

classmethod get_app(name=None, *, force_create=False)

Retrieve an instantiated Sanic instance

Parameters
  • name (Optional[str]) –

  • force_create (bool) –

Return type

sanic.app.Sanic

async handle_exception(request, exception)

A handler that catches specific exceptions and outputs a response.

Parameters
  • request (SanicASGITestClient) – The current request object

  • exception (BaseException) – The exception that was raised

Raises

ServerError – response 500

async handle_request(request)

Take a request from the HTTP Server and return a response object to be sent back The HTTP Server only expects a response object, so exception handling must be done here

Parameters
  • request (sanic.request.Request) – HTTP Request object

  • write_callback – Synchronous response function to be called with the response as the only argument

  • stream_callback – Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler.

Returns

Nothing

head(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True)

Add an API URL under the HEAD HTTP method

Parameters
  • uri (str) – URL to be tagged to HEAD method of HTTP

  • host (Optional[str], optional) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool], optional) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[str], optional) – API Version

  • name (Optional[str], optional) – Unique name that can be used to identify the Route

  • ignore_body (bool, optional) – whether the handler should ignore request body (eg. GET requests), defaults to True

Returns

Object decorated with route() method

listener(listener_or_event, event_or_none=None, apply=True)

Create a listener from a decorated function.

To be used as a deocrator:

@bp.listener("before_server_start")
async def before_server_start(app, loop):
    ...

See user guide re: listeners

Parameters
  • event – event to listen to

  • listener_or_event (Union[Callable[[..], Coroutine[Any, Any, None]], str]) –

  • event_or_none (Optional[str]) –

  • apply (bool) –

middleware(middleware_or_request, attach_to='request', apply=True)

Decorate and register middleware to be called before a request. Can either be called as @app.middleware or @app.middleware(‘request’)

See user guide re: middleware

Param

middleware_or_request: Optional parameter to use for identifying which type of middleware is being registered.

options(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True)

Add an API URL under the OPTIONS HTTP method

Parameters
  • uri (str) – URL to be tagged to OPTIONS method of HTTP

  • host (Optional[str], optional) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool], optional) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[str], optional) – API Version

  • name (Optional[str], optional) – Unique name that can be used to identify the Route

  • ignore_body (bool, optional) – whether the handler should ignore request body (eg. GET requests), defaults to True

Returns

Object decorated with route() method

patch(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)

Add an API URL under the PATCH HTTP method

Parameters
  • uri (str) – URL to be tagged to PATCH method of HTTP

  • host (Optional[str], optional) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool], optional) – Instruct Sanic to check if the request URLs need to terminate with a /

  • stream (Optional[bool], optional) – whether to allow the request to stream its body

  • version (Optional[str], optional) – API Version

  • name (Optional[str], optional) – Unique name that can be used to identify the Route

  • ignore_body (bool, optional) – whether the handler should ignore request body (eg. GET requests), defaults to True

Returns

Object decorated with route() method

post(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)

Add an API URL under the POST HTTP method

Parameters
  • uri (str) – URL to be tagged to POST method of HTTP

  • host (Optional[str]) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool]) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[int]) – API Version

  • name (Optional[str]) – Unique name that can be used to identify the Route

  • stream (bool) –

Returns

Object decorated with route() method

put(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)

Add an API URL under the PUT HTTP method

Parameters
  • uri (str) – URL to be tagged to PUT method of HTTP

  • host (Optional[str]) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool]) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[int]) – API Version

  • name (Optional[str]) – Unique name that can be used to identify the Route

  • stream (bool) –

Returns

Object decorated with route() method

classmethod register_app(app)

Register a Sanic instance

Parameters

app (sanic.app.Sanic) –

Return type

None

register_listener(listener, event)

Register the listener for a given event.

Parameters
  • listener (Callable) – callable i.e. setup_db(app, loop)

  • event (str) – when to register listener i.e. ‘before_server_start’

Returns

listener

Return type

Any

register_middleware(middleware, attach_to='request')

Register an application level middleware that will be attached to all the API URLs registered under this application.

This method is internally invoked by the middleware() decorator provided at the app level.

Parameters
  • middleware – Callback method to be attached to the middleware

  • attach_to (str) – The state at which the middleware needs to be invoked in the lifecycle of an HTTP Request. request - Invoke before the request is processed response - Invoke before the response is returned back

Returns

decorated method

register_named_middleware(middleware, route_names, attach_to='request')

Method for attaching middleware to specific routes. This is mainly an internal tool for use by Blueprints to attach middleware to only its specfic routes. But, it could be used in a more generalized fashion.

Parameters
  • middleware – the middleware to execute

  • route_names (Iterable[str]) – a list of the names of the endpoints

  • attach_to (str, optional) – whether to attach to request or response, defaults to “request”

route(uri, methods=None, host=None, strict_slashes=None, stream=False, version=None, name=None, ignore_body=False, apply=True, subprotocols=None, websocket=False, unquote=False, static=False)

Decorate a function to be registered as a route

Parameters
  • uri (str) – path of the URL

  • methods (Optional[Iterable[str]]) – list or tuple of methods allowed

  • host (Optional[str]) – the host, if required

  • strict_slashes (Optional[bool]) – whether to apply strict slashes to the route

  • stream (bool) – whether to allow the request to stream its body

  • version (Optional[Union[int, str, float]]) – route specific versioning

  • name (Optional[str]) – user defined route name for url_for

  • ignore_body (bool) – whether the handler should ignore request body (eg. GET requests)

  • apply (bool) –

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

  • websocket (bool) –

  • unquote (bool) –

  • static (bool) –

Returns

tuple of routes, decorated function

run(host=None, port=None, *, debug=False, auto_reload=None, ssl=None, sock=None, workers=1, protocol=None, backlog=100, register_sys_signals=True, access_log=None, unix=None, loop=None)

Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing.

Parameters
  • host (str) – Address to host on

  • port (int) – Port to host on

  • debug (bool) – Enables debug output (slows server)

  • auto_reload (Optional[bool]) – Reload app whenever its source code is changed. Enabled by default in debug mode.

  • ssl (SSLContext or dict) – SSLContext, or location of certificate and key for SSL encryption of worker(s)

  • sock (socket) – Socket for the server to accept connections from

  • workers (int) – Number of processes received before it is respected

  • protocol (type[Protocol]) – Subclass of asyncio Protocol class

  • backlog (int) – a number of unaccepted connections that the system will allow before refusing new connections

  • register_sys_signals (bool) – Register SIG* events

  • access_log (bool) – Enables writing access logs (slows server)

  • unix (str) – Unix socket to listen on instead of TCP port

  • loop (None) –

Returns

Nothing

Return type

None

signal(event, *, apply=True, condition=None)

For creating a signal handler, used similar to a route handler:

@app.signal("foo.bar.<thing>")
async def signal_handler(thing, **kwargs):
    print(f"[signal_handler] {thing=}", kwargs)
Parameters
  • event (str) – Representation of the event in one.two.three form

  • apply (bool, optional) – For lazy evaluation, defaults to True

  • condition (Dict[str, Any], optional) – For use with the condition argument in dispatch filtering, defaults to None

Return type

Callable[[Callable[[..], Coroutine[Any, Any, None]]], sanic.models.futures.FutureSignal]

static(uri, file_or_directory, pattern='/?.+', use_modified_since=True, use_content_range=False, stream_large_files=False, name='static', host=None, strict_slashes=None, content_type=None, apply=True)

Register a root to serve files from. The input can either be a file or a directory. This method will enable an easy and simple way to setup the Route necessary to serve the static files.

Parameters
  • uri – URL path to be used for serving static content

  • file_or_directory (Union[str, bytes, pathlib.PurePath]) – Path for the Static file/directory with static files

  • pattern – Regex Pattern identifying the valid static files

  • use_modified_since – If true, send file modified time, and return not modified if the browser’s matches the server’s

  • use_content_range – If true, process header for range requests and sends the file part that is requested

  • stream_large_files – If true, use the StreamingHTTPResponse.file_stream() handler rather than the HTTPResponse.file() handler to send the file. If this is an integer, this represents the threshold size to switch to StreamingHTTPResponse.file_stream()

  • name – user defined name used for url_for

  • host – Host IP or FQDN for the service to use

  • strict_slashes – Instruct Sanic to check if the request URLs need to terminate with a /

  • content_type – user defined content type for header

Returns

routes registered on the router

Return type

List[sanic.router.Route]

stop()

This kills the Sanic

async trigger_events(events, loop)

Trigger events (functions or async) :param events: one or more sync or async functions to execute :param loop: event loop

update_config(config)

Update app.config. Full implementation can be found in the user guide.

See user guide re: configuration

Parameters

config (Union[bytes, str, dict, Any]) –

url_for(view_name, **kwargs)

Build a URL based on a view name and the values provided.

In order to build a URL, all request parameters must be supplied as keyword arguments, and each parameter must pass the test for the specified parameter type. If these conditions are not met, a URLBuildError will be thrown.

Keyword arguments that are not request parameters will be included in the output URL’s query string.

There are several _special_ keyword arguments that will alter how the URL will be returned:

  1. _anchor: str - Adds an #anchor to the end

  2. _scheme: str - Should be either "http" or "https", default is "http"

  3. _external: bool - Whether to return the path or a full URL with scheme and host

  4. _host: str - Used when one or more hosts are defined for a route to tell Sanic which to use (only applies with _external=True)

  5. _server: str - If not using _host, this will be used for defining the hostname of the URL (only applies with _external=True), defaults to app.config.SERVER_NAME

If you want the PORT to appear in your URL, you should set it in:

app.config.SERVER_NAME = "myserver:7777"

See user guide re: routing

Parameters
  • view_name (str) – string referencing the view name

  • kwargs – keys and values that are used to build request parameters and query string arguments.

Returns

the built URL

Raises:

URLBuildError

websocket(uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None, apply=True)

Decorate a function to be registered as a websocket route

Parameters
  • uri (str) – path of the URL

  • host (Optional[str]) – Host IP or FQDN details

  • strict_slashes (Optional[bool]) – If the API endpoint needs to terminate with a “/” or not

  • subprotocols (Optional[List[str]]) – optional list of str with supported subprotocols

  • name (Optional[str]) – A unique name assigned to the URL so that it can be used with url_for()

  • version (Optional[int]) –

  • apply (bool) –

Returns

tuple of routes, decorated function

property asgi_client

A testing client that uses ASGI to reach into the application to execute hanlers.

Returns

testing client

Return type

SanicASGITestClient

property loop

Synonymous with asyncio.get_event_loop().

Note

Only supported when using the app.run method.

sanic.blueprints

class sanic.blueprints.Blueprint(name, url_prefix=None, host=None, version=None, strict_slashes=None)

Bases: sanic.base.BaseSanic

In Sanic terminology, a Blueprint is a logical collection of URLs that perform a specific set of tasks which can be identified by a unique name.

It is the main tool for grouping functionality and similar endpoints.

See user guide re: blueprints

Parameters
  • name – unique name of the blueprint

  • url_prefix – URL to be prefixed before all route URLs

  • host – IP Address of FQDN for the sanic server to use.

  • version – Blueprint Version

  • strict_slashes – Enforce the API urls are requested with a training /

add_route(handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, stream=False)

A helper method to register class instance or functions as a handler to the application url routes.

Parameters
  • handler – function or class instance

  • uri (str) – path of the URL

  • methods (Iterable[str]) – list or tuple of methods allowed, these are overridden if using a HTTPMethodView

  • host (Optional[str]) –

  • strict_slashes (Optional[bool]) –

  • version (Optional[int]) –

  • name (Optional[str]) – user defined route name for url_for

  • stream (bool) – boolean specifying if the handler is a stream handler

Returns

function or class instance

add_websocket_route(handler, uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None)

A helper method to register a function as a websocket route.

Parameters
  • handler – a callable function or instance of a class that can handle the websocket request

  • host (Optional[str]) – Host IP or FQDN details

  • uri (str) – URL path that will be mapped to the websocket handler handler

  • strict_slashes (Optional[bool]) – If the API endpoint needs to terminate with a “/” or not

  • subprotocols – Subprotocols to be used with websocket handshake

  • name (Optional[str]) – A unique name assigned to the URL so that it can be used with url_for()

  • version (Optional[int]) –

Returns

Objected decorated by websocket()

delete(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True)

Add an API URL under the DELETE HTTP method

Parameters
  • uri (str) – URL to be tagged to DELETE method of HTTP

  • host (Optional[str]) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool]) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[int]) – API Version

  • name (Optional[str]) – Unique name that can be used to identify the Route

  • ignore_body (bool) –

Returns

Object decorated with route() method

exception(*args, **kwargs)

This method enables the process of creating a global exception handler for the current blueprint under question.

Parameters
  • args – List of Python exceptions to be caught by the handler

  • kwargs – Additional optional arguments to be passed to the exception handler

:return a decorated method to handle global exceptions for any

route registered under this blueprint.

get(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True)

Add an API URL under the GET HTTP method

Parameters
  • uri (str) – URL to be tagged to GET method of HTTP

  • host (Optional[str]) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool]) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[int]) – API Version

  • name (Optional[str]) – Unique name that can be used to identify the Route

  • ignore_body (bool) –

Returns

Object decorated with route() method

static group(*blueprints, url_prefix='', version=None, strict_slashes=None)

Create a list of blueprints, optionally grouping them under a general URL prefix.

Parameters
  • blueprints – blueprints to be registered as a group

  • url_prefix – URL route to be prepended to all sub-prefixes

  • version – API Version to be used for Blueprint group

  • strict_slashes – Indicate strict slash termination behavior for URL

head(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True)

Add an API URL under the HEAD HTTP method

Parameters
  • uri (str) – URL to be tagged to HEAD method of HTTP

  • host (Optional[str], optional) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool], optional) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[str], optional) – API Version

  • name (Optional[str], optional) – Unique name that can be used to identify the Route

  • ignore_body (bool, optional) – whether the handler should ignore request body (eg. GET requests), defaults to True

Returns

Object decorated with route() method

listener(*args, **kwargs)

Create a listener from a decorated function.

To be used as a deocrator:

@bp.listener("before_server_start")
async def before_server_start(app, loop):
    ...

See user guide re: listeners

Parameters

event – event to listen to

middleware(*args, **kwargs)

Decorate and register middleware to be called before a request. Can either be called as @app.middleware or @app.middleware(‘request’)

See user guide re: middleware

Param

middleware_or_request: Optional parameter to use for identifying which type of middleware is being registered.

options(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True)

Add an API URL under the OPTIONS HTTP method

Parameters
  • uri (str) – URL to be tagged to OPTIONS method of HTTP

  • host (Optional[str], optional) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool], optional) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[str], optional) – API Version

  • name (Optional[str], optional) – Unique name that can be used to identify the Route

  • ignore_body (bool, optional) – whether the handler should ignore request body (eg. GET requests), defaults to True

Returns

Object decorated with route() method

patch(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)

Add an API URL under the PATCH HTTP method

Parameters
  • uri (str) – URL to be tagged to PATCH method of HTTP

  • host (Optional[str], optional) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool], optional) – Instruct Sanic to check if the request URLs need to terminate with a /

  • stream (Optional[bool], optional) – whether to allow the request to stream its body

  • version (Optional[str], optional) – API Version

  • name (Optional[str], optional) – Unique name that can be used to identify the Route

  • ignore_body (bool, optional) – whether the handler should ignore request body (eg. GET requests), defaults to True

Returns

Object decorated with route() method

post(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)

Add an API URL under the POST HTTP method

Parameters
  • uri (str) – URL to be tagged to POST method of HTTP

  • host (Optional[str]) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool]) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[int]) – API Version

  • name (Optional[str]) – Unique name that can be used to identify the Route

  • stream (bool) –

Returns

Object decorated with route() method

put(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)

Add an API URL under the PUT HTTP method

Parameters
  • uri (str) – URL to be tagged to PUT method of HTTP

  • host (Optional[str]) – Host IP or FQDN for the service to use

  • strict_slashes (Optional[bool]) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (Optional[int]) – API Version

  • name (Optional[str]) – Unique name that can be used to identify the Route

  • stream (bool) –

Returns

Object decorated with route() method

register(app, options)

Register the blueprint to the sanic app.

Parameters
  • app – Instance of sanic.app.Sanic class

  • options – Options to be used while registering the blueprint into the app. url_prefix - URL Prefix to override the blueprint prefix

route(*args, **kwargs)

Decorate a function to be registered as a route

Parameters
  • uri – path of the URL

  • methods – list or tuple of methods allowed

  • host – the host, if required

  • strict_slashes – whether to apply strict slashes to the route

  • stream – whether to allow the request to stream its body

  • version – route specific versioning

  • name – user defined route name for url_for

  • ignore_body – whether the handler should ignore request body (eg. GET requests)

Returns

tuple of routes, decorated function

signal(event, *args, **kwargs)

For creating a signal handler, used similar to a route handler:

@app.signal("foo.bar.<thing>")
async def signal_handler(thing, **kwargs):
    print(f"[signal_handler] {thing=}", kwargs)
Parameters
  • event (str) – Representation of the event in one.two.three form

  • apply (bool, optional) – For lazy evaluation, defaults to True

  • condition (Dict[str, Any], optional) – For use with the condition argument in dispatch filtering, defaults to None

static(*args, **kwargs)

Register a root to serve files from. The input can either be a file or a directory. This method will enable an easy and simple way to setup the Route necessary to serve the static files.

Parameters
  • uri – URL path to be used for serving static content

  • file_or_directory – Path for the Static file/directory with static files

  • pattern – Regex Pattern identifying the valid static files

  • use_modified_since – If true, send file modified time, and return not modified if the browser’s matches the server’s

  • use_content_range – If true, process header for range requests and sends the file part that is requested

  • stream_large_files – If true, use the StreamingHTTPResponse.file_stream() handler rather than the HTTPResponse.file() handler to send the file. If this is an integer, this represents the threshold size to switch to StreamingHTTPResponse.file_stream()

  • name – user defined name used for url_for

  • host – Host IP or FQDN for the service to use

  • strict_slashes – Instruct Sanic to check if the request URLs need to terminate with a /

  • content_type – user defined content type for header

Returns

routes registered on the router

Return type

List[sanic.router.Route]

websocket(uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None, apply=True)

Decorate a function to be registered as a websocket route

Parameters
  • uri (str) – path of the URL

  • host (Optional[str]) – Host IP or FQDN details

  • strict_slashes (Optional[bool]) – If the API endpoint needs to terminate with a “/” or not

  • subprotocols (Optional[List[str]]) – optional list of str with supported subprotocols

  • name (Optional[str]) – A unique name assigned to the URL so that it can be used with url_for()

  • version (Optional[int]) –

  • apply (bool) –

Returns

tuple of routes, decorated function

sanic.blueprint_group

class sanic.blueprint_group.BlueprintGroup(url_prefix=None, version=None, strict_slashes=None)

This class provides a mechanism to implement a Blueprint Group using the group() method in Blueprint. To avoid having to re-write some of the existing implementation, this class provides a custom iterator implementation that will let you use the object of this class as a list/tuple inside the existing implementation.

bp1 = Blueprint('bp1', url_prefix='/bp1')
bp2 = Blueprint('bp2', url_prefix='/bp2')

bp3 = Blueprint('bp3', url_prefix='/bp4')
bp3 = Blueprint('bp3', url_prefix='/bp4')

bpg = BlueprintGroup(bp3, bp4, url_prefix="/api", version="v1")

@bp1.middleware('request')
async def bp1_only_middleware(request):
    print('applied on Blueprint : bp1 Only')

@bp1.route('/')
async def bp1_route(request):
    return text('bp1')

@bp2.route('/<param>')
async def bp2_route(request, param):
    return text(param)

@bp3.route('/')
async def bp1_route(request):
    return text('bp1')

@bp4.route('/<param>')
async def bp2_route(request, param):
    return text(param)

group = Blueprint.group(bp1, bp2)

@group.middleware('request')
async def group_middleware(request):
    print('common middleware applied for both bp1 and bp2')

# Register Blueprint group under the app
app.blueprint(group)
app.blueprint(bpg)
__delitem__(index)

Abstract method implemented to turn the BlueprintGroup class into a list like object to support all the existing behavior.

This method is used to delete an item from the list of blueprint groups like it can be done on a regular list with index.

Parameters

index – Index to use for removing a new Blueprint item

Returns

None

Return type

None

__getitem__(item)

This method returns a blueprint inside the group specified by an index value. This will enable indexing, splice and slicing of the blueprint group like we can do with regular list/tuple.

This method is provided to ensure backward compatibility with any of the pre-existing usage that might break.

Parameters

item – Index of the Blueprint item in the group

Returns

Blueprint object

__init__(url_prefix=None, version=None, strict_slashes=None)

Create a new Blueprint Group

Parameters
  • url_prefix (Optional[str]) – URL: to be prefixed before all the Blueprint Prefix

  • version (Optional[Union[int, str, float]]) – API Version for the blueprint group. This will be inherited by each of the Blueprint

  • strict_slashes (Optional[bool]) – URL Strict slash behavior indicator

__iter__()

Tun the class Blueprint Group into an Iterable item

__len__()

Get the Length of the blueprint group object.

Returns

Length of Blueprint group object

Return type

int

__setitem__(index, item)

Abstract method implemented to turn the BlueprintGroup class into a list like object to support all the existing behavior.

This method is used to perform the list’s indexed setter operation.

Parameters
  • index – Index to use for inserting a new Blueprint item

  • item – New Blueprint object.

Returns

None

Return type

None

append(value)

The Abstract class MutableSequence leverages this append method to perform the BlueprintGroup.append operation. :param value: New Blueprint object. :return: None

Parameters

value (sanic.blueprints.Blueprint) –

Return type

None

insert(index, item)

The Abstract class MutableSequence leverages this insert method to perform the BlueprintGroup.append operation.

Parameters
Returns

None

Return type

None

middleware(*args, **kwargs)

A decorator that can be used to implement a Middleware plugin to all of the Blueprints that belongs to this specific Blueprint Group.

In case of nested Blueprint Groups, the same middleware is applied across each of the Blueprints recursively.

Parameters
  • args – Optional positional Parameters to be use middleware

  • kwargs – Optional Keyword arg to use with Middleware

Returns

Partial function to apply the middleware

property blueprints

Retrieve a list of all the available blueprints under this group.

Returns

List of Blueprint instance

property strict_slashes

URL Slash termination behavior configuration

Returns

bool

property url_prefix

Retrieve the URL prefix being used for the Current Blueprint Group

Returns

string with url prefix

property version

API Version for the Blueprint Group. This will be applied only in case if the Blueprint doesn’t already have a version specified

Returns

Version information

sanic.compat

class sanic.compat.Header

Bases: multidict._multidict.CIMultiDict

Container used for both request and response headers. It is a subclass of CIMultiDict.

It allows for multiple values for a single key in keeping with the HTTP spec. Also, all keys are case in-sensitive.

Please checkout the MultiDict documentation for more details about how to use the object. In general, it should work very similar to a regular dictionary.

get_all(key)

Convenience method mapped to getall().

Parameters

key (str) –

sanic.config

class sanic.config.Config(defaults=None, load_env=True, keep_alive=None)

Bases: dict

load(config)

Update app.config.

Note

Only upper case settings are considered

You can upload app config by providing path to py file holding settings.

# /some/py/file
A = 1
B = 2
config.update_config("${some}/py/file")

Yes you can put environment variable here, but they must be provided in format: ${some_env_var}, and mark that $some_env_var is treated as plain string.

You can upload app config by providing dict holding settings.

d = {"A": 1, "B": 2}
config.update_config(d)

You can upload app config by providing any object holding settings, but in such case config.__dict__ will be used as dict holding settings.

class C:
    A = 1
    B = 2

config.update_config(C)

See user guide re: config

Parameters

config (Union[bytes, str, dict, Any]) –

load_environment_vars(prefix='SANIC_')

Looks for prefixed environment variables and applies them to the configuration if present. This is called automatically when Sanic starts up to load environment variables into config.

It will automatically hyrdate the following types:

  • int

  • float

  • bool

Anything else will be imported as a str.

update_config(config)

Update app.config.

Note

Only upper case settings are considered

You can upload app config by providing path to py file holding settings.

# /some/py/file
A = 1
B = 2
config.update_config("${some}/py/file")

Yes you can put environment variable here, but they must be provided in format: ${some_env_var}, and mark that $some_env_var is treated as plain string.

You can upload app config by providing dict holding settings.

d = {"A": 1, "B": 2}
config.update_config(d)

You can upload app config by providing any object holding settings, but in such case config.__dict__ will be used as dict holding settings.

class C:
    A = 1
    B = 2

config.update_config(C)

See user guide re: config

Parameters

config (Union[bytes, str, dict, Any]) –

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

Sanic provides a pattern for providing a response when an exception occurs. However, if you do no handle an exception, it will provide a fallback. There are three fallback types:

  • HTML - default

  • Text

  • JSON

Setting app.config.FALLBACK_ERROR_FORMAT = "auto" will enable a switch that will attempt to provide an appropriate response format based upon the request type.

class sanic.errorpages.BaseRenderer(request, exception, debug)

Bases: object

Base class that all renderers must inherit from.

full()

Provide a formatted message that has all details and is mean to be used primarily for debugging and non-production environments.

Return type

sanic.response.HTTPResponse

minimal()

Provide a formatted message that is meant to not show any sensitive data or details.

Return type

sanic.response.HTTPResponse

render()

Outputs the exception as a HTTPResponse.

Returns

The formatted exception

Return type

str

class sanic.errorpages.HTMLRenderer(request, exception, debug)

Bases: sanic.errorpages.BaseRenderer

Render an exception as HTML.

The default fallback type.

full()

Provide a formatted message that has all details and is mean to be used primarily for debugging and non-production environments.

Return type

sanic.response.HTTPResponse

minimal()

Provide a formatted message that is meant to not show any sensitive data or details.

Return type

sanic.response.HTTPResponse

class sanic.errorpages.JSONRenderer(request, exception, debug)

Bases: sanic.errorpages.BaseRenderer

Render an exception as JSON.

full()

Provide a formatted message that has all details and is mean to be used primarily for debugging and non-production environments.

Return type

sanic.response.HTTPResponse

minimal()

Provide a formatted message that is meant to not show any sensitive data or details.

Return type

sanic.response.HTTPResponse

class sanic.errorpages.TextRenderer(request, exception, debug)

Bases: sanic.errorpages.BaseRenderer

Render an exception as plain text.

full()

Provide a formatted message that has all details and is mean to be used primarily for debugging and non-production environments.

Return type

sanic.response.HTTPResponse

minimal()

Provide a formatted message that is meant to not show any sensitive data or details.

Return type

sanic.response.HTTPResponse

sanic.errorpages.escape(text)

Minimal HTML escaping, not for attribute values (unlike html.escape).

sanic.errorpages.exception_response(request, exception, debug, renderer=None)

Render a response for the default FALLBACK exception handler.

Parameters
Return type

sanic.response.HTTPResponse

sanic.exceptions

exception sanic.exceptions.ContentRangeError(message, content_range)

Bases: sanic.exceptions.SanicException

Status: 416 Range Not Satisfiable

exception sanic.exceptions.FileNotFound(message, path, relative_url)

Bases: sanic.exceptions.NotFound

Status: 404 Not Found

exception sanic.exceptions.Forbidden(message, status_code=None, quiet=None)

Bases: sanic.exceptions.SanicException

Status: 403 Forbidden

exception sanic.exceptions.HeaderExpectationFailed(message, status_code=None, quiet=None)

Bases: sanic.exceptions.SanicException

Status: 417 Expectation Failed

exception sanic.exceptions.HeaderNotFound(message, status_code=None, quiet=None)

Bases: sanic.exceptions.InvalidUsage

Status: 400 Bad Request

exception sanic.exceptions.InvalidRangeType(message, content_range)

Bases: sanic.exceptions.ContentRangeError

Status: 416 Range Not Satisfiable

exception sanic.exceptions.InvalidSignal(message, status_code=None, quiet=None)

Bases: sanic.exceptions.SanicException

exception sanic.exceptions.InvalidUsage(message, status_code=None, quiet=None)

Bases: sanic.exceptions.SanicException

Status: 400 Bad Request

exception sanic.exceptions.LoadFileException(message, status_code=None, quiet=None)

Bases: sanic.exceptions.SanicException

exception sanic.exceptions.MethodNotSupported(message, method, allowed_methods)

Bases: sanic.exceptions.SanicException

Status: 405 Method Not Allowed

exception sanic.exceptions.NotFound(message, status_code=None, quiet=None)

Bases: sanic.exceptions.SanicException

Status: 404 Not Found

exception sanic.exceptions.PayloadTooLarge(message, status_code=None, quiet=None)

Bases: sanic.exceptions.SanicException

Status: 413 Payload Too Large

exception sanic.exceptions.PyFileError(file)

Bases: Exception

exception sanic.exceptions.RequestTimeout(message, status_code=None, quiet=None)

Bases: sanic.exceptions.SanicException

The Web server (running the Web site) thinks that there has been too long an interval of time between 1) the establishment of an IP connection (socket) between the client and the server and 2) the receipt of any data on that socket, so the server has dropped the connection. The socket connection has actually been lost - the Web server has ‘timed out’ on that particular socket connection.

exception sanic.exceptions.SanicException(message, status_code=None, quiet=None)

Bases: Exception

exception sanic.exceptions.ServerError(message, status_code=None, quiet=None)

Bases: sanic.exceptions.SanicException

Status: 500 Internal Server Error

exception sanic.exceptions.ServiceUnavailable(message, status_code=None, quiet=None)

Bases: sanic.exceptions.SanicException

Status: 503 Service Unavailable

The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.

exception sanic.exceptions.URLBuildError(message, status_code=None, quiet=None)

Bases: sanic.exceptions.ServerError

Status: 500 Internal Server Error

exception sanic.exceptions.Unauthorized(message, status_code=None, scheme=None, **kwargs)

Bases: sanic.exceptions.SanicException

Status: 401 Unauthorized

Parameters
  • message – Message describing the exception.

  • status_code – HTTP Status code.

  • scheme – Name of the authentication scheme to be used.

When present, kwargs is used to complete the WWW-Authentication header.

Examples:

# With a Basic auth-scheme, realm MUST be present:
raise Unauthorized("Auth required.",
                   scheme="Basic",
                   realm="Restricted Area")

# With a Digest auth-scheme, things are a bit more complicated:
raise Unauthorized("Auth required.",
                   scheme="Digest",
                   realm="Restricted Area",
                   qop="auth, auth-int",
                   algorithm="MD5",
                   nonce="abcdef",
                   opaque="zyxwvu")

# With a Bearer auth-scheme, realm is optional so you can write:
raise Unauthorized("Auth required.", scheme="Bearer")

# or, if you want to specify the realm:
raise Unauthorized("Auth required.",
                   scheme="Bearer",
                   realm="Restricted Area")
sanic.exceptions.abort(status_code, message=None)

Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided.

STATUS_CODES from sanic.helpers for the given status code.

Parameters
  • status_code (int) – The HTTP status code to return.

  • message (Optional[Union[str, bytes]]) – The HTTP response body. Defaults to the messages in

sanic.exceptions.add_status_code(code, quiet=None)

Decorator used for adding exceptions to SanicException.

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

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.

add(exception, handler)

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

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

log(message, level='error')

Deprecated, do not use.

lookup(exception)

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 or Exception) – Type of exception

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

class sanic.http.Http(protocol)

Bases: object

Internal helper for managing the HTTP request/response cycle

Raises
create_empty_request()

Current error handling code needs a request object that won’t exist if an error occurred during before a request was received. Create a bogus response for error handling use.

Return type

None

async error_response(exception)

Handle response when exception encountered

Parameters

exception (Exception) –

Return type

None

head_response_ignored(data, end_stream)

HEAD response: body data silently ignored.

Parameters
  • data (bytes) –

  • end_stream (bool) –

Return type

None

async http1()

HTTP 1.1 connection handler

async http1_request_header()

Receive and parse request header into self.request.

async http1_response_chunked(data, end_stream)

Format a part of response body in chunked encoding.

Parameters
  • data (bytes) –

  • end_stream (bool) –

Return type

None

async http1_response_normal(data, end_stream)

Format / keep track of non-chunked response.

Parameters
  • data (bytes) –

  • end_stream (bool) –

Return type

None

log_response()

Helper method provided to enable the logging of responses in case if the HttpProtocol.access_log is enabled.

Return type

None

async read()

Read some bytes of request body.

Return type

Optional[bytes]

respond(response)

Initiate new streaming response.

Nothing is sent until the first send() call on the returned object, and calling this function multiple times will just alter the response to be given.

Parameters

response (BaseHTTPResponse) –

Return type

BaseHTTPResponse

class sanic.http.Stage(value)

Bases: enum.Enum

Enum for representing the stage of the request/response cycle

IDLE Waiting for request
REQUEST Request headers being received
HANDLER Headers done, handler running
RESPONSE Response headers sent, body in progress
FAILED Unrecoverable state (error while sending response)

sanic.log

sanic.log.access_logger = <Logger sanic.access (WARNING)>

Logger used by Sanic for access logging

sanic.log.error_logger = <Logger sanic.error (WARNING)>

Logger used by Sanic for error logging

sanic.log.logger = <Logger sanic.root (WARNING)>

General Sanic logger

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 – The mimetype, defaults to text/plain

  • body – Bytes of the file

  • name – 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.

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

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
Returns

Content-Type header form the request

Return type

str

property cookies
Returns

Incoming cookies on the request

Return type

Dict[str, str]

property forwarded

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

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

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
Returns

peer ip of the socket

Return type

str

property match_info
Returns

matched info after resolving route

property path
Returns

path of the local HTTP request

Return type

str

property port
Returns

peer port of the socket

Return type

int

property query_args

Convenience property to access Request.get_query_args() with default values.

property query_string
Returns

representation of the requested query

Return type

str

property remote_addr

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

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
Returns

hostname the client connected to, by request.host

Return type

str

property server_path
Returns

full path of current URL; uses proxied or local path

Return type

str

property server_port

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

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

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', chunked='deprecated')

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.6. 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
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, chunked='deprecated', _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', chunked='deprecated')

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

class sanic.router.Router(delimiter='/', exception=<class 'sanic_routing.exceptions.NotFound'>, method_handler_exception=<class 'sanic_routing.exceptions.NoMethod'>, route_class=<class 'sanic_routing.route.Route'>, group_class=<class 'sanic_routing.group.RouteGroup'>, stacking=False, cascade_not_found=False)

Bases: sanic_routing.router.BaseRouter

The router implementation responsible for routing a Request object to the appropriate handler.

add(uri, methods, handler, host=None, strict_slashes=False, stream=False, ignore_body=False, version=None, name=None, unquote=False, static=False)

Add a handler to the router

Parameters
  • uri (str) – the path of the route

  • methods (Iterable[str]) – the types of HTTP methods that should be attached, example: ["GET", "POST", "OPTIONS"]

  • handler (RouteHandler) – the sync or async function to be executed

  • host (Optional[str], optional) – host that the route should be on, defaults to None

  • strict_slashes (bool, optional) – whether to apply strict slashes, defaults to False

  • stream (bool, optional) – whether to stream the response, defaults to False

  • ignore_body (bool, optional) – whether the incoming request body should be read, defaults to False

  • version (Union[str, float, int], optional) – a version modifier for the uri, defaults to None

  • name (Optional[str], optional) – an identifying name of the route, defaults to None

  • unquote (bool) –

  • static (bool) –

Returns

the route object

Return type

Route

find_route_by_view_name(view_name, name=None)

Find a route in the router based on the specified view name.

Parameters
  • view_name – string of view name to search by

  • kwargs – additional params, usually for static files

Returns

tuple containing (uri, Route)

get(path, method, host)

Retrieve a Route object containg the details about how to handle a response for a given request

Parameters
  • request (Request) – the incoming request object

  • path (str) –

  • method (str) –

  • host (Optional[str]) –

Returns

details needed for handling the request and returning the correct response

Return type

Tuple[ Route, RouteHandler, Dict[str, Any]]

sanic.server

class sanic.server.AsyncioServer(loop, serve_coro, connections, after_start, before_stop, after_stop)

Bases: object

Wraps an asyncio server with functionality that might be useful to a user who needs to manage the server lifecycle manually.

after_start()

Trigger “after_server_start” events

after_stop()

Trigger “after_server_stop” events

before_stop()

Trigger “before_server_stop” events

class sanic.server.ConnInfo(transport, unix=None)

Bases: object

Local and remote addresses and SSL status info.

class sanic.server.HttpProtocol(*, loop, app, signal=None, connections=None, state=None, unix=None, **kwargs)

Bases: asyncio.protocols.Protocol

This class provides a basic HTTP implementation of the sanic framework.

check_timeouts()

Runs itself periodically to enforce any expired timeouts.

close()

Force close the connection.

close_if_idle()

Close the connection if a request is not being sent or received

Returns

boolean - True if closed, false if staying open

Return type

bool

connection_lost(exc)

Called when the connection is lost or closed.

The argument is an exception object or None (the latter meaning a regular EOF is received or the connection was aborted or closed).

connection_made(transport)

Called when a connection is made.

The argument is the transport representing the pipe connection. To receive data, wait for data_received() calls. When the connection is closed, connection_lost() is called.

async connection_task()

Run a HTTP connection.

Timeouts and some additional error handling occur here, while most of everything else happens in class Http or in code called from there.

data_received(data)

Called when some data is received.

The argument is a bytes object.

Parameters

data (bytes) –

pause_writing()

Called when the transport’s buffer goes over the high-water mark.

Pause and resume calls are paired – pause_writing() is called once when the buffer goes strictly over the high-water mark (even if subsequent writes increases the buffer size even more), and eventually resume_writing() is called once when the buffer size reaches the low-water mark.

Note that if the buffer size equals the high-water mark, pause_writing() is not called – it must go strictly over. Conversely, resume_writing() is called when the buffer size is equal or lower than the low-water mark. These end conditions are important to ensure that things go as expected when either mark is zero.

NOTE: This is the only Protocol callback that is not called through EventLoop.call_soon() – if it were, it would have no effect when it’s most needed (when the app keeps writing without yielding until pause_writing() is called).

async receive_more()

Wait until more data is received into the Server protocol’s buffer

resume_writing()

Called when the transport’s buffer drains below the low-water mark.

See pause_writing() for details.

async send(data)

Writes data with backpressure control.

sanic.server.bind_socket(host, port, *, backlog=100)

Create TCP server socket. :param host: IPv4, IPv6 or hostname may be specified :param port: TCP port number :param backlog: Maximum number of connections to queue :return: socket.socket object

Parameters
  • host (str) –

  • port (int) –

Return type

socket.socket

sanic.server.bind_unix_socket(path, *, mode=438, backlog=100)

Create unix socket. :param path: filesystem path :param backlog: Maximum number of connections to queue :return: socket.socket object

Parameters

path (str) –

Return type

socket.socket

sanic.server.remove_unix_socket(path)

Remove dead unix socket during server exit.

Parameters

path (Optional[str]) –

Return type

None

sanic.server.serve(host, port, app, before_start=None, after_start=None, before_stop=None, after_stop=None, ssl=None, sock=None, unix=None, reuse_port=False, loop=None, protocol=<class 'sanic.server.HttpProtocol'>, backlog=100, register_sys_signals=True, run_multiple=False, run_async=False, connections=None, signal=<sanic.server.Signal object>, state=None, asyncio_server_kwargs=None)

Start asynchronous HTTP Server on an individual process.

Parameters
  • host – Address to host on

  • port – Port to host on

  • before_start (Optional[Iterable[Callable[[Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]]]) – function to be executed before the server starts listening. Takes arguments app instance and loop

  • after_start (Optional[Iterable[Callable[[Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]]]) – function to be executed after the server starts listening. Takes arguments app instance and loop

  • before_stop (Optional[Iterable[Callable[[Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]]]) – function to be executed when a stop signal is received before it is respected. Takes arguments app instance and loop

  • after_stop (Optional[Iterable[Callable[[Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]]]) – function to be executed when a stop signal is received after it is respected. Takes arguments app instance and loop

  • ssl (Optional[ssl.SSLContext]) – SSLContext

  • sock (Optional[socket.socket]) – Socket for the server to accept connections from

  • unix (Optional[str]) – Unix socket to listen on instead of TCP port

  • reuse_port (bool) – True for multiple workers

  • loop – asyncio compatible event loop

  • run_async (bool) – bool: Do not create a new event loop for the server, and return an AsyncServer object rather than running it

  • asyncio_server_kwargs – key-value args for asyncio/uvloop create_server method

  • protocol (Type[asyncio.protocols.Protocol]) –

  • backlog (int) –

  • register_sys_signals (bool) –

  • run_multiple (bool) –

Returns

Nothing

sanic.server.serve_multiple(server_settings, workers)

Start multiple server processes simultaneously. Stop on interrupt and terminate signals, and drain connections when complete.

Parameters
  • server_settings – kw arguments to be passed to the serve function

  • workers – number of workers to launch

  • stop_event – if provided, is used as a stop signal

Returns

sanic.server.trigger_events(events, loop)

Trigger event callbacks (functions or async)

Parameters
  • events (Optional[Iterable[Callable[[..], Any]]]) – one or more sync or async functions to execute

  • loop – event loop

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.

sanic.websocket

exception sanic.websocket.ConnectionClosed(code, reason)

Bases: websockets.exceptions.WebSocketException

Raised when trying to interact with a closed connection.

Provides the connection close code and reason in its code and reason attributes respectively.

Parameters
  • code (int) –

  • reason (str) –

Return type

None

class sanic.websocket.WebSocketProtocol(*args, websocket_timeout=10, websocket_max_size=None, websocket_max_queue=None, websocket_read_limit=65536, websocket_write_limit=65536, websocket_ping_interval=20, websocket_ping_timeout=20, **kwargs)

Bases: sanic.server.HttpProtocol

connection_lost(exc)

Called when the connection is lost or closed.

The argument is an exception object or None (the latter meaning a regular EOF is received or the connection was aborted or closed).

data_received(data)

Called when some data is received.

The argument is a bytes object.

sanic.worker