Skip to content

Instantly share code, notes, and snippets.

@tachyondecay
Last active April 26, 2025 23:38
Show Gist options
  • Save tachyondecay/2df8baaf7bb20099b6d4dc108e29ab3f to your computer and use it in GitHub Desktop.
Save tachyondecay/2df8baaf7bb20099b6d4dc108e29ab3f to your computer and use it in GitHub Desktop.
Blueprint static folder with dynamic url prefix
from flask import Blueprint, Flask, g, url_for
app = Flask(__name__)
elections = Blueprint("elections", __name__)
elec_bp = Blueprint("elec", __name__, static_folder='static')
@elec_bp.url_value_preprocessor
def pull_election_id(endpoint, values):
g.election_id = values.pop('election_id')
@elec_bp.url_defaults
def add_election_id(endpoint, values):
values.setdefault('election_id', g.election_id)
@elec_bp.route("/")
def test():
## Returns "/elec/1/static/index.js"
## To access election_id in route, use g.election_d
return url_for(".static", filename="index.js")
@elec_bp.route("/question/<int:question_id>/")
def question(question_id):
## Returns "/elec/1/static/index.js"
return url_for(".static", filename="index.js")
elections.register_blueprint(elec_bp, url_prefix="/<int:election_id>")
app.register_blueprint(elections, url_prefix="/elec")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment