0
0
Flaskframework~5 mins

Blueprint creation and registration in Flask

Choose your learning style9 modes available
Introduction

Blueprints help organize your Flask app by grouping routes and code. They make big apps easier to manage.

You want to split your app into parts like user pages and admin pages.
You want to reuse code across different apps.
You want to keep your main app file clean and simple.
You want to register routes only when needed.
You want to organize your app by features or sections.
Syntax
Flask
from flask import Blueprint

bp = Blueprint('name', __name__, url_prefix='/prefix')

@bp.route('/path')
def view_func():
    return 'Hello from blueprint!'

# In main app file
from flask import Flask
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 user-related routes under '/users'.
Flask
bp = Blueprint('users', __name__, url_prefix='/users')

@bp.route('/')
def users_home():
    return 'Users Home'
This blueprint handles admin routes with a '/admin' prefix.
Flask
bp = Blueprint('admin', __name__, url_prefix='/admin')

@bp.route('/dashboard')
def admin_dashboard():
    return 'Admin Dashboard'
This registers the blueprint with the main Flask app.
Flask
app = Flask(__name__)
app.register_blueprint(bp)
Sample Program

This example creates a blog blueprint with two routes. It registers the blueprint to the main app. When you visit '/blog/' you see the blog home. When you visit '/blog/post/1' you see post 1.

Flask
from flask import Flask, Blueprint

# Create a blueprint for blog
blog_bp = Blueprint('blog', __name__, url_prefix='/blog')

@blog_bp.route('/')
def blog_home():
    return 'Welcome to the Blog!'

@blog_bp.route('/post/<int:id>')
def show_post(id):
    return f'Post number {id}'

# Create main app
app = Flask(__name__)

# Register the blueprint
app.register_blueprint(blog_bp)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Blueprints let you organize routes and code separately from the main app.

Always register blueprints before running the app.

You can create many blueprints for different parts of your app.

Summary

Blueprints group routes and code for better organization.

Use Blueprint to create, then app.register_blueprint() to add it.

Blueprints help keep your Flask app clean and modular.