sanic.blueprints.Blueprint#

A logical collection of URLs that consist of a similar logical domain.

Inherits from: BaseSanic, RouteMixin, StaticMixin, BaseMixin, MiddlewareMixin, ListenerMixin, ExceptionMixin, SignalMixin

class Blueprint(name: str, url_prefix: Optional[str] = None, host: Optional[Union[List[str], str]] = None, version: Optional[Union[int, str, float]] = None, strict_slashes: Optional[bool] = None, version_prefix: str = "/v")

A Blueprint object is the main tool for grouping functionality and similar endpoints. It allows the developer to organize routes, exception handlers, middleware, and other web functionalities into separate, modular groups.

See Blueprints for more information.

Parameters
name
str

The name of the blueprint.

url_prefix
Optional[str]

The URL prefix for all routes defined on this blueprint.

host
Optional[Union[List[str], str]]

Host or list of hosts that this blueprint should respond to.

version
Optional[Union[int, str, float]]

Version number of the API implemented by this blueprint.

strict_slashes
Optional[bool]

Whether or not the URL should end with a slash.

version_prefix
str

Prefix for the version. Default is "/v".

add_route#

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

def add_route(self, handler: typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]], uri: <class 'str'>, methods: typing.Iterable[str] = frozenset({'GET'}), host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, stream: <class 'bool'> = False, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, unquote: <class 'bool'> = False, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]

Parameters
handler
RouteHandler

Function or class-based view used as a route handler.

uri
str

Path of the URL.

methods
Iterable[str]

List or tuple of methods allowed; these are overridden if using an HTTPMethodView.

host
Optional[Union[str, List[str]]]

Hostname or hostnames to match for this route.

strict_slashes
Optional[bool]

If set, a route's slashes will be strict. E.g. /foo will not match /foo/.

version
Optional[Union[int, str, float]]

Version of the API for this route.

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]

Custom error format string.

unquote
bool

Boolean specifying if the handler requires unquoting.

ctx_kwargs
Any

Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx). See below for examples.

Return
RouteHandler

The route handler.

Examples
from sanic import Sanic, text

app = Sanic("test")

async def handler(request):
    return text("OK")

app.add_route(handler, "/test", methods=["GET", "POST"])

You can use ctx_kwargs to add custom context to the route. This can often be useful when wanting to add metadata to a route that can be used by other parts of the application (like middleware).

from sanic import Sanic, text

app = Sanic("test")

async def handler(request):
    return text("OK")

async def custom_middleware(request):
    if request.route.ctx.monitor:
        do_some_monitoring()

app.add_route(handler, "/test", methods=["GET", "POST"], ctx_monitor=True)
app.register_middleware(custom_middleware)

add_signal#

Registers a signal handler for a specific event.

def add_signal(self, handler: Optional[Callable[..., Any]], event: Union[str, Enum], condition: Optional[Dict[str, Any]] = None, exclusive: bool = True): -> Callable[..., Any]

Parameters
handler
Optional[Callable[..., Any]]

The function to be called when the event occurs. Defaults to a noop if not provided.

event
str

The name of the event to listen for.

condition
Optional[Dict[str, Any]]

Optional condition to filter the event triggering. Defaults to None.

exclusive
bool

Whether or not the handler is exclusive. When True, the signal can only be dispatched when the condition has been met. This is inapplicable to blueprint signals, which are ALWAYS non-exclusive. Defaults to True.

Return
Callable[..., Any]

The handler that was registered.

add_websocket_route#

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

def add_websocket_route(self, handler, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, subprotocols = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any)

Parameters
handler
Callable

A callable function or instance of a class that can handle the websocket request.

uri
str

URL path that will be mapped to the websocket handler.

host
Optional[Union[str, List[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]]

Subprotocols to be used with websocket handshake.

version
Optional[Union[int, str, float]]

Versioning information.

name
Optional[str]

A unique name assigned to the URL.

version_prefix
str

URL path before the version value. Defaults to "/v".

error_format
Optional[str]

Format for error handling.

**ctx_kwargs
Any

Keyword arguments beginning with ctx_* prefix will be appended to the route context (route.ctx).

Return
Callable

Object passed as the handler.

after_reload_trigger#

Decorator for registering a listener for the after_reload_trigger event.

def after_reload_trigger(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]

This event is fired only on the reload process and NOT on any worker processes. This event is fired after the reload process triggers the reload. A change event has been detected and the reload process has been triggered.

See Listeners for more details.

Parameters
listener
ListenerType[Sanic]

The listener handler to attach.

Examples
@app.after_reload_trigger
async def on_after_reload_trigger(app: Sanic, changed: set[str]):
    print("After reload trigger, changed files: ", changed)

after_server_start#

Decorator for registering a listener for the after_server_start event.

def after_server_start(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]

This event is fired on all worker processes. You should typically use this event to run background tasks, or perform other actions that are not directly related to handling requests. In theory, it is possible that some requests may be handled before this event is fired, so you should not use this event to initialize resources that are required for handling requests.

A common use case for this event is to start a background task that periodically performs some action, such as clearing a cache or performing a health check.

See Listeners for more details.

Parameters
listener
ListenerType[Sanic]

The listener handler to attach.

Examples
@app.after_server_start
async def on_after_server_start(app: Sanic):
    print("After server start")

after_server_stop#

Decorator for registering a listener for the after_server_stop event.

def after_server_stop(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]

This event is fired on all worker processes. This event is fired after the server has stopped shutting down, and all requests have been handled. You should typically use this event to clean up resources that were initialized in the before_server_start event.

A common use case for this event is to close a database connection pool, or to close a cache client.

See Listeners for more details.

Parameters
listener
ListenerType[Sanic]

The listener handler to attach.

Examples
@app.after_server_stop
async def on_after_server_stop(app: Sanic):
    print("After server stop")

all_exceptions#

Enables the process of creating a global exception handler as a convenience.

def all_exceptions(self, handler: typing.Callable[..., typing.Any]): -> typing.Callable[..., typing.Any]

This following two examples are equivalent:

@app.exception(Exception)
async def handler(request: Request, exception: Exception) -> HTTPResponse:
    return text(f"Exception raised: {exception}")
@app.all_exceptions
async def handler(request: Request, exception: Exception) -> HTTPResponse:
    return text(f"Exception raised: {exception}")
Parameters
handler
Callable[..., Any]

A coroutine function to handle exceptions.

Return
Callable[..., Any]

A decorated method to handle global exceptions for any route registered under this blueprint.

apps#

Get the set of apps that this blueprint is registered to.

@property
def apps(self): -> Set[Sanic]

Return
Set[Sanic]

Set of apps that this blueprint is registered to.

Raises
SanicException

If the blueprint has not yet been registered to an app.

before_reload_trigger#

Decorator for registering a listener for the before_reload_trigger event.

def before_reload_trigger(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]

This event is fired only on the reload process and NOT on any worker processes. This event is fired before the reload process triggers the reload. A change event has been detected and the reload process is about to be triggered.

See Listeners for more details.

Parameters
listener
ListenerType[Sanic]

The listener handler to attach.

Examples
@app.before_reload_trigger
async def on_before_reload_trigger(app: Sanic):
    print("Before reload trigger")

before_server_start#

Decorator for registering a listener for the before_server_start event.

def before_server_start(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType] = None, priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]

This event is fired on all worker processes. You should typically use this event to initialize resources that are global in nature, or will be shared across requests and various parts of the application.

A common use case for this event is to initialize a database connection pool, or to initialize a cache client.

See Listeners for more details.

Parameters
listener
ListenerType[Sanic]

The listener handler to attach.

Examples
@app.before_server_start
async def on_before_server_start(app: Sanic):
    print("Before server start")

before_server_stop#

Decorator for registering a listener for the before_server_stop event.

def before_server_stop(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]

This event is fired on all worker processes. This event is fired before the server starts shutting down. You should not use this event to perform any actions that are required for handling requests, as some requests may continue to be handled after this event is fired.

A common use case for this event is to stop a background task that was started in the after_server_start event.

See Listeners for more details.

Parameters
listener
ListenerType[Sanic]

The listener handler to attach.

Examples
@app.before_server_stop
async def on_before_server_stop(app: Sanic):
    print("Before server stop")

catch_exception#

Register an exception handler for logging or processing.

def catch_exception(self, handler: Callable[[SignalMixin, Exception], Coroutine[Any, Any, None]]): -> None

This method allows the registration of a custom exception handler to catch and process exceptions that occur in the application. Unlike a typical exception handler that might modify the response to the client, this is intended to capture exceptions for logging or other internal processing, such as sending them to an error reporting utility.

Parameters
handler
Callable

A coroutine function that takes the application instance and the exception as arguments. It will be called when an exception occurs within the application's lifecycle.

Examples
app = Sanic("TestApp")

@app.catch_exception
async def report_exception(app: Sanic, exception: Exception):
    logging.error(f"An exception occurred: {exception}")

    # Send to an error reporting service
    await error_service.report(exception)

# Any unhandled exceptions within the application will now be
# logged and reported to the error service.

copy#

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

def copy(self, name: str, url_prefix: Optional[Union[str, Default]] = <Default>, version: Optional[Union[int, str, float, Default]] = <Default>, version_prefix: Union[str, Default] = <Default>, allow_route_overwrite: Union[bool, Default] = <Default>, strict_slashes: Optional[Union[bool, Default]] = <Default>, with_registration: bool = True, with_ctx: bool = False)

Parameters
name
str

Unique name of the blueprint.

url_prefix
Optional[Union[str, Default]]

URL to be prefixed before all route URLs.

version
Optional[Union[int, str, float, Default]]

Blueprint version.

version_prefix
Union[str, Default]

The prefix of the version number shown in the URL.

allow_route_overwrite
Union[bool, Default]

Whether to allow route overwrite or not.

strict_slashes
Optional[Union[bool, Default]]

Enforce the API URLs are requested with a trailing "/*".

with_registration
bool

Whether to register the new blueprint instance with Sanic apps that were registered with the old instance or not. Default is True.

with_ctx
bool

Whether the ctx will be copied or not. Default is False.

Return
Blueprint

A new Blueprint instance with the specified attributes.

delete#

Decorate a function handler to create a route definition using the DELETE HTTP method.

def delete(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, ignore_body: <class 'bool'> = False, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]

Parameters
uri
str

URL to be tagged to the DELETE method of HTTP.

host
Optional[Union[str, List[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[Union[int, str, float]]

API Version.

name
Optional[str]

Unique name that can be used to identify the Route.

ignore_body
bool

Whether or not to ignore the body in the request. Defaults to False.

version_prefix
str

URL path that should be before the version value. Defaults to "/v".

error_format
Optional[str]

Custom error format string.

**ctx_kwargs
Any

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

Return
RouteHandler

Object decorated with route method.

dispatch#

Dispatch a signal event

async def dispatch(self, args, kwargs)

Parameters
*args

Arguments to be passed to the signal event.

**kwargs

Keyword arguments to be passed to the signal event.

event#

Wait for a signal event to be dispatched.

def event(self, event: str, timeout: Optional[Union[int, float]] = None, condition: Optional[Dict[str, Any]] = None)

Parameters
event
str

Name of the signal event.

timeout
Optional[Union[int, float]]

Timeout for the event to be dispatched.

condition

If provided, method will only return when the signal is dispatched with the given condition.

Return
Awaitable

Awaitable for the event to be dispatched.

exception#

Decorator used to register an exception handler for the current application or blueprint instance.

def exception(self, exceptions: typing.Union[typing.Type[Exception], typing.List[typing.Type[Exception]]], apply: <class 'bool'> = True): -> typing.Callable

This method allows you to define a handler for specific exceptions that may be raised within the routes of this blueprint. You can specify one or more exception types to catch, and the handler will be applied to those exceptions.

When used on a Blueprint, the handler will only be applied to routes registered under that blueprint. That means they only apply to requests that have been matched, and the exception is raised within the handler function (or middleware) for that route.

A general exception like NotFound should only be registered on the application instance, not on a blueprint.

See Exceptions for more information.

Parameters
exceptions
Union[Type[Exception], List[Type[Exception]]]

List of Python exceptions to be caught by the handler.

apply
bool

Whether the exception handler should be applied. Defaults to True.

Return
Callable

A decorated method to handle global exceptions for any route registered under this blueprint.

Examples
from sanic import Blueprint, text

bp = Blueprint('my_blueprint')

@bp.exception(Exception)
def handle_exception(request, exception):
    return text("Oops, something went wrong!", status=500)
from sanic import Sanic, NotFound, text

app = Sanic('MyApp')

@app.exception(NotFound)
def ignore_404s(request, exception):
    return text(f"Yep, I totally found the page: {request.url}")

finalize_middleware#

Finalize the middleware configuration for the Sanic application.

def finalize_middleware(self): -> None

This method completes the middleware setup for the application. Middleware in Sanic is used to process requests globally before they reach individual routes or after routes have been processed.

Finalization consists of identifying defined routes and optimizing Sanic's performance to meet the application's specific needs. If you are manually adding routes, after Sanic has started, you will typically want to use the amend context manager rather than calling this method directly.

Note

This method is usually called internally during the server setup process and does not typically need to be invoked manually.

Examples
app.finalize_middleware()

get#

Decorate a function handler to create a route definition using the GET HTTP method.

def get(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, ignore_body: <class 'bool'> = True, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]

Parameters
uri
str

URL to be tagged to GET method of HTTP.

host
Optional[Union[str, List[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[Union[int, str, float]]

API Version.

name
Optional[str]

Unique name that can be used to identify the route.

ignore_body
bool

Whether the handler should ignore request body. This means the body of the request, if sent, will not be consumed. In that instance, you will see a warning in the logs. Defaults to True, meaning do not consume the body.

version_prefix
str

URL path that should be before the version value. Defaults to "/v".

error_format
Optional[str]

Custom error format string.

**ctx_kwargs
Any

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

Return
RouteHandler

Object decorated with route method.

group#

Group multiple blueprints (or other blueprint groups) together.

@staticmethod
def group(blueprints: Union[Blueprint, BlueprintGroup], url_prefix: Optional[str] = None, version: Optional[Union[int, str, float]] = None, strict_slashes: Optional[bool] = None, version_prefix: str = "/v", name_prefix: Optional[str] = ): -> BlueprintGroup

Gropuping blueprings is a method for modularizing and organizing your application's code. This can be a powerful tool for creating reusable components, logically structuring your application code, and easily maintaining route definitions in bulk.

This is the preferred way to group multiple blueprints together.

Parameters
blueprints
Union[Blueprint, BlueprintGroup]

Blueprints to be registered as a group.

url_prefix
Optional[str]

URL route to be prepended to all sub-prefixes. Default is None.

version
Optional[Union[int, str, float]]

API Version to be used for Blueprint group. Default is None.

strict_slashes
Optional[bool]

Indicate strict slash termination behavior for URL. Default is None.

version_prefix
str

Prefix to be used for the version in the URL. Default is "/v".

name_prefix
Optional[str]

Prefix to be used for the name of the blueprints in the group. Default is an empty string.

Return
BlueprintGroup

A group of blueprints.

Examples

The resulting group will have the URL prefixes '/v2/bp1' and '/v2/bp2' for bp1 and bp2, respectively.

bp1 = Blueprint('bp1', url_prefix='/bp1')
bp2 = Blueprint('bp2', url_prefix='/bp2')
group = group(bp1, bp2, version=2)

head#

Decorate a function handler to create a route definition using the HEAD HTTP method.

def head(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, ignore_body: <class 'bool'> = True, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]

Parameters
uri
str

URL to be tagged to HEAD method of HTTP.

host
Optional[Union[str, List[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[Union[int, str, float]]

API Version.

name
Optional[str]

Unique name that can be used to identify the route.

ignore_body
bool

Whether the handler should ignore request body. This means the body of the request, if sent, will not be consumed. In that instance, you will see a warning in the logs. Defaults to True, meaning do not consume the body.

version_prefix
str

URL path that should be before the version value. Defaults to "/v".

error_format
Optional[str]

Custom error format string.

**ctx_kwargs
Any

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

Return
RouteHandler

Object decorated with route method.

listener#

Create a listener for a specific event in the application's lifecycle.

def listener(self, listener_or_event: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], str], event_or_none: typing.Optional[str] = None, apply: <class 'bool'> = True, priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]], typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]]]

See Listeners for more details.

Note

Overloaded signatures allow for different ways of calling this method, depending on the types of the arguments.

Usually, it is prederred to use one of the convenience methods such as before_server_start or after_server_stop instead of calling this method directly.

@app.before_server_start
async def prefered_method(_):
    ...

@app.listener("before_server_start")
async def not_prefered_method(_):
    ...
Parameters
listener_or_event
Union[ListenerType[Sanic], str]

A listener function or an event name.

event_or_none
Optional[str]

The event name to listen for if listener_or_event is a function. Defaults to None.

apply
bool

Whether to apply the listener immediately. Defaults to True.

priority
int

The priority of the listener. Defaults to 0.

Return
Union[ListenerType[Sanic], Callable[[ListenerType[Sanic]], ListenerType[Sanic]]]

The listener or a callable that takes a listener.

Examples

The following code snippet shows how you can use this method as a decorator:

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

main_process_ready#

Decorator for registering a listener for the main_process_ready event.

def main_process_ready(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]

This event is fired only on the main process and NOT on any worker processes. It is fired after the main process has started and the Worker Manager has been initialized (ie, you will have access to app.manager instance). The typical use case for this event is to add a managed process to the Worker Manager.

See Running custom processes and Listeners for more details.

Parameters
listener
ListenerType[Sanic]

The listener handler to attach.

Examples
@app.main_process_ready
async def on_main_process_ready(app: Sanic):
    print("Main process ready")

main_process_start#

Decorator for registering a listener for the main_process_start event.

def main_process_start(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]

This event is fired only on the main process and NOT on any worker processes. You should typically use this event to initialize resources that are shared across workers, or to initialize resources that are not safe to be initialized in a worker process.

See Listeners for more details.

Parameters
listener
ListenerType[Sanic]

The listener handler to attach.

Examples
@app.main_process_start
async def on_main_process_start(app: Sanic):
    print("Main process started")

main_process_stop#

Decorator for registering a listener for the main_process_stop event.

def main_process_stop(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]

This event is fired only on the main process and NOT on any worker processes. You should typically use this event to clean up resources that were initialized in the main_process_start event.

See Listeners for more details.

Parameters
listener
ListenerType[Sanic]

The listener handler to attach.

Examples
@app.main_process_stop
async def on_main_process_stop(app: Sanic):
    print("Main process stopped")

middleware#

Decorator for registering middleware.

def middleware(self, middleware_or_request: typing.Union[typing.Callable[[~Request], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[~Request, sanic.response.types.BaseHTTPResponse], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], str], attach_to: <class 'str'> = request, apply: <class 'bool'> = True, priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Request], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[~Request, sanic.response.types.BaseHTTPResponse], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[typing.Union[typing.Callable[[~Request], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[~Request, sanic.response.types.BaseHTTPResponse], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]]]], typing.Union[typing.Callable[[~Request], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[~Request, sanic.response.types.BaseHTTPResponse], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]]]]]

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'). Although, it is recommended to use @app.on_request or @app.on_response instead for clarity and convenience.

See Middleware for more information.

Parameters
middleware_or_request
Union[Callable, str]

Middleware function or the keyword 'request' or 'response'.

attach_to
str

When to apply the middleware; either 'request' (before the request is handled) or 'response' (after the response is created). Defaults to 'request'.

apply
bool

Whether the middleware should be applied. Defaults to True.

priority
int

The priority level of the middleware. Lower numbers are executed first. Defaults to 0.

Return
Union[Callable, Callable[[Callable], Callable]]

The decorated middleware function or a partial function depending on how the method was called.

Examples
@app.middleware('request')
async def custom_middleware(request):
    ...

on_request#

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

def on_request(self, middleware = None, priority = 0): -> typing.Union[typing.Callable[[~Request], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[~Request, sanic.response.types.BaseHTTPResponse], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]]]

This is the same as @app.middleware('request').

Parameters
middleware
Callable

A callable that takes in a request. Defaults to None.

Return
Callable

The decorated middleware function or a partial function depending on how the method was called.

Examples
@app.on_request
async def custom_middleware(request):
    request.ctx.custom = 'value'

on_response#

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

def on_response(self, middleware = None, priority = 0)

This is the same as @app.middleware('response').

Parameters
middleware
Callable

A callable that takes in a request and response. Defaults to None.

Return
Callable

The decorated middleware function or a partial function depending on how the method was called.

Examples
@app.on_response
async def custom_middleware(request, response):
    response.headers['X-Server'] = 'Sanic'

options#

Decorate a function handler to create a route definition using the OPTIONS HTTP method.

def options(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, ignore_body: <class 'bool'> = True, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]

Parameters
uri
str

URL to be tagged to OPTIONS method of HTTP.

host
Optional[Union[str, List[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[Union[int, str, float]]

API Version.

name
Optional[str]

Unique name that can be used to identify the route.

ignore_body
bool

Whether the handler should ignore request body. This means the body of the request, if sent, will not be consumed. In that instance, you will see a warning in the logs. Defaults to True, meaning do not consume the body.

version_prefix
str

URL path that should be before the version value. Defaults to "/v".

error_format
Optional[str]

Custom error format string.

**ctx_kwargs
Any

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

Return
RouteHandler

Object decorated with route method.

patch#

Decorate a function handler to create a route definition using the PATCH HTTP method.

def patch(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, stream = False, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]

Parameters
uri
str

URL to be tagged to PATCH method of HTTP.

host
Optional[Union[str, List[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 /.

stream
bool

Set to True if full request streaming is needed, False otherwise. Defaults to False.

version
Optional[Union[int, str, float]]

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. Defaults to "/v".

error_format
Optional[str]

Custom error format string.

**ctx_kwargs
Any

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

Return
RouteHandler

Object decorated with route method.

post#

Decorate a function handler to create a route definition using the POST HTTP method.

def post(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, stream: <class 'bool'> = False, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]

Parameters
uri
str

URL to be tagged to POST method of HTTP.

host
Optional[Union[str, List[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 /.

stream
bool

Whether or not to stream the request body. Defaults to False.

version
Optional[Union[int, str, float]]

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. Defaults to "/v".

error_format
Optional[str]

Custom error format string.

**ctx_kwargs
Any

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

Return
RouteHandler

Object decorated with route method.

put#

Decorate a function handler to create a route definition using the PUT HTTP method.

def put(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, stream: <class 'bool'> = False, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]

Parameters
uri
str

URL to be tagged to PUT method of HTTP.

host
Optional[Union[str, List[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 /.

stream
bool

Whether or not to stream the request body. Defaults to False.

version
Optional[Union[int, str, float]]

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. Defaults to "/v".

error_format
Optional[str]

Custom error format string.

**ctx_kwargs
Any

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

Return
RouteHandler

Object decorated with route method.

register#

Register the blueprint to the sanic app.

def register(self, app, options)

Parameters
app
Sanic

Sanic app to register the blueprint to.

options
dict

Options to be passed to the blueprint.

register_futures#

Register futures to the apps.

@staticmethod
def register_futures(apps: Set[Sanic], bp: Blueprint, futures: Sequence[Tuple[Any, ...]])

Parameters
apps
Set[Sanic]

Set of apps to register the futures to.

bp
Blueprint

Blueprint that the futures belong to.

futures
Sequence[Tuple[Any, ...]]

Sequence of futures to be registered.

registered#

Check if the blueprint has been registered to an app.

@property
def registered(self): -> bool

Return
bool

True if the blueprint has been registered to an app, False otherwise.

reload_process_start#

Decorator for registering a listener for the reload_process_start event.

def reload_process_start(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]

This event is fired only on the reload process and NOT on any worker processes. This is similar to the main_process_start event, except that it is fired only when the reload process is started.

See Listeners for more details.

Parameters
listener
ListenerType[Sanic]

The listener handler to attach.

Examples
@app.reload_process_start
async def on_reload_process_start(app: Sanic):
    print("Reload process started")

reload_process_stop#

Decorator for registering a listener for the reload_process_stop event.

def reload_process_stop(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]

This event is fired only on the reload process and NOT on any worker processes. This is similar to the main_process_stop event, except that it is fired only when the reload process is stopped.

See Listeners for more details.

Parameters
listener
ListenerType[Sanic]

The listener handler to attach.

Examples
@app.reload_process_stop
async def on_reload_process_stop(app: Sanic):
    print("Reload process stopped")

reset#

Reset the blueprint to its initial state.

def reset(self): -> None

route#

Decorate a function to be registered as a route.

def route(self, uri: <class 'str'>, methods: typing.Optional[typing.Iterable[str]] = None, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, stream: <class 'bool'> = False, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, ignore_body: <class 'bool'> = False, apply: <class 'bool'> = True, subprotocols: typing.Optional[typing.List[str]] = None, websocket: <class 'bool'> = False, unquote: <class 'bool'> = False, static: <class 'bool'> = False, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[[typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Union[typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]], typing.Tuple[sanic_routing.route.Route, typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]]]]

Parameters
uri
str

Path of the URL.

methods
Optional[Iterable[str]]

List or tuple of methods allowed.

host
Optional[Union[str, List[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 (e.g. GET requests).

apply
bool

Apply middleware to the route.

subprotocols
Optional[List[str]]

List of subprotocols.

websocket
bool

Enable WebSocket support.

unquote
bool

Unquote special characters in the URL path.

static
bool

Enable static route.

version_prefix
str

URL path that should be before the version value; default: "/v".

error_format
Optional[str]

Error format for the route.

ctx_kwargs
Any

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

Return
RouteWrapper

Tuple of routes, decorated function.

Examples

Using the method to define a GET endpoint:

@app.route("/hello")
async def hello(request: Request):
    return text("Hello, World!")

Adding context kwargs to the route:

@app.route("/greet", ctx_name="World")
async def greet(request: Request):
    name = request.route.ctx.name
    return text(f"Hello, {name}!")

signal#

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

def signal(self, event: Union[str, Enum], apply: bool = True, condition: Optional[Dict[str, Any]] = None, exclusive: bool = True, priority: int = 0): -> Callable[[SignalHandler], SignalHandler]

@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

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

static#

Register a root to serve files from. The input can either be a file or a directory.

def static(self, uri: <class 'str'>, file_or_directory: typing.Union[os.PathLike, str], pattern: <class 'str'> = /?.+, use_modified_since: <class 'bool'> = True, use_content_range: <class 'bool'> = False, stream_large_files: typing.Union[bool, int] = False, name: <class 'str'> = static, host: typing.Optional[str] = None, strict_slashes: typing.Optional[bool] = None, content_type: typing.Optional[str] = None, apply: <class 'bool'> = True, resource_type: typing.Optional[str] = None, index: typing.Union[str, typing.Sequence[str], NoneType] = None, directory_view: <class 'bool'> = False, directory_handler: typing.Optional[sanic.handlers.directory.DirectoryHandler] = None)

This method provides an easy and simple way to set up the route necessary to serve static files.

Parameters
uri
str

URL path to be used for serving static content.

file_or_directory
Union[PathLike, str]

Path to the static file or directory with static files.

pattern
str

Regex pattern identifying the valid static files. Defaults to r"/?.+".

use_modified_since
bool

If true, send file modified time, and return not modified if the browser's matches the server's. Defaults to True.

use_content_range
bool

If true, process header for range requests and sends the file part that is requested. Defaults to False.

stream_large_files
Union[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, it represents the threshold size to switch to StreamingHTTPResponse.file_stream. Defaults to False, which means that the response will not be streamed.

name
str

User-defined name used for url_for. Defaults to "static".

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

content_type
Optional[str]

User-defined content type for header.

apply
bool

If true, will register the route immediately. Defaults to True.

resource_type
Optional[str]

Explicitly declare a resource to be a "file" or a "dir".

index
Optional[Union[str, Sequence[str]]]

When exposing against a directory, index is the name that will be served as the default file. When multiple file 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. Defaults to False.

directory_handler
Optional[DirectoryHandler]

An instance of DirectoryHandler that can be used for explicitly controlling and subclassing the behavior of the default directory handler.

Return
List[sanic.router.Route]

Routes registered on the router.

Examples

Serving a single file:

app.static('/foo', 'path/to/static/file.txt')

Serving all files from a directory:

app.static('/static', 'path/to/static/directory')

Serving large files with a specific threshold:

app.static('/static', 'path/to/large/files', stream_large_files=1000000)

websocket#

Decorate a function to be registered as a websocket route.

def websocket(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, subprotocols: typing.Optional[typing.List[str]] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, apply: <class 'bool'> = True, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any)

Parameters
uri
str

Path of the URL.

host
Optional[Union[str, List[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.

version
Optional[Union[int, str, float]]

WebSocket protocol version.

name
Optional[str]

A unique name assigned to the URL so that it can be used with url_for.

apply
bool

If set to False, it doesn't apply the route to the app. Default is True.

version_prefix
str

URL path that should be before the version value. Defaults to "/v".

error_format
Optional[str]

Custom error format string.

**ctx_kwargs
Any

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

Return
tuple

Tuple of routes, decorated function.

sanic.blueprints.BlueprintGroup#

This class provides a mechanism to implement a Blueprint Group.

Inherits from: MutableSequence, Sequence, Reversible, Collection, Sized, Iterable, Container

class BlueprintGroup(url_prefix: Optional[str] = None, version: Optional[Union[int, str, float]] = None, strict_slashes: Optional[bool] = None, version_prefix: str = "/v", name_prefix: Optional[str] = )

The BlueprintGroup class allows grouping blueprints under a common URL prefix, version, and other shared attributes. It integrates with Sanic's Blueprint system, offering a custom iterator to treat an object of this class as a list/tuple.

Although possible to instantiate a group directly, it is recommended to use the Blueprint.group method to create a group of blueprints.

Parameters
url_prefix
Optional[str]

URL to be prefixed before all the Blueprint Prefixes. Default is None.

version
Optional[Union[int, str, float]]

API Version for the blueprint group, inherited by each Blueprint. Default is None.

strict_slashes
Optional[bool]

URL Strict slash behavior indicator. Default is None.

version_prefix
str

Prefix for the version in the URL. Default is "/v".

name_prefix
Optional[str]

Prefix for the name of the blueprints in the group. Default is an empty string.

Examples
bp1 = Blueprint("bp1", url_prefix="/bp1")
bp2 = Blueprint("bp2", url_prefix="/bp2")

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


group1 = Blueprint.group(bp1, bp2)
group2 = Blueprint.group(bp3, bp4, version_prefix="/api/v", version="1")


@bp1.on_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 bp3_route(request):
    return text("bp3")


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


@group1.on_request
async def group_middleware(request):
    print("common middleware applied for both bp1 and bp2")


# Register Blueprint group under the app
app.blueprint(group1)
app.blueprint(group2)

append#

Add a new Blueprint object to the group.

def append(self, value: Blueprint): -> None

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

Parameters
value
Blueprint

New Blueprint object.

blueprints#

A list of all the available blueprints under this group.

@property
def blueprints(self): -> List[Blueprint]

Return
List[Blueprint]

List of all the available blueprints under this group.

clear#

S.clear() -> None -- remove all items from S

def clear(self)

count#

S.count(value) -> integer -- return number of occurrences of value

def count(self, value)

exception#

Decorate a function to handle exceptions for all blueprints in the group.

def exception(self, exceptions: Exception, kwargs): -> Callable

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

Parameters
*exceptions
Exception

Exceptions to handle

**kwargs
dict

Optional Keyword arg to use with Middleware

Examples
bp1 = Blueprint("bp1", url_prefix="/bp1")
bp2 = Blueprint("bp2", url_prefix="/bp2")
group1 = Blueprint.group(bp1, bp2)

@group1.exception(Exception)
def handler(request, exception):
    return text("Exception caught")

extend#

S.extend(iterable) -- extend sequence by appending elements from the iterable

def extend(self, values)

index#

S.index(value, [start, [stop]]) -> integer -- return first index of value.

def index(self, value, start = 0, stop = None)

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert#

Insert a new Blueprint object to the group at the specified index.

def insert(self, index: int, item: Blueprint): -> None

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.

middleware#

A decorator that can be used to implement a Middleware for all blueprints in the group.

def middleware(self, args, kwargs)

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

Parameters
*args
Optional

Optional positional Parameters to be use middleware

**kwargs
Optional

Optional Keyword arg to use with Middleware

name_prefix#

Name prefix for the Blueprint Group.

@property
def name_prefix(self): -> Optional[str]

This is mainly needed when blueprints are copied in order to avoid name conflicts.

Return
Optional[str]

Name prefix for the Blueprint Group.

on_request#

Convenience method to register a request middleware for all blueprints in the group.

def on_request(self, middleware = None)

Parameters
middleware
Optional

Optional positional Parameters to be use middleware

on_response#

Convenience method to register a response middleware for all blueprints in the group.

def on_response(self, middleware = None)

Parameters
middleware
Optional

Optional positional Parameters to be use middleware

pop#

S.pop([index]) -> item -- remove and return item at index (default last).

def pop(self, index = -1)

Raise IndexError if list is empty or index is out of range.

remove#

S.remove(value) -- remove first occurrence of value.

def remove(self, value)

Raise ValueError if the value is not present.

reverse#

S.reverse() -- reverse IN PLACE

def reverse(self)

strict_slashes#

Whether to enforce strict slashes for the Blueprint Group.

@property
def strict_slashes(self): -> Optional[bool]

Return
Optional[bool]

Whether to enforce strict slashes for the

url_prefix#

The URL prefix for the Blueprint Group.

@property
def url_prefix(self): -> Optional[Union[int, str, float]]

Return
Optional[Union[int, str, float]]

URL prefix for the Blueprint Group.

version#

API Version for the Blueprint Group, if any.

@property
def version(self): -> Optional[Union[str, int, float]]

Return
Optional[Union[str, int, float]]

API Version for the Blueprint

version_prefix#

Version prefix for the Blueprint Group.

@property
def version_prefix(self): -> str

Return
str

Version prefix for the Blueprint Group.

sanic.blueprints.lazy#

Decorator to register a function to be called later.

def lazy(func, as_decorator = True)

Parameters
func
Callable

Function to be called later.

as_decorator
bool

Whether the function should be called immediately or not.