Performance: Blueprint best practices
Blueprints affect the organization and loading of routes and templates, impacting initial app startup and request handling speed.
from flask import Flask from user import user_bp from admin import admin_bp app = Flask(__name__) app.register_blueprint(user_bp, url_prefix='/user') app.register_blueprint(admin_bp, url_prefix='/admin') if __name__ == '__main__': app.run()
from flask import Flask app = Flask(__name__) @app.route('/user') def user(): # complex logic here return 'User Page' @app.route('/admin') def admin(): # complex logic here return 'Admin Page' if __name__ == '__main__': app.run()
| Pattern | Module Loading | App Startup Time | Memory Usage | Verdict |
|---|---|---|---|---|
| Single file routes | Loads all modules at once | Slower startup | Higher memory | [X] Bad |
| Blueprints with lazy imports | Loads modules on registration | Faster startup | Lower memory | [OK] Good |
Blueprint in a Flask application?auth with a URL prefix /auth in a Flask app?app.register_blueprint(blueprint, url_prefix='...').from flask import Blueprint
bp = Blueprint('bp', __name__, url_prefix='/items')
@bp.route('/')
def list_items():
return 'List of items''List of items' when this Blueprint is registered with app.register_blueprint(bp)?url_prefix='/items', so all routes start with '/items'.@bp.route('/'), so it adds '/' after the prefix.from flask import Flask, Blueprint
app = Flask(__name__)
bp = Blueprint('bp', __name__)
@bp.route('/hello')
def hello():
return 'Hello!'
app.register_blueprint(bp, url_prefix='/greet')
if __name__ == '__main__':
app.run()admin_bp with url_prefix='/admin' and user_bp with url_prefix='/user'. Both define a route @bp.route('/dashboard'). What is the best practice to avoid URL conflicts and keep your app organized?Pass the test and this pattern moves unknown