How to Prefix Flask Routes
When dealing with a Flask application, it can be tedious to manually add a prefix to every route definition. This article presents a solution to automatically prefix all routes with a desired value.
In a Flask application, you can organize routes into blueprints. Each blueprint encapsulates a collection of related views and routes. By placing routes within a blueprint, you can assign a common prefix to them.
Code Example
Here's an example of how to use a blueprint to prefix all routes with "/abc/123":
# Create a blueprint bp = Blueprint('burritos', __name__, template_folder='templates') # Define routes within the blueprint @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" # Register the blueprint with the Flask app app = Flask(__name__) app.register_blueprint(bp, url_prefix='/abc/123')
By prefixing the blueprint with "/abc/123," all routes within the blueprint will automatically have that prefix applied. This eliminates the need to manually add the prefix to each route definition.
The above is the detailed content of How to Automatically Prefix Flask Routes?. For more information, please follow other related articles on the PHP Chinese website!