Labs ICT
โญ Pro Login

Blueprints

Organizing large apps into modules.

Blueprints

As your Flask app grows, putting everything in one file becomes unmanageable. Blueprints let you split your application into modular, reusable pieces. Each blueprint is a collection of routes, templates, and static files that you can register with your app. Think of them as mini-apps that plug into the main one.

Creating a Blueprint

A blueprint is just a Python package with a few key files. Here's the structure for an "auth" blueprint handling login and registration.

# auth/__init__.py
from flask import Blueprint

bp = Blueprint('auth', __name__)

from auth import routes

The Blueprint constructor takes a name and import name. The name is used for URL generation and debugging. After creating it, you import the routes at the bottom to avoid circular imports.

Defining Routes in Blueprints

Routes in a blueprint work exactly like regular Flask routes, just attached to the blueprint instead of the app.

# auth/routes.py
from flask import render_template, redirect, url_for, flash
from flask_login import login_user, logout_user, login_required
from auth import bp
from models import User

@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # handle login logic
        pass
    return render_template('auth/login.html')

@bp.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.login'))

Registering Blueprints

In your main app file, you register each blueprint. This is where you decide how the routes are grouped.

from flask import Flask
from auth import bp as auth_bp
from blog import bp as blog_bp

app = Flask(__name__)

app.register_blueprint(auth_bp, url_prefix='/auth')
app.register_blueprint(blog_bp, url_prefix='/blog')

The url_prefix argument adds a prefix to all routes in that blueprint. So a route at /login in the auth blueprint becomes /auth/login in the app. It's a clean way to organize route groups.

Blueprint Templates

Blueprints can have their own template folders. Put your templates in auth/templates/auth/ and reference them with render_template('auth/login.html'). The blueprint name acts as a namespace so templates from different blueprints don't collide.

Nested Blueprints

You can nest blueprints for even more organization. A blog blueprint might have sub-blueprints for posts and comments. It's like organizing your code into directories โ€” keep things grouped by feature.

Why Blueprints Keep Apps Organized

Without blueprints, you'd end up with one massive routes file handling everything. With blueprints, the auth code lives in the auth package, the blog code lives in the blog package, and the main app just ties them together. It's easier to navigate, easier to test, and easier for teams to work on different features without stepping on each other's toes.

Try it Yourself ->

๐Ÿงช Quick Quiz

What is a Blueprint?