好。它花了一些时间研究
werkzeug.routing和
flask.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 /,替代方案为/ alternate / path /
这种方法有一个缺点。Flask始终将最后定义的路由绑定到隐式定义的端点(
foo在您的代码中)。猜猜如果您重新定义端点会发生什么?你
url_for('old_endpoint')会全力以赴werkzeug.routing.BuildError。因此,我想整个问题的正确解决方案是在最后定义路径并
命名 替代项:
""" 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"))


