Flask Blueprint URL Prefixes
A URL prefix puts a blueprint under one address part. Every route in the blueprint gains the prefix.
Make the app and the blueprint
This line imports Flask and Blueprint together. The blueprint gains the /shop prefix at birth.
from flask import Flask, Blueprint
app = Flask(__name__)
shop = Blueprint("shop", __name__, url_prefix="/shop")Add a route to the blueprint
The route is /cart inside the blueprint. The prefix will put it under /shop/cart.
@shop.route("/cart")
def cart():
return "Your cart"Register, then ask both addresses
The app registers the blueprint. The prefixed address answers, and the bare address gives a 404.
app.register_blueprint(shop)
client = app.test_client()
print(client.get("/shop/cart").data.decode())
print(client.get("/cart").status_code)Example
from flask import Flask, Blueprint
app = Flask(__name__)
shop = Blueprint("shop", __name__, url_prefix="/shop")
@shop.route("/cart")
def cart():
return "Your cart"
app.register_blueprint(shop)
client = app.test_client()
print(client.get("/shop/cart").data.decode())
print(client.get("/cart").status_code)Key points
- url_prefix="/shop" puts the blueprint under /shop.
- The routes keep their own names after the prefix.
- Prefixes stop two blueprints sharing an address.
- The prefix is set when the blueprint is made.
In this example, the shop blueprint carries the prefix /shop. Its /cart route therefore answers at /shop/cart. The test client asks for the prefixed address and prints the page. It then asks for the bare /cart address, and the print shows the 404 status.
Note
The prefix starts with a slash.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where does the /cart route of a blueprint with url_prefix="/shop" answer?