0
0
Flaskframework~5 mins

Blueprint URL prefixes in Flask

Choose your learning style9 modes available
Introduction

Blueprint URL prefixes help organize your web app by grouping routes under a common starting path. This keeps URLs tidy and your code easier to manage.

You want to group related pages, like all user pages under '/users'.
You are building a big app and want to split routes into smaller parts.
You want to avoid repeating the same URL part for many routes.
You want to create reusable route groups that can be added with different prefixes.
Syntax
Flask
blueprint = Blueprint('name', __name__, url_prefix='/prefix')
The url_prefix adds a common start to all routes in this blueprint.
Routes inside the blueprint do not need to repeat the prefix.
Examples
This blueprint groups routes under '/users'. The route '/' inside becomes '/users/'.
Flask
from flask import Blueprint

users_bp = Blueprint('users', __name__, url_prefix='/users')

@users_bp.route('/')
def users_home():
    return 'Users Home'
The route '/dashboard' inside the admin blueprint is accessed at '/admin/dashboard'.
Flask
from flask import Blueprint

admin_bp = Blueprint('admin', __name__, url_prefix='/admin')

@admin_bp.route('/dashboard')
def dashboard():
    return 'Admin Dashboard'
Sample Program

This Flask app uses a blueprint with the prefix '/blog'. The route '/' inside the blueprint is accessed at '/blog/'. The route '/post/<id>' is accessed at '/blog/post/<id>'.

Flask
from flask import Flask, Blueprint

app = Flask(__name__)

# Create a blueprint with URL prefix '/blog'
blog_bp = Blueprint('blog', __name__, url_prefix='/blog')

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

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

# Register blueprint with the app
app.register_blueprint(blog_bp)

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

URL prefixes help keep your app routes organized and avoid conflicts.

You can register the same blueprint multiple times with different prefixes if needed.

Summary

Blueprint URL prefixes add a common path to all routes in a blueprint.

This makes your URLs cleaner and your code easier to maintain.

Use them to group related routes logically under one URL section.