gpt4 book ai didi

python - 可选的 URL 变量

转载 作者:太空狗 更新时间:2023-10-29 22:04:16 32 4
gpt4 key购买 nike

有没有办法在 Flask 中定义带有可选 URL 参数的 URL?本质上,我想做的是定义允许可选指定语言的规则:

/
/de -> matches / (but doesn't collide with /profile)
/profile
/de/profile

我想我已经找到了一种方法,但它涉及改变 Werkzeug 和 Flask 处理请求的方式(猴子修补或 fork 框架源)。不过,这似乎是处理此问题的一种过于复杂的方法。有没有一种我忽略的更简单的方法来做到这一点?

编辑:

根据 Brian 的回答,我得出以下结论:

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

(我还没有从变量列表中提取lang_code,但很快就会这样做)

现在这只是热门恕我直言。

最佳答案

以防万一您不知道,您可以为一个 View 注册多个路由。对每个 View 都执行此操作可能会很痛苦,但这是可行的...

DEFAULT_LANG = 'en'

@app.route('/profile')
@app.route('/<lang>/profile')
def profile(lang=DEFAULT_LANG):
pass

或者,也许您可​​以实现自己的 route 装饰器,它会为这两种情况自动调用 app.route...

from flask import Flask

app = Flask(__name__)

DEFAULT_LANG = 'en'

def lang_route(rule, **options):
def decorator(f):
endpoint = options.pop('endpoint', None)
app.add_url_rule(rule, endpoint, f, **options)
app.add_url_rule('/<lang>%s' % rule, endpoint, f, **options)
return f
return decorator

@lang_route('/profile') # also accepts '/<lang>/profile' automatically
def profile(lang=DEFAULT_LANG):
return lang

if __name__ == '__main__':
app.run(debug=True)

关于python - 可选的 URL 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13537606/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com