Skip to content

向模板发送表单数据

Web 应用程序中一个常见的模式是接收通过 HTML 表单提交的数据,然后将这些数据回显给用户,通常在确认页或结果页上。Flask 使用 request 对象和模板渲染使其变得简单直观。

当一个 HTML 表单被提交时(通常使用 POST 方法),用户输入的数据会作为 HTTP 请求的正文发送。Flask 通过 request.form 属性提供对这些数据的访问。request.form 的行为类似于字典,将字段名称(来自表单元素的 name 属性)映射到它们提交的值。

您可以在视图函数中收集这些数据,并将其传递给模板进行渲染。

考虑以下场景:我们有一个页面 (/) 显示一个用于输入学生详细信息的表单 (student.html)。当用户提交表单时,数据通过 POST 发送到另一个 URL (/result)。处理 /result 的视图函数将提取表单数据并将其传递给一个模板 (result.html),该模板将提交的信息显示在表格中。

以下是 Flask 应用程序 (app.py) 的 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']) # 允许 POST (用于提交) 和 GET (可选,用于直接访问)
def result():
# 检查请求方法是否为 POST (即表单已提交)
if request.method == 'POST':
# 获取表单数据,它是一个不可变字典
result_data = request.form
# 将字典传递给结果模板
return render_template("result.html", result=result_data)
else:
# 处理 GET 请求 (例如,重定向或显示错误/其他页面)
# 为简单起见,我们只返回学生表单
return redirect(url_for('student'))
if __name__ == '__main__':
# 启用调试模式进行开发 (自动重载,调试器)
app.run(debug=True)

表单的 HTML 代码 (templates/student.html):

<!doctype html>
<html>
<head>
<title>Student Details</title>
</head>
<body>
<h2>Enter Student Information</h2>
<form action="{{ url_for('result') }}" method="POST">
<p>Name <input type="text" name="Name" /></p>
<p>Physics Score <input type="text" name="Physics" /></p>
<p>Chemistry Score <input type="text" name="Chemistry" /></p>
<p>Maths Score <input type="text" name="Mathematics" /></p>
<p><input type="submit" value="Submit" /></p>
</form>
</body>
</html>

注意:我们在 action 属性中使用了 url_for('result')。这是在 Flask 中生成 URL 的推荐方式,因为它比硬编码路径更灵活。

结果页面的 HTML 代码 (templates/result.html):

<!doctype html>
<html>
<head>
<title>Submission Result</title>
</head>
<body>
<h2>Submitted Information</h2>
<table border="1">
<thead>
<tr>
<th>Field</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{# 遍历 'result' 字典中的键值对 #}
{# 对于 Python 3 使用 .items() #}
{% for key, value in result.items() %}
<tr>
<th>{{ key }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
<a href="{{ url_for('student') }}">Enter new data</a>
</body>
</html>

在 result.html 模板中,我们使用 result.items() 遍历 result 字典(从 result() 视图函数传递过来)。对于每个键值对(代表表单字段名称及其提交的值),我们创建一个表格行。

要运行此示例:将 Python 代码保存为 app.py,将 HTML 文件保存为 templates/student.html 和 templates/result.html。运行 python app.py 并在浏览器中访问 http://localhost:5000/。

您将看到学生信息表单。填写并点击“Submit”。浏览器将向 /result 发送一个 POST 请求,result() 函数将处理 request.form 数据,并渲染 result.html 模板,以表格形式显示您输入的数据。

虽然此示例直接使用了 request.form,但对于涉及验证、数据清理和 CSRF 保护的更复杂的应用程序,强烈建议使用 Flask-WTF 等扩展(在其他章节中介绍)。