BudiBadu Logo
Samplebadu

Flask by Example: Blueprint URL Groups

Flask 3.0+

As Flask applications grow, putting all routes in one file becomes unmanageable. Blueprints allow you to organize your application into distinct modules (e.g., auth, admin, api) with their own routes and templates.

Code

from flask import Flask, Blueprint

# --- In a separate file (e.g., auth.py) ---
# 1. Create a Blueprint
auth_bp = Blueprint('auth', __name__, url_prefix='/auth')

@auth_bp.route('/login')
def login():
    return "Auth Login Page"

@auth_bp.route('/register')
def register():
    return "Auth Register Page"

# --- In a separate file (e.g., admin.py) ---
admin_bp = Blueprint('admin', __name__, url_prefix='/admin')

@admin_bp.route('/dashboard')
def dashboard():
    return "Admin Dashboard"

# --- In your main app file (app.py) ---
app = Flask(__name__)

# 2. Register Blueprints
app.register_blueprint(auth_bp)
app.register_blueprint(admin_bp)

@app.route('/')
def index():
    return "Main Index"

# Resulting Routes:
# /              -> index
# /auth/login    -> auth.login
# /auth/register -> auth.register
# /admin/dashboard -> admin.dashboard

Explanation

Blueprints allow you to group related logic, such as authentication or administration features, into separate modules. Instead of attaching routes to the global app object, you attach them to a Blueprint, which is then registered with the main application.

This modularity enables you to apply configurations like url_prefix to a whole group of routes at once. It also makes it possible to reuse blueprints across different projects or share them as extensions.

Using Blueprints is the key to scaling Flask applications beyond a single file. It encourages a clean project structure where code is organized by feature rather than by technical layer, making maintenance much easier.

Code Breakdown

5
Blueprint('auth', __name__, url_prefix='/auth'). The first argument is the name of the blueprint, used for reverse URL lookups (e.g., url_for('auth.login')). The url_prefix is prepended to all routes defined in this blueprint.
7
@auth_bp.route('/login'). We use the blueprint object auth_bp instead of app. Because of the prefix, this route effectively becomes /auth/login.
26
app.register_blueprint(auth_bp). This is the step that actually connects the modular routes to the running application. Without this, the blueprint's routes are never active.
35
Reverse lookups must include the blueprint name. To link to the login page, you would use url_for('auth.login'), not just url_for('login').