blueprint of blueprints (Flask)
I wish the Blueprint object has a register_blueprint function just as the Flask object does. It would automatically place and registered blueprints under the current Blueprints' url.
The simplest way would be to create a function that takes an instance of a Flask
application and registers all your blueprints on it in one go. Something like this:
# sub_site/__init__.pyfrom .sub_page1 import bp as sb1bpfrom .sub_page2 import bp as sb2bp# ... etc. ...def register_sub_site(app, url_prefix="/sub-site"): app.register_blueprint(sb1bp, url_prefix=url_prefix) app.register_blueprint(sb2bp, url_prefix=url_prefix) # ... etc. ...# sub_site/sub_page1.pyfrom flask import Blueprintbp = Blueprint("sub_page1", __name__)@bp.route("/")def sub_page1_index(): pass
Alternately, you could use something like HipPocket
's autoload
function (full disclosure: I wrote HipPocket
) to simplify the import handling:
# sub_site/__init__.pyfrom hip_pocket.tasks import autoloaddef register_sub_site(app, url_prefix="/sub-site", base_import_name="sub_site"): autoload(app, base_import_name, blueprint_name="bp")
However, as it currently stands you couldn't use the same structure as example #1 (HipPocket assumes you are using packages for each Blueprint). Instead, your layout would look like this:
# sub_site/sub_page1/__init__.py# This space intentionally left blank# sub_site/sub_page1/routes.pyfrom flask import Blueprintbp = Blueprint("sub_page1", __name__)@bp.route("/")def sub_page1_index(): pass
Check this out: Nesting Blueprints → https://flask.palletsprojects.com/en/2.0.x/blueprints/#nesting-blueprints
parent = Blueprint('parent', __name__, url_prefix='/parent')child = Blueprint('child', __name__, url_prefix='/child')parent.register_blueprint(child)app.register_blueprint(parent)