gpt4 book ai didi

python - 使用 app.add_url_rule 时需要命名 url 吗?

转载 作者:行者123 更新时间:2023-11-28 16:43:28 25 4
gpt4 key购买 nike

来自 Flask 文档:

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

它还说:

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

确实,如果我执行 app.add_url_rule('/', None, index) 似乎一切正常。 (我不确定术语和“端点”到底是什么。)

一些进一步的问题:

  1. 有没有理由指定第二个参数?

  2. 第二个参数确实是“端点”吗?

  3. (不)指定第二个参数的好处/缺点是什么?

  4. 如果在另一个 url 规则中使用相同的名称怎么办?第一个被覆盖了吗?这是故意的吗?

最佳答案

在这种情况下,端点只是您应用程序的有效 URL 的一个术语。来自维基百科:

In service-oriented architecture, an endpoint is the entry point to a service, a process, or a queue or topic destination

至于命名您的 URL - 是的,它是可选的。定义名称有一些好处。例如,当使用 *url_for*() 或 redirect() 时,您可以将 url 的名称指定为快捷方式。这带来了一个额外的好处,即允许您更改 url 结构而无需更改与该 url 交互的每一行代码,因为它仅通过名称引用它。

因此在您的示例中,您可以像这样引用您的索引 url:

return redirect('index')

对于你的最后一个问题,我不确定会发生什么。尝试使用该名称解析 url 时可能会出错。无论哪种方式,都没有理由定义两个具有相同名称的不同 url。

关于python - 使用 app.add_url_rule 时需要命名 url 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16628325/

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