Is there a way to define URLs with optional URL params in Flask? Essentially, what I’d like to do is define rules that allow for optionally specified languages:
/
/de -> matches / (but doesn't collide with /profile)
/profile
/de/profile
I think I’ve figured out a way to do it, but it involves either making a change to how Werkzeug and Flask handles the request (either monkey patching or forking the framework source). This seems like an overly complex way to deal with this problem though.. Is there an easier way to do this that I’m overlooking?
Edit:
Based on Brian’s answer, here’s what I came up with:
app.py:
from loc import l10n
def create_app(config):
app = Flask(__name__)
app.config.from_pyfile(config)
bp = l10n.Blueprint()
bp.add_url_rule('/', 'home', lambda lang_code: lang_code)
bp.add_url_rule('/profile', 'profile', lambda lang_code: 'profile: %s' %
lang_code)
bp.register_app(app)
return app
if __name__ == '__main__':
create_app('dev.cfg').run()
loc/l10ln.py
class Blueprint(Blueprint_):
def __init__(self):
Blueprint_.__init__(self, 'loc', __name__)
def register_app(self, app):
app.register_blueprint(self, url_defaults={'lang_code': 'en'})
app.register_blueprint(self, url_prefix='/<lang_code>')
self.app = app
(I haven’t gotten to pulling lang_code from the variable list yet, but will be doing that shortly)
Now that’s just hot imho.
Blueprints might work for this, since they can be registered multiple times.
If that works, see Internationalized Blueprint URLs in the Flask documentation for a way to avoid specifying a
langargument in every view function.