<p>好的。对<code>werkzeug.routing</code>和<code>flask.helpers.url_for</code>代码进行了一些深入研究,但我已经找到了答案。您只需更改路由的<code>endpoint</code>(换句话说,您的路由名</strong>)</p>
<pre><code>@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"))
</code></pre>
<p>将产生</p>
<blockquote>
<p>canonical path is /canonical/path/, alternative is /alternate/path/</p>
</blockquote>
<p>这种方法有一个缺点。Flask总是将最后定义的路由绑定到隐式定义的端点(代码中的<code>foo</code>)。猜猜如果重新定义端点会发生什么?所有的<code>url_for('old_endpoint')</code>都会抛出<code>werkzeug.routing.BuildError</code>。所以,我想整个问题的正确解决方案是定义最后一个规范路径和<em>名称</em>替代路径:</p>
<pre><code>"""
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"))
</code></pre>