Warning

These documents are OUTDATED as of 2023-12-31.

Please refer to the latest version of the documentation at sanic.dev.

Blueprints

sanic.blueprints

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

Bases: BaseSanic

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

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](/en/guide/best-practices/blueprints) for more information.

Args:

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

Parameters:
  • name (str) –

  • url_prefix (Optional[str]) –

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

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

  • strict_slashes (bool | None) –

  • 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, unquote=False, **ctx_kwargs)

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

Args:

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.

Returns:

RouteHandler: The route handler.

Examples:

```python 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).

```python 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)

Parameters:
  • handler (Callable[[...], Coroutine[Any, Any, HTTPResponse | None]]) –

  • uri (str) –

  • methods (Iterable[str]) –

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

  • strict_slashes (bool | None) –

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

  • name (str | None) –

  • stream (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • unquote (bool) –

  • ctx_kwargs (Any) –

Return type:

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

add_signal(handler, event, condition=None, exclusive=True)

Registers a signal handler for a specific event.

Args:
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.

Returns:

Callable[…, Any]: The handler that was registered.

Parameters:
  • handler (Callable[[...], Any] | None) –

  • event (str | Enum) –

  • condition (Dict[str, Any] | None) –

  • exclusive (bool) –

Return type:

Callable[[…], 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.

Args:
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).

Returns:

Callable: Object passed as the handler.

Parameters:
  • uri (str) –

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

  • strict_slashes (bool | None) –

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

  • name (str | None) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

after_reload_trigger(listener, *, priority=0)

Decorator for registering a listener for the after_reload_trigger event.

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](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.after_reload_trigger async def on_after_reload_trigger(app: Sanic, changed: set[str]):

print(β€œAfter reload trigger, changed files: β€œ, changed)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

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

after_server_start(listener, *, priority=0)

Decorator for registering a listener for the after_server_start event.

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](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.after_server_start async def on_after_server_start(app: Sanic):

print(β€œAfter server start”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

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

after_server_stop(listener, *, priority=0)

Decorator for registering a listener for the after_server_stop event.

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](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.after_server_stop async def on_after_server_stop(app: Sanic):

print(β€œAfter server stop”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

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

all_exceptions(handler)

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

This following two examples are equivalent:

```python @app.exception(Exception) async def handler(request: Request, exception: Exception) -> HTTPResponse:

return text(f”Exception raised: {exception}”)

```

```python @app.all_exceptions async def handler(request: Request, exception: Exception) -> HTTPResponse:

return text(f”Exception raised: {exception}”)

```

Args:

handler (Callable[…, Any]): A coroutine function to handle exceptions.

Returns:
Callable[…, Any]: A decorated method to handle global exceptions for

any route registered under this blueprint.

Parameters:

handler (Callable[[...], Any]) –

Return type:

Callable[[…], Any]

before_reload_trigger(listener, *, priority=0)

Decorator for registering a listener for the before_reload_trigger event.

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](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.before_reload_trigger async def on_before_reload_trigger(app: Sanic):

print(β€œBefore reload trigger”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

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

before_server_start(listener=None, *, priority=0)

Decorator for registering a listener for the before_server_start event.

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](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.before_server_start async def on_before_server_start(app: Sanic):

print(β€œBefore server start”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

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

before_server_stop(listener, *, priority=0)

Decorator for registering a listener for the before_server_stop event.

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](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.before_server_stop async def on_before_server_stop(app: Sanic):

print(β€œBefore server stop”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

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

catch_exception(handler)

Register an exception handler for logging or processing.

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.

Args:
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.

Example:

```python 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. ```

Parameters:

handler (Callable[[SignalMixin, Exception], Coroutine[Any, Any, None]]) –

Return type:

None

copy(name, url_prefix=<Default>, version=<Default>, version_prefix=<Default>, allow_route_overwrite=<Default>, strict_slashes=<Default>, with_registration=True, with_ctx=False)

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

Args:

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.

Returns:

Blueprint: A new Blueprint instance with the specified attributes.

Parameters:
  • name (str) –

  • url_prefix (str | Default | None) –

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

  • version_prefix (str | Default) –

  • allow_route_overwrite (bool | Default) –

  • strict_slashes (bool | Default | None) –

  • with_registration (bool) –

  • with_ctx (bool) –

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

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

Args:

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

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

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

  • strict_slashes (bool | None) –

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

  • name (str | None) –

  • ignore_body (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

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

async dispatch(*args, **kwargs)

Dispatch a signal event

Args:

*args: Arguments to be passed to the signal event. **kwargs: Keyword arguments to be passed to the signal event.

event(event, timeout=None, *, condition=None)

Wait for a signal event to be dispatched.

Args:

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.

Returns:

Awaitable: Awaitable for the event to be dispatched.

Parameters:
  • event (str) –

  • timeout (int | float | None) –

  • condition (Dict[str, Any] | None) –

exception(*exceptions, apply=True)

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

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](/en/guide/best-practices/exceptions.html) for more information.

Args:
exceptions (Union[Type[Exception], List[Type[Exception]]]): List of

Python exceptions to be caught by the handler.

apply (bool, optional): Whether the exception handler should be

applied. Defaults to True.

Returns:
Callable: A decorated method to handle global exceptions for any route

registered under this blueprint.

Example:

```python 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)

```

```python 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}”)

Parameters:
  • exceptions (Type[Exception] | List[Type[Exception]]) –

  • apply (bool) –

Return type:

Callable

finalize_middleware()

Finalize the middleware configuration for the Sanic application.

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.

Example:

`python app.finalize_middleware() `

Return type:

None

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

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

Args:

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

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

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

  • strict_slashes (bool | None) –

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

  • name (str | None) –

  • ignore_body (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

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

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

Group multiple blueprints (or other blueprint groups) together.

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.

Args:
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.

Returns:

BlueprintGroup: A group of blueprints.

Example:

The resulting group will have the URL prefixes β€˜/v2/bp1’ and β€˜/v2/bp2’ for bp1 and bp2, respectively. `python bp1 = Blueprint('bp1', url_prefix='/bp1') bp2 = Blueprint('bp2', url_prefix='/bp2') group = group(bp1, bp2, version=2) `

Parameters:
  • blueprints (Blueprint | BlueprintGroup) –

  • url_prefix (str | None) –

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

  • strict_slashes (bool | None) –

  • version_prefix (str) –

  • name_prefix (str | None) –

Return type:

BlueprintGroup

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

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

Args:

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

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

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

  • strict_slashes (bool | None) –

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

  • name (str | None) –

  • ignore_body (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

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

listener(listener_or_event, event_or_none=None, apply=True, *, priority=0)

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

See [Listeners](/en/guide/basics/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.

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

…

@app.listener(β€œbefore_server_start”) async def not_prefered_method(_):

…

Args:

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.

Returns:

Union[ListenerType[Sanic], Callable[[ListenerType[Sanic]], ListenerType[Sanic]]]: The listener or a callable that takes a listener.

Example:

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

```python @bp.listener(β€œbefore_server_start”) async def before_server_start(app, loop):

…

```

Parameters:
  • 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) –

  • priority (int) –

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

main_process_ready(listener, *, priority=0)

Decorator for registering a listener for the main_process_ready event.

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](/en/guide/deployment/manager.html#running-custom-processes) and [Listeners](/en/guide/basics/listeners.html) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.main_process_ready async def on_main_process_ready(app: Sanic):

print(β€œMain process ready”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

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

main_process_start(listener, *, priority=0)

Decorator for registering a listener for the main_process_start event.

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](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.main_process_start async def on_main_process_start(app: Sanic):

print(β€œMain process started”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

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

main_process_stop(listener, *, priority=0)

Decorator for registering a listener for the main_process_stop event.

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](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.main_process_stop async def on_main_process_stop(app: Sanic):

print(β€œMain process stopped”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

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

Decorator for registering middleware.

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](/guide/basics/middleware) for more information.

Args:
middleware_or_request (Union[Callable, str]): Middleware function

or the keyword β€˜request’ or β€˜response’.

attach_to (str, optional): When to apply the middleware;

either β€˜request’ (before the request is handled) or β€˜response’ (after the response is created). Defaults to β€˜request’.

apply (bool, optional): Whether the middleware should be applied.

Defaults to True.

priority (int, optional): The priority level of the middleware.

Lower numbers are executed first. Defaults to 0.

Returns:
Union[Callable, Callable[[Callable], Callable]]: The decorated

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

Example:

```python @app.middleware(β€˜request’) async def custom_middleware(request):

…

```

Parameters:
Return type:

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

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’).

Args:
middleware (Callable, optional): A callable that takes in a

request. Defaults to None.

Returns:
Callable: The decorated middleware function or a partial function

depending on how the method was called.

Examples:

```python @app.on_request async def custom_middleware(request):

request.ctx.custom = β€˜value’

```

Return type:

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

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’).

Args:
middleware (Callable, optional): A callable that takes in a

request and response. Defaults to None.

Returns:
Callable: The decorated middleware function or a partial function

depending on how the method was called.

Examples:

```python @app.on_response async def custom_middleware(request, response):

response.headers[β€˜X-Server’] = β€˜Sanic’

```

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

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

Args:

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

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

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

  • strict_slashes (bool | None) –

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

  • name (str | None) –

  • ignore_body (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

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

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

Args:

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

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

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

  • strict_slashes (bool | None) –

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

  • name (str | None) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

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

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

Args:

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

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

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

  • strict_slashes (bool | None) –

  • stream (bool) –

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

  • name (str | None) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

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

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

Args:

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

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

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

  • strict_slashes (bool | None) –

  • stream (bool) –

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

  • name (str | None) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

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

register(app, options)

Register the blueprint to the sanic app.

Args:

app (Sanic): Sanic app to register the blueprint to. options (dict): Options to be passed to the blueprint.

static register_futures(apps, bp, futures)

Register futures to the apps.

Args:

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.

Parameters:
  • apps (Set[Sanic]) –

  • bp (Blueprint) –

  • futures (Sequence[Tuple[Any, ...]]) –

reload_process_start(listener, *, priority=0)

Decorator for registering a listener for the reload_process_start event.

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](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.reload_process_start async def on_reload_process_start(app: Sanic):

print(β€œReload process started”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

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

reload_process_stop(listener, *, priority=0)

Decorator for registering a listener for the reload_process_stop event.

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](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.reload_process_stop async def on_reload_process_stop(app: Sanic):

print(β€œReload process stopped”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

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

reset()

Reset the blueprint to its initial state.

Return type:

None

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.

Args:

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

Returns:

RouteWrapper: Tuple of routes, decorated function.

Examples:

Using the method to define a GET endpoint:

```python @app.route(β€œ/hello”) async def hello(request: Request):

return text(β€œHello, World!”)

```

Adding context kwargs to the route:

```python @app.route(β€œ/greet”, ctx_name=”World”) async def greet(request: Request):

name = request.route.ctx.name return text(f”Hello, {name}!”)

```

Parameters:
  • uri (str) –

  • methods (Iterable[str] | None) –

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

  • strict_slashes (bool | None) –

  • stream (bool) –

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

  • name (str | None) –

  • ignore_body (bool) –

  • apply (bool) –

  • subprotocols (List[str] | None) –

  • websocket (bool) –

  • unquote (bool) –

  • static (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

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

signal(event, *, apply=True, condition=None, exclusive=True, priority=0)

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

  • priority (int) –

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 provides an easy and simple way to set up the route necessary to serve static files.

Args:

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, optional): Regex pattern identifying the valid

static files. Defaults to r”/?.+”.

use_modified_since (bool, optional): 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, optional): If true, process header for

range requests and sends the file part that is requested. Defaults to False.

stream_large_files (Union[bool, int], optional): 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, optional): User-defined name used for url_for.

Defaults to β€œstatic”.

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

content_type (Optional[str], optional): User-defined content type

for header.

apply (bool, optional): If true, will register the route

immediately. Defaults to True.

resource_type (Optional[str], optional): Explicitly declare a

resource to be a β€œfile” or a β€œdir”.

index (Optional[Union[str, Sequence[str]]], optional): 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, optional): Whether to fallback to showing

the directory viewer when exposing a directory. Defaults to False.

directory_handler (Optional[DirectoryHandler], optional): An

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

Returns:

List[sanic.router.Route]: Routes registered on the router.

Examples:

Serving a single file: `python app.static('/foo', 'path/to/static/file.txt') `

Serving all files from a directory: `python app.static('/static', 'path/to/static/directory') `

Serving large files with a specific threshold: `python app.static('/static', 'path/to/large/files', stream_large_files=1000000) `

Parameters:
  • uri (str) –

  • file_or_directory (PathLike | str) –

  • pattern (str) –

  • use_modified_since (bool) –

  • use_content_range (bool) –

  • stream_large_files (bool | int) –

  • name (str) –

  • host (str | None) –

  • strict_slashes (bool | None) –

  • content_type (str | None) –

  • apply (bool) –

  • resource_type (str | None) –

  • index (str | Sequence[str] | None) –

  • directory_view (bool) –

  • directory_handler (DirectoryHandler | None) –

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.

Args:

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

Returns:

tuple: Tuple of routes, decorated function.

Parameters:
  • uri (str) –

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

  • strict_slashes (bool | None) –

  • subprotocols (List[str] | None) –

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

  • name (str | None) –

  • apply (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

property apps: Set[Sanic]

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

Returns:

Set[Sanic]: Set of apps that this blueprint is registered to.

Raises:
SanicException: If the blueprint has not yet been registered to

an app.

property registered: bool

Check if the blueprint has been registered to an app.

Returns:
bool: True if the blueprint has been registered to an app,

False otherwise.

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

Bases: MutableSequence

This class provides a mechanism to implement a Blueprint Group.

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.

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

```python 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) ```

Parameters:
  • url_prefix (Optional[str]) –

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

  • strict_slashes (Optional[bool]) –

  • version_prefix (str) –

  • name_prefix (Optional[str]) –

append(value)

Add a new Blueprint object to the group.

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

Args:

value (Blueprint): New Blueprint object.

Returns:

None

Parameters:

value (Blueprint) –

Return type:

None

clear() None -- remove all items from S
count(value) integer -- return number of occurrences of value
exception(*exceptions, **kwargs)

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

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

Args:

*exceptions (Exception): Exceptions to handle **kwargs (dict): Optional Keyword arg to use with Middleware

Returns:

Partial function to apply the middleware

Examples:

```python 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”)

```

Parameters:

exceptions (Exception) –

Return type:

Callable

extend(values)

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

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

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(index, item)

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

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

Args:

index (int): Index to use for removing a new Blueprint item item (Blueprint): New Blueprint object.

Returns:

None

Parameters:
Return type:

None

middleware(*args, **kwargs)

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

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

Args:

*args (Optional): Optional positional Parameters to be use middleware **kwargs (Optional): Optional Keyword arg to use with Middleware

Returns:

Partial function to apply the middleware

on_request(middleware=None)

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

Args:

middleware (Optional): Optional positional Parameters to be use middleware

Returns:

Partial function to apply the middleware

on_response(middleware=None)

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

Args:

middleware (Optional): Optional positional Parameters to be use middleware

Returns:

Partial function to apply the middleware

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

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

remove(value)

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()

S.reverse() – reverse IN PLACE

property blueprints: List[Blueprint]

A list of all the available blueprints under this group.

Returns:
List[Blueprint]: List of all the available blueprints under

this group.

property name_prefix: str | None

Name prefix for the Blueprint Group.

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

Returns:

Optional[str]: Name prefix for the Blueprint Group.

property strict_slashes: bool | None

Whether to enforce strict slashes for the Blueprint Group.

Returns:

Optional[bool]: Whether to enforce strict slashes for the

property url_prefix: int | float | str | None

The URL prefix for the Blueprint Group.

Returns:
Optional[Union[int, str, float]]: URL prefix for the Blueprint

Group.

property version: int | float | str | None

API Version for the Blueprint Group, if any.

Returns:

Optional[Union[str, int, float]]: API Version for the Blueprint

property version_prefix: str

Version prefix for the Blueprint Group.

Returns:

str: Version prefix for the Blueprint Group.

sanic.blueprints.lazy(func, as_decorator=True)

Decorator to register a function to be called later.

Args:

func (Callable): Function to be called later. as_decorator (bool): Whether the function should be called

immediately or not.

sanic.blueprint_group

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

This class provides a mechanism to implement a Blueprint Group.

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.

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

```python 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) ```

Parameters:
  • url_prefix (Optional[str]) –

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

  • strict_slashes (Optional[bool]) –

  • version_prefix (str) –

  • name_prefix (Optional[str]) –

__delitem__(index: int) None
__delitem__(index: slice) None

Delete the Blueprint object at the specified 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.

Args:

index (int): Index to use for removing a new Blueprint item

Returns:

None

Raises:

IndexError: If the index is out of range.

__getitem__(item: int) Blueprint
__getitem__(item: slice) MutableSequence[Blueprint]

Get the Blueprint object at the specified index.

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.

Returns:

Blueprint: Blueprint object at the specified index.

Raises:

IndexError: If the index is out of range.

__init__(url_prefix=None, version=None, strict_slashes=None, version_prefix='/v', name_prefix='')
Parameters:
  • url_prefix (str | None) –

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

  • strict_slashes (bool | None) –

  • version_prefix (str) –

  • name_prefix (str | None) –

__iter__()

Iterate over the list of blueprints in the group.

Returns:

Iterator[Blueprint]: Iterator for the list of blueprints in

Return type:

Iterator[Blueprint]

__len__()

Get the Length of the blueprint group object.

Returns:

int: Length of the blueprint group object.

Return type:

int

__setitem__(index: int, item: Blueprint) None
__setitem__(index: slice, item: Iterable[Blueprint]) None

Set the Blueprint object at the specified 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 perform the list’s indexed setter operation.

Args:

index (int): Index to use for removing a new Blueprint item item (Blueprint): New Blueprint object.

Returns:

None

Raises:

IndexError: If the index is out of range.

append(value)

Add a new Blueprint object to the group.

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

Args:

value (Blueprint): New Blueprint object.

Returns:

None

Parameters:

value (Blueprint) –

Return type:

None

exception(*exceptions, **kwargs)

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

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

Args:

*exceptions (Exception): Exceptions to handle **kwargs (dict): Optional Keyword arg to use with Middleware

Returns:

Partial function to apply the middleware

Examples:

```python 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”)

```

Parameters:

exceptions (Exception) –

Return type:

Callable

insert(index, item)

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

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

Args:

index (int): Index to use for removing a new Blueprint item item (Blueprint): New Blueprint object.

Returns:

None

Parameters:
Return type:

None

middleware(*args, **kwargs)

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

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

Args:

*args (Optional): Optional positional Parameters to be use middleware **kwargs (Optional): Optional Keyword arg to use with Middleware

Returns:

Partial function to apply the middleware

on_request(middleware=None)

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

Args:

middleware (Optional): Optional positional Parameters to be use middleware

Returns:

Partial function to apply the middleware

on_response(middleware=None)

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

Args:

middleware (Optional): Optional positional Parameters to be use middleware

Returns:

Partial function to apply the middleware

property blueprints: List[Blueprint]

A list of all the available blueprints under this group.

Returns:
List[Blueprint]: List of all the available blueprints under

this group.

property name_prefix: str | None

Name prefix for the Blueprint Group.

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

Returns:

Optional[str]: Name prefix for the Blueprint Group.

property strict_slashes: bool | None

Whether to enforce strict slashes for the Blueprint Group.

Returns:

Optional[bool]: Whether to enforce strict slashes for the

property url_prefix: int | float | str | None

The URL prefix for the Blueprint Group.

Returns:
Optional[Union[int, str, float]]: URL prefix for the Blueprint

Group.

property version: int | float | str | None

API Version for the Blueprint Group, if any.

Returns:

Optional[Union[str, int, float]]: API Version for the Blueprint

property version_prefix: str

Version prefix for the Blueprint Group.

Returns:

str: Version prefix for the Blueprint Group.