名称作为hello函数的参数被分配了None,但是如果在URL中提供,为什么render_template中的名称将采用名称的值?基本上我的问题是Python如何知道哪个名称为None以及哪个名称在url中给出?
from flask import render_template
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
hello.html是:
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
Flask是一个框架,在幕后(尤其是werkzeug
)有很多代码来处理所有请求,然后调用您的view函数,然后准备一个完整的响应。
因此,答案是,Python不知道URL,但是Flask知道并调用name
(None
或覆盖默认值)或不带View函数的视图函数。
name
视图函数的变量以相同的名称传递到模板。这是name
该行中的两个:
return render_template('hello.html', name=name)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句