Flask 简明教程
Flask – Sending Form Data to Template
我们已经看到,可以在 URL 规则中指定 http 方法。触发函数收到的 Form 数据可以以字典对象的形式收集,并将其转发到模板以便在相应的网页上渲染它。
We have already seen that the http method can be specified in URL rule. The Form data received by the triggered function can collect it in the form of a dictionary object and forward it to a template to render it on a corresponding web page.
在下面的示例中, ‘/’ URL 渲染一个包含表单的网页 (student.html)。填写其中的数据将发布到 ‘/result’ URL,该 URL 会触发 result() 函数。
In the following example, ‘/’ URL renders a web page (student.html) which has a form. The data filled in it is posted to the ‘/result’ URL which triggers the result() function.
results() 函数会以字典对象收集 request.form 中存在的表单数据,然后将其发送给 result.html 进行渲染。
The results() function collects form data present in request.form in a dictionary object and sends it for rendering to result.html.
模板会动态渲染 form 数据的 HTML 表格。
The template dynamically renders an HTML table of form data.
以下是应用程序的 Python 代码:
Given below is the Python code of application −
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def student():
return render_template('student.html')
@app.route('/result',methods = ['POST', 'GET'])
def result():
if request.method == 'POST':
result = request.form
return render_template("result.html",result = result)
if __name__ == '__main__':
app.run(debug = True)
以下是 student.html 的 HTML 脚本:
Given below is the HTML script of student.html.
<html>
<body>
<form action = "http://localhost:5000/result" method = "POST">
<p>Name <input type = "text" name = "Name" /></p>
<p>Physics <input type = "text" name = "Physics" /></p>
<p>Chemistry <input type = "text" name = "chemistry" /></p>
<p>Maths <input type ="text" name = "Mathematics" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
以下是模板 (result.html) 的代码:
Code of template (result.html) is given below −
<!doctype html>
<html>
<body>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
运行 Python 脚本,并在浏览器中输入 URL http://localhost:5000/ 。
Run the Python script and enter the URL http://localhost:5000/ in the browser.
当点击 Submit 按钮时,表单数据以 HTML 表格形式呈现在 result.html 上。
When the Submit button is clicked, form data is rendered on result.html in the form of HTML table.