问题描述
flask.url_for(endpoint, **values)
在我看来,endpoint
东西似乎很神奇.它的行为方式如下:
The endpoint
thing seems like magic to me. It behaves these ways:
- 在单个文件中,
url_for('dothat')
可以获取修饰的方法dothat
- 使用包装,
views.dothat
可以通过url_for('dothat')
获取,当我期望我必须提供完全合格方法名称,如url_for('myapp.views.dothat')
- in a single file, a decorated method
dothat
can be acquired byurl_for('dothat')
- with packaging,
views.dothat
can be acquired byurl_for('dothat')
, when I was expecting that I must provide the fully qualified method name, as inurl_for('myapp.views.dothat')
因此,如果不是完全限定的方法名称,Flask将作为端点使用什么?
So if it's not the fully qualified method name, what does Flask take in as endpoint?
推荐答案
Flask不不使用模块名称作为端点.它只是默认为函数名.
Flask does not use the module name for the endpoint. It simply defaults to the function name.
如果您使用相同的名称注册两个不同的功能(例如,在两个不同的模块中),则会引发AssertionError
异常:
If you register two different functions with the same name (say, in two different modules), an AssertionError
exception is raised:
raise AssertionError('View function mapping is overwriting an '
'existing endpoint function: %s' % endpoint)
在这种情况下,您可以指定一个明确的端点名称:
You can specify an explicit endpoint name in such cases:
@app.route('/', endpoint='alt_homepage')
def homepage():
pass
请参见 @Flask.route()
文档:
注册视图(使用@app.route()
装饰器)时,将确定端点名称(除非明确设置了端点名称),并将其与路由注册一起存储. url_for()
使用路由注册来查找针对该名称注册的所有路由,并找到最适合您还传递给url_for()
的参数的路由.
When you register a view (with the @app.route()
decorator), the endpoint name is determined (unless you set one explicitly) and stored with the route registration. url_for()
uses the route registration to find all routes registered against that name and finds the one best fitting the parameters you also passed to url_for()
.
这篇关于Flask url_for如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!