ApplicationΒΆ

sanic.appΒΆ

class sanic.app.Sanic(name=None, config=None, ctx=None, router=None, signal_router=None, error_handler=None, env_prefix='SANIC_', request_class=None, strict_slashes=False, log_config=None, configure_logging=True, dumps=None, loads=None, inspector=False, inspector_class=None)ΒΆ

Bases: StaticHandleMixin, BaseSanic, StartupMixin

The main application instance

Parameters:
  • name (Optional[str]) –

  • config (Optional[Config]) –

  • ctx (Optional[Any]) –

  • router (Optional[Router]) –

  • signal_router (Optional[SignalRouter]) –

  • error_handler (Optional[ErrorHandler]) –

  • env_prefix (Optional[str]) –

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

  • strict_slashes (bool) –

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

  • configure_logging (bool) –

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

  • loads (Optional[Callable[..., Any]]) –

  • inspector (bool) –

  • inspector_class (Optional[Type[Inspector]]) –

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

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

Parameters:
  • handler (Callable[[...], Coroutine[Any, Any, HTTPResponse | None]]) – 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 (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • version (int | str | float | None) –

  • name (str | None) – 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

  • ctx_kwargs (Any) – Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx)

  • error_format (str | None) –

  • unquote (bool) –

Returns:

function or class instance

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

add_task(task, *, name=None, register=True)ΒΆ

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, coroutine or awaitable

  • name (Optional[str]) –

  • register (bool) –

Return type:

Optional[Task[Any]]

add_websocket_route(handler, uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ΒΆ

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 (str | List[str] | None) – Host IP or FQDN details

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

  • strict_slashes (bool | None) – If the API endpoint needs to terminate with a β€œ/” or not

  • subprotocols – Subprotocols to be used with websocket handshake

  • name (str | None) – 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

  • ctx_kwargs (Any) – Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx)

  • version (int | str | float | None) –

  • error_format (str | None) –

Returns:

Objected decorated by websocket()

blueprint(blueprint, **options)ΒΆ

Register a blueprint on the application.

Parameters:
  • blueprint (Blueprint | Iterable[Blueprint] | BlueprintGroup) – Blueprint object or (list, tuple) thereof

  • options (Any) – 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, noisy_exceptions=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

  • noisy_exceptions (bool) – Log exceptions that are normally considered to be quiet/silent

  • unix (str | None) –

Returns:

AsyncioServer if return_asyncio_server is true, else Nothing

Return type:

AsyncioServer | None

delete(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None, **ctx_kwargs)ΒΆ

Add an API URL under the DELETE HTTP method

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

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

  • strict_slashes (bool | None) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (int | str | float | None) – API Version

  • name (str | None) – Unique name that can be used to identify the Route

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

  • ctx_kwargs (Any) – Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx)

  • ignore_body (bool) –

  • error_format (str | None) –

Returns:

Object decorated with route() method

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

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, **ctx_kwargs)ΒΆ

Add an API URL under the GET HTTP method

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

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

  • strict_slashes (bool | None) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (int | str | float | None) – API Version

  • name (str | None) – Unique name that can be used to identify the Route

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

  • ctx_kwargs (Any) – Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx)

  • ignore_body (bool) –

  • error_format (str | None) –

Returns:

Object decorated with route() method

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

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

Retrieve an instantiated Sanic instance

Parameters:
  • name (str | None) –

  • force_create (bool) –

Return type:

Sanic

async handle_exception(request, exception, run_middleware=True)ΒΆ

A handler that catches specific exceptions and outputs a response.

Parameters:
  • request (Request) – The current request object

  • exception (BaseException) – The exception that was raised

  • run_middleware (bool) –

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 (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, **ctx_kwargs)ΒΆ

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

  • ctx_kwargs (Any) – Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx)

  • error_format (str | None) –

Returns:

Object decorated with route() method

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

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 (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | str) –

  • event_or_none (str | None) –

  • apply (bool) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | Callable[[Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]], Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]]

middleware(middleware_or_request, attach_to='request', apply=True, *, priority=0)ΒΆ

Decorate and register middleware to be called before a request is handled or after a response is created. 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.

on_request(middleware=None, *, priority=0)ΒΆ

Register a middleware to be called before a request is handled.

This is the same as @app.middleware(β€˜request’).

Param:

middleware: A callable that takes in request.

on_response(middleware=None, *, priority=0)ΒΆ

Register a middleware to be called after a response is created.

This is the same as @app.middleware(β€˜response’).

Param:

middleware: A callable that takes in a request and its response.

options(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None, **ctx_kwargs)ΒΆ

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

  • ctx_kwargs (Any) – Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx)

  • error_format (str | None) –

Returns:

Object decorated with route() method

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

patch(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ΒΆ

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

  • ctx_kwargs (Any) – Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx)

  • error_format (str | None) –

Returns:

Object decorated with route() method

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

post(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ΒΆ

Add an API URL under the POST HTTP method

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

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

  • strict_slashes (bool | None) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (int | str | float | None) – API Version

  • name (str | None) – Unique name that can be used to identify the Route

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

  • ctx_kwargs (Any) – Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx)

  • stream (bool) –

  • error_format (str | None) –

Returns:

Object decorated with route() method

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

put(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ΒΆ

Add an API URL under the PUT HTTP method

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

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

  • strict_slashes (bool | None) – Instruct Sanic to check if the request URLs need to terminate with a /

  • version (int | str | float | None) – API Version

  • name (str | None) – Unique name that can be used to identify the Route

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

  • ctx_kwargs (Any) – Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx)

  • stream (bool) –

  • error_format (str | None) –

Returns:

Object decorated with route() method

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

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

register_middleware(middleware, attach_to='request', *, priority=<sanic.helpers.Default object>)ΒΆ

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 (Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | 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

  • priority (Default | int) –

Returns:

decorated method

Return type:

Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Middleware

register_named_middleware(middleware, route_names, attach_to='request', *, priority=<sanic.helpers.Default object>)ΒΆ

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

Parameters:
  • middleware (Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]]) – 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”

  • priority (Default | int) –

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, **ctx_kwargs)ΒΆ

Decorate a function to be registered as a route

Example using context kwargs

@app.route(..., ctx_foo="foobar")
async def route_handler(request: Request):
    assert request.route.ctx.foo == "foobar"
Parameters:
  • uri (str) – path of the URL

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

  • host (str | List[str] | None) – the host, if required

  • strict_slashes (bool | None) – whether to apply strict slashes to the route

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

  • version (int | str | float | None) – route specific versioning

  • name (str | None) – 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

  • ctx_kwargs (Any) – Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx)

  • apply (bool) –

  • subprotocols (List[str] | None) –

  • websocket (bool) –

  • unquote (bool) –

  • static (bool) –

  • error_format (str | None) –

Returns:

tuple of routes, decorated function

Return type:

Callable[[Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]], Callable[[…], Coroutine[Any, Any, HTTPResponse | None]] | Tuple[Route, Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]]]

run(host=None, port=None, *, dev=False, debug=False, auto_reload=None, version=HTTP.VERSION_1, ssl=None, sock=None, workers=1, protocol=None, backlog=100, register_sys_signals=True, access_log=None, unix=None, loop=None, reload_dir=None, noisy_exceptions=None, motd=True, fast=False, verbosity=0, motd_display=None, auto_tls=False, single_process=False, legacy=False)ΒΆ

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 (bool | None) – Reload app whenever its source code is changed. Enabled by default in debug mode.

  • ssl (str, dict, SSLContext or list) – 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

  • noisy_exceptions (bool) – Log exceptions that are normally considered to be quiet/silent

  • dev (bool) –

  • version (HTTP | Literal[1] | ~typing.Literal[3]) –

  • loop (AbstractEventLoop | None) –

  • reload_dir (str | List[str] | None) –

  • motd (bool) –

  • fast (bool) –

  • verbosity (int) –

  • motd_display (Dict[str, str] | None) –

  • auto_tls (bool) –

  • single_process (bool) –

  • legacy (bool) –

Returns:

Nothing

Return type:

None

signal(event, *, apply=True, condition=None, exclusive=True)ΒΆ

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

  • exclusive (bool) – When True, the signal can only be dispatched when the condition has been met. When False, the signal can be dispatched either with or without it. THIS IS INAPPLICABLE TO BLUEPRINT SIGNALS. THEY ARE ALWAYS NON-EXCLUSIVE, defaults to True

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, index=None, directory_view=False, directory_handler=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 (str) – URL path to be used for serving static content

  • file_or_directory (PathLike | str | bytes) – Path for the Static file/directory with static files

  • pattern (str) – Regex Pattern identifying the valid static files

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

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

  • stream_large_files (bool | int) – 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 (str) – user defined name used for url_for

  • host (str | None) – Host IP or FQDN for the service to use

  • strict_slashes (bool | None) – Instruct Sanic to check if the request URLs need to terminate with a /

  • content_type (str | None) – user defined content type for header

  • apply (bool) – If true, will register the route immediately

  • resource_type (str | None) – Explicitly declare a resource to be a ” file” or a β€œdir”

  • index (str | Sequence[str] | None) – When exposing against a directory, index is the name that will be served as the default file. When multiple files names are passed, then they will be tried in order.

  • directory_view (bool) – Whether to fallback to showing the directory viewer when exposing a directory

  • directory_handler (DirectoryHandler | None) – An instance of DirectoryHandler that can be used for explicitly controlling and subclassing the behavior of the default directory handler

Returns:

routes registered on the router

Return type:

List[sanic.router.Route]

stop(terminate=True, unregister=False)ΒΆ

This kills the Sanic

Parameters:
  • terminate (bool) –

  • unregister (bool) –

classmethod unregister_app(app)ΒΆ

Unregister a Sanic instance

Parameters:

app (Sanic) –

Return type:

None

update_config(config)ΒΆ

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

See user guide re: configuration

Parameters:

config (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, **ctx_kwargs)ΒΆ

Decorate a function to be registered as a websocket route

Parameters:
  • uri (str) – path of the URL

  • host (str | List[str] | None) – Host IP or FQDN details

  • strict_slashes (bool | None) – If the API endpoint needs to terminate with a β€œ/” or not

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

  • name (str | None) – 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

  • ctx_kwargs (Any) – Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx)

  • version (int | str | float | None) –

  • apply (bool) –

  • error_format (str | None) –

Returns:

tuple of routes, decorated function

property asgi_clientΒΆ

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

Returns:

testing client

Return type:

SanicASGITestClient

property loopΒΆ

Synonymous with asyncio.get_event_loop().

Note

Only supported when using the app.run method.

property m: WorkerMultiplexerΒΆ

Interface for interacting with the worker processes

property state: ApplicationStateΒΆ
Returns:

The application state

sanic.configΒΆ

class sanic.config.Config(defaults=None, env_prefix='SANIC_', keep_alive=None, *, converters=None)ΒΆ

Bases: dict

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

  • env_prefix (Optional[str]) –

  • keep_alive (Optional[bool]) –

  • converters (Optional[Sequence[Callable[[str], Any]]]) –

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 (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. Environment variables should start with the defined prefix and should only contain uppercase letters.

It will automatically hydrate the following types:

  • int

  • float

  • bool

Anything else will be imported as a str. If you would like to add additional types to this list, you can use sanic.config.Config.register_type(). Just make sure that they are registered before you instantiate your application.

class Foo:
    def __init__(self, name) -> None:
        self.name = name


config = Config(converters=[Foo])
app = Sanic(__name__, config=config)

See user guide re: config

register_type(converter)ΒΆ

Allows for adding custom function to cast from a string value to any other type. The function should raise ValueError if it is not the correct type.

Parameters:

converter (Callable[[str], Any]) –

Return type:

None

update([E, ]**F) None.  Update D from dict/iterable E and F.ΒΆ

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

Parameters:
  • other (Any) –

  • kwargs (Any) –

Return type:

None

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 (bytes | str | dict | Any) –

class sanic.config.DescriptorMeta(name, bases, namespace, **kwargs)ΒΆ

Bases: ABCMeta

sanic.application.constantsΒΆ

enum sanic.application.constants.Mode(value)ΒΆ

Bases: StrEnum

An enumeration.

Member Type:

str

Valid values are as follows:

PRODUCTION = <Mode.PRODUCTION: 'production'>ΒΆ
DEBUG = <Mode.DEBUG: 'debug'>ΒΆ
enum sanic.application.constants.Server(value)ΒΆ

Bases: StrEnum

An enumeration.

Member Type:

str

Valid values are as follows:

SANIC = <Server.SANIC: 'sanic'>ΒΆ
ASGI = <Server.ASGI: 'asgi'>ΒΆ
enum sanic.application.constants.ServerStage(value)ΒΆ

Bases: IntEnum

An enumeration.

Member Type:

int

Valid values are as follows:

STOPPED = <ServerStage.STOPPED: 1>ΒΆ
PARTIAL = <ServerStage.PARTIAL: 2>ΒΆ
SERVING = <ServerStage.SERVING: 3>ΒΆ

sanic.application.stateΒΆ

class sanic.application.state.ApplicationServerInfo(settings: 'Dict[str, Any]', stage: 'ServerStage' = <ServerStage.STOPPED: 1>, server: 'Optional[AsyncioServer]' = None)ΒΆ

Bases: object

Parameters:
class sanic.application.state.ApplicationState(app: 'Sanic', asgi: 'bool' = False, coffee: 'bool' = False, fast: 'bool' = False, host: 'str' = '', port: 'int' = 0, ssl: 'Optional[SSLContext]' = None, sock: 'Optional[socket]' = None, unix: 'Optional[str]' = None, mode: 'Mode' = <Mode.PRODUCTION: 'production'>, reload_dirs: 'Set[Path]' = <factory>, auto_reload: 'bool' = False, server: 'Server' = <Server.SANIC: 'sanic'>, is_running: 'bool' = False, is_started: 'bool' = False, is_stopping: 'bool' = False, verbosity: 'int' = 0, workers: 'int' = 0, primary: 'bool' = True, server_info: 'List[ApplicationServerInfo]' = <factory>, _init: 'bool' = False)ΒΆ

Bases: object

Parameters:
  • app (Sanic) –

  • asgi (bool) –

  • coffee (bool) –

  • fast (bool) –

  • host (str) –

  • port (int) –

  • ssl (Optional[SSLContext]) –

  • sock (Optional[socket]) –

  • unix (Optional[str]) –

  • mode (Mode) –

  • reload_dirs (Set[Path]) –

  • auto_reload (bool) –

  • server (Server) –

  • is_running (bool) –

  • is_started (bool) –

  • is_stopping (bool) –

  • verbosity (int) –

  • workers (int) –

  • primary (bool) –

  • server_info (List[ApplicationServerInfo]) –

  • _init (bool) –