- 烧瓶教程
- 烧瓶 - 主页
- 烧瓶 - 概述
- 烧瓶 - 环境
- 烧瓶 - 应用
- Flask - 路由
- Flask - 可变规则
- Flask - URL 构建
- Flask - HTTP 方法
- 烧瓶 - 模板
- Flask - 静态文件
- Flask - 请求对象
- 将表单数据发送到模板
- 烧瓶-cookie
- 烧瓶 - 会话
- Flask - 重定向和错误
- Flask - 消息闪烁
- Flask - 文件上传
- Flask - 扩展
- 烧瓶 - 邮件
- 烧瓶 - WTF
- 烧瓶-SQLite
- Flask-SQLAlchemy
- 烧瓶 - Sijax
- Flask - 部署
- Flask-FastCGI
- Flask 有用资源
- Flask - 快速指南
- Flask - 有用的资源
- Flask - 讨论
Flask – 将表单数据发送到模板
我们已经看到可以在 URL 规则中指定 http 方法。触发的函数接收到的表单数据可以以字典对象的形式收集并转发到模板以呈现在相应的网页上。
在以下示例中,“/” URL 呈现一个具有表单的网页 (student.html)。填写的数据将发布到触发result()函数的“/result” URL 。
results ()函数收集字典对象中request.form中存在的表单数据,并将其发送到result.html进行渲染。
该模板动态呈现表单数据的 HTML 表。
下面给出的是应用程序的 Python 代码 -
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 脚本。
<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)如下:
<!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/ 。
单击“提交”按钮后,表单数据将以HTML 表格的形式呈现在result.html上。

