python - 烧瓶中的可选路由参数是否需要在函数中设置为“无”?
问题描述
此代码取自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()
)
解决方案
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
中存在一个上下文切换,用于何时name
是None
和何时是某事:
{% if name %}
<b> Hello {{ name }}! </b>
{% else %}
<b> Hello! </b>
{% endif %}
推荐阅读
- asp.net-web-api - 在 Dynamics CRM 中使用 C# 和 WEB API 批量插入
- python - TensorFlow numpy 重复
- sql-server - 有人可以转换代码以使其使用 EXEC @sql 而不是 EXEC sp_executesql 吗?
- python - 安装 discord.py 1.0 时遇到问题
- hyperledger-fabric - fabric-sdk-go 拨号连接超时
- php - Laravel 5.6 + SAML2
- php - Jquery Bootstrap 模态框不适用于 wordpress 中的检查验证
- objective-c - 使用 NSURLRequest 发送 NSMutableDictionary 数据的 NSMutableArray
- android - Android xml Preview 在设备微调器中显示 Null
- layout - 在颤动中将小部件自动包装到新行