Blueprintsο
sanic.blueprintsο
- class sanic.blueprints.Blueprint(name=None, url_prefix=None, host=None, version=None, strict_slashes=None, version_prefix='/v')ο
Bases:
BaseSanic
In Sanic terminology, a Blueprint is a logical collection of URLs that perform a specific set of tasks which can be identified by a unique name.
It is the main tool for grouping functionality and similar endpoints.
- Parameters:
name (str) β unique name of the blueprint
url_prefix (Optional[str]) β URL to be prefixed before all route URLs
host (Optional[Union[List[str], str]]) β IP Address or FQDN for the sanic server to use.
version (Optional[Union[int, str, float]]) β Blueprint Version
strict_slashes (bool | None) β Enforce the API urls are requested with a trailing /
version_prefix (str) β
- add_route(handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, stream=False, version_prefix='/v', error_format=None, unquote=False, **ctx_kwargs)ο
A helper method to register class instance or functions as a handler to the application url routes.
- Parameters:
handler (Callable[[...], Coroutine[Any, Any, HTTPResponse | None]]) β function or class instance
uri (str) β path of the URL
methods (Iterable[str]) β list or tuple of methods allowed, these are overridden if using a HTTPMethodView
host (str | List[str] | None) β
strict_slashes (bool | None) β
version (int | str | float | None) β
name (str | None) β user defined route name for url_for
stream (bool) β boolean specifying if the handler is a stream handler
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)error_format (str | None) β
unquote (bool) β
- Returns:
function or class instance
- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- add_websocket_route(handler, uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ο
A helper method to register a function as a websocket route.
- Parameters:
handler β a callable function or instance of a class that can handle the websocket request
host (str | List[str] | None) β Host IP or FQDN details
uri (str) β URL path that will be mapped to the websocket handler handler
strict_slashes (bool | None) β If the API endpoint needs to terminate with a β/β or not
subprotocols β Subprotocols to be used with websocket handshake
name (str | None) β A unique name assigned to the URL so that it can be used with
url_for()
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)version (int | str | float | None) β
error_format (str | None) β
- Returns:
Objected decorated by
websocket()
- copy(name, url_prefix=<sanic.helpers.Default object>, version=<sanic.helpers.Default object>, version_prefix=<sanic.helpers.Default object>, strict_slashes=<sanic.helpers.Default object>, with_registration=True, with_ctx=False)ο
Copy a blueprint instance with some optional parameters to override the values of attributes in the old instance.
- Parameters:
name (str) β unique name of the blueprint
url_prefix (str | Default | None) β URL to be prefixed before all route URLs
version (int | str | float | Default | None) β Blueprint Version
version_prefix (str | Default) β the prefix of the version number shown in the URL.
strict_slashes (bool | Default | None) β Enforce the API urls are requested with a trailing /
with_registration (bool) β whether register new blueprint instance with sanic apps that were registered with the old instance or not.
with_ctx (bool) β whether
ctx
will be copied or not.
- delete(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=False, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the DELETE HTTP method
- Parameters:
uri (str) β URL to be tagged to DELETE method of HTTP
host (str | List[str] | None) β Host IP or FQDN for the service to use
strict_slashes (bool | None) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (int | str | float | None) β API Version
name (str | None) β Unique name that can be used to identify the Route
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)ignore_body (bool) β
error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- exception(*exceptions, apply=True)ο
This method enables the process of creating a global exception handler for the current blueprint under question.
- Parameters:
args β List of Python exceptions to be caught by the handler
kwargs β Additional optional arguments to be passed to the exception handler
- :return a decorated method to handle global exceptions for any
route registered under this blueprint.
- get(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the GET HTTP method
- Parameters:
uri (str) β URL to be tagged to GET method of HTTP
host (str | List[str] | None) β Host IP or FQDN for the service to use
strict_slashes (bool | None) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (int | str | float | None) β API Version
name (str | None) β Unique name that can be used to identify the Route
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)ignore_body (bool) β
error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- static group(*blueprints, url_prefix=None, version=None, strict_slashes=None, version_prefix='/v')ο
Create a list of blueprints, optionally grouping them under a general URL prefix.
- Parameters:
blueprints (Blueprint | BlueprintGroup) β blueprints to be registered as a group
url_prefix (str | None) β URL route to be prepended to all sub-prefixes
version (int | str | float | None) β API Version to be used for Blueprint group
strict_slashes (bool | None) β Indicate strict slash termination behavior for URL
version_prefix (str) β
- Return type:
- head(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the HEAD HTTP method
- Parameters:
uri (str) β URL to be tagged to HEAD method of HTTP
host (Optional[str], optional) β Host IP or FQDN for the service to use
strict_slashes (Optional[bool], optional) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (Optional[str], optional) β API Version
name (Optional[str], optional) β Unique name that can be used to identify the Route
ignore_body (bool, optional) β whether the handler should ignore request body (eg. GET requests), defaults to True
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- listener(listener_or_event, event_or_none=None, apply=True)ο
Create a listener from a decorated function.
To be used as a decorator:
@bp.listener("before_server_start") async def before_server_start(app, loop): ...
- Parameters:
event β event to listen to
listener_or_event (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | str) β
event_or_none (str | None) β
apply (bool) β
- Return type:
Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | Callable[[Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]], Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]]
- middleware(middleware_or_request, attach_to='request', apply=True, *, priority=0)ο
Decorate and register middleware to be called before a request is handled or after a response is created. Can either be called as @app.middleware or @app.middleware(βrequestβ).
- Param:
middleware_or_request: Optional parameter to use for identifying which type of middleware is being registered.
- on_request(middleware=None, *, priority=0)ο
Register a middleware to be called before a request is handled.
This is the same as @app.middleware(βrequestβ).
- Param:
middleware: A callable that takes in request.
- on_response(middleware=None, *, priority=0)ο
Register a middleware to be called after a response is created.
This is the same as @app.middleware(βresponseβ).
- Param:
middleware: A callable that takes in a request and its response.
- options(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the OPTIONS HTTP method
- Parameters:
uri (str) β URL to be tagged to OPTIONS method of HTTP
host (Optional[str], optional) β Host IP or FQDN for the service to use
strict_slashes (Optional[bool], optional) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (Optional[str], optional) β API Version
name (Optional[str], optional) β Unique name that can be used to identify the Route
ignore_body (bool, optional) β whether the handler should ignore request body (eg. GET requests), defaults to True
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- patch(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the PATCH HTTP method
- Parameters:
uri (str) β URL to be tagged to PATCH method of HTTP
host (Optional[str], optional) β Host IP or FQDN for the service to use
strict_slashes (Optional[bool], optional) β Instruct
Sanic
to check if the request URLs need to terminate with a /stream (Optional[bool], optional) β whether to allow the request to stream its body
version (Optional[str], optional) β API Version
name (Optional[str], optional) β Unique name that can be used to identify the Route
ignore_body (bool, optional) β whether the handler should ignore request body (eg. GET requests), defaults to True
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- post(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the POST HTTP method
- Parameters:
uri (str) β URL to be tagged to POST method of HTTP
host (str | List[str] | None) β Host IP or FQDN for the service to use
strict_slashes (bool | None) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (int | str | float | None) β API Version
name (str | None) β Unique name that can be used to identify the Route
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)stream (bool) β
error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- put(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the PUT HTTP method
- Parameters:
uri (str) β URL to be tagged to PUT method of HTTP
host (str | List[str] | None) β Host IP or FQDN for the service to use
strict_slashes (bool | None) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (int | str | float | None) β API Version
name (str | None) β Unique name that can be used to identify the Route
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)stream (bool) β
error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- register(app, options)ο
Register the blueprint to the sanic app.
- Parameters:
app β Instance of
sanic.app.Sanic
classoptions β Options to be used while registering the blueprint into the app. url_prefix - URL Prefix to override the blueprint prefix
- route(uri, methods=None, host=None, strict_slashes=None, stream=False, version=None, name=None, ignore_body=False, apply=True, subprotocols=None, websocket=False, unquote=False, static=False, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Decorate a function to be registered as a route
Example using context kwargs
@app.route(..., ctx_foo="foobar") async def route_handler(request: Request): assert request.route.ctx.foo == "foobar"
- Parameters:
uri (str) β path of the URL
methods (Iterable[str] | None) β list or tuple of methods allowed
host (str | List[str] | None) β the host, if required
strict_slashes (bool | None) β whether to apply strict slashes to the route
stream (bool) β whether to allow the request to stream its body
version (int | str | float | None) β route specific versioning
name (str | None) β user defined route name for url_for
ignore_body (bool) β whether the handler should ignore request body (eg. GET requests)
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)apply (bool) β
subprotocols (List[str] | None) β
websocket (bool) β
unquote (bool) β
static (bool) β
error_format (str | None) β
- Returns:
tuple of routes, decorated function
- Return type:
Callable[[Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]], Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]] | Tuple[Route, Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]]]
- signal(event, *, apply=True, condition=None, exclusive=True)ο
For creating a signal handler, used similar to a route handler:
@app.signal("foo.bar.<thing>") async def signal_handler(thing, **kwargs): print(f"[signal_handler] {thing=}", kwargs)
- Parameters:
event (str) β Representation of the event in
one.two.three
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
- Return type:
Callable[[Callable[[β¦], Coroutine[Any, Any, None]]], Callable[[β¦], Coroutine[Any, Any, None]]]
- static(uri, file_or_directory, pattern='/?.+', use_modified_since=True, use_content_range=False, stream_large_files=False, name='static', host=None, strict_slashes=None, content_type=None, apply=True, resource_type=None, index=None, directory_view=False, directory_handler=None)ο
Register a root to serve files from. The input can either be a file or a directory. This method will enable an easy and simple way to setup the
Route
necessary to serve the static files.- Parameters:
uri (str) β URL path to be used for serving static content
file_or_directory (PathLike | str) β Path for the Static file/directory with static files
pattern (str) β Regex Pattern identifying the valid static files
use_modified_since (bool) β If true, send file modified time, and return not modified if the browserβs matches the serverβs
use_content_range (bool) β If true, process header for range requests and sends the file part that is requested
stream_large_files (bool | int) β If true, use the
StreamingHTTPResponse.file_stream()
handler rather than theHTTPResponse.file()
handler to send the file. If this is an integer, this represents the threshold size to switch toStreamingHTTPResponse.file_stream()
name (str) β user defined name used for url_for
host (str | None) β Host IP or FQDN for the service to use
strict_slashes (bool | None) β Instruct
Sanic
to check if the request URLs need to terminate with a /content_type (str | None) β user defined content type for header
apply (bool) β If true, will register the route immediately
resource_type (str | None) β Explicitly declare a resource to be a β fileβ or a βdirβ
index (str | Sequence[str] | None) β When exposing against a directory, index is the name that will be served as the default file. When multiple files names are passed, then they will be tried in order.
directory_view (bool) β Whether to fallback to showing the directory viewer when exposing a directory
directory_handler (DirectoryHandler | None) β An instance of
DirectoryHandler
that can be used for explicitly controlling and subclassing the behavior of the default directory handler
- Returns:
routes registered on the router
- Return type:
List[sanic.router.Route]
- websocket(uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None, apply=True, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Decorate a function to be registered as a websocket route
- Parameters:
uri (str) β path of the URL
host (str | List[str] | None) β Host IP or FQDN details
strict_slashes (bool | None) β If the API endpoint needs to terminate with a β/β or not
subprotocols (List[str] | None) β optional list of str with supported subprotocols
name (str | None) β A unique name assigned to the URL so that it can be used with
url_for()
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)version (int | str | float | None) β
apply (bool) β
error_format (str | None) β
- Returns:
tuple of routes, decorated function
sanic.blueprint_groupο
- class sanic.blueprint_group.BlueprintGroup(url_prefix=None, version=None, strict_slashes=None, version_prefix='/v')ο
This class provides a mechanism to implement a Blueprint Group using the
group()
method inBlueprint
. To avoid having to re-write some of the existing implementation, this class provides a custom iterator implementation that will let you use the object of this class as a list/tuple inside the existing implementation.bp1 = Blueprint('bp1', url_prefix='/bp1') bp2 = Blueprint('bp2', url_prefix='/bp2') bp3 = Blueprint('bp3', url_prefix='/bp4') bp3 = Blueprint('bp3', url_prefix='/bp4') bpg = BlueprintGroup(bp3, bp4, url_prefix="/api", version="v1") @bp1.middleware('request') async def bp1_only_middleware(request): print('applied on Blueprint : bp1 Only') @bp1.route('/') async def bp1_route(request): return text('bp1') @bp2.route('/<param>') async def bp2_route(request, param): return text(param) @bp3.route('/') async def bp1_route(request): return text('bp1') @bp4.route('/<param>') async def bp2_route(request, param): return text(param) group = Blueprint.group(bp1, bp2) @group.middleware('request') async def group_middleware(request): print('common middleware applied for both bp1 and bp2') # Register Blueprint group under the app app.blueprint(group) app.blueprint(bpg)
- Parameters:
url_prefix (Optional[str]) β
version (Optional[Union[int, str, float]]) β
strict_slashes (Optional[bool]) β
version_prefix (str) β
- __delitem__(index)ο
Abstract method implemented to turn the BlueprintGroup class into a list like object to support all the existing behavior.
This method is used to delete an item from the list of blueprint groups like it can be done on a regular list with index.
- Parameters:
index β Index to use for removing a new Blueprint item
- Returns:
None
- Return type:
None
- __getitem__(item)ο
This method returns a blueprint inside the group specified by an index value. This will enable indexing, splice and slicing of the blueprint group like we can do with regular list/tuple.
This method is provided to ensure backward compatibility with any of the pre-existing usage that might break.
- Parameters:
item β Index of the Blueprint item in the group
- Returns:
Blueprint object
- __init__(url_prefix=None, version=None, strict_slashes=None, version_prefix='/v')ο
Create a new Blueprint Group
- Parameters:
url_prefix (str | None) β URL: to be prefixed before all the Blueprint Prefix
version (int | str | float | None) β API Version for the blueprint group. This will be inherited by each of the Blueprint
strict_slashes (bool | None) β URL Strict slash behavior indicator
version_prefix (str) β
- __iter__()ο
Tun the class Blueprint Group into an Iterable item
- __len__()ο
Get the Length of the blueprint group object.
- Returns:
Length of Blueprint group object
- Return type:
int
- __setitem__(index, item)ο
Abstract method implemented to turn the BlueprintGroup class into a list like object to support all the existing behavior.
This method is used to perform the listβs indexed setter operation.
- Parameters:
index β Index to use for inserting a new Blueprint item
item β New Blueprint object.
- Returns:
None
- Return type:
None
- append(value)ο
The Abstract class MutableSequence leverages this append method to perform the BlueprintGroup.append operation. :param value: New Blueprint object. :return: None
- Parameters:
value (Blueprint) β
- Return type:
None
- exception(*exceptions, **kwargs)ο
A decorator that can be used to implement a global exception handler for all the Blueprints that belong to this Blueprint Group.
In case of nested Blueprint Groups, the same handler is applied across each of the Blueprints recursively.
- Parameters:
args β List of Python exceptions to be caught by the handler
kwargs β Additional optional arguments to be passed to the exception handler
- Returns:
a decorated method to handle global exceptions for any blueprint registered under this group.
- insert(index, item)ο
The Abstract class MutableSequence leverages this insert method to perform the BlueprintGroup.append operation.
- Parameters:
index (int) β Index to use for removing a new Blueprint item
item (Blueprint) β New Blueprint object.
- Returns:
None
- Return type:
None
- middleware(*args, **kwargs)ο
A decorator that can be used to implement a Middleware plugin to all of the Blueprints that belongs to this specific Blueprint Group.
In case of nested Blueprint Groups, the same middleware is applied across each of the Blueprints recursively.
- Parameters:
args β Optional positional Parameters to be use middleware
kwargs β Optional Keyword arg to use with Middleware
- Returns:
Partial function to apply the middleware
- property blueprints: List[Blueprint]ο
Retrieve a list of all the available blueprints under this group.
- Returns:
List of Blueprint instance
- property strict_slashes: bool | Noneο
URL Slash termination behavior configuration
- Returns:
bool
- property url_prefix: int | str | float | Noneο
Retrieve the URL prefix being used for the Current Blueprint Group
- Returns:
string with url prefix
- property version: int | str | float | Noneο
API Version for the Blueprint Group. This will be applied only in case if the Blueprint doesnβt already have a version specified
- Returns:
Version information
- property version_prefix: strο
Version prefix; defaults to
/v
- Returns:
str