Blueprints are objects that can be used for sub-routing within an application.
Instead of adding routes to the application instance, blueprints define similar
methods for adding routes, which are then registered with the application in a
flexible and pluggable manner.

Blueprints are especially useful for larger applications, where your
application logic can be broken down into several groups or areas of
responsibility.

Blueprints may also be registered as part of a list or tuple, where the registrar will recursively cycle through any sub-sequences of blueprints and register them accordingly. The Blueprint.group method is provided to simplify this process, allowing a ‘mock’ backend directory structure mimicking what’s seen from the front end. Consider this (quite contrived) example:

Using this middleware will ensure that you can apply a common middleware to all the blueprints that form the
current blueprint group under consideration.

bp1=Blueprint('bp1',url_prefix='/bp1')bp2=Blueprint('bp2',url_prefix='/bp2')@bp1.middleware('request')asyncdefbp1_only_middleware(request):print('applied on Blueprint : bp1 Only')@bp1.route('/')asyncdefbp1_route(request):returntext('bp1')@bp2.route('/<param>')asyncdefbp2_route(request,param):returntext(param)group=Blueprint.group(bp1,bp2)@group.middleware('request')asyncdefgroup_middleware(request):print('common middleware applied for both bp1 and bp2')# Register Blueprint group under the appapp.blueprint(group)

# suppose bp.name == 'bp'bp.static('/web/path','/folder/to/serve')# also you can pass name parameter to it for url_forbp.static('/web/path','/folder/to/server',name='uploads')app.url_for('static',name='bp.uploads',filename='file.txt')=='/bp/web/path/file.txt'

Blueprints can be very useful for API versioning, where one blueprint may point
at /v1/<routes>, and another pointing at /v2/<routes>.

When a blueprint is initialised, it can take an optional version argument,
which will be prepended to all routes defined on the blueprint. This feature
can be used to implement our API versioning scheme.

# blueprints.pyfromsanic.responseimporttextfromsanicimportBlueprintblueprint_v1=Blueprint('v1',url_prefix='/api',version="v1")blueprint_v2=Blueprint('v2',url_prefix='/api',version="v2")@blueprint_v1.route('/')asyncdefapi_v1_root(request):returntext('Welcome to version 1 of our documentation')@blueprint_v2.route('/')asyncdefapi_v2_root(request):returntext('Welcome to version 2 of our documentation')

When we register our blueprints on the app, the routes /v1/api and /v2/api will now
point to the individual blueprints, which allows the creation of sub-sites
for each API version.