Blueprints help organize your Flask app by grouping routes and templates. They make your code cleaner and easier to manage.
0
0
Blueprint routes and templates in Flask
Introduction
You want to split a big app into smaller parts like user, admin, and blog sections.
You want to reuse routes and templates in different projects.
You want to keep your code organized when working with a team.
You want to load templates specific to a part of your app.
You want to avoid cluttering the main app file with many routes.
Syntax
Flask
from flask import Blueprint, render_template bp = Blueprint('bp_name', __name__, template_folder='templates') @bp.route('/path') def view_func(): return render_template('template.html')
The first argument is the blueprint's name, used internally.
template_folder tells Flask where to find templates for this blueprint.
Examples
This blueprint handles user-related routes and templates.
Flask
from flask import Blueprint, render_template user_bp = Blueprint('user', __name__, template_folder='user_templates') @user_bp.route('/profile') def profile(): return render_template('profile.html')
This blueprint is for admin routes and templates.
Flask
from flask import Blueprint, render_template admin_bp = Blueprint('admin', __name__, template_folder='admin_templates') @admin_bp.route('/dashboard') def dashboard(): return render_template('dashboard.html')
Sample Program
This example creates a blueprint named 'simple' with one route '/hello'. The blueprint is registered with the app under the URL prefix '/bp'. When you visit '/bp/hello', it shows a message from the blueprint.
Flask
from flask import Flask, Blueprint, render_template_string app = Flask(__name__) # Create a blueprint bp = Blueprint('simple', __name__, template_folder='templates') # Define a route in the blueprint @bp.route('/hello') def hello(): # Use a simple template string for demo return render_template_string('<h1>Hello from Blueprint!</h1>') # Register the blueprint with the app app.register_blueprint(bp, url_prefix='/bp') if __name__ == '__main__': app.run(debug=False)
OutputSuccess
Important Notes
Always register your blueprint with the main app using app.register_blueprint().
Use url_prefix to add a common path before all blueprint routes.
Blueprint templates can be stored in a separate folder to keep things tidy.
Summary
Blueprints group routes and templates to organize your Flask app.
Register blueprints with the main app to activate their routes.
Use url_prefix to avoid route conflicts and keep URLs clear.