Adding prefixes to Flask routes can be a hassle when managing several routes. Manually setting prefixes limits your flexibility and increases the risk of errors. Exploring an automated approach can streamline your development workflow.
In Flask, blueprints provide a solution to this challenge. By grouping related views together in a blueprint, you can apply a prefix to all routes within that blueprint.
Consider the following Python code:
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"
This code defines a blueprint named 'burritos' with two routes: '/' and '/about'. Now, you can register this blueprint with your Flask application, specifying the desired prefix:
app = Flask(__name__) app.register_blueprint(bp, url_prefix='/abc/123')
With this configuration, all routes in the 'burritos' blueprint will automatically have the prefix '/abc/123' applied. Consequently, accessing 'index_page' requires the URL '/abc/123/' instead of just '/', and '/about_page' is accessed through '/abc/123/about'.
The above is the detailed content of How can I automate route prefixing in Flask?. For more information, please follow other related articles on the PHP Chinese website!