Flask Blueprints: Organising Large Applications
When your app.py grows past 300 lines, it's time for Blueprints — Flask's built-in module system.
What Is a Blueprint?
A Blueprint is a collection of routes, templates, and static files that can be registered on an app later. Think of it as a mini-app.
Project Structure
myapp/
app.py
routes/
__init__.py
auth.py
blog.py
admin.py
templates/
auth/
login.html
blog/
index.html
admin/
dashboard.html
Creating a Blueprint
# routes/auth.py
from flask import Blueprint, render_template, redirect, url_for, session
auth_bp = Blueprint('auth', __name__, url_prefix='/auth')
@auth_bp.route('/login')
def login():
return render_template('auth/login.html')
@auth_bp.route('/logout')
def logout():
session.clear()
return redirect(url_for('main.index'))
Registering Blueprints
# app.py
from flask import Flask
from routes.auth import auth_bp
from routes.blog import blog_bp
from routes.admin import admin_bp
def create_app():
app = Flask(__name__)
app.secret_key = 'change-me'
app.register_blueprint(auth_bp)
app.register_blueprint(blog_bp)
app.register_blueprint(admin_bp)
return app
Blueprint-Specific Templates
Flask searches templates/auth/login.html when you call render_template('auth/login.html') from a Blueprint — namespacing prevents collisions.
URL Prefixes
# All routes in blog_bp are at /blog/...
blog_bp = Blueprint('blog', __name__, url_prefix='/blog')
# Admin blueprint guarded by a before_request check
admin_bp = Blueprint('admin', __name__, url_prefix='/admin')
@admin_bp.before_request
def require_admin():
if session.get('user_role') != 'admin':
abort(403)
Cross-Blueprint URL Generation
# From any template or route:
url_for('auth.login') # → /auth/login
url_for('blog.index') # → /blog/
url_for('admin.dashboard') # → /admin/
Blueprints keep your code readable, testable, and team-friendly as your app scales.
0 Comments
Join the conversation
No comments yet. Be the first!