Skip to content
项目
群组
代码片段
帮助
当前项目
正在载入...
登录 / 注册
切换导航面板
S
studyweb
项目
项目
详情
活动
周期分析
仓库
仓库
文件
提交
分支
标签
贡献者
图表
比较
统计图
议题
0
议题
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
CI / CD
CI / CD
流水线
作业
日程
统计图
Wiki
Wiki
代码片段
代码片段
成员
成员
折叠边栏
关闭边栏
活动
图像
聊天
创建新问题
作业
提交
问题看板
Open sidebar
project
studyweb
Commits
9ce011f1
提交
9ce011f1
authored
7月 07, 2026
作者:
zhangqianwei
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
cfm_完成模块七 工程实操和模块六 RAG 基础(第一版)
上级
3f3cf23b
隐藏空白字符变更
内嵌
并排
正在显示
2 个修改的文件
包含
3871 行增加
和
0 行删除
+3871
-0
模块六-RAG基础.md
docs/RAG基础/模块六-RAG基础.md
+1483
-0
模块七-工程实操.md
docs/工程实操/模块七-工程实操.md
+2388
-0
没有找到文件。
docs/RAG基础/模块六-RAG基础.md
0 → 100644
浏览文件 @
9ce011f1
# 模块六 RAG 基础
> 从零搭建一套检索增强生成(Retrieval-Augmented Generation)系统。
> 本模块不依赖任何 LLM 微调经验,只要有 Python 基础就能上手。
---
## 目录
| 章节 | 名称 | 难度 | 预计耗时 |
| -------------------- | ---------- | ---------- | -------- |
|
[
6.1
](
#61-rag-原理
)
| RAG 原理 | ★★★★☆ | 45 min |
|
[
6.2
](
#62-文档处理
)
| 文档处理 | ★★★☆☆ | 50 min |
|
[
6.3
](
#63-文本分块
)
| 文本分块 | ★★★★☆ | 50 min |
|
[
6.4
](
#64-embedding
)
| Embedding | ★★★★☆ | 50 min |
|
[
6.5
](
#65-向量数据库
)
| 向量数据库 | ★★★★☆ | 55 min |
---
## 6.1 RAG 原理
> 用 1-2 句话说清:**RAG 就是让大模型"开卷考试"**——回答前先去知识库里查资料,再根据资料作答。
---
### 什么是 RAG?
**RAG(Retrieval-Augmented Generation,检索增强生成)**
是一种把"信息检索"与"文本生成"结合的架构。它解决了大语言模型(LLM)最致命的两个短板:
1.
**幻觉(Hallucination)**
:模型会一本正经地胡说八道,因为它"不知道自己不知道"。
2.
**知识过时**
:模型的知识停留在训练截止日,问它"昨天发生了什么"它答不上来。
RAG 的思路朴素到惊艳:
**既然模型会骗人,那就给它一本参考资料,让它照着抄。**
> 这就像一个学生参加开卷考试——不能带手机(不能联网),但可以翻书(检索本地知识库)。
> 比起闭卷考试(纯 LLM),开卷的准确率显著更高。
---
### 为什么需要 RAG?
下表对比三种主流"扩展 LLM 知识"方案的优劣:
| 方案 | 原理 | 优点 | 缺点 | 适用场景 |
| ---------------------------------- | ------------------------- | -------------------------------- | ------------------ | -------------------- |
|
**Fine-tuning(微调)**
| 用领域数据继续训练模型 | 风格可定制 | 成本高、知识难更新 | 模型行为/风格改造 |
|
**Long Context(长上下文)**
| 把资料塞进 prompt | 简单直接 | 上下文窗口有限、贵 | 一次性喂少量资料 |
|
**RAG(检索增强)**
⭐ | 检索相关片段后让 LLM 参考 |
**成本低、易更新、可解释**
| 检索不准会拖后腿 | 文档问答、企业知识库 |
记住一个结论:
**90% 的"让 LLM 知道新知识"的场景,RAG 比微调更划算。**
---
### RAG 完整流程图
下面这张图是本模块的"导航星图",每一章都会展开图中对应的一个节点:
```
text
┌──────────────────────────────────────┐
│ 用户提问 │
│ "公司的年假是几天?" │
└──────────────────┬───────────────────┘
│
▼
┌────────────────────────────────────────────────────────────────────────┐
│ ① 离线索引(一次性) │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│ │ 文档加载 │ → │ 文本分块 │ → │ Embedding│ → │ 写入向量数据库 │ │
│ │ PDF/Word │ │ 切 chunk │ │ 向量化 │ │ Chroma/FAISS │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────────────┘ │
│ ↑ 6.1 → 6.5 │
└────────────────────────────────────────────────────────────────────────┘
┌────────────────────────────────────────────────────────────────────────┐
│ ② 在线问答(每次请求) │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│ │ 用户问题 │ → │ Embed │ → │ 相似度检索 │ → │ Top-K 片段 │ │
│ │ query │ │ 问题向量化│ │ 向量库查 │ │ 作为上下文 │ │
│ └──────────┘ └──────────┘ └──────────┘ └────────┬─────────┘ │
│ ↑ │ │
│ │ ▼ │
│ │ ┌──────────────────────────────────────────────┐ │
│ │ │ Prompt 拼接: │ │
│ │ │ "根据以下资料回答问题... \n\n │ │
│ │ │ 【资料】{Top-K} │ │
│ │ │ 【问题】{query}" │ │
│ │ └────────────────────┬─────────────────────────┘ │
│ │ ▼ │
│ │ ┌──────────────────────────────────────────────┐ │
│ │ │ 调用 LLM(BGE/Qwen/OpenAI) │ │
│ │ └────────────────────┬─────────────────────────┘ │
│ │ ▼ │
│ └─────────────── ③ 生成回答,返回给用户 │
└────────────────────────────────────────────────────────────────────────┘
```
**关键点**
:
-
**离线部分(左半边)**
:跑一次就好,把知识"装进"向量库。
-
**在线部分(右半边)**
:每次用户提问都会跑,决定了
**响应速度和答案质量**
。
-
**闭环**
:用户对答案的反馈(点赞/点踩)可回流到检索环节,持续优化。
---
### 举个例子:最小 RAG Demo(30 行代码)
下面这段代码是 RAG 的"Hello World",先有个体感:
```
python
# pip install chromadb openai
import
chromadb
from
chromadb.utils
import
embedding_functions
# 1. 准备"知识库"(实际场景从 PDF/Word 加载,见 6.2)
docs
=
[
"公司年假为 10 个工作日,入职满 1 年增加至 15 天。"
,
"病假需提供医院证明,3 天以内无需审批。"
,
"婚假为 10 个自然日,需提前 7 天申请。"
,
]
# 2. 写入向量库(实际场景用 BGE,见 6.4)
client
=
chromadb
.
Client
()
ef
=
embedding_functions
.
DefaultEmbeddingFunction
()
# 默认模型
collection
=
client
.
create_collection
(
"hr"
)
collection
.
add
(
documents
=
docs
,
ids
=
[
"1"
,
"2"
,
"3"
])
# 3. 用户提问 → 检索 → 回答(实际场景用 LLM 生成,见 6.5)
question
=
"年假有几天?"
results
=
collection
.
query
(
query_texts
=
[
question
],
n_results
=
1
)
print
(
f
"问:{question}"
)
print
(
f
"答(检索片段):{results['documents'][0][0]}"
)
```
```
bash
# 运行结果
问:年假有几天?
答(检索片段):公司年假为 10 个工作日,入职满 1 年增加至 15 天。
```
> 这段代码虽然没用 LLM 生成答案,但完整跑通了 **"检索 → 取 Top-K"** 这个 RAG 最核心的环节。
> 加上 LLM 生成,就是 6.5 的内容。
---
### 进阶玩法:进阶 RAG 的"五个杠杆"
工业级 RAG 系统会把下面五个方向都做透:
| 杠杆 | 解决的问题 | 典型技术 |
| -------------------------- | ------------------ | ----------------------------------------- |
|
**更好的分块**
| 答案上下文不完整 | 滑动窗口、父子分块、语义分块 |
|
**更好的 Embedding**
| 检索不准 | BGE-M3、E5、领域微调 |
|
**更好的检索**
| 召回率低 | 混合检索(BM25 + 向量)、重排序(Rerank) |
|
**更好的 Prompt**
| 答非所问 | 引用标注、拒答机制、Few-shot |
|
**更好的评估**
| 不知道改进有没有用 | RAGAS、ARES、Golden Set |
本模块聚焦前两项 + Chroma 入门,足够让你搭起一个能用的最小 RAG 系统。
---
### 正解 vs 错误
| 维度 | 正解 ✅ | 错误 ❌ |
| ---------------------- | ---------------------------- | ----------------------------- |
|
**知识更新**
| 改文档 → 重建索引(分钟级) | 重新微调模型(天级 + 几万块) |
|
**可解释性**
| 能给出"答案来自哪段原文" | 只能让 LLM 自由发挥 |
|
**幻觉**
| 答案有据可查 | 一本正经地胡说 |
|
**首次搭建成本**
| 几百行代码 + 一台机器 | 几块 GPU + 训练数据 + 调参 |
|
**数据安全**
| 文档留在内网 | 上传到第三方训练(数据外泄) |
|
**适用规模**
| 文档量 1 ~ 100 万 | 需要"风格/能力"改造时 |
---
### 思考题 / Q&A
1.
**如果文档里没有用户问题的答案,RAG 系统应该如何"优雅地拒答"?**
提示:Prompt 拼接时可以加一句"如果资料中没有答案,请回答'我不知道'"。
2.
**为什么"检索到的 Top-K 片段"可能并不能直接喂给 LLM?**
提示:考虑上下文长度限制、片段之间的冗余、片段与问题的相关度排序。
3.
**如果公司有 100 万份合同文档,朴素 RAG 的检索速度会变慢吗?怎么解决?**
提示:向量库的索引结构(HNSW、IVF)和分库分表。
4.
**RAG 与"搜索引擎 + LLM"有什么区别?**
提示:搜索返回的是 URL 列表,RAG 返回的是
**已经切成 chunk 的文本片段**
,颗粒度更细。
---
### 本节小结
-
RAG = 检索(Retrieval)+ 增强(Augmented)+ 生成(Generation),本质是让 LLM "开卷考试"。
-
三件事让 LLM 知道新知识:微调(贵、慢)、长上下文(贵、有限)、RAG(便宜、易更新)——
**90% 场景首选 RAG**
。
-
RAG 流程分
**离线索引**
(文档→分块→Embedding→入库)和
**在线问答**
(问题→Embedding→检索→Prompt→LLM)两段。
-
进阶 RAG 的五个杠杆:分块、Embedding、检索、Prompt、评估。
-
本模块五章分别对应:原理(6.1)、文档加载(6.2)、分块(6.3)、Embedding(6.4)、向量库(6.5)。
---
### 验收标准
```
☐ 能用一句话向同事解释 RAG 是什么("开卷考试" 类比)
☐ 能徒手画出 RAG 完整流程图(离线索引 + 在线问答)
☐ 能说出 RAG 相对 Fine-tuning 的三个优势(成本、更新、可解释)
☐ 能解释为什么 Top-K 检索结果不能直接喂给 LLM(长度、相关度、冗余)
☐ 能跑通 6.1 的最小 Demo(30 行代码)
```
---
### 官方来源
-
Lewis, P., et al. (2020).
*Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks*
.
[
arXiv:2005.11401
](
https://arxiv.org/abs/2005.11401
)
— RAG 原始论文
-
Gao, Y., et al. (2023).
*Retrieval-Augmented Generation for Large Language Models: A Survey*
.
[
arXiv:2312.10997
](
https://arxiv.org/abs/2312.10997
)
-
Datawhale
*Happy-LLM*
第 5 章 RAG 基础 —
[
GitHub
](
https://github.com/datawhalechina/happy-llm
)
-
Chroma 官方文档 —
[
docs.trychroma.com
](
https://docs.trychroma.com/
)
---
> **下一节预告:[6.2 文档处理](#62-文档处理)** —— 把 PDF/Word 真的"读"进 Python。
---
## 6.2 文档处理
> 用 1-2 句话说清:**文档处理 = 把 PDF/Word/Markdown 这些"非结构化"文件,变成 RAG 能吃进去的纯文本。**
---
### 什么是文档处理?
RAG 系统的第一步叫
**Document Loading(文档加载)**
——把五花八门的原始文件读成 Python 字符串。
| 文件类型 | 推荐库 | 安装命令 |
| ------------------------------- | ---------------------------- | ---------------------------- |
|
**PDF**
|
`pdfplumber`
|
`pip install pdfplumber`
|
|
**Word**
|
`python-docx`
|
`pip install python-docx`
|
|
**Markdown / HTML / TXT**
| 内置 +
`unstructured`
|
`pip install unstructured`
|
|
**图片(含文字)**
|
`pytesseract`
或多模态模型 | 进阶内容,本模块不展开 |
|
**Excel / CSV**
|
`pandas`
|
`pip install pandas`
|
> ⚠️ **为什么不用 PyPDF2?** 因为它对中文表格、双栏排版的支持非常差。`pdfplumber` 能逐字符定位坐标,**表格抽取**首选它。
---
### 为什么需要专门学"文档处理"?
直觉上"读个文件"很简单,但生产环境你会遇到这些坑:
1.
**PDF 双栏排版乱序**
:左栏读到底再读右栏,逻辑全错。
2.
**扫描件 PDF**
:是图片不是文字,要 OCR。
3.
**Word 表格**
:默认库读不到表格里的内容。
4.
**乱码**
:GBK / UTF-8 编码混用。
5.
**页眉页脚**
:每次都重复出现,污染检索。
本节教你
**逐个击破**
。
---
### 5 分钟快速上手:pdfplumber 读 PDF
```
python
import
pdfplumber
with
pdfplumber
.
open
(
"demo.pdf"
)
as
pdf
:
for
i
,
page
in
enumerate
(
pdf
.
pages
[:
3
]):
# 只看前 3 页
text
=
page
.
extract_text
()
print
(
f
"==== 第 {i+1} 页 ===="
)
print
(
text
)
```
```
bash
# 安装
pip
install
pdfplumber
# 准备一个测试 PDF(用 wget 拉一篇论文摘要)
wget
-O
demo.pdf https://arxiv.org/pdf/2005.11401v1
```
> 小技巧:`page.extract_words()` 能拿到每个词的位置坐标,**双栏 PDF 可以按 x 坐标重排序**。
---
### 举个例子:抽取 PDF 表格
```
python
import
pdfplumber
with
pdfplumber
.
open
(
"report.pdf"
)
as
pdf
:
page
=
pdf
.
pages
[
0
]
table
=
page
.
extract_table
()
for
row
in
table
:
print
(
" | "
.
join
(
cell
or
""
for
cell
in
row
))
```
```
bash
# 运行结果(示意)
季度 | 营收 | 同比
Q1 | 1.2亿 | +15%
Q2 | 1.5亿 | +20%
```
---
### 5 分钟快速上手:python-docx 读 Word
```
python
from
docx
import
Document
doc
=
Document
(
"demo.docx"
)
# 读所有段落
for
i
,
para
in
enumerate
(
doc
.
paragraphs
):
if
para
.
text
.
strip
():
# 跳过空行
print
(
f
"[段落 {i}] {para.text}"
)
# 读所有表格
for
t_idx
,
table
in
enumerate
(
doc
.
tables
):
print
(
f
"
\n
==== 表格 {t_idx} ===="
)
for
row
in
table
.
rows
:
print
(
" | "
.
join
(
cell
.
text
for
cell
in
row
.
cells
))
```
```
bash
pip
install
python-docx
```
---
### 举个例子:保留 Word 中的"标题层级"
RAG 通常想知道"这段是哪一章",以便后续做"按章节分块"。python-docx 提供了
`style.name`
:
```
python
from
docx
import
Document
doc
=
Document
(
"手册.docx"
)
for
para
in
doc
.
paragraphs
:
if
para
.
style
.
name
.
startswith
(
"Heading"
):
level
=
para
.
style
.
name
.
replace
(
"Heading "
,
""
)
print
(
f
"{' ' * (int(level)-1)}H{level} {para.text}"
)
```
```
bash
# 运行结果
H1 第一章 入职流程
H2 1.1 准备材料
H2 1.2 签订合同
H2 第二章 考勤
H2 2.1 打卡
```
---
### 进阶玩法:批量处理 + 编码自适应
真实项目里要处理一个文件夹的混合文件,下面的
`load_document()`
是个可直接复用的模板:
```
python
from
pathlib
import
Path
import
pdfplumber
from
docx
import
Document
def
load_document
(
path
:
str
|
Path
)
->
str
:
"""根据后缀自动选择加载器,返回纯文本。"""
path
=
Path
(
path
)
suffix
=
path
.
suffix
.
lower
()
if
suffix
==
".pdf"
:
with
pdfplumber
.
open
(
path
)
as
pdf
:
return
"
\n\n
"
.
join
(
p
.
extract_text
()
or
""
for
p
in
pdf
.
pages
)
if
suffix
==
".docx"
:
doc
=
Document
(
path
)
parts
=
[
p
.
text
for
p
in
doc
.
paragraphs
if
p
.
text
.
strip
()]
for
table
in
doc
.
tables
:
for
row
in
table
.
rows
:
parts
.
append
(
" | "
.
join
(
cell
.
text
for
cell
in
row
.
cells
))
return
"
\n\n
"
.
join
(
parts
)
if
suffix
in
{
".md"
,
".txt"
}:
for
enc
in
(
"utf-8"
,
"gbk"
,
"gb18030"
):
try
:
return
path
.
read_text
(
encoding
=
enc
)
except
UnicodeDecodeError
:
continue
raise
ValueError
(
f
"无法识别编码:{path}"
)
raise
ValueError
(
f
"暂不支持的文件类型:{suffix}"
)
# 批量加载
docs_dir
=
Path
(
"./knowledge_base"
)
for
fp
in
docs_dir
.
iterdir
():
try
:
text
=
load_document
(
fp
)
print
(
f
"✅ {fp.name}:{len(text)} 字"
)
except
Exception
as
e
:
print
(
f
"❌ {fp.name}:{e}"
)
```
---
### 正解 vs 错误
| 维度 | 正解 ✅ | 错误 ❌ |
| -------------------- | -------------------------------------- | --------------------------------------------- |
|
**PDF 库选型**
|
`pdfplumber`
(表格、坐标、中文友好) |
`PyPDF2`
(表格丢失、中文乱码) |
|
**Word 表格**
| 单独遍历
`doc.tables`
| 只读
`doc.paragraphs`
(表格内容丢失) |
|
**编码**
| 依次尝试 utf-8 / gbk / gb18030 | 直接
`read_text()`
抛
`UnicodeDecodeError`
|
|
**扫描件 PDF**
| 先 OCR(
`pytesseract`
/ 多模态) | 当文本直接读,全是乱码 |
|
**大文件**
| 流式逐页读 + 立即释放 | 一次性
`read()`
占满内存 |
|
**页眉页脚**
| 关键词过滤或坐标过滤 | 原样塞进 chunk(污染检索) |
---
### 思考题 / Q&A
1.
**同一份 PDF 在 `pdfplumber` 和 `PyMuPDF` (fitz) 里读出的文本顺序不一样,可能是什么原因?**
提示:底层 PDF 解析逻辑、字符位置坐标计算方式。
2.
**如果 Word 文档里嵌入了图片,python-docx 默认会怎么处理?**
提示:图片本身读不到文字,需要 OCR。
3.
**为什么不能直接把 PDF 转成 Word 再读?**
提示:转换会丢失原始文本坐标,表格结构可能错乱。
4.
**如何处理"双栏排版"的 PDF?**
提示:先
`extract_words()`
,按 x 坐标分组,再按 y 坐标排序。
---
### 本节小结
-
文档处理是 RAG 的"入口",常见库:
`pdfplumber`
(PDF)、
`python-docx`
(Word)、
`unstructured`
(万能但慢)。
-
PDF 抽表格用
`extract_table()`
;抽坐标用
`extract_words()`
。
-
Word 抽段落用
`doc.paragraphs`
,抽表格用
`doc.tables`
;
**二者必须分别遍历**
。
-
处理文件夹用
`load_document()`
工厂函数,根据后缀分发。
-
编码自适应:依次尝试 utf-8 → gbk → gb18030。
---
### 完整代码
```
python
"""06_load_documents.py —— 批量加载 PDF / Word / Markdown"""
from
pathlib
import
Path
import
pdfplumber
from
docx
import
Document
def
load_document
(
path
:
str
|
Path
)
->
str
:
path
=
Path
(
path
)
suffix
=
path
.
suffix
.
lower
()
if
suffix
==
".pdf"
:
with
pdfplumber
.
open
(
path
)
as
pdf
:
return
"
\n\n
"
.
join
(
p
.
extract_text
()
or
""
for
p
in
pdf
.
pages
)
if
suffix
==
".docx"
:
doc
=
Document
(
path
)
parts
=
[
p
.
text
for
p
in
doc
.
paragraphs
if
p
.
text
.
strip
()]
for
table
in
doc
.
tables
:
for
row
in
table
.
rows
:
parts
.
append
(
" | "
.
join
(
cell
.
text
for
cell
in
row
.
cells
))
return
"
\n\n
"
.
join
(
parts
)
if
suffix
in
{
".md"
,
".txt"
}:
for
enc
in
(
"utf-8"
,
"gbk"
,
"gb18030"
):
try
:
return
path
.
read_text
(
encoding
=
enc
)
except
UnicodeDecodeError
:
continue
raise
ValueError
(
f
"无法识别编码:{path}"
)
raise
ValueError
(
f
"暂不支持的文件类型:{suffix}"
)
if
__name__
==
"__main__"
:
docs_dir
=
Path
(
"./knowledge_base"
)
for
fp
in
sorted
(
docs_dir
.
iterdir
()):
try
:
text
=
load_document
(
fp
)
print
(
f
"✅ {fp.name}:{len(text)} 字"
)
except
Exception
as
e
:
print
(
f
"❌ {fp.name}:{e}"
)
```
---
### 验收标准
```
☐ 能用 pdfplumber 读 PDF 文本
☐ 能用 pdfplumber 抽 PDF 表格
☐ 能用 python-docx 读 Word 段落和表格
☐ 能识别 Word 标题层级(Heading 1/2/3)
☐ 能写出处理 .pdf / .docx / .md / .txt 的通用函数
☐ 知道遇到乱码时的编码尝试顺序
☐ 知道扫描件 PDF 必须 OCR
```
---
### 官方来源
-
`pdfplumber`
官方文档 —
[
github.com/jsvine/pdfplumber
](
https://github.com/jsvine/pdfplumber
)
-
`python-docx`
官方文档 —
[
python-docx.readthedocs.io
](
https://python-docx.readthedocs.io/
)
-
Unstructured 开源框架 —
[
unstructured.io
](
https://unstructured.io/
)
-
Datawhale
*Happy-LLM*
第 5 章文档加载部分
---
> **下一节预告:[6.3 文本分块](#63-文本分块)** —— 把"一整本书"切成 RAG 能吃的小块。
---
## 6.3 文本分块
> 用 1-2 句话说清:**文本分块(Chunking) = 把长文档切成"语义完整 + 长度可控"的小段,是 RAG 质量的胜负手。**
---
### 什么是文本分块?
把一份 100 页的 PDF 读成一大坨字符串后,
**不能**
整段喂给 LLM(超上下文窗口),也不能整段当检索单位(信息密度太低)。所以要切。
理想的 chunk 应该满足:
| 标准 | 解释 |
| ------------------------- | --------------------------------- |
|
**长度可控**
| 一般 200 ~ 800 字(中英文差异大) |
|
**语义完整**
| 不要把一句话从中间切断 |
|
**重叠(overlap)**
| 跨 chunk 的信息不丢失 |
|
**可定位**
| 知道 chunk 来自哪一页、哪一节 |
---
### 为什么分块这么重要?
**RAG 的答案质量 ≈ 检索质量 ≈ 分块质量。**
一句话概括它的影响:
> **"垃圾进,垃圾出"——分块错了,再贵的 Embedding 和 LLM 也救不回来。**
反例 1:把整本书当 1 个 chunk → 检索出的片段太长,LLM 找不到重点。
反例 2:每句话 1 个 chunk → 上下文断裂,LLM 答非所问。
反例 3:分块刚好切在"因为...所以..."中间 →
**逻辑断了**
。
---
### 5 分钟快速上手:固定长度分块
最简单的方法:用
`len()`
切。
```
python
def
fixed_chunk
(
text
:
str
,
chunk_size
:
int
=
500
,
overlap
:
int
=
50
)
->
list
[
str
]:
"""按字符数固定切分,含 overlap。"""
chunks
=
[]
start
=
0
while
start
<
len
(
text
):
end
=
start
+
chunk_size
chunks
.
append
(
text
[
start
:
end
])
start
+=
chunk_size
-
overlap
return
chunks
sample
=
"RAG 让大模型开卷考试。"
*
100
chunks
=
fixed_chunk
(
sample
,
chunk_size
=
200
,
overlap
=
20
)
print
(
f
"共 {len(chunks)} 个 chunk"
)
```
```
bash
# 运行结果
共 6 个 chunk
```
> **缺点**:可能在句子中间切断,语义断裂。
---
### 举个例子:3 种主流分块方法对比
| 方法 | 切分依据 | 优点 | 缺点 | 适用场景 |
| -------------------------------------- | ------------------------------- | ----------------- | -------------------- | -------------------------- |
|
**固定长度(Fixed-size)**
| 字符数 | 简单、可控 | 切断句子 | 快速原型 |
|
**按段落(Paragraph)**
`\n\n`
| 自然段落 | 语义完整 | 长度不可控 |
**绝大多数场景首选**
|
|
**按句子(Sentence)**
| NLTK / 正则切句 | 颗粒细 | 太碎、缺上下文 | 长答案问答 |
|
**递归分块(Recursive)**
⭐ | 按
`\n\n → \n → 。`
递归 | 兼顾长度与语义 | 实现稍复杂 |
**工业界默认**
|
|
**语义分块(Semantic)**
| Embedding 相似度 | 主题连贯 | 慢、要 Embedding API | 高质量场景 |
|
**父子分块(Parent-Child)**
| 小 chunk 检索 + 大 chunk 喂 LLM | 检索准 + 上下文全 | 存储翻倍 | 复杂文档 |
**结论:80% 的项目用"递归分块"就够,下面是 LangChain 的实现。**
---
### 5 分钟快速上手:LangChain RecursiveCharacterTextSplitter
```
bash
pip
install
langchain-text-splitters
```
```
python
from
langchain_text_splitters
import
RecursiveCharacterTextSplitter
text
=
"""第一章 入职流程
新员工入职第一天,需要签订劳动合同、领取工牌、熟悉办公环境。
第二章 考勤制度
公司采用弹性工作制,每天 8 小时工作制。
迟到 15 分钟以内不扣工资,15-30 分钟扣半天工资。"""
splitter
=
RecursiveCharacterTextSplitter
(
chunk_size
=
50
,
chunk_overlap
=
10
,
separators
=
[
"
\n\n
"
,
"
\n
"
,
"。"
,
","
,
" "
,
""
],
# 优先级从高到低
)
chunks
=
splitter
.
split_text
(
text
)
for
i
,
c
in
enumerate
(
chunks
):
print
(
f
"[{i}] {c}"
)
```
```
bash
# 运行结果
[
0] 第一章 入职流程
新员工入职第一天,需要签订劳动合同、领取工牌、熟悉办公环境。
[
1] 第二章 考勤制度
公司采用弹性工作制,每天 8 小时工作制。
[
2] 迟到 15 分钟以内不扣工资,15-30 分钟扣半天工资。
```
> 看明白了吗?splitter **优先按 `\n\n`(段落)切**;段落不够大才退到 `\n`;再不够退到句号;以此类推。这就是"递归"的意思。
---
### 进阶玩法:带元数据的分块
生产环境的 chunk 必须
**带元数据**
(来源、页码、章节),否则溯源、过滤都做不了:
```
python
from
langchain_text_splitters
import
RecursiveCharacterTextSplitter
from
langchain_core.documents
import
Document
# 1. 原始文档带元数据
docs
=
[
Document
(
page_content
=
"公司年假为 10 个工作日。"
,
metadata
=
{
"source"
:
"员工手册.pdf"
,
"page"
:
5
,
"chapter"
:
"第三章 假期"
},
),
Document
(
page_content
=
"迟到 15 分钟以内不扣工资。"
,
metadata
=
{
"source"
:
"员工手册.pdf"
,
"page"
:
12
,
"chapter"
:
"第五章 考勤"
},
),
]
# 2. 分块时保留元数据
splitter
=
RecursiveCharacterTextSplitter
(
chunk_size
=
100
,
chunk_overlap
=
20
)
chunks
=
splitter
.
split_documents
(
docs
)
for
c
in
chunks
:
print
(
f
"[{c.metadata['chapter']}] {c.page_content}"
)
```
```
bash
# 运行结果
[
第三章 假期] 公司年假为 10 个工作日。
[
第五章 考勤] 迟到 15 分钟以内不扣工资。
```
> 元数据能让你在 RAG 答案里加"来源标注"(如 `[[员工手册.pdf P5]]`),提升可解释性。
---
### 举个例子:中文场景的分块参数
中文文档分块参数和英文
**不一样**
:
| 场景 | chunk_size | overlap | 备注 |
| ------------------ | ---------------- | --------- | -------------- |
|
**英文 FAQ**
| 200 ~ 400 tokens | 20 ~ 50 | 英文单词短 |
|
**中文手册**
| 300 ~ 600 字 | 30 ~ 80 | 汉字信息密度高 |
|
**法律合同**
| 200 ~ 400 字 | 50 ~ 100 | 必须按条款切 |
|
**论文**
| 500 ~ 1000 字 | 100 ~ 200 | 上下文重要 |
> **经验法则**:`overlap ≈ chunk_size × 10%`。
---
### 正解 vs 错误
| 维度 | 正解 ✅ | 错误 ❌ |
| -------------------- | ------------------------------ | ----------------------- |
|
**方法选型**
| Recursive(默认)/ 按段落 | 固定字符切(切断句子) |
|
**chunk_size**
| 中文 300-400 tokens | 1000+(LLM 抓不住重点) |
|
**overlap**
| chunk_size 的 10%~20% | 0(边界信息丢失) |
|
**元数据**
| 必带 source/page/chapter | 只存文本(无法溯源) |
|
**长文档**
| 先按章节切,再按段落切(两级) | 一刀切到底 |
|
**法律/医疗**
| 按条款/段落切,禁用固定长度 | 切断关键条款 |
---
### 思考题 / Q&A
1.
**chunk 越小检索越准吗?**
提示:考虑召回率 vs 精度的权衡。
2.
**overlap 设多大合适?**
提示:考虑跨 chunk 的指代关系(如"它"、"上述")。
3.
**如何处理"一段里既有标题又有正文"的情况?**
提示:先按标题切,再在每个章节内部按段落切(两级分块)。
4.
**如果 chunk 太长导致 Embedding 超限(比如 BGE 限制 512 tokens),该怎么办?**
提示:用 tokenizer 预检查,或者直接按 token 切(tiktoken)。
---
### 本节小结
-
分块是 RAG 质量的
**胜负手**
——垃圾进,垃圾出。
-
三种主流方法:固定长度(玩具)、按段落(首选)、递归分块(工业默认)。
-
LangChain
`RecursiveCharacterTextSplitter`
是最常用的工具,
**按优先级递归切**
。
-
必须带元数据(source/page/chapter),否则无法溯源。
-
中文 chunk_size 通常 300~600 字,overlap 约 10%~20%。
---
### 完整代码
```
python
"""06_chunk_documents.py —— 递归分块 + 元数据保留"""
from
pathlib
import
Path
import
pdfplumber
from
langchain_text_splitters
import
RecursiveCharacterTextSplitter
def
load_pdf
(
path
:
Path
)
->
list
[
dict
]:
"""读 PDF,返回 [{text, metadata}, ...]"""
docs
=
[]
with
pdfplumber
.
open
(
path
)
as
pdf
:
for
i
,
page
in
enumerate
(
pdf
.
pages
):
text
=
page
.
extract_text
()
or
""
if
text
.
strip
():
docs
.
append
({
"text"
:
text
,
"metadata"
:
{
"source"
:
path
.
name
,
"page"
:
i
+
1
},
})
return
docs
def
chunk_documents
(
docs
:
list
[
dict
],
chunk_size
:
int
=
400
,
overlap
:
int
=
50
)
->
list
[
dict
]:
"""递归分块,保留元数据"""
splitter
=
RecursiveCharacterTextSplitter
(
chunk_size
=
chunk_size
,
chunk_overlap
=
overlap
,
separators
=
[
"
\n\n
"
,
"
\n
"
,
"。"
,
","
,
" "
,
""
],
)
chunks
=
[]
for
d
in
docs
:
for
piece
in
splitter
.
split_text
(
d
[
"text"
]):
chunks
.
append
({
"text"
:
piece
,
"metadata"
:
d
[
"metadata"
]})
return
chunks
if
__name__
==
"__main__"
:
pdf_path
=
Path
(
"员工手册.pdf"
)
raw
=
load_pdf
(
pdf_path
)
chunks
=
chunk_documents
(
raw
,
chunk_size
=
400
,
overlap
=
50
)
print
(
f
"原始文档:{len(raw)} 页"
)
print
(
f
"切分后:{len(chunks)} 个 chunk
\n
"
)
for
c
in
chunks
[:
3
]:
print
(
f
"[{c['metadata']['source']} P{c['metadata']['page']}] {c['text'][:80]}…"
)
```
---
### 验收标准
```
☐ 能解释为什么分块是 RAG 质量的胜负手
☐ 能说出 3 种分块方法的优劣(固定 / 段落 / 递归)
☐ 能用 LangChain RecursiveCharacterTextSplitter 切分中文文档
☐ 能解释 separators 优先级顺序的含义
☐ 能在分块时保留 source / page / chapter 元数据
☐ 知道 chunk_size 和 overlap 的推荐范围
☐ 能解释"父子分块"为什么能提升检索质量
```
---
### 官方来源
-
LangChain Text Splitters —
[
python.langchain.com/docs/modules/data_connection/document_transformers
](
https://python.langchain.com/docs/modules/data_connection/document_transformers/
)
-
Greg Kamradt 的分块综述 —
[
github.com/FullStackRetrieval-com/RetrievalTutorials
](
https://github.com/FullStackRetrieval-com/RetrievalTutorials
)
-
Datawhale
*Happy-LLM*
文本分块章节
---
> **下一节预告:[6.4 Embedding](#64-embedding)** —— 把 chunk 变成向量,让机器理解"语义"。
---
## 6.4 Embedding
> 用 1-2 句话说清:**Embedding = 把文本变成一组数字(向量),让机器能算出"两个句子像不像"。**
---
### 什么是 Embedding?
**Embedding(嵌入)**
是 NLP 里的"翻译官"——它把人类语言
**翻译成**
一串浮点数(通常 384、768、1024、1536 维),让计算机能用数学方式衡量"相似度"。
直觉理解:
```
text
"猫" → [0.21, -0.45, 0.78, ..., 0.33] (768 个数字)
"小猫" → [0.22, -0.44, 0.76, ..., 0.31] (和"猫"几乎一样!)
"汽车" → [-0.33, 0.67, -0.12, ..., 0.05] (和"猫"差距很大)
→ 两个向量"近" = 两个语义"像"
```
> **关键洞察**:模型不是记住"猫"这个字符串,而是学到"猫"在概念空间里的位置。位置相近 = 语义相近。
---
### 为什么 RAG 必须用 Embedding?
如果不把文本变成向量,机器就只能做"字符串匹配"——搜"年假"找不到"带薪休假",搜"apple"找不到"苹果"。
**Embedding 把"语义匹配"变成"向量距离计算",这是 RAG 能回答"看起来没问过的问题"的核心机制。**
---
### 5 分钟快速上手:BGE(中文首选)⭐
**BGE(BAAI General Embedding)**
是智源研究院开源的 Embedding 系列,中文效果 SOTA(State of the Art,当前最强),
**完全免费、本地运行**
。
```
bash
pip
install
sentence-transformers
```
```
python
from
sentence_transformers
import
SentenceTransformer
# 首次运行会自动从 HuggingFace 下载约 400MB
model
=
SentenceTransformer
(
"BAAI/bge-small-zh-v1.5"
)
sentences
=
[
"公司年假为 10 个工作日"
,
"带薪休假有多少天?"
,
"今天天气真好"
,
]
vectors
=
model
.
encode
(
sentences
)
print
(
f
"向量维度:{vectors.shape}"
)
# (3, 512)
print
(
f
"前 5 维:{vectors[0][:5]}"
)
# [0.025, -0.034, ...]
# 计算相似度
import
numpy
as
np
sim
=
model
.
similarity
(
vectors
,
vectors
)
print
(
f
"'年假' vs '带薪休假':{sim[0][1]:.3f}"
)
# 高
print
(
f
"'年假' vs '天气真好':{sim[0][2]:.3f}"
)
# 低
```
```
bash
# 运行结果
向量维度:
(
3, 512
)
前 5 维:[ 0.0253
-0
.0341 0.0117
-0
.0089 0.0421]
'年假'
vs
'带薪休假'
:0.812
'年假'
vs
'天气真好'
:0.184
```
> 看清楚了吗?"年假"和"带薪休假"的相似度 **0.812**,而和"天气真好"只有 **0.184** —— Embedding 真的"懂"语义。
---
### 举个例子:BGE 常用模型选型
| 模型 | 维度 | 大小 | 中文效果 | 适用场景 |
| ------------------------------------ | ---- | ------ | ---------- | ---------------------- |
|
**`bge-small-zh-v1.5`**
⭐ | 512 | 90 MB | ⭐⭐⭐⭐ |
**本地原型首选**
|
|
`bge-base-zh-v1.5`
| 768 | 400 MB | ⭐⭐⭐⭐⭐ | 中文生产环境 |
|
`bge-large-zh-v1.5`
| 1024 | 1.3 GB | ⭐⭐⭐⭐⭐ | 追求极致质量 |
|
`bge-m3`
| 1024 | 2.2 GB | ⭐⭐⭐⭐⭐ | 多语言、长文本 |
|
`text-embedding-3-small`
(OpenAI) | 1536 | 云端 | ⭐⭐⭐⭐ | 不想本地部署 |
> **经验法则**:刚开始用 `bge-small-zh-v1.5` 跑通流程;中文质量不够再换 `bge-base-zh-v1.5`;多语言/长文本用 `bge-m3`。
---
### 进阶玩法:OpenAI Embedding(云端方案,副方案)
如果不想本地部署,可以用 OpenAI 的 Embedding API。
**注意:会按 token 计费,文档量大时成本可观。**
```
bash
pip
install
openai
export
OPENAI_API_KEY
=
"sk-..."
```
```
python
from
openai
import
OpenAI
client
=
OpenAI
()
def
embed_openai
(
texts
:
list
[
str
],
model
:
str
=
"text-embedding-3-small"
)
->
list
[
list
[
float
]]:
"""OpenAI Embedding 封装"""
resp
=
client
.
embeddings
.
create
(
input
=
texts
,
model
=
model
)
return
[
item
.
embedding
for
item
in
resp
.
data
]
# 用法
texts
=
[
"公司年假为 10 个工作日"
,
"带薪休假有多少天?"
]
vectors
=
embed_openai
(
texts
)
print
(
f
"维度:{len(vectors[0])}"
)
# 1536
```
#### BGE vs OpenAI 对比
| 维度 | BGE(本地) ⭐ | OpenAI(云端) |
| ---------------------- | -------------- | ------------------ |
|
**成本**
| 0(电费) | ~$0.02 / 1M tokens |
|
**中文效果**
| ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
|
**数据隐私**
| 完全本地 | 传到 OpenAI |
|
**速度(首字)**
| 慢(模型加载) | 快(API 调用) |
|
**速度(批量)**
| 快(GPU) | 中等(网络) |
|
**离线可用**
| ✅ | ❌ |
> **推荐**:BGE 主、OpenAI 副。开发用 BGE 省钱 + 数据安全;生产环境有海外/多语言需求时换 OpenAI。
---
### 举个例子:双方案切换的统一接口
写一个
`Embedder`
抽象类,业务代码就能在两个方案间无缝切换:
```
python
from
abc
import
ABC
,
abstractmethod
import
numpy
as
np
class
Embedder
(
ABC
):
@abstractmethod
def
embed
(
self
,
texts
:
list
[
str
])
->
np
.
ndarray
:
"""输入文本列表,返回 (n, dim) 的 numpy 数组"""
raise
NotImplementedError
class
BGEEmbedder
(
Embedder
):
"""本地 BGE 方案"""
def
__init__
(
self
,
model_name
:
str
=
"BAAI/bge-small-zh-v1.5"
):
from
sentence_transformers
import
SentenceTransformer
self
.
model
=
SentenceTransformer
(
model_name
)
def
embed
(
self
,
texts
:
list
[
str
])
->
np
.
ndarray
:
return
self
.
model
.
encode
(
texts
,
normalize_embeddings
=
True
)
class
OpenAIEmbedder
(
Embedder
):
"""云端 OpenAI 方案"""
def
__init__
(
self
,
model
:
str
=
"text-embedding-3-small"
):
from
openai
import
OpenAI
self
.
client
=
OpenAI
()
self
.
model
=
model
def
embed
(
self
,
texts
:
list
[
str
])
->
np
.
ndarray
:
resp
=
self
.
client
.
embeddings
.
create
(
input
=
texts
,
model
=
self
.
model
)
return
np
.
array
([
d
.
embedding
for
d
in
resp
.
data
])
# 使用:切换方案只改一行
# embedder: Embedder = BGEEmbedder()
embedder
:
Embedder
=
OpenAIEmbedder
()
texts
=
[
"年假有几天?"
,
"带薪休假政策"
]
vectors
=
embedder
.
embed
(
texts
)
print
(
vectors
.
shape
)
# (2, 512) 或 (2, 1536)
```
---
### 进阶玩法:批量编码 + 缓存
实战时一次要 Embedding 几千个 chunk,必须批量 + 缓存:
```
python
import
hashlib
import
json
from
pathlib
import
Path
import
numpy
as
np
class
CachedEmbedder
:
"""带本地缓存的 Embedder"""
def
__init__
(
self
,
base
:
Embedder
,
cache_dir
:
str
=
".embed_cache"
):
self
.
base
=
base
self
.
cache_dir
=
Path
(
cache_dir
)
self
.
cache_dir
.
mkdir
(
exist_ok
=
True
)
def
_key
(
self
,
text
:
str
)
->
str
:
return
hashlib
.
md5
(
text
.
encode
(
"utf-8"
))
.
hexdigest
()
def
embed
(
self
,
texts
:
list
[
str
])
->
np
.
ndarray
:
results
:
dict
[
int
,
np
.
ndarray
]
=
{}
missing
:
list
[
tuple
[
int
,
str
]]
=
[]
# 1. 查缓存
for
i
,
t
in
enumerate
(
texts
):
fp
=
self
.
cache_dir
/
f
"{self._key(t)}.npy"
if
fp
.
exists
():
results
[
i
]
=
np
.
load
(
fp
)
else
:
missing
.
append
((
i
,
t
))
# 2. 算缺失的
if
missing
:
new_vectors
=
self
.
base
.
embed
([
t
for
_
,
t
in
missing
])
for
(
i
,
t
),
vec
in
zip
(
missing
,
new_vectors
):
fp
=
self
.
cache_dir
/
f
"{self._key(t)}.npy"
np
.
save
(
fp
,
vec
)
results
[
i
]
=
vec
# 3. 按原顺序返回
return
np
.
stack
([
results
[
i
]
for
i
in
range
(
len
(
texts
))])
```
> 加了缓存后,**重复内容(比如用户问同一个问题)不会重复扣 API 费**,生产环境必备。
---
### 正解 vs 错误
| 维度 | 正解 ✅ | 错误 ❌ |
| ------------------ | ----------------------------- | --------------------------- |
|
**模型选型**
| 中文 BGE / 多语 bge-m3 | 用英文模型跑中文(效果差) |
|
**首选手册**
|
`bge-small-zh-v1.5`
(轻量) | 一上来就
`bge-large`
(慢) |
|
**数据隐私**
| 内部文档用 BGE 本地 | 全用 OpenAI(敏感数据外泄) |
|
**批量调用**
| 一次
`encode([...])`
几十条 | 一条一条调(慢 10 倍) |
|
**归一化**
|
`normalize_embeddings=True`
| 不归一化(点积失真) |
|
**重复内容**
| 加缓存 | 每次重算(烧钱) |
---
### 思考题 / Q&A
1.
**Embedding 维度越高效果越好吗?**
提示:考虑存储成本和检索速度。
2.
**为什么需要 `normalize_embeddings=True`?**
提示:余弦相似度 vs 点积的区别。
3.
**BGE 模型对输入长度有限制吗?超出怎么办?**
提示:bge-small/base 限制 512 tokens,超出会被截断;bge-m3 支持 8192 tokens。
4.
**如何评估一个 Embedding 模型在你的业务上的效果?**
提示:构造 100 对"问题-答案",看 Top-K 命中率。
---
### 本节小结
-
**Embedding**
= 把文本变成向量,让机器能算语义相似度。
-
**BGE**
(智源开源)是中文首选,
`bge-small-zh-v1.5`
入门、
`bge-large-zh-v1.5`
求质、
`bge-m3`
多语言。
-
**OpenAI**
`text-embedding-3-small`
是云端备选,
**注意成本和数据隐私**
。
-
推荐
**BGE 主、OpenAI 副**
,通过抽象类切换。
-
实战必须
**批量调用 + 归一化 + 缓存**
。
---
### 完整代码
```
python
"""06_embed_chunks.py —— 双方案 Embedding + 缓存"""
from
pathlib
import
Path
import
numpy
as
np
from
sentence_transformers
import
SentenceTransformer
class
BGEEmbedder
:
"""本地 BGE Embedder"""
def
__init__
(
self
,
model_name
:
str
=
"BAAI/bge-small-zh-v1.5"
):
self
.
model
=
SentenceTransformer
(
model_name
)
def
embed
(
self
,
texts
:
list
[
str
])
->
np
.
ndarray
:
return
self
.
model
.
encode
(
texts
,
normalize_embeddings
=
True
)
class
CachedEmbedder
:
"""带磁盘缓存的装饰器"""
def
__init__
(
self
,
base
:
BGEEmbedder
,
cache_dir
:
str
=
".embed_cache"
):
import
hashlib
self
.
base
=
base
self
.
cache_dir
=
Path
(
cache_dir
)
self
.
cache_dir
.
mkdir
(
exist_ok
=
True
)
self
.
_hash
=
lambda
t
:
hashlib
.
md5
(
t
.
encode
())
.
hexdigest
()
def
embed
(
self
,
texts
:
list
[
str
])
->
np
.
ndarray
:
results
=
{}
missing
,
missing_idx
=
[],
[]
for
i
,
t
in
enumerate
(
texts
):
fp
=
self
.
cache_dir
/
f
"{self._hash(t)}.npy"
if
fp
.
exists
():
results
[
i
]
=
np
.
load
(
fp
)
else
:
missing
.
append
(
t
)
missing_idx
.
append
(
i
)
if
missing
:
new_vecs
=
self
.
base
.
embed
(
missing
)
for
i
,
t
,
v
in
zip
(
missing_idx
,
missing
,
new_vecs
):
np
.
save
(
self
.
cache_dir
/
f
"{self._hash(t)}.npy"
,
v
)
results
[
i
]
=
v
return
np
.
stack
([
results
[
i
]
for
i
in
range
(
len
(
texts
))])
if
__name__
==
"__main__"
:
embedder
=
CachedEmbedder
(
BGEEmbedder
())
chunks
=
[
"公司年假为 10 个工作日"
,
"带薪休假政策"
,
"今天天气真好"
,
]
vectors
=
embedder
.
embed
(
chunks
)
print
(
f
"维度:{vectors.shape}"
)
sim
=
embedder
.
base
.
model
.
similarity
(
vectors
,
vectors
)
print
(
f
"'年假' vs '带薪休假':{sim[0][1]:.3f}"
)
print
(
f
"'年假' vs '天气真好':{sim[0][2]:.3f}"
)
```
---
### 验收标准
```
☐ 能用一句话解释 Embedding 是什么
☐ 能说出 BGE-small-zh-v1.5 的向量维度(512)
☐ 能用 BGE 计算两句话的相似度
☐ 能写出 BGE 与 OpenAI 双方案的统一接口
☐ 知道为什么需要 normalize_embeddings=True
☐ 能用 np.save 实现 Embedding 缓存
☐ 知道 bge-m3 适合多语言/长文本场景
```
---
### 官方来源
-
BAAI BGE 官方仓库 —
[
github.com/FlagOpen/FlagEmbedding
](
https://github.com/FlagOpen/FlagEmbedding
)
-
Sentence-Transformers 文档 —
[
sbert.net
](
https://www.sbert.net/
)
-
OpenAI Embedding API —
[
platform.openai.com/docs/guides/embeddings
](
https://platform.openai.com/docs/guides/embeddings
)
-
MTEB Leaderboard(Embedding 模型排行榜)—
[
huggingface.co/spaces/mteb/leaderboard
](
https://huggingface.co/spaces/mteb/leaderboard
)
---
> **下一节预告:[6.5 向量数据库](#65-向量数据库)** —— 把向量"装进"数据库,让百万级文档也能秒级检索。
---
## 6.5 向量数据库
> 用 1-2 句话说清:**向量数据库 = 能高效存储向量 + 做最近邻(ANN)检索的数据库,是 RAG 的"记忆中枢"。**
---
### 什么是向量数据库?
把 chunk Embedding 之后,必须找个地方存起来,并支持
**快速相似度检索**
。传统数据库(MySQL、PostgreSQL)用
`WHERE text LIKE '%年假%'`
做
**字符串匹配**
,慢且不准。向量数据库专门做
**向量最近邻检索(ANN, Approximate Nearest Neighbor)**
。
```
text
传统数据库:找"完全相同"的记录
向量数据库:找"最相似"的记录(余弦相似度 / L2 距离 / 点积)
```
| 数据库 | 类型 | 特点 | 适用场景 |
| ------------------- | ----------------- | ------------------------ | ------------------------- |
|
**Chroma**
⭐ | 轻量、Python 原生 | 开源、本地、单行代码上手 |
**原型 + 教学首选**
|
|
**Milvus**
| 企业级、分布式 | 超大规模、支持混合检索 | 大规模生产 |
|
**Qdrant**
| Rust 实现、高性能 | API 友好、支持过滤 | 生产级 |
|
**FAISS**
| Facebook 开源 | 纯 Python 绑定、GPU 加速 | 离线批检索 |
|
**Pinecone**
| 云服务 | 全托管、免运维 | 企业云部署 |
|
**pgvector**
| PostgreSQL 扩展 | 复用现有 DB | 已有 PG 的团队 |
> 本节聚焦 **Chroma**(安装零门槛、API 简洁),因为它最适合教学和原型开发。
---
### 为什么 RAG 不能用普通数据库存向量?
假设我们有 10 万个 chunk,每个向量 512 维:
-
**普通数据库**
:
`SELECT * FROM chunks WHERE text LIKE '%关键词%'`
—— 10 万次字符串扫描,毫秒级?不可能,秒级起步。
-
**向量数据库**
:利用
**HNSW / IVF 等 ANN 索引**
,把 10 万向量组织成图/树结构,
**毫秒级返回 Top-K**
。
关键差异:
```
text
暴力检索: 遍历 100,000 个向量 × 512 维乘法 = 5,120 万次运算
ANN 索引: 在 100~1000 个候选中找 Top-K = 5~50 万次运算
```
---
### 5 分钟快速上手:Chroma CRUD
```
bash
pip
install
chromadb
```
```
python
import
chromadb
# 1. 创建持久化数据库
client
=
chromadb
.
PersistentClient
(
path
=
"./chroma_db"
)
# 2. 创建 Collection(类似"表")
collection
=
client
.
get_or_create_collection
(
name
=
"knowledge_base"
,
metadata
=
{
"description"
:
"公司知识库"
}
)
# 3. 插入数据(每条必须有 id)
collection
.
add
(
documents
=
[
"公司年假为 10 个工作日,满 1 年增加至 15 天。"
,
"病假需提供医院证明,3 天以内无需审批。"
,
"婚假为 10 个自然日,需提前 7 天申请。"
,
],
ids
=
[
"doc_001"
,
"doc_002"
,
"doc_003"
],
metadatas
=
[
{
"source"
:
"员工手册.pdf"
,
"page"
:
5
},
{
"source"
:
"员工手册.pdf"
,
"page"
:
12
},
{
"source"
:
"HR政策.docx"
,
"page"
:
3
},
]
)
# 4. 查询
results
=
collection
.
query
(
query_texts
=
[
"年假有几天?"
],
n_results
=
2
,
)
print
(
results
[
"documents"
][
0
])
print
(
results
[
"metadatas"
][
0
])
print
(
f
"距离:{results['distances'][0]}"
)
```
```
bash
# 运行结果
[
'公司年假为 10 个工作日,满 1 年增加至 15 天。'
,
'婚假为 10 个自然日,需提前 7 天申请。'
]
[{
'source'
:
'员工手册.pdf'
,
'page'
: 5
}
,
{
'source'
:
'HR政策.docx'
,
'page'
: 3
}]
[
0.123, 0.456]
```
---
### 举个例子:Chroma 完整 RAG 流程(入库 → 检索)
把 6.2 ~ 6.4 串起来,跑通整个离线索引流程:
```
python
import
chromadb
from
sentence_transformers
import
SentenceTransformer
# 1. Embedder(BGE,本地)
model
=
SentenceTransformer
(
"BAAI/bge-small-zh-v1.5"
)
# 2. Chroma
client
=
chromadb
.
PersistentClient
(
path
=
"./chroma_db"
)
collection
=
client
.
get_or_create_collection
(
name
=
"full_rag_demo"
,
embedding_function
=
None
,
# 我们手动 Embed,不用 Chroma 内置的
)
# 3. 文档
docs
=
[
{
"id"
:
"001"
,
"text"
:
"公司年假为 10 个工作日,满 1 年增加至 15 天。"
,
"meta"
:
{
"source"
:
"员工手册"
}},
{
"id"
:
"002"
,
"text"
:
"病假需提供医院证明,3 天以内无需审批。"
,
"meta"
:
{
"source"
:
"HR政策"
}},
{
"id"
:
"003"
,
"text"
:
"婚假为 10 个自然日,需提前 7 天申请。"
,
"meta"
:
{
"source"
:
"HR政策"
}},
]
# 4. 批量 Embed + 入库
texts
=
[
d
[
"text"
]
for
d
in
docs
]
ids
=
[
d
[
"id"
]
for
d
in
docs
]
metas
=
[
d
[
"meta"
]
for
d
in
docs
]
embeddings
=
model
.
encode
(
texts
,
normalize_embeddings
=
True
)
collection
.
add
(
documents
=
texts
,
embeddings
=
embeddings
.
tolist
(),
ids
=
ids
,
metadatas
=
metas
,
)
# 5. 检索
query
=
"年假多少天?"
q_emb
=
model
.
encode
([
query
],
normalize_embeddings
=
True
)
results
=
collection
.
query
(
query_embeddings
=
q_emb
.
tolist
(),
n_results
=
2
,
)
print
(
f
"问:{query}"
)
print
(
f
"答(Top-1):{results['documents'][0][0]}"
)
print
(
f
"来源:{results['metadatas'][0][0]['source']}"
)
```
```
bash
# 运行结果
问:年假多少天?
答(Top-1):公司年假为 10 个工作日,满 1 年增加至 15 天。
来源:员工手册
```
---
### 进阶玩法:更新 / 删除 / 过滤检索
```
python
# 更新:已有 id 的文档会覆盖
collection
.
upsert
(
documents
=
[
"公司年假更新为 15 个工作日。"
],
ids
=
[
"doc_001"
],
)
# 删除
collection
.
delete
(
ids
=
[
"doc_002"
])
# 过滤检索(只查 metadata 符合条件的)
results
=
collection
.
query
(
query_texts
=
[
"假期政策"
],
n_results
=
3
,
where
=
{
"source"
:
"HR政策"
},
# 只查 HR政策
# where={"page": {"$gte": 5}}, # 第 5 页及以后
)
```
---
### 进阶玩法:度量方式选型
Chroma 支持三种相似度度量:
| 度量方式 | 适用场景 | 特点 |
| --------------------------------- | ---------------------- | -------------------------- |
|
**余弦相似度(cosine)**
⭐ | 通用首选,已归一化向量 | 值范围
[
-1, 1
]
,越大越相似 |
|
**欧氏距离(L2)**
| 图像/特征向量 | 值越小越相似 |
|
**点积(dot product)**
| 未归一化的 Embedding | 值越大越相似 |
```
python
collection
=
client
.
get_or_create_collection
(
name
=
"demo"
,
metadata
=
{
"hnsw:space"
:
"cosine"
},
# "l2" 或 "ip"
)
```
> 当使用 BGE 的 `normalize_embeddings=True` 时,**余弦相似度 = 点积**,用哪个都行。
---
### Chroma 的限制与应对
| 限制 | 说明 | 应对方案 |
| -------------------- | -------------------------- | ------------------------------ |
|
**单机**
| 不支持分布式 | 规模大时迁移到 Milvus / Qdrant |
|
**Qdrant**
| 持久化依赖磁盘 I/O | 对接 S3 备份 |
|
**过滤检索慢**
|
`where`
过滤不走向量索引 | 先粗召回再内存过滤 |
---
### 正解 vs 错误
| 维度 | 正解 ✅ | 错误 ❌ |
| ------------------- | ------------------------------ | -------------------------------------- |
|
**入库时机**
| 离线一次性建索引 | 每次请求都重建(慢) |
|
**持久化**
|
`PersistentClient(path=...)`
| 每次重建 collection(丢数据) |
|
**ID**
| 业务 ID(如
`doc_001`
) | 每次用 UUID(无法更新) |
|
**n_results**
| 3~5(够用 + 不太长) | 100(context 爆炸) |
|
**度量方式**
| cosine(已归一化时) | ip 混用 cosine(数值混乱) |
|
**Embedding**
| 手动控制(自己调 BGE) | 依赖 Chroma 内置 Embedding(不够灵活) |
|
**过滤**
|
`where`
先粗筛 | 全量检索再内存过滤(慢) |
---
### 思考题 / Q&A
1.
**Chroma 的 `add` 和 `upsert` 有什么区别?**
提示:
`add`
要求 ID 不存在,
`upsert`
是"有则更新,无则插入"。
2.
**向量数据库里的"距离"(distance)越小越好还是越大越好?**
提示:取决于度量方式(cosine / L2 / dot)。
3.
**如果有 1000 万个 chunk,Chroma 还够用吗?**
提示:单机内存瓶颈;建议迁移 Milvus / Qdrant。
4.
**如何让 RAG 答案标注"这段话来自哪个文件第几页"?**
提示:存入
`metadatas`
里,检索后取出来拼进 prompt。
---
### 本节小结
-
向量数据库 = 高效存储向量 + ANN 检索,专门解决"找最相似的 K 个"这个问题。
-
**Chroma**
是教学/原型首选(Python 原生、单行安装);生产用 Milvus / Qdrant。
-
Chroma 核心操作:
`add`
/
`upsert`
/
`delete`
/
`query`
。
-
`metadata`
是溯源关键,检索后要把
`source`
/
`page`
拼进 prompt,LLM 才能说"根据第 X 页"。
-
`normalize_embeddings=True`
时,cosine = dot product,用哪个都行。
-
离线建索引(一次性),在线检索(每次请求)。
---
### 完整代码
```
python
"""06_vector_store.py —— Chroma 完整 RAG 流程"""
import
chromadb
from
sentence_transformers
import
SentenceTransformer
class
RAGVectorStore
:
"""封装 Chroma + BGE 的 RAG 向量库"""
def
__init__
(
self
,
db_path
:
str
=
"./chroma_db"
,
collection_name
:
str
=
"rag"
):
self
.
embedder
=
SentenceTransformer
(
"BAAI/bge-small-zh-v1.5"
)
self
.
client
=
chromadb
.
PersistentClient
(
path
=
db_path
)
self
.
collection
=
self
.
client
.
get_or_create_collection
(
name
=
collection_name
,
metadata
=
{
"hnsw:space"
:
"cosine"
},
)
def
add_documents
(
self
,
docs
:
list
[
dict
]):
"""批量入库:docs = [{"id", "text", "metadata"}, ...]"""
texts
=
[
d
[
"text"
]
for
d
in
docs
]
ids
=
[
d
[
"id"
]
for
d
in
docs
]
metas
=
[
d
.
get
(
"metadata"
,
{})
for
d
in
docs
]
embeddings
=
self
.
embedder
.
encode
(
texts
,
normalize_embeddings
=
True
)
self
.
collection
.
add
(
documents
=
texts
,
embeddings
=
embeddings
.
tolist
(),
ids
=
ids
,
metadatas
=
metas
,
)
print
(
f
"✅ 入库 {len(docs)} 条"
)
def
search
(
self
,
query
:
str
,
top_k
:
int
=
3
,
filter_meta
:
dict
=
None
)
->
list
[
dict
]:
"""语义检索"""
q_emb
=
self
.
embedder
.
encode
([
query
],
normalize_embeddings
=
True
)
kwargs
=
{
"query_embeddings"
:
q_emb
.
tolist
(),
"n_results"
:
top_k
,
}
if
filter_meta
:
kwargs
[
"where"
]
=
filter_meta
results
=
self
.
collection
.
query
(
**
kwargs
)
return
[
{
"text"
:
doc
,
"metadata"
:
meta
,
"distance"
:
dist
,
}
for
doc
,
meta
,
dist
in
zip
(
results
[
"documents"
][
0
],
results
[
"metadatas"
][
0
],
results
[
"distances"
][
0
],
)
]
if
__name__
==
"__main__"
:
store
=
RAGVectorStore
(
db_path
=
"./chroma_db"
,
collection_name
=
"demo"
)
# 入库
store
.
add_documents
([
{
"id"
:
"001"
,
"text"
:
"公司年假为 10 个工作日,满 1 年增加至 15 天。"
,
"metadata"
:
{
"source"
:
"员工手册"
,
"page"
:
5
}},
{
"id"
:
"002"
,
"text"
:
"病假需提供医院证明,3 天以内无需审批。"
,
"metadata"
:
{
"source"
:
"HR政策"
,
"page"
:
12
}},
{
"id"
:
"003"
,
"text"
:
"婚假为 10 个自然日,需提前 7 天申请。"
,
"metadata"
:
{
"source"
:
"HR政策"
,
"page"
:
3
}},
])
# 检索
results
=
store
.
search
(
"年假有几天?"
)
for
r
in
results
:
print
(
f
" [{r['distance']:.3f}] {r['text']}"
)
print
(
f
" 来源:{r['metadata']}"
)
```
---
### 验收标准
```
☐ 能说出向量数据库和普通数据库的核心区别(ANN 检索 vs 字符串匹配)
☐ 能用 Chroma 创建一个 Collection 并完成 add / query / delete
☐ 能解释 metadata 的作用(溯源、过滤)
☐ 能用 BGE + Chroma 串起完整的"入库 → 检索"流程
☐ 能用 where 参数做 metadata 过滤检索
☐ 能区分 cosine / L2 / dot product 三种度量方式
☐ 知道什么时候该从 Chroma 迁移到 Milvus / Qdrant
☐ 能说出 Chroma 的三个主要限制(单机、过滤慢、内存)
```
---
### 官方来源
-
Chroma 官方文档 —
[
docs.trychroma.com
](
https://docs.trychroma.com/
)
-
HNSW 算法原理解释 —
[
www.pinecone.io/learn/vector-index
](
https://www.pinecone.io/learn/vector-index/
)
-
Milvus 官方文档 —
[
milvus.io/docs/overview.md
](
https://milvus.io/docs/overview.md
)
-
Datawhale
*Happy-LLM*
向量数据库章节
docs/工程实操/模块七-工程实操.md
0 → 100644
浏览文件 @
9ce011f1
# 模块七 工程实操
> **本模块导读**:本模块面向 Python 后端 / LLM 应用开发者,目标是掌握开发即部署的核心工程工具。从 FastAPI 构建 HTTP API,到 PostgreSQL 持久化数据,到 Redis 缓存加速,再到 Docker 容器化部署,最后用 pytest 写出可维护的测试。学完本模块,你应该能独立搭起一个**前后端分离 + 数据库持久化 + 容器化部署**的最小完整系统。
>
> **章节列表**:
>
> - **7.1 FastAPI** ← 本模块当前章节(★4)
> - 7.2 PostgreSQL
> - 7.3 Redis
> - 7.4 Docker
> - 7.5 pytest
>
> **阅读建议**:边看边敲。每章的"5 分钟快速上手"都是可直接运行的最小示例,建议动手跑一遍再往下走。
---
## 目录
| 章节 | 名称 | 难度 | 预计耗时 |
| --- | --- | --- | --- |
|
[
7.1
](
#71-fastapi
)
| FastAPI | ★★★★☆ | 50 min |
|
[
7.2
](
#72-postgresql
)
| PostgreSQL | ★★★★☆ | 55 min |
|
[
7.3
](
#73-redis
)
| Redis | ★★★☆☆ | 45 min |
|
[
7.4
](
#74-docker
)
| Docker | ★★★★☆ | 55 min |
|
[
7.5
](
#75-pytest
)
| pytest | ★★★☆☆ | 45 min |
---
## 7.1 FastAPI
> 用 1-2 句话说清:**FastAPI = 用 Python 写 API 的现代框架**,比 Flask 快 2~10 倍,自带 Swagger 文档、自动参数校验、async 支持。
---
### 什么是 FastAPI?
**FastAPI**
是一个现代、高性能的 Python Web 框架,用于构建 HTTP API。它的核心特点:
| 特点 | 说明 |
| --- | --- |
|
**快**
| 基于 Starlette(异步),性能接近 Node.js,远超 Flask |
|
**自动文档**
| 启动服务后访问
`/docs`
直接看到 Swagger UI |
|
**类型安全**
| 用 Pydantic 做请求/响应校验,类型错了直接 422 |
|
**async**
| 原生支持
`async def`
,一个进程扛几千并发 |
### 为什么需要 FastAPI?
假设你要写一个"根据问题检索知识库并回答"的 API:
| 方案 | 代码量 | 文档 | 性能 | 类型校验 |
| --- | --- | --- | --- | --- |
|
**Flask**
| 多(手写路由+参数解析)| 无 | 中 | 无 |
|
**Django**
| 重(适合大项目)| 有(DRF)| 中 | 有 |
|
**FastAPI**
⭐ | 少 |
**自动**
|
**高**
|
**自动**
|
---
### 5 分钟快速上手:最小 FastAPI 服务
```
bash
pip
install
fastapi uvicorn
```
```
python
from
fastapi
import
FastAPI
app
=
FastAPI
()
@app.get
(
"/"
)
def
read_root
():
return
{
"message"
:
"你好,FastAPI!"
}
@app.get
(
"/items/{item_id}"
)
def
read_item
(
item_id
:
int
,
q
:
str
|
None
=
None
):
return
{
"item_id"
:
item_id
,
"q"
:
q
}
```
```
bash
# 启动服务
uvicorn main:app
--reload
--port
8000
```
```
bash
# 运行结果
# INFO: Uvicorn running on http://127.0.0.1:8000
# 访问 http://127.0.0.1:8000/docs 看到 Swagger UI
```
---
### 举个例子:FastAPI vs Flask 对比
#### FastAPI 写法
```
python
from
fastapi
import
FastAPI
,
Query
,
Path
from
pydantic
import
BaseModel
,
Field
from
typing
import
Optional
app
=
FastAPI
()
class
Item
(
BaseModel
):
name
:
str
price
:
float
description
:
Optional
[
str
]
=
None
@app.post
(
"/items/"
)
def
create_item
(
item
:
Item
):
return
{
"item_id"
:
42
,
**
item
.
model_dump
()}
@app.get
(
"/items/{item_id}"
)
def
get_item
(
item_id
:
int
=
Path
(
...
,
gt
=
0
),
q
:
Optional
[
str
]
=
Query
(
None
,
min_length
=
3
,
max_length
=
50
),
):
return
{
"item_id"
:
item_id
,
"q"
:
q
}
```
#### Flask 等价写法
```
python
from
flask
import
Flask
,
request
,
jsonify
from
functools
import
wraps
app
=
Flask
(
__name__
)
def
validate_item
(
f
):
@wraps
(
f
)
def
wrapper
(
*
args
,
**
kwargs
):
data
=
request
.
get_json
()
if
not
data
or
"name"
not
in
data
or
"price"
not
in
data
:
return
jsonify
({
"error"
:
"缺少字段"
}),
400
try
:
data
[
"price"
]
=
float
(
data
[
"price"
])
except
(
TypeError
,
ValueError
):
return
jsonify
({
"error"
:
"price 必须是数字"
}),
400
return
f
(
data
)
return
wrapper
@app.route
(
"/items/"
,
methods
=
[
"POST"
])
@validate_item
def
create_item
(
data
):
return
jsonify
({
"item_id"
:
42
,
**
data
})
@app.route
(
"/items/<int:item_id>"
,
methods
=
[
"GET"
])
def
get_item
(
item_id
):
q
=
request
.
args
.
get
(
"q"
,
""
)
return
jsonify
({
"item_id"
:
item_id
,
"q"
:
q
})
```
#### 对比结果
| 维度 | FastAPI | Flask |
| --- | --- | --- |
|
**类型校验**
| Pydantic 自动 | 手写装饰器 |
|
**Swagger 文档**
|
`/docs`
自动生成 | 手动写
`flasgger`
|
|
**参数校验语法**
|
`@Query`
,
`@Path`
装饰器 |
`request.args.get()`
手动解析 |
|
**异步支持**
|
`async def`
原生 | 需要
`asgiref`
兼容层 |
|
**开箱即用**
| 错误 422 自动返回 | 自定义 400 返回 |
---
### 进阶玩法:Pydantic 模型 + 422 错误演示
Pydantic 是 FastAPI 的"自动门卫"——请求参数不对,直接返回 422,而不是让业务代码崩溃。
```
python
from
fastapi
import
FastAPI
,
HTTPException
from
pydantic
import
BaseModel
,
Field
,
field_validator
from
datetime
import
date
app
=
FastAPI
()
class
UserCreate
(
BaseModel
):
username
:
str
=
Field
(
...
,
min_length
=
3
,
max_length
=
20
)
email
:
str
=
Field
(
...
,
pattern
=
r"^[\w\.-]+@[\w\.-]+\.\w+$"
)
age
:
int
=
Field
(
...
,
ge
=
0
,
le
=
150
)
birthday
:
date
@field_validator
(
"username"
)
@classmethod
def
username_no_space
(
cls
,
v
:
str
)
->
str
:
if
" "
in
v
:
raise
ValueError
(
"用户名不能包含空格"
)
return
v
@app.post
(
"/users/"
)
def
create_user
(
user
:
UserCreate
):
return
{
"msg"
:
"创建成功"
,
"user"
:
user
.
model_dump
()}
```
```
bash
# 测试 1:正常请求
$
curl
-X
POST http://localhost:8000/users/
\
-H
"Content-Type: application/json"
\
-d
'{"username":"alice","email":"alice@example.com","age":25,"birthday":"1999-01-01"}'
# {"msg":"创建成功","user":{"username":"alice","email":"alice@example.com","age":25,"birthday":"1999-01-01"}}
# 测试 2:校验失败(422)
$
curl
-X
POST http://localhost:8000/users/
\
-H
"Content-Type: application/json"
\
-d
'{"username":"al","email":"not-an-email","age":-1,"birthday":"1999-01-01"}'
# {
# "detail": [
# {
# "loc": ["body", "username"],
# "msg": "String should have at least 3 characters",
# "type": "string_too_short"
# },
# {
# "loc": ["body", "email"],
# "msg": "String should match pattern ...",
# "type": "string_pattern_mismatch"
# },
# {
# "loc": ["body", "age"],
# "msg": "Input should be greater than or equal to 0",
# "type": "greater_than_equal"
# }
# ]
# }
```
---
### 进阶玩法:依赖注入(Depends)
FastAPI 的
`Depends`
就像"自动挡"——你需要什么,框架自动挂上,你只管踩油门。
```
python
from
fastapi
import
FastAPI
,
Depends
,
HTTPException
,
status
from
fastapi.security
import
HTTPBearer
,
HTTPAuthorizationCredentials
from
pydantic
import
BaseModel
from
typing
import
Optional
app
=
FastAPI
()
security
=
HTTPBearer
()
# 模拟数据库
FAKE_DB
=
{
"alice"
:
{
"role"
:
"admin"
},
"bob"
:
{
"role"
:
"user"
}}
# 依赖 1:验证 Token
def
verify_token
(
credentials
:
HTTPAuthorizationCredentials
=
Depends
(
security
)):
if
credentials
.
scheme
!=
"Bearer"
:
raise
HTTPException
(
status_code
=
401
,
detail
=
"无效的认证方式"
)
if
credentials
.
credentials
!=
"secret-token"
:
raise
HTTPException
(
status_code
=
401
,
detail
=
"Token 无效"
)
return
credentials
.
credentials
# 依赖 2:获取当前用户
def
get_current_user
(
token
:
str
=
Depends
(
verify_token
))
->
dict
:
for
name
,
info
in
FAKE_DB
.
items
():
if
name
in
token
:
return
{
"username"
:
name
,
**
info
}
return
{
"username"
:
"unknown"
,
"role"
:
"guest"
}
# 路由使用
@app.get
(
"/profile"
)
def
get_profile
(
user
:
dict
=
Depends
(
get_current_user
)):
return
{
"username"
:
user
[
"username"
],
"role"
:
user
[
"role"
]}
@app.delete
(
"/users/{username}"
)
def
delete_user
(
username
:
str
,
user
:
dict
=
Depends
(
get_current_user
),
):
if
user
.
get
(
"role"
)
!=
"admin"
:
raise
HTTPException
(
status_code
=
403
,
detail
=
"仅管理员可操作"
)
return
{
"msg"
:
f
"用户 {username} 已删除"
}
```
> **核心理解**:`Depends` 让你把认证、数据库连接、参数校验抽成独立的"依赖函数",每个路由需要什么就 `Depends` 什么,代码干净、可复用、可测试。
---
### 进阶玩法:中间件
中间件 = 请求进来和响应出去时会"路过"的公共处理层。
```
python
from
fastapi
import
FastAPI
,
Request
import
time
app
=
FastAPI
()
@app.middleware
(
"http"
)
async
def
add_process_time_header
(
request
:
Request
,
call_next
):
start_time
=
time
.
time
()
response
=
await
call_next
(
request
)
process_time
=
time
.
time
()
-
start_time
response
.
headers
[
"X-Process-Time"
]
=
str
(
process_time
)
return
response
@app.middleware
(
"http"
)
async
def
log_requests
(
request
:
Request
,
call_next
):
print
(
f
"📥 {request.method} {request.url.path}"
)
response
=
await
call_next
(
request
)
print
(
f
"📤 {response.status_code}"
)
return
response
@app.get
(
"/hello"
)
def
hello
():
return
{
"message"
:
"world"
}
```
```
bash
# 响应头会多出 X-Process-Time
$
curl
-i
http://localhost:8000/hello
# HTTP/1.1 200 OK
# X-Process-Time: 0.00023
```
---
### 进阶玩法:异步路由
FastAPI 支持
`async def`
,让 I/O 密集型操作(数据库查询、HTTP 调用)并发执行。
```
python
import
asyncio
import
time
from
fastapi
import
FastAPI
app
=
FastAPI
()
# 同步路由(每个请求顺序执行)
@app.get
(
"/sync/slow"
)
def
sync_slow
():
time
.
sleep
(
1
)
return
{
"type"
:
"sync"
,
"time"
:
1
}
# 异步路由(可并发)
@app.get
(
"/async/slow"
)
async
def
async_slow
():
await
asyncio
.
sleep
(
1
)
return
{
"type"
:
"async"
,
"time"
:
1
}
# 模拟并发:同时触发 3 个异步请求
@app.get
(
"/async/batch"
)
async
def
async_batch
():
start
=
time
.
time
()
# asyncio.gather 并发执行 3 个 1 秒任务
results
=
await
asyncio
.
gather
(
asyncio
.
sleep
(
1
),
asyncio
.
sleep
(
1
),
asyncio
.
sleep
(
1
),
)
elapsed
=
time
.
time
()
-
start
return
{
"tasks"
:
3
,
"total_time"
:
round
(
elapsed
,
2
)}
```
```
bash
# 同步:3 次请求串行 = 3 秒
$
time
curl http://localhost:8000/sync/slow
$
time
curl http://localhost:8000/sync/slow
$
time
curl http://localhost:8000/sync/slow
# 总耗时 ≈ 3 秒
# 异步:3 次请求并发 = 1 秒
$
time
curl http://localhost:8000/async/batch
# {"tasks": 3, "total_time": 1.0}
```
> **什么时候用 async def?** 只要路由里有 `await`(数据库查询、外部 API、文件读写),就用 `async def`。只有纯计算没有 I/O 时才用同步 `def`。
---
### 正解 vs 错误
| 维度 | 正解 ✅ | 错误 ❌ |
| --- | --- | --- |
|
**路由参数**
|
`@app.get("/items/{item_id}")`
+ 函数参数
`item_id`
| 手动
`request.path_params`
|
|
**请求体**
| Pydantic 模型
`def create(item: Item)`
|
`request.get_json()`
手动解析 |
|
**参数校验**
|
`Field(..., ge=0, min_length=3)`
| 不校验,裸传类型 |
|
**错误返回**
|
`raise HTTPException(422, detail="...")`
|
`return {"error": ...}`
(状态码 200) |
|
**异步**
| I/O 密集 →
`async def`
+
`await`
| CPU 密集用
`async def`
(反而更慢) |
|
**uvicorn 启动**
|
`uvicorn main:app --reload`
|
`python main.py`
(不支持热重载) |
---
### 思考题 / Q&A
1.
**FastAPI 的 `raise HTTPException` 和普通 `return` 有什么区别?**
提示:HTTPException 会让框架走错误处理流程,返回正确的状态码(如 401/403/422);普通 return 永远是 200。
2.
**`Depends` 和普通函数参数有什么区别?**
提示:Depends 的函数会被 FastAPI 自动调用;普通参数需要调用方手动传入。
3.
**什么时候不能用 `async def`?**
提示:同步库(如
`requests`
而不是
`httpx`
)会阻塞事件循环,导致整个服务卡住。
4.
**如何让 FastAPI 返回文件下载?**
提示:
`from fastapi.responses import FileResponse`
。
---
### 本节小结
-
FastAPI = 高性能 + 自动文档 + 类型安全,比 Flask 更适合 API 开发。
-
**Pydantic**
是 FastAPI 的"门卫",校验失败返回 422,字段级别精细控制。
-
**`Depends`**
是依赖注入,认证/数据库连接等公共逻辑抽成独立函数。
-
**中间件**
处理请求/响应的横切关注点(日志、计时、CORS)。
-
**async def**
适合 I/O 密集场景;CPU 密集用同步
`def`
。
-
访问
`/docs`
查看自动生成的 Swagger 文档,是最实用的开发神器。
---
### 完整代码
```
python
"""07_fastapi_demo.py —— FastAPI 完整 CRUD 示例"""
from
fastapi
import
FastAPI
,
HTTPException
,
Depends
,
Query
,
Path
from
pydantic
import
BaseModel
,
Field
from
typing
import
Optional
from
datetime
import
date
app
=
FastAPI
(
title
=
"知识库问答 API"
,
version
=
"1.0.0"
)
# ===== 数据模型 =====
class
Item
(
BaseModel
):
name
:
str
=
Field
(
...
,
min_length
=
1
,
max_length
=
100
)
price
:
float
=
Field
(
...
,
gt
=
0
)
description
:
Optional
[
str
]
=
None
tags
:
list
[
str
]
=
[]
class
ItemResponse
(
Item
):
item_id
:
int
# ===== 模拟数据库 =====
db
:
dict
[
int
,
dict
]
=
{
1
:
{
"item_id"
:
1
,
"name"
:
"笔记本"
,
"price"
:
4999.0
,
"description"
:
"高性能轻薄本"
,
"tags"
:
[
"电脑"
]},
}
next_id
=
2
# ===== 路由 =====
@app.get
(
"/items/"
,
response_model
=
list
[
ItemResponse
])
def
list_items
(
skip
:
int
=
0
,
limit
:
int
=
10
):
return
list
(
db
.
values
())[
skip
:
skip
+
limit
]
@app.get
(
"/items/{item_id}"
,
response_model
=
ItemResponse
)
def
get_item
(
item_id
:
int
=
Path
(
...
,
gt
=
0
)):
if
item_id
not
in
db
:
raise
HTTPException
(
status_code
=
404
,
detail
=
f
"商品 {item_id} 不存在"
)
return
db
[
item_id
]
@app.post
(
"/items/"
,
response_model
=
ItemResponse
,
status_code
=
201
)
def
create_item
(
item
:
Item
):
global
next_id
record
=
{
"item_id"
:
next_id
,
**
item
.
model_dump
()}
db
[
next_id
]
=
record
next_id
+=
1
return
record
@app.put
(
"/items/{item_id}"
,
response_model
=
ItemResponse
)
def
update_item
(
item_id
:
int
,
item
:
Item
):
if
item_id
not
in
db
:
raise
HTTPException
(
status_code
=
404
,
detail
=
f
"商品 {item_id} 不存在"
)
db
[
item_id
]
=
{
"item_id"
:
item_id
,
**
item
.
model_dump
()}
return
db
[
item_id
]
@app.delete
(
"/items/{item_id}"
,
status_code
=
204
)
def
delete_item
(
item_id
:
int
):
if
item_id
not
in
db
:
raise
HTTPException
(
status_code
=
404
,
detail
=
f
"商品 {item_id} 不存在"
)
del
db
[
item_id
]
if
__name__
==
"__main__"
:
import
uvicorn
uvicorn
.
run
(
"__main__:app"
,
host
=
"0.0.0.0"
,
port
=
8000
,
reload
=
True
)
```
```
bash
# 启动
uvicorn 07_fastapi_demo:app
--reload
--port
8000
# 测试
curl http://localhost:8000/items/
# 列表
curl http://localhost:8000/items/1
# 详情
curl
-X
POST http://localhost:8000/items/
\
-H
"Content-Type: application/json"
\
-d
'{"name":"键盘","price":299.0}'
# 创建
curl
-X
DELETE http://localhost:8000/items/1
# 删除
```
---
### 验收标准
```
☐ 能用 FastAPI + uvicorn 启动一个完整服务
☐ 能定义 Pydantic 请求体并用 Field() 做字段校验
☐ 能识别 FastAPI 返回 422 错误的原因(参数校验失败)
☐ 能用 Depends 实现依赖注入(认证、数据连接)
☐ 能自定义中间件处理日志或计时
☐ 能区分同步 def 和异步 async def 的适用场景
☐ 能用 /docs 查看自动生成的 Swagger 文档
☐ 能用 uvicorn --reload 实现热重载
```
---
### 官方来源
-
FastAPI 官方文档 —
[
fastapi.tiangolo.com/zh/tutorial/
](
https://fastapi.tiangolo.com/zh/tutorial/
)
-
Pydantic 官方文档 —
[
docs.pydantic.dev
](
https://docs.pydantic.dev/
)
-
Uvicorn 官方文档 —
[
www.uvicorn.org/
](
https://www.uvicorn.org/
)
-
FastAPI vs Flask 性能对比 —
[
fastapi.tiangolo.com/benchmarks/
](
https://fastapi.tiangolo.com/benchmarks/
)
---
> **下一节预告:[7.2 PostgreSQL](#72-postgresql)** —— 关系型数据库是所有后端系统的"硬盘"。
---
## 7.2 PostgreSQL
> 用 1-2 句话说清:**PostgreSQL = 功能最强大的开源关系型数据库**,支持 JSON、全文搜索、向量存储(pgvector),是生产环境存储结构化数据的首选。
---
### 什么是 PostgreSQL?
**PostgreSQL**
是一个功能强大的开源对象-关系型数据库系统(ORDBMS)。"关系型"意味着数据以
**表(table)**
的形式存储,表和表之间通过
**外键**
关联。
直觉理解:
```
text
表(Table)= Excel 里的一个工作表
列(Column)= 一列属性(id、name、price)
行(Row)= 一条记录(一个具体商品)
主键(Primary Key)= 每行的唯一身份证号
外键(Foreign Key)= 关联到另一张表
```
### 为什么需要 PostgreSQL?
| 方案 | 适用场景 | 缺点 |
| --- | --- | --- |
|
**JSON 文件**
| 玩具项目 | 读写并发差、无事务、无索引 |
|
**Excel**
| 单人本地分析 | 无法多人协作、无并发 |
|
**PostgreSQL**
⭐ | 所有生产环境 | 需要部署和维护 |
> FastAPI 可以接 JSON 文件存数据,但重启就丢、并发就崩。**PostgreSQL 让数据持久化、安全、可查询。**
---
### 5 分钟快速上手:psql 命令行
```
bash
# 安装
# Ubuntu
sudo
apt
install
postgresql postgresql-client
-y
# macOS
brew
install
postgresql@16
&&
brew services start postgresql@16
```
```
bash
# 登录 PostgreSQL(默认用户 postgres)
sudo
-u
postgres psql
# 或者
psql
-U
postgres
-h
localhost
-d
postgres
```
```
sql
-- 创建用户
CREATE
USER
cfm
WITH
PASSWORD
'yourpassword'
;
-- 创建数据库
CREATE
DATABASE
myapp
OWNER
cfm
;
-- 授权
GRANT
ALL
PRIVILEGES
ON
DATABASE
myapp
TO
cfm
;
-- 切换到数据库
\
c
myapp
```
```
sql
-- 创建表
CREATE
TABLE
users
(
id
SERIAL
PRIMARY
KEY
,
username
VARCHAR
(
50
)
UNIQUE
NOT
NULL
,
email
VARCHAR
(
100
)
UNIQUE
NOT
NULL
,
created_at
TIMESTAMP
DEFAULT
CURRENT_TIMESTAMP
);
-- 插入数据
INSERT
INTO
users
(
username
,
email
)
VALUES
(
'alice'
,
'alice@example.com'
),
(
'bob'
,
'bob@example.com'
);
-- 查询
SELECT
*
FROM
users
;
-- 更新
UPDATE
users
SET
email
=
'alice.new@example.com'
WHERE
username
=
'alice'
;
-- 删除
DELETE
FROM
users
WHERE
username
=
'bob'
;
```
---
### 举个例子:数据类型速查
| 类型 | 说明 | 示例 |
| --- | --- | --- |
|
`SERIAL`
| 自动增长的整数(主键) |
`id SERIAL PRIMARY KEY`
|
|
`VARCHAR(n)`
| 可变长度字符串,最大 n 字符 |
`username VARCHAR(50)`
|
|
`TEXT`
| 无长度限制的字符串 |
`content TEXT`
|
|
`INTEGER`
| 32 位整数 |
`age INTEGER`
|
|
`BIGINT`
| 64 位整数 |
`views BIGINT`
|
|
`BOOLEAN`
| 布尔值 |
`is_active BOOLEAN`
|
|
`TIMESTAMP`
| 日期时间 |
`created_at TIMESTAMP`
|
|
`DATE`
| 日期 |
`birthday DATE`
|
|
`FLOAT / REAL`
| 32 位浮点 |
`price REAL`
|
|
`DOUBLE PRECISION`
| 64 位浮点 |
`score DOUBLE PRECISION`
|
|
`JSONB`
| 二进制 JSON(可建索引)|
`metadata JSONB`
|
|
`ARRAY`
| 数组 |
`tags TEXT[]`
|
---
### 进阶玩法:索引与 EXPLAIN ANALYZE
索引 = 书的目录,让查询从"逐页翻"变成"直接翻到那一页"。
```
sql
-- 创建索引
CREATE
INDEX
idx_users_email
ON
users
(
email
);
CREATE
INDEX
idx_users_created
ON
users
(
created_at
DESC
);
-- 复合索引(同时按两列查)
CREATE
INDEX
idx_orders_user_status
ON
orders
(
user_id
,
status
);
```
```
sql
-- 不用索引:全表扫描
EXPLAIN
SELECT
*
FROM
users
WHERE
email
=
'alice@example.com'
;
-- Seq Scan on users (cost=0.00..1.05 rows=1 width=104)
-- Filter: ((email)::text = 'alice@example.com'::text)
-- 用索引:索引扫描
CREATE
INDEX
idx_users_email
ON
users
(
email
);
EXPLAIN
SELECT
*
FROM
users
WHERE
email
=
'alice@example.com'
;
-- Index Scan using idx_users_email on users (cost=0.00..2.02 rows=1 width=104)
-- Index Cond: ((email)::text = 'alice@example.com'::text)
```
```
sql
-- ANALYZE 后看到实际执行时间
EXPLAIN
(
ANALYZE
,
BUFFERS
)
SELECT
*
FROM
users
WHERE
id
>
500
;
-- 看到 "actual time=0.021..0.045" 才是真执行
```
> **经验法则**:WHERE / JOIN / ORDER BY 里高频出现的列,建索引。别对所有列都建(写入会变慢)。
---
### 进阶玩法:psycopg2 在 Python 中操作 PostgreSQL
```
bash
pip
install
psycopg2-binary
```
```
python
import
psycopg2
from
contextlib
import
contextmanager
@contextmanager
def
get_conn
():
conn
=
psycopg2
.
connect
(
host
=
"localhost"
,
port
=
5432
,
dbname
=
"myapp"
,
user
=
"cfm"
,
password
=
"yourpassword"
,
)
try
:
yield
conn
conn
.
commit
()
except
Exception
:
conn
.
rollback
()
raise
finally
:
conn
.
close
()
# 查询
with
get_conn
()
as
conn
:
with
conn
.
cursor
()
as
cur
:
cur
.
execute
(
"SELECT id, username, email FROM users WHERE id >
%
s"
,
(
0
,))
rows
=
cur
.
fetchall
()
for
row
in
rows
:
print
(
f
"id={row[0]}, username={row[1]}, email={row[2]}"
)
# 插入
with
get_conn
()
as
conn
:
with
conn
.
cursor
()
as
cur
:
cur
.
execute
(
"INSERT INTO users (username, email) VALUES (
%
s,
%
s) RETURNING id"
,
(
"charlie"
,
"charlie@example.com"
),
)
new_id
=
cur
.
fetchone
()[
0
]
print
(
f
"新用户 id={new_id}"
)
```
> **防注入**:永远用 `%s` 占位符 + 传参,不要用 `f"SELECT ... WHERE id = {user_input}"` 字符串拼接!
---
### 进阶玩法:SQLAlchemy ORM(三种关系)
SQLAlchemy 把 SQL 语句变成 Python 对象,让代码更 Pythonic。
```
bash
pip
install
sqlalchemy psycopg2-binary
```
```
python
from
sqlalchemy
import
(
create_engine
,
Column
,
Integer
,
String
,
Text
,
ForeignKey
,
DateTime
,
Boolean
,
UniqueConstraint
)
from
sqlalchemy.orm
import
(
declarative_base
,
relationship
,
sessionmaker
,
Session
)
from
datetime
import
datetime
Base
=
declarative_base
()
# ===== 一对一(User ←→ Profile)=====
class
User
(
Base
):
__tablename__
=
"users"
id
=
Column
(
Integer
,
primary_key
=
True
,
autoincrement
=
True
)
username
=
Column
(
String
(
50
),
unique
=
True
,
nullable
=
False
)
email
=
Column
(
String
(
100
),
unique
=
True
,
nullable
=
False
)
created_at
=
Column
(
DateTime
,
default
=
datetime
.
utcnow
)
# 一对一关系:User 有一个 Profile
profile
=
relationship
(
"Profile"
,
back_populates
=
"user"
,
uselist
=
False
)
class
Profile
(
Base
):
__tablename__
=
"profiles"
id
=
Column
(
Integer
,
primary_key
=
True
)
user_id
=
Column
(
Integer
,
ForeignKey
(
"users.id"
),
unique
=
True
)
bio
=
Column
(
Text
)
avatar_url
=
Column
(
String
(
200
))
# 反向引用
user
=
relationship
(
"User"
,
back_populates
=
"profile"
)
# ===== 一对多(User ←→ Post)=====
class
Post
(
Base
):
__tablename__
=
"posts"
id
=
Column
(
Integer
,
primary_key
=
True
)
user_id
=
Column
(
Integer
,
ForeignKey
(
"users.id"
))
title
=
Column
(
String
(
200
),
nullable
=
False
)
content
=
Column
(
Text
)
published
=
Column
(
Boolean
,
default
=
False
)
created_at
=
Column
(
DateTime
,
default
=
datetime
.
utcnow
)
# 多方(Post)持有外键
author
=
relationship
(
"User"
,
back_populates
=
"posts"
)
User
.
posts
=
relationship
(
"Post"
,
back_populates
=
"author"
)
# ===== 多对多(Student ←→ Course)=====
student_courses
=
Table
(
"student_courses"
,
Base
.
metadata
,
Column
(
"student_id"
,
Integer
,
ForeignKey
(
"students.id"
),
primary_key
=
True
),
Column
(
"course_id"
,
Integer
,
ForeignKey
(
"courses.id"
),
primary_key
=
True
),
)
class
Student
(
Base
):
__tablename__
=
"students"
id
=
Column
(
Integer
,
primary_key
=
True
)
name
=
Column
(
String
(
50
))
courses
=
relationship
(
"Course"
,
secondary
=
student_courses
,
back_populates
=
"students"
)
class
Course
(
Base
):
__tablename__
=
"courses"
id
=
Column
(
Integer
,
primary_key
=
True
)
name
=
Column
(
String
(
100
))
students
=
relationship
(
"Student"
,
secondary
=
student_courses
,
back_populates
=
"courses"
)
# ===== 创建表 & 操作 =====
engine
=
create_engine
(
"postgresql://cfm:yourpassword@localhost/myapp"
)
Base
.
metadata
.
create_all
(
engine
)
Session
=
sessionmaker
(
bind
=
engine
)
session
=
Session
()
# 一对一示例
user
=
User
(
username
=
"alice"
,
email
=
"alice@example.com"
)
user
.
profile
=
Profile
(
bio
=
"爱编程"
,
avatar_url
=
"https://avatar.com/alice.png"
)
session
.
add
(
user
)
session
.
commit
()
# 一对多示例
post
=
Post
(
title
=
"FastAPI 入门"
,
content
=
"FastAPI 真香"
,
author
=
user
)
session
.
add
(
post
)
session
.
commit
()
# 多对多示例
s1
=
Student
(
name
=
"张三"
)
s2
=
Student
(
name
=
"李四"
)
c1
=
Course
(
name
=
"Python 入门"
)
s1
.
courses
.
append
(
c1
)
s2
.
courses
.
append
(
c1
)
session
.
add_all
([
s1
,
s2
,
c1
])
session
.
commit
()
# 查询
alice_posts
=
session
.
query
(
Post
)
.
filter_by
(
author_id
=
user
.
id
)
.
all
()
python_students
=
session
.
query
(
Student
)
.
filter
(
Student
.
courses
.
any
(
name
=
"Python 入门"
))
.
all
()
```
---
### 正解 vs 错误
| 维度 | 正解 ✅ | 错误 ❌ |
| --- | --- | --- |
|
**防注入**
|
`cur.execute("... %s", (val,))`
|
`cur.execute(f"... {val}")`
|
|
**主键**
|
`SERIAL PRIMARY KEY`
或
`id SERIAL`
| 手动管理 ID(容易冲突) |
|
**NULL**
| 显式
`NULL`
/
`NOT NULL`
| 默认 NULL 导致空指针查询 |
|
**索引**
| 高频 WHERE 列建索引 | 全部列建索引(写变慢) |
|
**事务**
| 用 context manager 自动 commit/rollback | 忘记 commit(数据丢失) |
|
**连接**
| 连接池(
`pool_size=5`
) | 每次请求都
`connect()`
新建连接 |
---
### 思考题 / Q&A
1.
**SERIAL 和 AUTO_INCREMENT 有什么区别?**
提示:SERIAL 是 PostgreSQL 的序列机制,会创建独立的 sequence 对象;AUTO_INCREMENT 是 MySQL 的写法。
2.
**为什么查询要加 `EXPLAIN ANALYZE`?**
提示:
`EXPLAIN`
只估算,
`ANALYZE`
才真执行;估算可能和实际差很多。
3.
**ORM 和原生 SQL 各自的优劣?**
提示:ORM 写起来快、防注入、可读性好;原生 SQL 性能更精细、控制力更强。
4.
**JSONB 和 JSON 有什么区别?**
提示:JSONB 是二进制存储,可建索引;JSON 是文本存储,查询时需要解析。
---
### 本节小结
-
PostgreSQL = 功能最强的开源关系型数据库,JSONB / 向量 / 全文搜索开箱即用。
-
**psql**
是 PostgreSQL 的命令行客户端,
`\c`
切换数据库,
`\dt`
查看表,
`\d`
查看表结构。
-
**psycopg2**
是 Python 连接 PostgreSQL 的驱动,永远用
`%s`
占位符防注入。
-
**SQLAlchemy ORM**
把表变成 Python 类,关系(一对一/一对多/多对多)用
`relationship`
表达。
-
**索引**
用
`EXPLAIN ANALYZE`
看查询计划;高频 WHERE 列建索引。
-
连接池 + context manager 是 Python 操作 DB 的标准模式。
---
### 完整代码
```
python
"""07_postgres_demo.py —— SQLAlchemy ORM 完整示例"""
from
sqlalchemy
import
(
create_engine
,
Column
,
Integer
,
String
,
Text
,
ForeignKey
,
DateTime
,
Boolean
,
Table
,
UniqueConstraint
)
from
sqlalchemy.orm
import
declarative_base
,
relationship
,
sessionmaker
from
datetime
import
datetime
DATABASE_URL
=
"postgresql://cfm:password@localhost/myapp"
engine
=
create_engine
(
DATABASE_URL
,
pool_size
=
5
,
echo
=
False
)
Base
=
declarative_base
()
Session
=
sessionmaker
(
bind
=
engine
)
# 多对多关联表
student_courses
=
Table
(
"student_courses"
,
Base
.
metadata
,
Column
(
"student_id"
,
Integer
,
ForeignKey
(
"students.id"
),
primary_key
=
True
),
Column
(
"course_id"
,
Integer
,
ForeignKey
(
"courses.id"
),
primary_key
=
True
),
)
class
User
(
Base
):
__tablename__
=
"users"
id
=
Column
(
Integer
,
primary_key
=
True
,
autoincrement
=
True
)
username
=
Column
(
String
(
50
),
unique
=
True
,
nullable
=
False
)
email
=
Column
(
String
(
100
),
unique
=
True
,
nullable
=
False
)
created_at
=
Column
(
DateTime
,
default
=
datetime
.
utcnow
)
profile
=
relationship
(
"Profile"
,
back_populates
=
"user"
,
uselist
=
False
)
posts
=
relationship
(
"Post"
,
back_populates
=
"author"
)
courses
=
relationship
(
"Course"
,
secondary
=
student_courses
,
back_populates
=
"students"
)
class
Profile
(
Base
):
__tablename__
=
"profiles"
id
=
Column
(
Integer
,
primary_key
=
True
)
user_id
=
Column
(
Integer
,
ForeignKey
(
"users.id"
),
unique
=
True
)
bio
=
Column
(
Text
)
avatar_url
=
Column
(
String
(
200
))
user
=
relationship
(
"User"
,
back_populates
=
"profile"
)
class
Post
(
Base
):
__tablename__
=
"posts"
id
=
Column
(
Integer
,
primary_key
=
True
)
user_id
=
Column
(
Integer
,
ForeignKey
(
"users.id"
))
title
=
Column
(
String
(
200
),
nullable
=
False
)
content
=
Column
(
Text
)
published
=
Column
(
Boolean
,
default
=
False
)
created_at
=
Column
(
DateTime
,
default
=
datetime
.
utcnow
)
author
=
relationship
(
"User"
,
back_populates
=
"posts"
)
class
Student
(
Base
):
__tablename__
=
"students"
id
=
Column
(
Integer
,
primary_key
=
True
)
name
=
Column
(
String
(
50
))
courses
=
relationship
(
"Course"
,
secondary
=
student_courses
,
back_populates
=
"students"
)
class
Course
(
Base
):
__tablename__
=
"courses"
id
=
Column
(
Integer
,
primary_key
=
True
)
name
=
Column
(
String
(
100
))
students
=
relationship
(
"Student"
,
secondary
=
student_courses
,
back_populates
=
"courses"
)
if
__name__
==
"__main__"
:
Base
.
metadata
.
create_all
(
engine
)
session
=
Session
()
try
:
# 一对一
u
=
User
(
username
=
"alice"
,
email
=
"alice@example.com"
)
u
.
profile
=
Profile
(
bio
=
"Py 开发"
)
session
.
add
(
u
)
session
.
commit
()
print
(
f
"✅ 用户 {u.username},简介:{u.profile.bio}"
)
# 一对多
p
=
Post
(
title
=
"FastAPI 入门"
,
content
=
"真香"
,
author
=
u
)
session
.
add
(
p
)
session
.
commit
()
print
(
f
"✅ 帖子:{p.title},作者:{p.author.username}"
)
# 多对多
s
=
Student
(
name
=
"李四"
)
c
=
Course
(
name
=
"RAG 基础"
)
s
.
courses
.
append
(
c
)
session
.
add_all
([
s
,
c
])
session
.
commit
()
print
(
f
"✅ 学生 {s.name} 选课:{[co.name for co in s.courses]}"
)
finally
:
session
.
close
()
```
---
### 验收标准
```
☐ 能在 psql 中完成 CRUD(增删改查)操作
☐ 能用 psycopg2 在 Python 中执行带参数的 SQL(防注入)
☐ 能用 SQLAlchemy ORM 定义表模型(含主键、外键)
☐ 能用 relationship 实现一对一、一对多、多对多三种关系
☐ 能为高频查询字段建立索引
☐ 能用 EXPLAIN ANALYZE 分析查询性能
☐ 知道什么时候用 ORM,什么时候用原生 SQL
☐ 知道 JSONB 和 TEXT 的适用场景差异
```
---
### 官方来源
-
PostgreSQL 官方文档 —
[
www.postgresql.org/docs/
](
https://www.postgresql.org/docs/
)
-
SQLAlchemy 官方文档 —
[
docs.sqlalchemy.org/
](
https://docs.sqlalchemy.org/
)
-
psycopg2 官方文档 —
[
www.psycopg.org/docs/
](
https://www.psycopg.org/docs/
)
-
PostgreSQL EXPLAIN ANALYZE —
[
www.postgresql.org/docs/current/sql-explain.html
](
https://www.postgresql.org/docs/current/sql-explain.html
)
---
> **下一节预告:[7.3 Redis](#73-redis)** —— 让你的应用快 10 倍的内存数据库。
---
## 7.3 Redis
> 用 1-2 句话说清:**Redis = 内存数据库**,读写速度比 PostgreSQL 快 10~100 倍,用来缓存热点数据、做分布式锁、当消息队列。
---
### 什么是 Redis?
**Redis(Remote Dictionary Server)**
是一个开源的
**内存键值数据库**
。数据存在内存(RAM)里,读写速度极快(微秒级),但断电会丢(除非开启持久化)。
| 维度 | Redis(内存) | PostgreSQL(磁盘) |
| --- | --- | --- |
|
**速度**
| 微秒级(100k+ QPS)| 毫秒级(1k~10k QPS)|
|
**容量**
| 受 RAM 限制(GB 级)| 受磁盘限制(TB 级)|
|
**持久化**
| 可选(RDB / AOF)| 默认持久化 |
|
**适用场景**
| 缓存、锁、队列、计数器 | 主数据存储、复杂查询 |
### 生活类比
-
**字典 vs 图书馆**
:Redis 像随身字典(查得快但装不下所有书),PostgreSQL 像图书馆(能存所有书但查得慢)。
-
**Cache-Aside(旁路缓存)**
= 查字典:先去字典里找(缓存),找不到再去图书馆(数据库)查,查到后把字典更新。
---
### 5 分钟快速上手:5 种数据类型
```
bash
# 安装 Redis
# Ubuntu
sudo
apt
install
redis-server
-y
&&
sudo
systemctl start redis
# macOS
brew
install
redis
&&
brew services start redis
# 连接
redis-cli
```
#### 5 种数据类型 + 常用命令
```
bash
# ===== 1. STRING(字符串):缓存、计数器、Token =====
SET user:token:alice
"abc123token"
SET user:token:alice
"new_token"
# 覆盖
GET user:token:alice
# "new_token"
SETNX user:token:bob
"token_bob"
# 不存在才设置(分布式锁用)
EXPIRE user:token:alice 3600
# 设置过期时间(秒)
TTL user:token:alice
# 查看剩余 TTL(秒)
SET user:token:alice
"token_v2"
EX 7200
# SET + EX 原子操作
INCR article:views:001
# 原子自增(PV 统计)
DECR article:views:001
# 原子自减
INCRBY article:views:001 100
# 批量自增
# ===== 2. HASH(哈希):存对象 =====
HSET user:1001 name
"Alice"
email
"alice@example.com"
age
"25"
HGET user:1001 name
# "Alice"
HGETALL user:1001
# 所有字段
HINCRBY user:1001 age 1
# 原子自增年龄
# ===== 3. LIST(列表):队列、消息、排行榜 =====
LPUSH tasks
"清洗数据"
# 左边插入
LPUSH tasks
"训练模型"
LPUSH tasks
"部署服务"
LLEN tasks
# 3
LRANGE tasks 0
-1
# 查看全部
RPOP tasks
# 右边弹出(队列)
# ===== 4. SET(集合):去重、标签、共同好友 =====
SADD articles:tags:AI
"LLM"
"RAG"
"Agent"
SADD articles:tags:Backend
"FastAPI"
"PostgreSQL"
"Redis"
SADD articles:tags:AI
"RAG"
# 已存在,自动去重
SMEMBERS articles:tags:AI
# 查看所有标签
# ===== 5. ZSET(有序集合):排行榜、权重队列 =====
ZADD leaderboard 1500
"Alice"
ZADD leaderboard 1200
"Bob"
ZADD leaderboard 1800
"Charlie"
ZREVRANGE leaderboard 0
-1
WITHSCORES
# 降序排列
ZRANK leaderboard
"Bob"
# 查看 Bob 的排名(从 0 开始)
ZSCORE leaderboard
"Alice"
# 1500.0
```
---
### 进阶玩法:Python 客户端 redis-py
```
bash
pip
install
redis
```
```
python
import
redis
r
=
redis
.
Redis
(
host
=
"localhost"
,
port
=
6379
,
db
=
0
,
decode_responses
=
True
)
# String
r
.
set
(
"user:1001:token"
,
"abc123"
,
ex
=
3600
)
# 过期 1 小时
token
=
r
.
get
(
"user:1001:token"
)
print
(
f
"Token: {token}"
)
print
(
f
"TTL: {r.ttl('user:1001:token')} 秒"
)
# Hash
r
.
hset
(
"user:1001"
,
mapping
=
{
"name"
:
"Alice"
,
"email"
:
"alice@example.com"
,
"role"
:
"admin"
,
})
user_info
=
r
.
hgetall
(
"user:1001"
)
print
(
user_info
)
# {'name': 'Alice', 'email': 'alice@example.com', 'role': 'admin'}
# List
r
.
lpush
(
"tasks"
,
"任务A"
,
"任务B"
,
"任务C"
)
r
.
rpush
(
"tasks"
,
"任务D"
)
while
r
.
llen
(
"tasks"
)
>
0
:
task
=
r
.
rpop
(
"tasks"
)
print
(
f
"处理任务:{task}"
)
# Set
r
.
sadd
(
"articles:tags"
,
"RAG"
,
"FastAPI"
,
"PostgreSQL"
,
"RAG"
)
# 自动去重
tags
=
r
.
smembers
(
"articles:tags"
)
print
(
f
"标签:{tags}"
)
# {'RAG', 'FastAPI', 'PostgreSQL'}
# ZSet
r
.
zadd
(
"leaderboard"
,
{
"Alice"
:
1500
,
"Bob"
:
1200
,
"Charlie"
:
1800
})
top3
=
r
.
zrevrange
(
"leaderboard"
,
0
,
2
,
withscores
=
True
)
for
name
,
score
in
top3
:
print
(
f
" {name}: {score}"
)
```
---
### 进阶玩法:Cache-Aside 缓存模式
```
查数据 → 先看 Redis(缓存)
→ 命中 → 直接返回(快!)
→ 未命中 → 查 PostgreSQL
→ 查到 → 写 Redis(设置过期时间)
→ 返回结果
```
```
python
import
redis
import
psycopg2
cache
=
redis
.
Redis
(
host
=
"localhost"
,
port
=
6379
,
decode_responses
=
True
)
def
get_article_by_id
(
article_id
:
int
)
->
dict
|
None
:
"""Cache-Aside 模式:先读缓存,缓存未命中再读数据库"""
cache_key
=
f
"article:{article_id}"
# 1. 先查 Redis
cached
=
cache
.
get
(
cache_key
)
if
cached
:
print
(
f
"✅ 缓存命中:{cache_key}"
)
import
json
return
json
.
loads
(
cached
)
# 2. 缓存未命中,查数据库
print
(
f
"❌ 缓存未命中,查询数据库..."
)
with
psycopg2
.
connect
(
database
=
"myapp"
,
user
=
"cfm"
,
password
=
"pwd"
)
as
conn
:
with
conn
.
cursor
()
as
cur
:
cur
.
execute
(
"SELECT id, title, content FROM articles WHERE id =
%
s"
,
(
article_id
,))
row
=
cur
.
fetchone
()
if
row
:
article
=
{
"id"
:
row
[
0
],
"title"
:
row
[
1
],
"content"
:
row
[
2
]}
# 3. 写缓存,过期 5 分钟
import
json
cache
.
setex
(
cache_key
,
300
,
json
.
dumps
(
article
))
return
article
return
None
```
---
### 进阶玩法:分布式锁(SETNX 的坑 + Lua 正确解法)
#### 错误做法:SETNX + EXPIRE 分开(竞态条件!)
```
python
# ❌ 错误代码:SETNX 和 EXPIRE 之间进程崩溃,锁永久存在
def
wrong_lock
(
lock_key
:
str
)
->
bool
:
acquired
=
r
.
setnx
(
lock_key
,
"1"
)
# 抢锁
if
acquired
:
r
.
expire
(
lock_key
,
10
)
# 10 秒后过期
return
True
return
False
# 问题:如果进程在 setnx 和 expire 之间崩溃,锁永远不过期!
```
#### 正确做法:SET NX EX(原子操作)
```
python
# ✅ 正确代码:SET + NX + EX 一次性完成
import
time
def
acquire_lock
(
lock_key
:
str
,
timeout
:
int
=
10
)
->
bool
:
"""原子获取分布式锁"""
result
=
r
.
set
(
lock_key
,
"1"
,
nx
=
True
,
ex
=
timeout
)
return
result
is
not
None
def
release_lock
(
lock_key
:
str
,
expected_value
:
str
=
"1"
):
"""释放锁(Lua 脚本保证原子性)"""
lua_script
=
"""
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
"""
r
.
eval
(
lua_script
,
1
,
lock_key
,
expected_value
)
# 使用
lock_key
=
"task:process:order:123"
if
acquire_lock
(
lock_key
,
timeout
=
30
):
try
:
print
(
"获取锁成功,开始处理任务..."
)
time
.
sleep
(
2
)
print
(
"任务处理完成"
)
finally
:
release_lock
(
lock_key
)
else
:
print
(
"获取锁失败,另一个进程正在处理"
)
```
> **为什么用 Lua 脚本?** 因为检查锁的值(`get`)和删除锁(`del`)必须是原子操作——否则会出现"检查时锁还在,删除时锁已被别人续期"的情况。
---
### 正解 vs 错误
| 维度 | 正解 ✅ | 错误 ❌ |
| --- | --- | --- |
|
**分布式锁**
|
`SET key val NX EX 10`
原子操作 |
`SETNX`
+
`EXPIRE`
分开(进程崩溃会死锁)|
|
**缓存过期**
|
`SETEX`
/
`SET key val EX 300`
|
`SET`
后忘记
`EXPIRE`
(内存泄漏)|
|
**缓存更新**
| 先删缓存再更新数据库(Cache-Aside)| 先更新 DB 再更新缓存(脏读)|
|
**大数据**
| 分批
`LRANGE key 0 99`
| 一次性
`LRANGE key 0 -1`
(内存爆炸)|
|
**连接池**
|
`redis.ConnectionPool()`
复用连接 | 每次操作新建连接(连接开销大)|
---
### 思考题 / Q&A
1.
**Redis 和 Memcached 有什么区别?**
提示:Redis 支持 5 种数据类型(Memcached 只支持 String);Redis 支持持久化;Redis 有主从复制。
2.
**缓存穿透、缓存击穿、缓存雪崩分别是什么?**
提示:穿透 = 恶意查不存在的数据;击穿 = 热 key 过期瞬间大量请求;雪崩 = 大量 key 同时过期。
3.
**为什么分布式锁不能用 `SETNX` + `EXPIRE`?**
提示:两条命令不是原子的,中间崩溃会导致锁永远不过期。
4.
**Redis 的 RDB 和 AOF 持久化有什么区别?**
提示:RDB 是定时快照(快但可能丢最近数据);AOF 是追加日志(慢但丢得少)。
---
### 本节小结
-
**Redis**
= 内存键值数据库,微秒级读写,用来缓存、锁、队列、计数器。
-
5 种数据类型:String(计数器/Token)、Hash(对象)、List(队列)、Set(去重)、ZSet(排行榜)。
-
**Cache-Aside**
模式:先读缓存 → 未命中读 DB → 写回缓存。
-
**分布式锁**
:用
`SET key val NX EX 10`
(原子),释放用 Lua 脚本保证 check-then-del 的原子性。
-
`redis.ConnectionPool()`
复用连接是生产环境标配。
---
### 完整代码
```
python
"""07_redis_demo.py —— Cache-Aside + 分布式锁完整示例"""
import
redis
import
json
import
time
import
threading
POOL
=
redis
.
ConnectionPool
(
host
=
"localhost"
,
port
=
6379
,
db
=
0
,
decode_responses
=
True
)
r
=
redis
.
Redis
(
connection_pool
=
POOL
)
# ===== 缓存操作 =====
def
cache_get
(
key
:
str
):
"""读缓存"""
val
=
r
.
get
(
key
)
if
val
:
return
json
.
loads
(
val
)
return
None
def
cache_set
(
key
:
str
,
value
:
dict
,
ttl
:
int
=
300
):
"""写缓存"""
r
.
setex
(
key
,
ttl
,
json
.
dumps
(
value
,
ensure_ascii
=
False
))
def
cache_delete
(
key
:
str
):
"""删缓存"""
r
.
delete
(
key
)
# ===== 模拟数据库 =====
FAKE_DB
=
{
"user:001"
:
{
"id"
:
1
,
"name"
:
"Alice"
,
"role"
:
"admin"
},
"user:002"
:
{
"id"
:
2
,
"name"
:
"Bob"
,
"role"
:
"user"
},
}
def
db_query
(
key
:
str
):
return
FAKE_DB
.
get
(
key
)
# ===== Cache-Aside =====
def
get_user
(
user_id
:
int
)
->
dict
|
None
:
key
=
f
"user:{user_id:03d}"
data
=
cache_get
(
key
)
if
data
:
print
(
f
"✅ 命中缓存: {key}"
)
return
data
print
(
f
"❌ 缓存未命中,查数据库: {key}"
)
data
=
db_query
(
key
)
if
data
:
cache_set
(
key
,
data
,
ttl
=
60
)
return
data
# ===== 分布式锁 =====
def
acquire_lock
(
lock_key
:
str
,
timeout
:
int
=
10
)
->
bool
:
return
r
.
set
(
lock_key
,
"1"
,
nx
=
True
,
ex
=
timeout
)
is
not
None
def
release_lock
(
lock_key
:
str
):
lua
=
"if redis.call('get', KEYS[1]) == '1' then return redis.call('del', KEYS[1]) else return 0 end"
r
.
eval
(
lua
,
1
,
lock_key
)
def
with_lock
(
lock_key
:
str
,
fn
,
timeout
:
int
=
10
):
if
acquire_lock
(
lock_key
,
timeout
):
try
:
return
fn
()
finally
:
release_lock
(
lock_key
)
else
:
raise
RuntimeError
(
f
"获取锁失败: {lock_key}"
)
if
__name__
==
"__main__"
:
# Cache-Aside 测试
print
(
"=== Cache-Aside ==="
)
get_user
(
1
)
# 缓存未命中
get_user
(
1
)
# 缓存命中
# 分布式锁测试
print
(
"
\n
=== 分布式锁 ==="
)
lock_key
=
"task:demo"
try
:
result
=
with_lock
(
lock_key
,
lambda
:
"任务执行成功!"
)
print
(
result
)
except
RuntimeError
as
e
:
print
(
e
)
```
---
### 验收标准
```
☐ 能区分 String / Hash / List / Set / ZSet 的适用场景
☐ 能用 redis-py 完成基本 CRUD 操作
☐ 能用 Cache-Aside 模式优化读多写少业务
☐ 能正确实现基于 SET NX EX 的分布式锁
☐ 能解释 SETNX + EXPIRE 分开写的竞态条件风险
☐ 知道 Redis 为什么比 PostgreSQL 快(内存 vs 磁盘)
☐ 能说出缓存穿透、击穿、雪崩的简要区别
```
---
### 官方来源
-
Redis 官方文档 —
[
redis.io/docs/
](
https://redis.io/docs/
)
-
redis-py 官方文档 —
[
redis-py.readthedocs.io/
](
https://redis-py.readthedocs.io/
)
-
Redis 分布式锁详解 —
[
redis.io/docs/manual/patterns/distributed-locks/
](
https://redis.io/docs/manual/patterns/distributed-locks/
)
-
Redis persistence —
[
redis.io/docs/management/persistence/
](
https://redis.io/docs/management/persistence/
)
---
> **下一节预告:[7.4 Docker](#74-docker)** —— 一次构建,到处运行,让你的服务"集装箱化"。
---
## 7.4 Docker
> 用 1-2 句话说清:**Docker = 软件的"集装箱"**,把代码 + 依赖 + 环境打包成一个镜像,在任何机器上都能原样运行,彻底解决"在我电脑上能跑"的问题。
---
### 什么是 Docker?
**Docker**
是一个容器化平台。它的核心概念:
| 概念 | 解释 | 类比 |
| --- | --- | --- |
|
**镜像(Image)**
| 应用程序的只读模板 | 集装箱的蓝图 |
|
**容器(Container)**
| 镜像的运行实例 | 根据蓝图造出的集装箱 |
|
**仓库(Registry)**
| 存放镜像的地方(Docker Hub) | 集装箱的存放仓库 |
### 为什么需要 Docker?
```
没有 Docker:
"在我电脑上能跑!" → 对方:Python 3.8、装了 numpy 1.21...
→ 环境配置 2 小时
有了 Docker:
"docker run app" → 直接跑!任何机器、环境一致
```
| 维度 | 物理机 | 虚拟机(VM) | Docker 容器 ⭐ |
| --- | --- | --- | --- |
|
**启动速度**
| 小时级 | 分钟级 |
**秒级**
|
|
**资源占用**
| 全量 | 完整 OS(GB 级)|
**共享内核(MB 级)**
|
|
**一致性**
| 环境依赖人 | 好(但重)|
**最好(极轻)**
|
|
**适用场景**
| 测试 | 多系统隔离 |
**服务容器化**
|
---
### 5 分钟快速上手:Dockerfile + 运行
#### 第一步:写 Dockerfile
```
dockerfile
# 07/Dockerfile
# ===== 构建阶段 =====
FROM
python:3.11-slim AS builder
WORKDIR
/app
# 1. 安装依赖到独立层
COPY
requirements.txt .
RUN
pip
install
--user
--no-cache-dir
-r
requirements.txt
# ===== 运行阶段 =====
FROM
python:3.11-slim
WORKDIR
/app
# 2. 只复制必要的文件(利用构建阶段缓存)
COPY
--from=builder /root/.local /root/.local
COPY
. .
# 3. 设置环境变量(PATH 里加上 pip install 的路径)
ENV
PATH=/root/.local/bin:$PATH
# 4. 不使用 root 运行(安全最佳实践)
RUN
adduser
--disabled-password
--gecos
''
appuser
USER
appuser
# 5. 暴露端口
EXPOSE
8000
# 6. 启动命令
CMD
["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```
> **多阶段构建的好处**:最终镜像只包含运行时代码(约 150MB),不包含构建工具(约 500MB)。
#### 第二步:写 requirements.txt
```
text
fastapi==0.111.0
uvicorn[standard]==0.30.0
psycopg2-binary==2.9.9
redis==5.0.0
pydantic==2.7.0
```
#### 第三步:构建 + 运行
```
bash
# 构建镜像(-t 指定名字,. 指当前目录)
docker build
-t
myapp:1.0.0
.
# 查看镜像大小
docker images |
grep
myapp
# myapp 1.0.0 a1b2c3d4e5f6 About a minute ago 158MB
# 运行容器
docker run
-d
\
--name
myapp
\
-p
8000:8000
\
-e
DATABASE_URL
=
"postgresql://user:pass@db:5432/myapp"
\
-e
REDIS_URL
=
"redis://redis:6379/0"
\
--restart
unless-stopped
\
myapp:1.0.0
# 查看运行状态
docker ps
# 查看日志
docker logs
-f
myapp
# 进入容器调试
docker
exec
-it
myapp /bin/bash
# 停止 & 删除
docker stop myapp
&&
docker
rm
myapp
```
---
### 进阶玩法:docker-compose.yml 多服务编排
生产环境通常有多个服务:
**Web(FastAPI)+ PostgreSQL + Redis**
。
```
yaml
# docker-compose.yml
version
:
"
3.9"
services
:
# ===== Web 服务 =====
web
:
build
:
context
:
.
dockerfile
:
Dockerfile
container_name
:
myapp_web
ports
:
-
"
8000:8000"
environment
:
-
DATABASE_URL=postgresql://cfm:password@db:5432/myapp
-
REDIS_URL=redis://redis:6379/0
depends_on
:
db
:
condition
:
service_healthy
redis
:
condition
:
service_started
restart
:
unless-stopped
volumes
:
-
./app_data:/app/data
# 数据持久化
# ===== PostgreSQL 数据库 =====
db
:
image
:
postgres:16-alpine
container_name
:
myapp_db
environment
:
POSTGRES_USER
:
cfm
POSTGRES_PASSWORD
:
password
POSTGRES_DB
:
myapp
ports
:
-
"
5432:5432"
volumes
:
-
pg_data:/var/lib/postgresql/data
-
./init.sql:/docker-entrypoint-initdb.d/init.sql
# 初始化脚本
healthcheck
:
test
:
[
"
CMD-SHELL"
,
"
pg_isready
-U
cfm
-d
myapp"
]
interval
:
5s
timeout
:
5s
retries
:
5
restart
:
unless-stopped
# ===== Redis 缓存 =====
redis
:
image
:
redis:7-alpine
container_name
:
myapp_redis
ports
:
-
"
6379:6379"
volumes
:
-
redis_data:/data
command
:
redis-server --appendonly yes
# 开启 AOF 持久化
restart
:
unless-stopped
volumes
:
pg_data
:
redis_data
:
```
```
bash
# 启动所有服务(后台运行)
docker-compose up
-d
# 查看所有服务状态
docker-compose ps
# 查看日志(-f 实时)
docker-compose logs
-f
web
# 停止所有服务(保留数据卷)
docker-compose down
# 停止 + 删除数据卷(清空数据库)
docker-compose down
-v
```
---
### 进阶玩法:GPU 支持(nvidia-container-toolkit)
让容器能访问宿主机的 NVIDIA GPU,是跑 AI 模型(Embedding、LLM)的必备能力。
```
bash
# 1. 检查宿主机是否有 GPU
nvidia-smi
```
```
bash
# 2. 安装 nvidia-container-toolkit
distribution
=
$(
.
/etc/os-release
;
echo
$ID$VERSION_ID
)
curl
-s
-L
https://nvidia.github.io/nvidia-docker/gpgkey |
sudo
apt-key add -
curl
-s
-L
https://nvidia.github.io/nvidia-docker/
$distribution
/nvidia-docker.list |
\
sudo tee
/etc/apt/sources.list.d/nvidia-docker.list
sudo
apt update
&&
sudo
apt
install
-y
nvidia-container-toolkit
sudo
systemctl restart docker
```
```
dockerfile
# Dockerfile 添加 GPU 支持
FROM
nvidia/cuda:12.1.1-runtime-ubuntu22.04
WORKDIR
/app
# PyTorch + GPU 版
RUN
pip
install
torch torchvision
--index-url
https://download.pytorch.org/whl/cu121
# 容器启动时必须加 --gpus all
# docker run --gpus all my_pytorch_app
```
```
bash
# 运行带 GPU 的容器
docker run
--gpus
all
\
--rm
\
nvidia/cuda:12.1.1-runtime-ubuntu22.04
\
nvidia-smi
# 在容器内验证 GPU 访问
docker run
--gpus
all
--rm
pytorch/pytorch:2.3.1-cuda12.1-cudnn8-runtime
\
python
-c
"import torch; print(f'CUDA available: {torch.cuda.is_available()}'); print(f'Device: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else None}')"
# CUDA available: True
# Device: NVIDIA GeForce RTX 4090
```
---
### 正解 vs 错误
| 维度 | 正解 ✅ | 错误 ❌ |
| --- | --- | --- |
|
**构建缓存**
| 把不常改的指令放前面(依赖层先 COPY)| 每次改代码都
`pip install`
重新跑 |
|
**最终镜像用户**
|
`adduser + USER appuser`
| 用 root 运行容器(不安全)|
|
**端口映射**
|
`-p 8000:8000`
(宿主机:容器)|
`-p 8000`
(不指定宿主机端口会随机分配)|
|
**数据持久化**
| 用
`volumes:`
持久化 DB / Redis 数据 | 容器删数据丢(默认 tmpfs)|
|
**健康检查**
|
`healthcheck`
+
`depends_on: condition: service_healthy`
| 不等 DB 就连(启动失败)|
|
**.dockerignore**
| 排除
`.git/`
`node_modules/`
`__pycache__/`
| 把所有文件都打包进镜像 |
**.dockerignore 示例**
```
text
.git
.gitignore
__pycache__
*.pyc
.env
.venv
venv/
*.md
tests/
```
---
### 思考题 / Q&A
1.
**`docker stop` 和 `docker kill` 有什么区别?**
提示:stop 发送 SIGTERM(优雅停止),kill 发送 SIGKILL(强制杀死)。
2.
**多阶段构建(multi-stage build)的核心好处是什么?**
提示:最终镜像只包含运行时,不需要构建工具,体积大幅缩小。
3.
**为什么 `depends_on` 不够,还要加 `healthcheck`?**
提示:PostgreSQL 启动后需要几秒初始化,
`depends_on`
只保证容器启动了,不保证服务就绪。
4.
**如何排查容器启动失败?**
提示:
`docker logs <container>`
→
`docker exec -it <container> /bin/bash`
→ 检查配置文件。
---
### 本节小结
-
**Docker**
把应用打包成镜像,实现"一次构建,到处运行";核心三件:镜像(Image)、容器(Container)、仓库(Registry)。
-
**Dockerfile**
最佳实践:多阶段构建、用
`python:3.11-slim`
(轻量)、加
`.dockerignore`
、不用 root 用户。
-
**docker-compose.yml**
编排多服务(web + db + redis),用
`healthcheck`
确保依赖服务就绪再启动。
-
**GPU 支持**
:
`nvidia-container-toolkit`
+
`--gpus all`
,容器内
`nvidia-smi`
验证。
-
数据(DB、Redis)用
`volumes:`
持久化,容器删除后数据不丢。
---
### 完整代码
#### `Dockerfile`
```
dockerfile
# ============================================================
# 07/Dockerfile —— FastAPI + PostgreSQL + Redis 多阶段构建
# ============================================================
# ---------- 构建阶段 ----------
FROM
python:3.11-slim AS builder
WORKDIR
/app
# 依赖层(不常变,优先构建)
COPY
requirements.txt .
RUN
pip
install
--user
--no-cache-dir
-r
requirements.txt
# ---------- 运行阶段 ----------
FROM
python:3.11-slim
WORKDIR
/app
# 复制依赖
COPY
--from=builder /root/.local /root/.local
ENV
PATH=/root/.local/bin:$PATH
# 复制代码(放在最后,充分利用构建缓存)
COPY
. .
# 安全:非 root 用户
RUN
adduser
--disabled-password
--gecos
''
appuser
USER
appuser
EXPOSE
8000
CMD
["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```
#### `docker-compose.yml`
```
yaml
version
:
"
3.9"
services
:
web
:
build
:
.
container_name
:
myapp_web
ports
:
-
"
8000:8000"
environment
:
-
DATABASE_URL=postgresql://cfm:password@db:5432/myapp
-
REDIS_URL=redis://redis:6379/0
depends_on
:
db
:
condition
:
service_healthy
redis
:
condition
:
service_started
restart
:
unless-stopped
volumes
:
-
./app_data:/app/data
db
:
image
:
postgres:16-alpine
container_name
:
myapp_db
environment
:
POSTGRES_USER
:
cfm
POSTGRES_PASSWORD
:
password
POSTGRES_DB
:
myapp
ports
:
-
"
5432:5432"
volumes
:
-
pg_data:/var/lib/postgresql/data
healthcheck
:
test
:
[
"
CMD-SHELL"
,
"
pg_isready
-U
cfm
-d
myapp"
]
interval
:
5s
timeout
:
5s
retries
:
5
restart
:
unless-stopped
redis
:
image
:
redis:7-alpine
container_name
:
myapp_redis
ports
:
-
"
6379:6379"
volumes
:
-
redis_data:/data
command
:
redis-server --appendonly yes
restart
:
unless-stopped
volumes
:
pg_data
:
redis_data
:
```
```
bash
# 常用命令速查
docker build
-t
myapp:1.0.0
.
# 构建镜像
docker run
-d
-p
8000:8000 myapp:1.0.0
# 运行
docker-compose up
-d
# 启动所有服务
docker-compose down
# 停止(保留数据)
docker-compose down
-v
# 停止(删除数据)
docker-compose logs
-f
web
# 查看 web 日志
docker
exec
-it
myapp_web /bin/bash
# 进入容器
docker ps
# 查看运行中的容器
docker images
# 查看本地镜像
docker system prune
-f
# 清理无用的构建缓存
```
---
### 验收标准
```
☐ 能编写多阶段构建的 Dockerfile(构建层 + 运行层分离)
☐ 能用 docker-compose.yml 启动多容器(web + db + redis)
☐ 能进入容器调试(docker exec -it)
☐ 能让容器访问宿主机 GPU(nvidia-smi 在容器内验证)
☐ 能在容器中正确持久化数据(volumes)
☐ 能解释 healthcheck 的作用和写法
☐ 知道 .dockerignore 的必要性
☐ 能用 docker-compose up -d / down / logs 日常操作
```
---
### 官方来源
-
Docker 官方文档 —
[
docs.docker.com/get-started/
](
https://docs.docker.com/get-started/
)
-
Dockerfile 最佳实践 —
[
docs.docker.com/develop/develop-images/dockerfile_best-practices/
](
https://docs.docker.com/develop/develop-images/dockerfile_best-practices/
)
-
docker-compose 官方文档 —
[
docs.docker.com/compose/
](
https://docs.docker.com/compose/
)
-
nvidia-container-toolkit —
[
docs.nvidia.com/datacenter/cloud-native/container-toolkit/
](
https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/
)
---
> **下一节预告:[7.5 pytest](#75-pytest)** —— 写出"不会坏"的代码。
---
## 7.5 pytest
> 用 1-2 句话说清:**pytest = Python 最流行的测试框架**,用最少的代码写出最可读的测试,自动发现测试、详细报错、丰富插件生态。
---
### 什么是 pytest?
**pytest**
是一个 Python 测试框架,核心哲学:
**测试代码应该和被测代码一样简单**
。
对比传统 unittest:
```
python
# unittest 风格(啰嗦)
import
unittest
class
TestMath
(
unittest
.
TestCase
):
def
test_add
(
self
):
self
.
assertEqual
(
1
+
1
,
2
)
```
```
python
# pytest 风格(简洁)
def
test_add
():
assert
1
+
1
==
2
```
| 维度 | unittest | pytest |
| --- | --- | --- |
|
**语法**
|
`self.assertEqual(a, b)`
|
`assert a == b`
|
|
**发现测试**
| 需继承 TestCase 类 | 自动发现
`test_*.py`
|
|
**失败报告**
| 简单 | 彩色 + 精确行号 + 变量值 |
|
**Fixture**
| setUp/tearDown |
`@pytest.fixture`
更灵活 |
|
**生态**
| 标准库 | 插件丰富(覆盖率、并行、mock)|
---
### 5 分钟快速上手
```
bash
pip
install
pytest
```
```
python
# test_basic.py
def
add
(
a
,
b
):
return
a
+
b
def
test_add_
整数
():
assert
add
(
1
,
2
)
==
3
def
test_add_
字符串
():
assert
add
(
"Hello, "
,
"World!"
)
==
"Hello, World!"
def
test_add_
负数
():
assert
add
(
-
5
,
3
)
==
-
2
```
```
bash
# 运行(自动发现 test_*.py 文件)
pytest
# 运行结果
# ========================== test session starts ==========================
# collected 3 items
# test_basic.py::test_add_整数 PASSED [ 33%]
# test_basic.py::test_add_字符串 PASSED [ 66%]
# test_basic.py::test_add_负数 PASSED [100%]
# ========================== 3 passed in 0.12s ==========================
```
---
### 进阶玩法:Fixture(三种作用域)
Fixture = 测试的"准备工作",类似 setUp,但远比 setUp 强大。
**生活类比**
:Fixture 就像酒店入住——你提前订好房间(fixture),check-in(测试运行)时房间已经准备好,check-out(测试结束)后自动清理。
```
python
import
pytest
import
tempfile
import
os
# ===== scope="function"(默认):每个测试函数执行一次 =====
@pytest.fixture
def
empty_file
(
tmp_path
):
"""创建空文件,测试结束后自动清理"""
f
=
tmp_path
/
"test.txt"
f
.
write_text
(
""
)
return
f
def
test_file_is_empty
(
empty_file
):
assert
empty_file
.
read_text
()
==
""
assert
empty_file
.
stat
()
.
st_size
==
0
def
test_write_to_file
(
empty_file
):
empty_file
.
write_text
(
"Hello"
)
assert
empty_file
.
read_text
()
==
"Hello"
# ===== scope="module":整个 .py 模块执行一次 =====
@pytest.fixture
(
scope
=
"module"
)
def
db_connection
():
"""整个模块共享数据库连接(只连一次)"""
print
(
"
\n
🔌 连接数据库..."
)
conn
=
{
"connected"
:
True
,
"data"
:
[]}
yield
conn
print
(
"
\n
🔌 关闭数据库连接..."
)
conn
[
"connected"
]
=
False
def
test_insert
(
db_connection
):
db_connection
[
"data"
]
.
append
(
"record_1"
)
assert
len
(
db_connection
[
"data"
])
==
1
def
test_query
(
db_connection
):
# 此时 db_connection["data"] 仍有 record_1(跨测试共享)
assert
isinstance
(
db_connection
[
"connected"
],
bool
)
# ===== scope="session":整个测试会话(多个文件)只执行一次 =====
@pytest.fixture
(
scope
=
"session"
)
def
app_config
():
"""全局配置,整个测试会话只读一次"""
return
{
"env"
:
"test"
,
"debug"
:
True
,
"version"
:
"1.0.0"
}
def
test_config_env
(
app_config
):
assert
app_config
[
"env"
]
==
"test"
def
test_config_debug
(
app_config
):
assert
app_config
[
"debug"
]
is
True
```
```
bash
$
pytest
-s
-v
test_fixture.py
# 输出可见 scope 行为:
# 🔌 连接数据库... ← module fixture,只执行一次
# test_fixture.py::test_insert PASSED
# test_fixture.py::test_query PASSED
# 🔌 关闭数据库连接... ← 最后自动清理
```
#### 三种 scope 总结
| scope | 创建次数 | 适用场景 |
| --- | --- | --- |
|
`function`
(默认)| 每个测试函数 | 独立资源(文件、网络请求)|
|
`module`
| 每个
`.py`
文件 | 共享数据库连接、配置 |
|
`session`
| 整个测试会话 | 全局配置、一次性初始化 |
---
### 进阶玩法:参数化测试(parametrize)
减少重复代码,一套测试覆盖多种输入。
```
python
import
pytest
class
Calculator
:
def
divide
(
self
,
a
,
b
):
if
b
==
0
:
raise
ZeroDivisionError
(
"除数不能为零"
)
return
a
/
b
@pytest.fixture
def
calc
():
return
Calculator
()
@pytest.mark.parametrize
(
"a,b,expected"
,
[
(
10
,
2
,
5.0
),
(
9
,
3
,
3.0
),
(
1
,
1
,
1.0
),
(
0
,
5
,
0.0
),
(
-
6
,
2
,
-
3.0
),
])
def
test_divide_success
(
calc
,
a
,
b
,
expected
):
assert
calc
.
divide
(
a
,
b
)
==
expected
@pytest.mark.parametrize
(
"a,b"
,
[
(
1
,
0
),
(
10
,
0.0
),
(
-
5
,
0
),
])
def
test_divide_by_zero
(
calc
,
a
,
b
):
with
pytest
.
raises
(
ZeroDivisionError
):
calc
.
divide
(
a
,
b
)
```
```
bash
$
pytest
-v
# test_divide.py::test_divide_success[10-2-5.0] PASSED [ 12%]
# test_divide.py::test_divide_success[9-3-3.0] PASSED [ 25%]
# test_divide.py::test_divide_success[1-1-1.0] PASSED [ 37%]
# test_divide.py::test_divide_success[0-5-0.0] PASSED [ 50%]
# test_divide.py::test_divide_success[-6-2-3.0] PASSED [ 62%]
# test_divide.py::test_divide_by_zero[1-0] PASSED [ 75%]
# test_divide.py::test_divide_by_zero[10-0.0] PASSED [ 87%]
# test_divide.py::test_divide_by_zero[-5-0] PASSED [100%]
# ========================== 8 passed in 0.18s ==========================
```
---
### 进阶玩法:Mock 模拟外部依赖
**生活类比**
:Mock = 考试替身。真正测"考试成绩"时,不需要真的去考试教室,用替身模拟考试结果即可。
```
python
import
pytest
from
unittest.mock
import
patch
,
MagicMock
# ===== 场景:测试调用外部天气 API 的函数 =====
def
fetch_weather
(
city
:
str
)
->
dict
:
"""调用真实的天气 API(需要网络)"""
import
requests
resp
=
requests
.
get
(
f
"https://api.weather.com/v3/wx/current?city={city}"
)
resp
.
raise_for_status
()
return
resp
.
json
()
# 方案 1:Mock 整个 requests.get
@patch
(
"requests.get"
)
def
test_fetch_weather_success
(
mock_get
):
"""Mock 返回成功的响应(不需要真实网络)"""
mock_response
=
MagicMock
()
mock_response
.
json
.
return_value
=
{
"city"
:
"北京"
,
"temp"
:
22
,
"condition"
:
"晴"
}
mock_response
.
raise_for_status
.
return_value
=
None
mock_get
.
return_value
=
mock_response
result
=
fetch_weather
(
"北京"
)
assert
result
[
"city"
]
==
"北京"
assert
result
[
"temp"
]
==
22
mock_get
.
assert_called_once
()
# 验证调用过
mock_get
.
assert_called_with
(
"https://api.weather.com/v3/wx/current?city=北京"
)
@patch
(
"requests.get"
)
def
test_fetch_weather_api_error
(
mock_get
):
"""Mock API 返回错误(测试错误处理路径)"""
import
requests
mock_get
.
side_effect
=
requests
.
HTTPError
(
"API 限流"
)
with
pytest
.
raises
(
requests
.
HTTPError
)
as
exc_info
:
fetch_weather
(
"北京"
)
assert
"限流"
in
str
(
exc_info
.
value
)
# ===== 方案 2:Mock 具体类(更精确)=====
@pytest.fixture
def
mock_redis
():
"""Mock Redis(不需要真实 Redis 服务)"""
with
patch
(
"redis.Redis"
)
as
mock
:
mock_instance
=
MagicMock
()
mock
.
return_value
=
mock_instance
mock_instance
.
get
.
return_value
=
None
# 模拟缓存未命中
yield
mock_instance
def
test_cache_miss_queries_db
(
mock_redis
):
"""缓存未命中时,应该查询数据库"""
# ... 测试逻辑
mock_redis
.
get
.
assert_called
()
```
---
### 实战:FastAPI + pytest 集成测试
```
python
# test_api.py —— 测试 FastAPI 应用
import
pytest
from
fastapi.testclient
import
TestClient
from
07
_fastapi_demo
import
app
# 导入 FastAPI app
client
=
TestClient
(
app
)
def
test_list_items
():
response
=
client
.
get
(
"/items/"
)
assert
response
.
status_code
==
200
assert
isinstance
(
response
.
json
(),
list
)
def
test_create_item
():
response
=
client
.
post
(
"/items/"
,
json
=
{
"name"
:
"测试商品"
,
"price"
:
9.9
,
"description"
:
"测试用"
,
"tags"
:
[
"test"
]},
)
assert
response
.
status_code
==
201
data
=
response
.
json
()
assert
data
[
"name"
]
==
"测试商品"
assert
"item_id"
in
data
def
test_create_item_validation_error
():
"""测试参数校验失败返回 422"""
response
=
client
.
post
(
"/items/"
,
json
=
{
"name"
:
""
,
"price"
:
-
1
},
# name 为空、price 为负
)
assert
response
.
status_code
==
422
errors
=
response
.
json
()[
"detail"
]
assert
any
(
"name"
in
str
(
e
)
for
e
in
errors
)
assert
any
(
"price"
in
str
(
e
)
for
e
in
errors
)
def
test_get_item_not_found
():
response
=
client
.
get
(
"/items/999999"
)
assert
response
.
status_code
==
404
assert
"不存在"
in
response
.
json
()[
"detail"
]
def
test_delete_item
():
# 先创建一个
create_resp
=
client
.
post
(
"/items/"
,
json
=
{
"name"
:
"待删除"
,
"price"
:
1.0
})
item_id
=
create_resp
.
json
()[
"item_id"
]
# 删除
del_resp
=
client
.
delete
(
f
"/items/{item_id}"
)
assert
del_resp
.
status_code
==
204
# 确认不存在
get_resp
=
client
.
get
(
f
"/items/{item_id}"
)
assert
get_resp
.
status_code
==
404
```
```
bash
$
pytest test_api.py
-v
# ========================== test session starts ==========================
# test_api.py::test_list_items PASSED [ 14%]
# test_api.py::test_create_item PASSED [ 28%]
# test_api.py::test_create_item_validation_error PASSED [ 42%]
# test_api.py::test_get_item_not_found PASSED [ 57%]
# test_api.py::test_delete_item PASSED [ 71%]
# ========================== 5 passed in 0.35s ==========================
```
---
### 正解 vs 错误
| 维度 | 正解 ✅ | 错误 ❌ |
| --- | --- | --- |
|
**测试文件**
|
`test_*.py`
或
`*_test.py`
| 随意命名(pytest 不发现)|
|
**Fixture 清理**
| 自动(函数结束即清理)| 手动 try/finally(繁琐且易漏)|
|
**Mock 范围**
| Mock 具体对象(
`mock.patch("module.Class")`
)| Mock 错误位置(不生效)|
|
**测试隔离**
| 每个测试独立,不依赖执行顺序 | 测试 A 改了全局状态影响测试 B |
|
**断言**
|
`assert actual == expected`
|
`if actual != expected: raise`
|
|
**外部 API**
| Mock | 真实调用(慢、不稳定、可能收费)|
---
### 思考题 / Q&A
1.
**`mock.patch` 应该写在函数参数里还是函数体内?**
提示:参数里更简洁,且 pytest 会自动 cleanup;函数体内需要手动
`mock.stop()`
。
2.
**`FakeRedis` 和 `fakeredis` 库的作用是什么?**
提示:不需要真实的 Redis 服务就能测试 Redis 相关代码。
3.
**如何只运行某个测试文件或某个测试函数?**
提示:
`pytest test_api.py::test_create_item -v`
。
4.
**`pytest.fixture` 的 `autouse=True` 有什么用?**
提示:自动应用到所有测试,无需在每个测试函数参数里声明。
---
### 本节小结
-
**pytest**
是 Python 测试首选,用
`assert`
代替
`self.assertXxx`
,代码简洁、报错友好。
-
**Fixture**
三种 scope:
`function`
(默认)→
`module`
(模块共享)→
`session`
(整个会话共享)。
-
**`@pytest.mark.parametrize`**
用一套测试代码覆盖多种输入,减少重复。
-
**Mock**
用
`unittest.mock.patch`
模拟外部依赖(API、数据库、Redis),让测试独立、可重复。
-
`TestClient`
让 FastAPI 测试不需要启动真实服务器。
-
**测试最佳实践**
:测试应该是独立的、可重复的、不依赖执行顺序的。
---
### 完整代码
```
python
"""07_pytest_demo.py —— 完整 pytest 示例"""
import
pytest
from
unittest.mock
import
patch
,
MagicMock
# ===== 被测代码(模拟)=====
class
UserService
:
def
__init__
(
self
,
db
,
cache
):
self
.
db
=
db
self
.
cache
=
cache
def
get_user
(
self
,
user_id
:
int
)
->
dict
|
None
:
# 先查缓存
cached
=
self
.
cache
.
get
(
f
"user:{user_id}"
)
if
cached
:
return
cached
# 缓存未命中,查数据库
user
=
self
.
db
.
query
(
user_id
)
if
user
:
self
.
cache
.
set
(
f
"user:{user_id}"
,
user
,
ttl
=
300
)
return
user
# ===== 测试代码 =====
class
TestUserService
:
@pytest.fixture
def
mock_db
(
self
):
return
MagicMock
()
@pytest.fixture
def
mock_cache
(
self
):
return
MagicMock
()
@pytest.fixture
def
service
(
self
,
mock_db
,
mock_cache
):
return
UserService
(
mock_db
,
mock_cache
)
def
test_cache_hit
(
self
,
service
,
mock_cache
):
"""缓存命中时,不查数据库"""
mock_cache
.
get
.
return_value
=
{
"id"
:
1
,
"name"
:
"Alice"
}
result
=
service
.
get_user
(
1
)
assert
result
[
"name"
]
==
"Alice"
mock_db
.
query
.
assert_not_called
()
# 数据库不应被调用
def
test_cache_miss
(
self
,
service
,
mock_cache
,
mock_db
):
"""缓存未命中时,查数据库并写缓存"""
mock_cache
.
get
.
return_value
=
None
mock_db
.
query
.
return_value
=
{
"id"
:
2
,
"name"
:
"Bob"
}
result
=
service
.
get_user
(
2
)
assert
result
[
"name"
]
==
"Bob"
mock_db
.
query
.
assert_called_once_with
(
2
)
mock_cache
.
set
.
assert_called_once
()
def
test_user_not_found
(
self
,
service
,
mock_cache
,
mock_db
):
"""用户不存在时返回 None"""
mock_cache
.
get
.
return_value
=
None
mock_db
.
query
.
return_value
=
None
result
=
service
.
get_user
(
999
)
assert
result
is
None
# ===== 参数化测试 =====
@pytest.mark.parametrize
(
"a,b,expected"
,
[
(
2
,
3
,
5
),
(
-
1
,
1
,
0
),
(
0
,
0
,
0
),
(
100
,
-
50
,
50
),
])
def
test_add
(
a
,
b
,
expected
):
assert
a
+
b
==
expected
# ===== 运行入口 =====
if
__name__
==
"__main__"
:
pytest
.
main
([
__file__
,
"-v"
])
```
```
bash
# 常用命令
pytest
# 发现并运行所有测试
pytest
-v
# 详细输出
pytest
-v
test_api.py
# 只跑某个文件
pytest
-k
"test_add"
# 只跑名字含 test_add 的测试
pytest
--cov
=
.
# 生成覆盖率报告(需 pip install pytest-cov)
pytest
--fixtures
# 列出所有可用的 fixture
```
---
### 验收标准
```
☐ 能用 pytest 编写基本测试用例(test_*.py)
☐ 能用 assert 写断言并解读 pytest 失败输出
☐ 能用 @pytest.fixture 定义 fixture 并理解三种 scope
☐ 能用 @pytest.mark.parametrize 减少重复的测试代码
☐ 能用 unittest.mock.patch 模拟外部 API
☐ 能用 TestClient 测试 FastAPI 路由
☐ 能区分什么是应该 Mock 的(外部依赖),什么是应该真实测的(核心逻辑)
☐ 能用 pytest -v / -k / --cov 常用选项
```
---
### 官方来源
-
pytest 官方文档 —
[
docs.pytest.org/
](
https://docs.pytest.org/
)
-
unittest.mock 官方文档 —
[
docs.python.org/3/library/unittest.mock.html
](
https://docs.python.org/3/library/unittest.mock.html
)
-
FastAPI Testing —
[
fastapi.tiangolo.com/tutorial/testing/
](
https://fastapi.tiangolo.com/tutorial/testing/
)
-
pytest-cov(覆盖率插件)—
[
pytest-cov.readthedocs.io/
](
https://pytest-cov.readthedocs.io/
)
---
### 本模块小结
| 章节 | 核心工具 | 解决了什么问题 |
| --- | --- | --- |
|
**7.1 FastAPI**
| FastAPI + Pydantic | 用 Python 快速构建类型安全的 HTTP API |
|
**7.2 PostgreSQL**
| psql + psycopg2 + SQLAlchemy | 结构化数据的持久化存储与查询 |
|
**7.3 Redis**
| redis-py | 热点数据缓存、分布式锁、高并发计数 |
|
**7.4 Docker**
| Dockerfile + docker-compose | 一次构建、到处运行、多服务编排 |
|
**7.5 pytest**
| pytest + unittest.mock | 写出可维护、可重复、可自动化的测试 |
**完整系统的最小架构图**
:
```
text
用户浏览器
│
▼
┌─────────────────────────┐
│ FastAPI (Docker 容器) │ ← 7.1
│ ┌─────────────────┐ │
│ │ Pydantic 校验 │ │
│ │ Depends 认证 │ │
│ └─────────────────┘ │
└──────────┬──────────────┘
│ ┌──────────────────┐
▼ │ Redis (Docker) │ ← 7.3
┌──────────────────┐ │ 缓存 / 锁 / 队列 │
│ PostgreSQL (Docker)│ └──────────────────┘
│ 持久化存储 │ ← 7.2
└──────────────────┘
本地测试:pytest + TestClient ← 7.5
打包部署:Dockerfile + docker-compose ← 7.4
```
### 本模块验收标准
```
☐ 能独立用 FastAPI + PostgreSQL + Redis 搭起一个 CRUD API 服务
☐ 能用 Dockerfile 把服务打包成镜像并 docker-compose 启动
☐ 能用 pytest 为 API 写集成测试(TestClient)
☐ 能用 Mock 隔离外部依赖,写出稳定快速的单元测试
☐ 能解释 Docker 的容器化优势(对比虚拟机、物理机)
☐ 能用 Cache-Aside 模式优化读多写少场景
☐ 知道分布式锁的正确实现方式(SET NX EX + Lua)
```
编写
预览
Markdown
格式
0%
重试
或
添加新文件
添加附件
取消
您添加了
0
人
到此讨论。请谨慎行事。
请先完成此评论的编辑!
取消
请
注册
或者
登录
后发表评论