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

查看:91
本文介绍了如果我的方法具有多个路由注释,该如何使用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代码,但是我已经弄清楚了.您只需更改路线的endpoint(换句话说,您命名您的路线)

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天全站免登陆