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
- 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:
- 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:
middleware_or_request (Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | str) β
attach_to (str) β
apply (bool) β
priority (int) β
- 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.
- 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
formapply (bool, optional) β For lazy evaluation, defaults to
True
condition (Dict[str, Any], optional) β For use with the
condition
argument in dispatch filtering, defaults toNone
exclusive (bool) β When
True
, the signal can only be dispatched when the condition has been met. WhenFalse
, the signal can be dispatched either with or without it. THIS IS INAPPLICABLE TO BLUEPRINT SIGNALS. THEY ARE ALWAYS NON-EXCLUSIVE, defaults toTrue
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:
index (int) β
item (Blueprint) β
- 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.
- 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:
index (int) β
item (Blueprint) β
- 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.
- 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.