Sometimes, we want to add a prefix to all Python Flask routes
In this article, we’ll look at how to add a prefix to all Python Flask routes.
How to add a prefix to all Python Flask routes?
To add a prefix to all Python Flask routes, we can create a blueprint.
For instance, we write
bp = Blueprint('burritos', __name__,
template_folder='templates')
@bp.route("/")
def index_page():
return "eat burritos"
@bp.route("/about")
def about_page():
return "eat burritos"
to create the bp
blueprint with the Blueprint
class.
We call it with the burritos'
string to set that as the blueprint name.
Then we create routes in the blueprint with the bp.route
decorator.
Next, we register our blueprint with app.register_blueprint
app = Flask(__name__)
app.register_blueprint(bp, url_prefix='/abc/123')
We set the URL prefix by setting the url_prefix
argument when registering.
Conclusion
To add a prefix to all Python Flask routes, we can create a blueprint.