Blueprints help split a big Flask app into smaller parts. This makes the app easier to build and manage.
0
0
Why blueprints organize large applications in Flask
Introduction
When your app has many pages or features that need separate code.
When you want different teams to work on different parts of the app.
When you want to reuse parts of your app in other projects.
When you want to keep your code clean and organized.
When you want to add new features without changing the main app file.
Syntax
Flask
from flask import Blueprint bp = Blueprint('name', __name__, url_prefix='/prefix') @bp.route('/route') def view_func(): return 'Hello from blueprint!' # In main app file from flask import Flask from your_blueprint_file import bp app = Flask(__name__) app.register_blueprint(bp)
The first argument to Blueprint is the blueprint's name.
url_prefix adds a prefix to all routes in the blueprint.
Examples
This blueprint handles blog pages under the '/blog' URL.
Flask
bp = Blueprint('blog', __name__, url_prefix='/blog') @bp.route('/') def blog_home(): return 'Welcome to the blog!'
This blueprint manages admin pages with '/admin' prefix.
Flask
bp = Blueprint('admin', __name__, url_prefix='/admin') @bp.route('/dashboard') def dashboard(): return 'Admin dashboard here.'
Sample Program
This example shows a simple Flask app with a blueprint for user pages. The user blueprint has a route '/profile' that shows a user profile page. The blueprint is registered to the main app with the prefix '/user'. So the full URL is '/user/profile'.
Flask
from flask import Flask, Blueprint # Create a blueprint for user pages user_bp = Blueprint('user', __name__, url_prefix='/user') @user_bp.route('/profile') def profile(): return 'User profile page' # Create main app app = Flask(__name__) # Register the blueprint app.register_blueprint(user_bp) if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Blueprints let you group related routes and code together.
They help keep your main app file small and clean.
You can register many blueprints in one app.
Summary
Blueprints split big Flask apps into smaller parts.
They make code easier to manage and reuse.
Use blueprints to organize routes with URL prefixes.