[英]What is the “endpoint” in flask's .add_url_rule()?
Consider the following code 请考虑以下代码
import flask
class API:
def hello(self):
return flask.Response('hello', 200)
api = API()
app = flask.Flask(__name__)
app.add_url_rule('/', 'hello', api.hello)
app.run()
It returns "hello" upon a GET
call to /
. 它返回的“hello”在一个GET
调用/
。
The documentation for add_url_rule
states that add_url_rule
的文档说明了这一点
[
add_url_rule
] works exactly like theroute()
decorator. [add_url_rule
]的工作原理与route()
装饰器完全相同。
It requires however at least three parameters. 然而,它至少需要三个参数。 The first and third one are understandable and mimic @route()
. 第一个和第三个是可以理解的并且模仿@route()
。 What is the second one ( hello
in my case)? 第二个是什么(在我的情况下hello
)?
The documentation further states that this is 文档进一步指出这是
endpoint – the endpoint for the registered URL rule. endpoint - 已注册URL规则的端点。 Flask itself assumes the name of the view function as endpoint Flask本身将视图函数的名称视为端点
What does this mean? 这是什么意思? Why isn't the URL ( /
) and the method to call ( api.hello
) sufficient? 为什么URL( /
)和调用方法( api.hello
)不够? What is the role of the "endpoint"? “终点”的作用是什么? How is it exactly used? 它是如何使用的?
It's the name for the route; 这是路线的名称 ; the one you'd use in the url_for()
function for example. 例如,你在url_for()
函数中使用的那个。 The endpoint name is the registration key for views, a symbolic name by which you can reference the route from other parts of your application. 端点名称是视图的注册键,是一个符号名称,您可以通过该名称引用应用程序其他部分的路径。
@route()
takes the same parameter; @route()
采用相同的参数; the default is the name of the decorated function. 默认值是修饰函数的名称。 This is documented both in the add_url_rule()
documentation as well as the documentation for @route()
: 这在add_url_rule()
文档以及@route()
的文档中@route()
记录:
- endpoint – the endpoint for the registered URL rule. endpoint - 已注册URL规则的端点。 Flask itself assumes the name of the view function as endpoint. Flask本身将视图函数的名称视为端点。
(bold italic emphasis mine). (粗体斜体强调我的)。
Note that the example in the documentation tried to show the same: 请注意,文档中的示例尝试显示相同的内容:
Basically this example: 基本上这个例子:
@app.route('/') def index(): pass
Is equivalent to the following: 相当于以下内容:
def index(): pass app.add_url_rule('/', 'index', index)
Note that the second argument 'index'
matches the function name. 请注意,第二个参数'index'
与函数名称匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.