Skip to content

Instantly share code, notes, and snippets.

@berend
Last active August 27, 2023 21:45
Show Gist options
  • Save berend/fb8fd98be235aec7c6d12782805d7bff to your computer and use it in GitHub Desktop.
Save berend/fb8fd98be235aec7c6d12782805d7bff to your computer and use it in GitHub Desktop.
Versioning with flask blueprint
from flask import Blueprint
from flask import Flask
app = Flask(__name__)
v1 = Blueprint("version1", "version1")
v2 = Blueprint('version2', "version2")
@v2.route("/foo")
def index():
return "v2 foo looks different than v1"
@v1.route("/foo")
def index():
return "v1 foo looks different than v2"
@v2.route("/bar")
@v1.route("/bar")
def hello():
return "bar stays the same for v1 and v2"
@app.route('/get_rules')
def root():
rules = [str(rule) for rule in app.url_map.iter_rules()]
return "\n".join(rules)
app.register_blueprint(v1, url_prefix="/v1")
app.register_blueprint(v2, url_prefix="/v2")
app.register_blueprint(v2, url_prefix="/")
app.run(port=8080)
@berend
Copy link
Author

berend commented Aug 28, 2018

This snippet showcases the following:

  • multiple versions in the same code
  • version prefixes via Blueprints
  • routes can use the same code (/v1/bar and /v2/bar)
  • the latest version is also the "root" version ( /bar is equal to /v2/bar

There are some pitfalls here:

  • app.register() calls must be below the route definitions
  • url_prefix has no default to /, so app.register_blueprint(v2) simply does nothing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment