Add a prefix to all Flask routes

Evan Hahn picture Evan Hahn · Sep 23, 2013 · Viewed 88.6k times · Source

I have a prefix that I want to add to every route. Right now I add a constant to the route at every definition. Is there a way to do this automatically?

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"

Answer

Miguel picture Miguel · Sep 23, 2013

You can put your routes in a 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"

Then you register the blueprint with the application using a prefix:

app = Flask(__name__)
app.register_blueprint(bp, url_prefix='/abc/123')