gpt4 book ai didi

python - flask 的 .add_url_rule() 中的 "endpoint"是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:05 25 4
gpt4 key购买 nike

考虑以下代码

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()

它在 GET 调用 / 时返回“hello”。

documentation for add_url_rule指出

[add_url_rule] works exactly like the route() decorator.

但是它至少需要三个参数。第一个和第三个是可以理解的并且模仿了@route()。第二个是什么(hello 在我的例子中)?

文档进一步说明这是

endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint

这是什么意思?为什么 URL (/) 和调用方法 (api.hello) 不够用? “端点”的作用是什么?具体怎么用?

最佳答案

这是路线的名称;您将在 url_for() function 中使用的那个例如。端点名称是 View 的注册 key ,是一个符号名称,您可以通过它从应用程序的其他部分引用路由。

@route() 采用相同的参数;默认是装饰函数的名称。这在 add_url_rule() 文档以及 @route() 的文档中都有记录。 :

  • endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint.

(粗体斜体强调我的)。

请注意,文档中的示例试图显示相同的内容:

Basically this example:

@app.route('/')
def index():
pass

Is equivalent to the following:

def index():
pass
app.add_url_rule('/', 'index', index)

请注意,第二个参数 'index' 与函数名称匹配。

关于python - flask 的 .add_url_rule() 中的 "endpoint"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45607711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com