Skip to content

Blueprints

Blueprints are used to modularly organize routes, templates, static files, and error handlers, facilitating splitting and reuse in large projects.

Define Blueprint:

python
# app/blog/__init__.py
from flask import Blueprint

bp = Blueprint("blog", __name__, url_prefix="/blog")

@bp.get("/")
def list_posts():
    return "Blog list"

Register Blueprint:

python
# app/__init__.py
from .blog import bp as blog_bp
app.register_blueprint(blog_bp)

Template/Static Isolation:

python
bp = Blueprint("blog", __name__, template_folder="templates", static_folder="static")

Named Endpoints: Use blueprint_name.view_func to reference, such as url_for("blog.list_posts").

Blueprints and Factory: Use with application factory for lazy registration to avoid circular imports.

Error Handling and Hooks: Blueprints can register before_app_request/after_app_request hooks and error handlers, which only apply to their namespace.

Content is for learning and research only.