gpt4 book ai didi

python - 如果我的方法有多个路由注释,我该如何使用 url_for?

转载 作者:IT老高 更新时间:2023-10-28 21:43:16 26 4
gpt4 key购买 nike

所以我有一个可以通过多条路线访问的方法:

@app.route("/canonical/path/")
@app.route("/alternate/path/")
def foo():
return "hi!"

现在,我怎样才能调用 url_for("foo") 并知道我会得到第一条路线?

最佳答案

好的。花了一些时间研究 werkzeug.routingflask.helpers.url_for 代码,但我已经弄清楚了。您只需更改路线的 endpoint(换句话说,您命名您的路线)

@app.route("/canonical/path/", endpoint="foo-canonical")
@app.route("/alternate/path/")
def foo():
return "hi!"

@app.route("/wheee")
def bar():
return "canonical path is %s, alternative is %s" % (url_for("foo-canonical"), url_for("foo"))

会产生

canonical path is /canonical/path/, alternative is /alternate/path/

这种方法有一个缺点。 Flask 总是将最后定义的路由绑定(bind)到隐式定义的端点(代码中的 foo )。猜猜如果重新定义端点会发生什么?你所有的 url_for('old_endpoint') 都会抛出 werkzeug.routing.BuildError。所以,我想整个问题的正确解决方案是定义规范路径最后一个和 name 替代方案:

""" 
since url_for('foo') will be used for canonical path
we don't have other options rather then defining an endpoint for
alternative path, so we can use it with url_for
"""
@app.route('/alternative/path', endpoint='foo-alternative')
"""
we dont wanna mess with the endpoint here -
we want url_for('foo') to be pointing to the canonical path
"""
@app.route('/canonical/path')
def foo():
pass

@app.route('/wheee')
def bar():
return "canonical path is %s, alternative is %s" % (url_for("foo"), url_for("foo-alternative"))

关于python - 如果我的方法有多个路由注释,我该如何使用 url_for?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7782046/

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