Home > Article > Backend Development > How can I automate route prefixing in my Flask application?
Automating Route Prefixing in Flask Applications
When working with Flask, one may encounter the need to add a prefix to all application routes. Manually appending a constant to each route, as demonstrated below, can become tedious.
PREFIX = "/abc/123" @app.route(PREFIX + "/") def index_page(): return "This is a website about burritos" @app.route(PREFIX + "/about") def about_page(): return "This is a website about burritos"
Fortunately, Flask provides a convenient solution to this issue through the use of blueprints. By organizing routes into a blueprint, as shown below, you can define a common prefix for all routes within the blueprint.
bp = Blueprint('burritos', __name__, template_folder='templates') @bp.route("/") def index_page(): return "This is a website about burritos" @bp.route("/about") def about_page(): return "This is a website about burritos"
Subsequently, register the blueprint with the Flask application using the desired prefix:
app = Flask(__name__) app.register_blueprint(bp, url_prefix='/abc/123')
This approach ensures that all routes within the 'burritos' blueprint will automatically inherit the '/abc/123' prefix, providing a more efficient and maintainable way to manage route prefixes in Flask applications.
The above is the detailed content of How can I automate route prefixing in my Flask application?. For more information, please follow other related articles on the PHP Chinese website!