如果我的方法有多个路由注释,我该如何使用 url_for? [英] How do I use url_for if my method has multiple route annotations?

查看:25
本文介绍了如果我的方法有多个路由注释,我该如何使用 url_for?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have a method that is accessible by multiple routes:

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

现在,我如何调用 url_for("foo") 并知道我会得到第一条路由?

Now, how can I call url_for("foo") and know that I will get the first route?

推荐答案

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

Ok. It took some delving into the werkzeug.routing and flask.helpers.url_for code, but I've figured out. You just change the endpoint for the route (in other words, you name your route)

@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/,替代路径是/alternate/path/

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

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

There is a drawback of this approach. Flask always binds the last defined route to the endpoint defined implicitly (foo in your code). Guess what happens if you redefine the endpoint? All your url_for('old_endpoint') will throw werkzeug.routing.BuildError. So, I guess the right solution for the whole issue is defining canonical path the last and name alternative:

""" 
   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"))

这篇关于如果我的方法有多个路由注释,我该如何使用 url_for?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆