Application

sanic.app

class sanic.app.Sanic(name=None, config=None, ctx=None, router=None, signal_router=None, error_handler=None, load_env=True, env_prefix='SANIC_', request_class=None, strict_slashes=False, log_config=None, configure_logging=True, register=None, dumps=None)

Bases: sanic.base.BaseSanic

The main application instance

Parameters
  • name (str) –

  • config (Optional[Config]) –

  • ctx (Optional[Any]) –

  • router (Optional[Router]) –

  • signal_router (Optional[SignalRouter]) –

  • error_handler (Optional[ErrorHandler]) –

  • load_env (Union[bool, str]) –

  • env_prefix (Optional[str]) –

  • request_class (Optional[Type[Request]]) –

  • strict_slashes (bool) –

  • log_config (Optional[Dict[str, Any]]) –

  • configure_logging (bool) –

  • register (Optional[bool]) –

  • dumps (Optional[Callable[..., AnyStr]]) –

Return type

None

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

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

Parameters
  • handler (Callable[[...], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]) – 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

  • version_prefix (str) – URL path that should be before the version value; default: /v

  • error_format (Optional[str]) –

Returns

function or class instance

Return type

Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]

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 (Union[Future[Any], Coroutine[Any, Any, Any], Awaitable[Any]]) – future, couroutine or awaitable

Return type

None

add_websocket_route(handler, uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None, version_prefix='/v', error_format=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_prefix (str) – URL path that should be before the version value; default: /v

  • version (Optional[int]) –

  • error_format (Optional[str]) –

Returns

Objected decorated by websocket()

blueprint(blueprint, **options)

Register a blueprint on the application.

Parameters
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.async_server.AsyncioServer]

delete(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None)

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

  • version_prefix (str) – URL path that should be before the version value; default: /v

  • ignore_body (bool) –

  • error_format (Optional[str]) –

Returns

Object decorated with route() method

Return type

Callable[[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]], Union[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]], Tuple[sanic_routing.route.Route, Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]]]]

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, version_prefix='/v', error_format=None)

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

  • version_prefix (str) – URL path that should be before the version value; default: /v

  • ignore_body (bool) –

  • error_format (Optional[str]) –

Returns

Object decorated with route() method

Return type

Callable[[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]], Union[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]], Tuple[sanic_routing.route.Route, Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]]]]

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

Retrieve an instantiated Sanic instance

Parameters
  • name (Optional[str]) –

  • force_create (bool) –

Return type

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

Returns

Nothing

head(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None)

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

  • version_prefix (str) – URL path that should be before the version value; default: /v

  • error_format (Optional[str]) –

Returns

Object decorated with route() method

Return type

Callable[[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]], Union[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]], Tuple[sanic_routing.route.Route, Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]]]]

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

Create a listener from a decorated function.

To be used as a decorator:

@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[[sanic.models.handler_types.Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]], str]) –

  • event_or_none (Optional[str]) –

  • apply (bool) –

Return type

Callable[[sanic.models.handler_types.Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]

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, version_prefix='/v', error_format=None)

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

  • version_prefix (str) – URL path that should be before the version value; default: /v

  • error_format (Optional[str]) –

Returns

Object decorated with route() method

Return type

Callable[[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]], Union[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]], Tuple[sanic_routing.route.Route, Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]]]]

patch(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=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

  • version_prefix (str) – URL path that should be before the version value; default: /v

  • error_format (Optional[str]) –

Returns

Object decorated with route() method

Return type

Callable[[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]], Union[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]], Tuple[sanic_routing.route.Route, Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]]]]

post(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=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

  • version_prefix (str) – URL path that should be before the version value; default: /v

  • stream (bool) –

  • error_format (Optional[str]) –

Returns

Object decorated with route() method

Return type

Callable[[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]], Union[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]], Tuple[sanic_routing.route.Route, Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]]]]

put(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=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

  • version_prefix (str) – URL path that should be before the version value; default: /v

  • stream (bool) –

  • error_format (Optional[str]) –

Returns

Object decorated with route() method

Return type

Callable[[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]], Union[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]], Tuple[sanic_routing.route.Route, Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]]]]

classmethod register_app(app)

Register a Sanic instance

Parameters

app (Sanic) –

Return type

None

register_listener(listener, event)

Register the listener for a given event.

Parameters
  • listener (Callable[[sanic.models.handler_types.Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]) – callable i.e. setup_db(app, loop)

  • event (str) – when to register listener i.e. β€˜before_server_start’

Returns

listener

Return type

Callable[[sanic.models.handler_types.Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]

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
Returns

decorated method

Return type

Union[Callable[[sanic.request.Request], Union[sanic.response.HTTPResponse, None, Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]], Callable[[sanic.request.Request, sanic.response.BaseHTTPResponse], Union[sanic.response.HTTPResponse, None, Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]]]

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
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, version_prefix='/v', error_format=None)

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)

  • version_prefix (str) – URL path that should be before the version value; default: /v

  • apply (bool) –

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

  • websocket (bool) –

  • unquote (bool) –

  • static (bool) –

  • error_format (Optional[str]) –

Returns

tuple of routes, decorated function

Return type

Callable[[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]], Union[Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]], Tuple[sanic_routing.route.Route, Callable[[…], Coroutine[Any, Any, Optional[sanic.response.HTTPResponse]]]]]]

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, reload_dir=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) –

  • reload_dir (Optional[Union[List[str], str]]) –

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]]], Callable[[…], Coroutine[Any, Any, None]]]

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, resource_type=None)

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

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, version_prefix='/v', error_format=None)

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_prefix (str) – URL path that should be before the version value; default: /v

  • version (Optional[int]) –

  • apply (bool) –

  • error_format (Optional[str]) –

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

class sanic.config.Config(defaults=None, load_env=True, env_prefix='SANIC_', keep_alive=None)

Bases: dict

Parameters
  • defaults (Dict[str, Optional[Union[str, bool, int, float]]]) –

  • load_env (Optional[Union[bool, str]]) –

  • env_prefix (Optional[str]) –

  • keep_alive (Optional[bool]) –

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]) –