Python Web后端开发 · 篇2

请求与响应:和用户"对话"

深入HTTP请求处理、表单交互与Jinja2模板渲染

上一篇我们学会了用Flask创建简单的Web页面。但真实的Web应用远不止展示静态内容——它需要接收用户的输入、处理数据、动态生成页面。这篇文章将带你深入理解HTTP请求的处理方式,掌握表单交互、模板渲染等核心技能。

目录

1 GET vs POST 请求深入对比
2 request对象:获取各种请求数据
3 Jinja2模板引擎:动态页面生成
4 模板继承:base.html + 子模板
5 Flash消息:给用户反馈
6 实战:用户注册表单

一、GET vs POST 请求深入对比

在篇1中我们简单了解了GET和POST。现在来深入对比它们的区别,理解在不同场景下应该如何选择。

对比维度
GET请求
POST请求
数据传输
参数拼接在URL后面
数据放在请求体(Body)中
URL示例
/search?q=python&page=1
/login(数据在body中)
数据长度
受URL长度限制(约2KB)
理论上无限制
缓存
可以被浏览器缓存
不会被缓存
书签
可以收藏为书签
不能收藏(缺数据)
幂等性
幂等(多次请求结果相同)
非幂等(可能重复提交)
使用场景
搜索、查看、列表
注册、登录、提交、上传

选择原则:如果请求只是"读取"数据,用GET;如果请求会"修改"数据或包含敏感信息(密码、个人信息),用POST。

二、request对象:获取请求数据

Flask提供了一个全局的 request 对象,它包含了当前请求的所有信息。你可以把它理解为一个"请求数据包",里面装着用户发送的所有数据。

Python request对象使用示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from flask import Flask, request, jsonify
app = Flask(__name__)
# 1. 获取GET请求的查询参数
# 访问: /search?q=python&page=2
@app.route("/search")
def search():
query = request.args.get("q", "") # 获取参数q,默认为空
page = request.args.get("page", 1, type=int) # 转为int类型
return f"搜索: {query}, 第{page}页"
# 2. 获取POST表单数据
@app.route("/login", methods=["POST"])
def login():
username = request.form.get("username")
password = request.form.get("password")
return f"登录用户: {username}"
# 3. 获取JSON数据(前后端分离常用)
@app.route("/api/data", methods=["POST"])
def api_data():
data = request.get_json()
name = data.get("name")
age = data.get("age")
return jsonify({"message": f"收到: {name}, {age}岁"})
# 4. 获取请求的其他信息
@app.route("/info")
def info():
method = request.method # 请求方法: GET/POST
url = request.url # 完整URL
ip = request.remote_addr # 客户端IP地址
browser = request.user_agent # 浏览器信息
return f"方法:{method}, IP:{ip}"
if __name__ == "__main__":
app.run(debug=True)

request对象的核心属性速查:

属性/方法
说明
request.args
URL查询参数(GET请求)
request.form
表单数据(POST请求)
request.get_json()
解析JSON请求体
request.method
请求方法(GET/POST等)
request.files
上传的文件
request.headers
请求头信息
小贴士:.get() vs 下标访问

推荐使用 request.args.get("key") 而不是 request.args["key"]。前者在参数不存在时返回None,后者会抛出400错误,导致页面崩溃。

三、Jinja2模板引擎

篇1中我们直接在Python代码里写HTML字符串,这种方式只适合极简单的页面。真实的Web应用需要把HTML模板和Python逻辑分离——这就是模板引擎的作用。

Flask内置了 Jinja2 模板引擎。它允许你在HTML文件中嵌入变量、条件判断和循环,动态生成页面内容。

基本用法:变量传递

Python + HTML 模板渲染示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Python端:app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
# 向模板传递变量
user = {"name": "小明", "age": 25}
hobbies = ["编程", "阅读", "游泳"]
return render_template("home.html",
user=user,
hobbies=hobbies)
if __name__ == "__main__":
app.run(debug=True)
# ──────────────────────────────────
# HTML模板:templates/home.html
# (放在项目根目录下的templates文件夹中)
#
# <h1>你好, {{ user.name }}!</h1>
# <p>年龄: {{ user.age }}</p>
#
# {# 条件判断 #}
# {% if user.age >= 18 %}
# <p>你已成年</p>
# {% else %}
# <p>你还未成年</p>
# {% endif %}
#
# {# 循环遍历 #}
# <h3>爱好:</h3>
# <ul>
# {% for hobby in hobbies %}
# <li>{{ hobby }}</li>
# {% endfor %}
# </ul>

Jinja2模板中的核心语法:

四、模板继承:base.html + 子模板

网站通常有多个页面共享相同的头部导航和页脚。模板继承让你定义一个"基础模板",子模板只需要填写自己不同的部分。

HTML 模板继承示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!-- templates/base.html 基础模板 -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}默认标题{% endblock %}</title>
</head>
<body>
<!-- 公共导航栏 -->
<nav>
<a href="/">首页</a> |
<a href="/about">关于</a>
</nav>
<!-- 子模板内容插入区域 -->
{% block content %}
{% endblock %}
<!-- 公共页脚 -->
<footer>
<p>版权所有 2024</p>
</footer>
</body>
</html>
<!-- ────────────────────────────── -->
<!-- templates/about.html 子模板 -->
{% extends "base.html" %}
{% block title %}关于我们{% endblock %}
{% block content %}
<h1>关于我们</h1>
<p>这是一个Flask学习项目</p>
{% endblock %}

模板继承的工作方式:

  1. {% extends "base.html" %} — 声明继承哪个基础模板
  2. {% block name %}...{% endblock %} — 定义可被子模板覆盖的区域
  3. 子模板只需要重写自己需要修改的block

五、Flash消息:给用户反馈

当用户提交表单后,你通常需要给用户一个反馈:"注册成功"或"密码太短"。Flask提供了 flash() 函数来实现这种一次性消息。

Python + HTML Flash消息示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# app.py
from flask import Flask, flash, redirect, url_for
app = Flask(__name__)
app.secret_key = "my-secret-key" # 必须设置才能使用flash
@app.route("/register", methods=["POST"])
def register():
username = request.form.get("username")
if not username:
flash("用户名不能为空!", "error")
else:
flash(f"注册成功, 欢迎 {username}!", "success")
return redirect(url_for("home"))
# ──────────────────────────────────
# 在模板中显示Flash消息:
#
# {% with messages = get_flashed_messages(with_categories=true) %}
# {% if messages %}
# {% for category, message in messages %}
# <div class="flash-{{ category }}">{{ message }}</div>
# {% endfor %}
# {% endif %}
# {% endwith %}
常见错误:SecretKey未设置

使用 flash() 之前,必须设置 app.secret_key,否则会报错 RuntimeError: The session is unavailable。

生产环境中,请使用随机字符串,且不要硬编码在代码里(后续篇3会讲解环境变量管理)。

六、实战:用户注册表单

让我们把前面学的知识组合起来,实现一个完整的用户注册系统——包含表单、验证、Flash消息反馈和模板渲染。

Python register_app.py - 完整注册系统
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from flask import (Flask, render_template, request,
flash, redirect, url_for)
app = Flask(__name__)
app.secret_key = "dev-secret-key-change-in-production"
# 模拟用户数据库(内存列表)
users_db = [
{"username": "admin", "email": "admin@test.com"}
]
@app.route("/")
def home():
return render_template("index.html", users=users_db)
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
# 获取表单数据
username = request.form.get("username", "").strip()
email = request.form.get("email", "").strip()
password = request.form.get("password", "")
# 表单验证
errors = []
if not username:
errors.append("用户名不能为空")
elif len(username) < 3:
errors.append("用户名至少3个字符")
if not email or "@" not in email:
errors.append("请输入有效的邮箱地址")
if len(password) < 6:
errors.append("密码至少6个字符")
# 检查用户名是否已存在
for user in users_db:
if user["username"] == username:
errors.append("用户名已被注册")
break
if errors:
for err in errors:
flash(err, "error")
return render_template("register.html",
username=username,
email=email)
# 注册成功,添加到列表
users_db.append({
"username": username,
"email": email
})
flash(f"注册成功!欢迎 {username}", "success")
return redirect(url_for("home"))
# GET请求:显示注册表单
return render_template("register.html")
if __name__ == "__main__":
app.run(debug=True)
小贴士:表单验证的重要性

永远不要信任用户输入!无论前端是否有JavaScript验证,后端都必须再次验证数据。这是Web安全的基本原则。后续篇3中我们会学习使用WTForms库来更优雅地处理表单验证。

常见错误速查

错误1:jinja2.exceptions.TemplateNotFound

原因:模板文件不在 templates/ 文件夹中。确保项目结构是:app.py 旁边有 templates/ 文件夹。

错误2:jinja2.exceptions.UndefinedError

原因:模板中使用了未在 render_template() 中传递的变量。检查变量名是否一致。

错误3:Method Not Allowed (405)

原因:路由只定义了GET,但表单提交了POST。记得在 methods 中同时包含GET和POST。

知识回顾

GET适合读取数据,POST适合提交/修改数据
request对象提供args(GET参数)、form(POST表单)、get_json()(JSON数据)
Jinja2模板引擎用 {{ }} 输出变量,{% %} 执行逻辑
模板继承通过 extends 和 block 实现页面复用
flash() 配合 secret_key 可以给用户显示一次性反馈消息

下一篇预告

篇3:数据库操作——让数据"记住"

本篇我们用内存列表存储用户数据,但真实应用需要持久化存储。下一篇将学习SQLite数据库和SQLAlchemy ORM,让你掌握数据的增删改查,并将注册系统升级为数据库版本。

Python Web后端开发系列 · 篇2/5

相关阅读
想动手实操?你需要一台服务器
学编程离不开动手实操。一台入门级云服务器是你最好的练习场,数据库、对象存储、CDN、短信也都能用上,入门配置很便宜,够你把学到的东西真跑一遍。
查看腾讯云优惠查看阿里云优惠
想系统入门?配一本书
看文章学的是零散知识点,想系统入门还得有一本书打底。
Python 入门书C 与 Python 入门Web 开发书