首页 > 解决方案 > 烧瓶中的可选路由参数是否需要在函数中设置为“无”?

问题描述

此代码取自https://code.visualstudio.com/docs/python/tutorial-flask#_optional-activities,用于在 Visual Studio 代码中使用 flask 和 python 设置一个基本的 webapp。

为什么函数“hello_there”有参数“name = None”?函数不应该只传递名称而不指定其他任何内容吗?对我来说,render_template 应该将 name 设置为 None,因为“name = None”是函数参数。这个答案:render_template 中的flask 参数暗示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()
    )

标签: pythonflaskurl-routing

解决方案


name = None是所谓的默认参数值,在您发布的函数的情况下,它似乎可以作为确保函数hello_there在有或没有name被传递的情况下工作的一种方式。

注意函数装饰器:

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

这意味着对该函数的预期调用可能带有带有参数名称。通过将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

请注意您发布的函数在name以下内容中的引用方式return

    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 %}

推荐阅读