Flask Cheatsheet
Blueprints
Use this Flask reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
What Blueprints Are
A Blueprint is a collection of routes, templates, static files, and error handlers that can be registered on a Flask app. Use them to split a large application into modular components.
Creating a Blueprint
# myapp/blueprints/auth.py from flask import Blueprint, render_template, redirect, url_for auth_bp = Blueprint( "auth", # blueprint name (used in url_for: "auth.login") __name__, # import name (for template/static lookup) url_prefix="/auth", # prepend to all routes in this blueprint template_folder="templates", # blueprint-local templates/ dir static_folder="static", # blueprint-local static/ dir static_url_path="/auth/static", ) @auth_bp.route("/login", methods=["GET", "POST"]) def login(): return render_template("auth/login.html") @auth_bp.route("/logout") def logout(): return redirect(url_for("auth.login"))
Registering a Blueprint
# myapp/__init__.py from flask import Flask from .blueprints.auth import auth_bp from .blueprints.api import api_bp from .blueprints.admin import admin_bp def create_app(): app = Flask(__name__) app.register_blueprint(auth_bp) app.register_blueprint(api_bp, url_prefix="/api/v1") # override prefix at registration app.register_blueprint(admin_bp, url_prefix="/admin", name="admin_v2") # rename return app
register_blueprint options:
| Option | Description |
|---|---|
url_prefix | Override the blueprint's own url_prefix |
name | Override the blueprint name (endpoint namespace) |
subdomain | Mount blueprint on a subdomain |
url_defaults | Dict of default URL values for all routes |
cli_group | CLI command group name |
Blueprint url_for
Always namespace with blueprint_name.view_function:
url_for("auth.login") url_for("api.get_user", user_id=1) url_for("admin.dashboard") # From within the same blueprint, use ".view_name" shorthand: url_for(".login") # resolves to current blueprint's endpoint
Blueprint Hooks
Hooks on a blueprint apply only to that blueprint's requests:
@auth_bp.before_request def require_login(): if not current_user.is_authenticated: return redirect(url_for("auth.login")) @auth_bp.after_request def add_auth_header(response): response.headers["X-Auth-By"] = "MyApp" return response @auth_bp.teardown_request def teardown(exception): pass
App-wide hooks registered on the blueprint (rare — use app hooks instead):
@auth_bp.before_app_request def before_all_requests(): ... @auth_bp.after_app_request def after_all_requests(response): return response
Error Handlers on Blueprints
Blueprint error handlers only catch errors raised within that blueprint's views (Flask 2.3+ — earlier versions require app-level handlers for HTTP errors):
@auth_bp.errorhandler(403) def forbidden(e): return render_template("auth/403.html"), 403 @auth_bp.app_errorhandler(404) def not_found(e): return render_template("errors/404.html"), 404 # app-wide 404
Template Lookup with Blueprints
Flask searches the app's templates/ before blueprint templates. To avoid name collisions, namespace blueprint templates in a subfolder:
myapp/
templates/
base.html # app templates
blueprints/
auth/
templates/
auth/
login.html # render as "auth/login.html"
static/
auth.cssauth_bp = Blueprint("auth", __name__, template_folder="templates") @auth_bp.route("/login") def login(): return render_template("auth/login.html") # finds blueprint template
Static Files with Blueprints
auth_bp = Blueprint( "auth", __name__, static_folder="static", static_url_path="/auth-static", ) # In templates: # url_for("auth.static", filename="auth.css") # → /auth-static/auth.css
Context Processors per Blueprint
@auth_bp.context_processor def inject_user(): return {"current_user": get_current_user()}
CLI Commands per Blueprint
import click @auth_bp.cli.command("create-admin") @click.argument("email") def create_admin(email): """Create an admin user.""" user = User(email=email, role="admin") db.session.add(user) db.session.commit() click.echo(f"Admin {email} created.")
flask auth create-admin admin@example.com
Nesting Blueprints (Flask 2.0+)
parent_bp = Blueprint("parent", __name__, url_prefix="/parent") child_bp = Blueprint("child", __name__, url_prefix="/child") @child_bp.route("/page") def page(): return "child page" # url: /parent/child/page parent_bp.register_blueprint(child_bp) app.register_blueprint(parent_bp)
Typical Blueprint File Structure
myapp/
blueprints/
auth/
__init__.py # Blueprint definition
routes.py # view functions (optional split)
forms.py
models.py
templates/
auth/
login.html
static/
auth.css
api/
__init__.py
v1.py
v2.py# blueprints/auth/__init__.py from flask import Blueprint auth_bp = Blueprint("auth", __name__, template_folder="templates", static_folder="static") from . import routes # import views to register them # noqa: E402,F401
Registering the Same Blueprint Multiple Times
# Mount the same blueprint at two prefixes with different names app.register_blueprint(api_bp, url_prefix="/api/v1", name="api_v1") app.register_blueprint(api_bp, url_prefix="/api/v2", name="api_v2") url_for("api_v1.get_user", id=1) # /api/v1/users/1 url_for("api_v2.get_user", id=1) # /api/v2/users/1
Common Gotchas
- Forgetting
blueprint_name.inurl_forraisesBuildError. - Blueprint templates shadow app templates if names collide — use subdirectories.
- Blueprint
before_requesthooks only fire for that blueprint's routes, not the whole app. static_url_pathdefaults tostatic_foldername if not set; set it explicitly to avoid collisions withapp.static_url_path.- Running
flask routesshows all endpoints including blueprint namespace.