Blueprints

sanic.blueprints

class sanic.blueprints.Blueprint(name=None, url_prefix=None, host=None, version=None, strict_slashes=None, version_prefix='/v')

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 (str) – unique name of the blueprint

  • url_prefix (Optional[str]) – URL to be prefixed before all route URLs

  • host (Optional[str]) – IP Address of FQDN for the sanic server to use.

  • version (Optional[Union[int, str, float]]) – Blueprint Version

  • strict_slashes (Optional[bool]) – Enforce the API urls are requested with a trailing /

  • version_prefix (str) –

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_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()

copy(name, url_prefix=<sanic.helpers.Default object>, version=<sanic.helpers.Default object>, version_prefix=<sanic.helpers.Default object>, strict_slashes=<sanic.helpers.Default object>, with_registration=True, with_ctx=False)

Copy a blueprint instance with some optional parameters to override the values of attributes in the old instance.

Parameters
  • name (str) – unique name of the blueprint

  • url_prefix (Optional[Union[str, sanic.helpers.Default]]) – URL to be prefixed before all route URLs

  • version (Optional[Union[int, str, float, sanic.helpers.Default]]) – Blueprint Version

  • version_prefix (Union[str, sanic.helpers.Default]) – the prefix of the version number shown in the URL.

  • strict_slashes (Optional[Union[bool, sanic.helpers.Default]]) – Enforce the API urls are requested with a trailing /

  • with_registration (bool) – whether register new blueprint instance with sanic apps that were registered with the old instance or not.

  • with_ctx (bool) – whether ctx will be copied or not.

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

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

static group(*blueprints, url_prefix=None, version=None, strict_slashes=None, version_prefix='/v')

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

Parameters
  • blueprints (Union[sanic.blueprints.Blueprint, sanic.blueprint_group.BlueprintGroup]) – blueprints to be registered as a group

  • url_prefix (Optional[str]) – URL route to be prepended to all sub-prefixes

  • version (Optional[Union[int, str, float]]) – API Version to be used for Blueprint group

  • strict_slashes (Optional[bool]) – Indicate strict slash termination behavior for URL

  • version_prefix (str) –

Return type

sanic.blueprint_group.BlueprintGroup

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(*args, **kwargs)

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

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

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)

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

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

sanic.blueprint_group

class sanic.blueprint_group.BlueprintGroup(url_prefix=None, version=None, strict_slashes=None, version_prefix='/v')

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)
Parameters
  • url_prefix (Optional[str]) –

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

  • strict_slashes (Optional[bool]) –

  • version_prefix (str) –

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

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

  • version_prefix (str) –

__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 (Blueprint) –

Return type

None

exception(*exceptions, **kwargs)

A decorator that can be used to implement a global exception handler for all the Blueprints that belong to this Blueprint Group.

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

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

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

Returns

a decorated method to handle global exceptions for any blueprint registered under this group.

insert(index, item)

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

Parameters
  • index (int) – Index to use for removing a new Blueprint item

  • item (Blueprint) – New Blueprint object.

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: List[Blueprint]

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

Returns

List of Blueprint instance

property strict_slashes: Optional[bool]

URL Slash termination behavior configuration

Returns

bool

property url_prefix: Optional[Union[int, str, float]]

Retrieve the URL prefix being used for the Current Blueprint Group

Returns

string with url prefix

property version: Optional[Union[int, str, float]]

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

property version_prefix: str

Version prefix; defaults to /v

Returns

str