flask中的可选路由参数是否需要在函数中设置为"none"?

Do optional routing parameters in flask need to be set to "none" in a function?

此代码取自 https://code.visualstudio.com/docs/python/tutorial-flask#_optional-activities,用于使用 Flask 和 visual studio 代码中的 python 设置基本 Web 应用程序。

为什么函数"hello_there"有参数"name = None"?该函数不应该只传递名称而不指定其他任何内容吗?对我来说,render_template 应该将名称设置为 None,因为 "name = None" 是函数参数。这个答案: 暗示 flask 覆盖了函数参数。如果是这样,函数是否需要具有 "name = None" 参数?

@app.route("/hello/")
@app.route("/hello/<name>")
def hello_there(name = None):
    return render_template(
        "hello_there.html",
        name=name,
        date=datetime.now()
    )

name = None 就是所谓的 default argument value 并且在您发布的函数的情况下,似乎可以作为确保函数 hello_there 在有或没有 name 正在通过。

注意函数装饰器:

@app.route("/hello/")
@app.route("/hello/<name>")

这意味着此函数的预期调用是 withwithout 参数名称。通过将 name 默认参数设置为 None,我们可以确保如果从未传递 name 函数仍然能够正确呈现页面。注意以下几点:

>>> def func(a):
...     return a

>>> print(func())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() missing 1 required positional argument: 'a'

对比

>>> def func(a = None):
...     return a

>>> print(func())
None

请注意 return:

中引用了您发布的函数 name
    return render_template(
        "hello_there.html",
        name=name,
        date=datetime.now()
    )

如果 name 没有预先定义,那么你会看到上面列出的错误。另一件事是 - 如果我不得不猜测 - 我会假设在模板 hello_there.html 中有一个上下文切换,当 nameNone 和当它是什么时:

{% if name %}
    <b> Hello {{ name }}! </b>
{% else %}
    <b> Hello! </b>
{% endif %}