0
0
Flaskframework~5 mins

Blueprint best practices in Flask

Choose your learning style9 modes available
Introduction

Blueprints help organize your Flask app into smaller parts. This makes your code easier to manage and reuse.

You want to split a large app into smaller sections like user accounts and blog posts.
You need to reuse parts of your app in different projects.
You want to keep your routes and views organized by feature.
You want to separate API routes from web page routes.
You want to make your app easier to test and maintain.
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
from your_blueprint_file import bp

app = Flask(__name__)
app.register_blueprint(bp)

The first argument to Blueprint is its name, used internally.

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 is for API routes, returning JSON data.
Flask
bp = Blueprint('api', __name__, url_prefix='/api')

@bp.route('/data')
def api_data():
    return {'data': 123}
Sample Program

This app uses a blueprint to handle blog routes. The blog homepage is at '/blog/' and individual posts at '/blog/post/<id>'.

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__)
app.register_blueprint(blog_bp)

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

Always give your blueprint a unique name to avoid conflicts.

Use url_prefix to keep routes organized and avoid clashes.

Register blueprints before running the app.

Summary

Blueprints help split your app into smaller, manageable parts.

Use url_prefix to group related routes under a common path.

Register blueprints in your main app to activate their routes.