Repository navigation
Expand file tree
/
Copy pathday6-fastapi-notes.html
More file actions
606 lines (542 loc) · 16.9 KB
/
Copy pathday6-fastapi-notes.html
File metadata and controls
606 lines (542 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Day 6 FastAPI 学习笔记</title>
<style>
:root {
color-scheme: light;
--bg: #f6f8fc;
--paper: #ffffff;
--ink: #172033;
--muted: #5d667a;
--line: #dfe4ee;
--blue: #2563eb;
--green: #15803d;
--amber: #b45309;
--red: #b91c1c;
--cyan: #0e7490;
--code-bg: #101828;
--code-ink: #e5edf8;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
background: var(--bg);
color: var(--ink);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
line-height: 1.7;
}
main {
width: min(1080px, calc(100% - 32px));
margin: 0 auto;
padding: 32px 0 48px;
}
header {
padding: 28px 0 20px;
border-bottom: 1px solid var(--line);
}
h1 {
margin: 0 0 10px;
font-size: 36px;
line-height: 1.15;
letter-spacing: 0;
}
h2 {
margin: 0 0 14px;
font-size: 24px;
letter-spacing: 0;
}
h3 {
margin: 0 0 10px;
font-size: 18px;
letter-spacing: 0;
}
p {
margin: 0 0 12px;
}
code {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 0.95em;
}
pre {
margin: 12px 0 0;
padding: 16px;
overflow-x: auto;
background: var(--code-bg);
color: var(--code-ink);
border-radius: 8px;
line-height: 1.55;
}
pre code {
color: inherit;
font-size: 14px;
}
a {
color: var(--blue);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.subtitle {
max-width: 820px;
color: var(--muted);
font-size: 17px;
}
.meta {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 18px;
}
.pill {
display: inline-flex;
align-items: center;
min-height: 30px;
padding: 4px 10px;
border: 1px solid var(--line);
border-radius: 999px;
background: var(--paper);
color: var(--muted);
font-size: 14px;
}
.section {
margin-top: 24px;
padding: 24px;
background: var(--paper);
border: 1px solid var(--line);
border-radius: 8px;
}
.grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 14px;
}
.grid.two {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.item {
min-height: 126px;
padding: 16px;
border: 1px solid var(--line);
border-radius: 8px;
background: #fbfcff;
}
.item strong {
display: block;
margin-bottom: 6px;
}
.item span {
color: var(--muted);
}
.table-wrap {
overflow-x: auto;
border: 1px solid var(--line);
border-radius: 8px;
}
table {
width: 100%;
border-collapse: collapse;
min-width: 760px;
background: var(--paper);
}
th,
td {
padding: 13px 14px;
border-bottom: 1px solid var(--line);
text-align: left;
vertical-align: top;
}
th {
background: #f1f5fb;
font-weight: 700;
}
tr:last-child td {
border-bottom: 0;
}
.note,
.success,
.warning,
.danger {
margin-top: 14px;
padding: 14px 16px;
border-radius: 8px;
border: 1px solid;
}
.note {
background: #eff6ff;
border-color: #bfdbfe;
color: #1e3a8a;
}
.success {
background: #ecfdf5;
border-color: #bbf7d0;
color: #14532d;
}
.warning {
background: #fff7ed;
border-color: #fed7aa;
color: #7c2d12;
}
.danger {
background: #fef2f2;
border-color: #fecaca;
color: #7f1d1d;
}
.steps,
.checklist {
margin: 0;
padding-left: 22px;
}
.steps li,
.checklist li {
margin: 7px 0;
}
.tag-blue,
.tag-green,
.tag-amber,
.tag-cyan,
.tag-red {
display: inline-flex;
align-items: center;
min-height: 28px;
padding: 2px 8px;
border-radius: 8px;
font-size: 13px;
font-weight: 700;
}
.tag-blue {
background: #dbeafe;
color: var(--blue);
}
.tag-green {
background: #dcfce7;
color: var(--green);
}
.tag-amber {
background: #fef3c7;
color: var(--amber);
}
.tag-cyan {
background: #cffafe;
color: var(--cyan);
}
.tag-red {
background: #fee2e2;
color: var(--red);
}
footer {
margin-top: 32px;
color: var(--muted);
font-size: 14px;
text-align: center;
}
@media (max-width: 760px) {
main {
width: min(100% - 24px, 1080px);
padding-top: 20px;
}
h1 {
font-size: 30px;
}
.section {
padding: 18px;
}
.grid,
.grid.two {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<main>
<header>
<h1>Day 6 FastAPI 学习笔记</h1>
<p class="subtitle">今天把路径参数、查询参数、请求体、响应模型、状态码和错误处理串起来,完成一个内存版 Todo CRUD。</p>
<div class="meta">
<span class="pill">主题:内存版 CRUD</span>
<span class="pill">资源:Todo</span>
<span class="pill">代码:my_day06/main.py</span>
<span class="pill">接口:GET、POST、PUT、PATCH、DELETE</span>
</div>
</header>
<section class="section">
<h2>今天结论</h2>
<div class="grid">
<div class="item">
<strong>CRUD 是接口设计习惯</strong>
<span><code>POST</code> 新增,<code>GET</code> 查询,<code>PUT/PATCH</code> 更新,<code>DELETE</code> 删除。</span>
</div>
<div class="item">
<strong>模型要按场景拆开</strong>
<span><code>TodoCreate</code>、<code>TodoUpdate</code>、<code>TodoPatch</code>、<code>TodoRead</code> 的职责不同。</span>
</div>
<div class="item">
<strong>PATCH 只改传入字段</strong>
<span><code>model_dump(exclude_unset=True)</code> 可以避免没传的字段被默认值覆盖。</span>
</div>
</div>
<div class="success">
一句话记法:内存字典负责暂存数据,Pydantic 模型负责输入输出结构,HTTP 方法负责表达你要做哪种操作。
</div>
</section>
<section class="section">
<h2>CRUD 对照表</h2>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>操作</th>
<th>含义</th>
<th>HTTP 方法</th>
<th>本节接口</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="tag-green">Create</span></td>
<td>新增资源</td>
<td><code>POST</code></td>
<td><code>POST /todos</code></td>
</tr>
<tr>
<td><span class="tag-blue">Read</span></td>
<td>查询资源</td>
<td><code>GET</code></td>
<td><code>GET /todos</code>、<code>GET /todos/{todo_id}</code></td>
</tr>
<tr>
<td><span class="tag-amber">Update</span></td>
<td>修改资源</td>
<td><code>PUT</code>、<code>PATCH</code></td>
<td><code>PUT /todos/{todo_id}</code>、<code>PATCH /todos/{todo_id}</code></td>
</tr>
<tr>
<td><span class="tag-red">Delete</span></td>
<td>删除资源</td>
<td><code>DELETE</code></td>
<td><code>DELETE /todos/{todo_id}</code></td>
</tr>
</tbody>
</table>
</div>
</section>
<section class="section">
<h2>内存版数据</h2>
<p>Day 6 还没有接数据库,所以先用 Python 字典模拟数据表。</p>
<pre><code>todos = {
1: {
"id": 1,
"title": "阅读 Day 6 教程",
"description": "理解内存版 CRUD 的接口设计",
"priority": 3,
"completed": False,
"internal_note": "学习数据,不返回给客户端",
}
}</code></pre>
<div class="warning">
内存版数据适合练接口,但应用重启后,运行期间新增、修改、删除的数据都会丢失。真正项目后面要换成数据库。
</div>
</section>
<section class="section">
<h2>模型拆分</h2>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>模型</th>
<th>使用场景</th>
<th>关键字段</th>
<th>为什么这样设计</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>TodoCreate</code></td>
<td>新增 Todo</td>
<td><code>title</code>、<code>description</code>、<code>priority</code></td>
<td>客户端不传 <code>id</code>,新 Todo 默认未完成。</td>
</tr>
<tr>
<td><code>TodoUpdate</code></td>
<td>整体替换 Todo</td>
<td>完整可写字段</td>
<td><code>PUT</code> 更像用一份新对象替换旧对象。</td>
</tr>
<tr>
<td><code>TodoPatch</code></td>
<td>局部修改 Todo</td>
<td>所有字段都可选</td>
<td><code>PATCH</code> 只修改客户端传来的字段。</td>
</tr>
<tr>
<td><code>TodoRead</code></td>
<td>返回给客户端</td>
<td><code>id</code>、<code>title</code>、<code>priority</code>、<code>completed</code></td>
<td>响应模型只暴露客户端应该看到的数据。</td>
</tr>
</tbody>
</table>
</div>
<div class="note">
模型拆开以后,接口意图会更清楚:请求模型描述“客户端要给我什么”,响应模型描述“我要返回给客户端什么”。
</div>
</section>
<section class="section">
<h2>查询列表</h2>
<p><code>GET /todos</code> 支持按标题、完成状态、最低优先级和数量限制来筛选。</p>
<pre><code>@app.get("/todos", response_model=TodoListResponse)
async def list_todos(
q: Optional[str] = None,
completed: Optional[bool] = None,
min_priority: int = 1,
limit: int = 50,
):
result = list(todos.values())
if completed is not None:
result = [
todo
for todo in result
if todo["completed"] == completed
]</code></pre>
<div class="warning">
这里要写 <code>completed is not None</code>,不能写 <code>if completed</code>。因为 <code>completed=false</code> 也是有效筛选条件。
</div>
</section>
<section class="section">
<h2>404 复用函数</h2>
<p>详情、更新、删除都会遇到“资源不存在”的情况,所以抽出 <code>get_todo_or_404</code>。</p>
<pre><code>def get_todo_or_404(todo_id: int) -> dict:
todo = todos.get(todo_id)
if todo is None:
raise HTTPException(status_code=404, detail="Todo 不存在")
return todo</code></pre>
<div class="success">
这个函数让接口代码更干净:先拿到 Todo,拿不到就直接返回 <code>404</code>。
</div>
</section>
<section class="section">
<h2>新增 Todo</h2>
<p><code>POST /todos</code> 会生成新的 <code>id</code>,把请求体转成字典,再存进内存。</p>
<pre><code>@app.post(
"/todos",
response_model=TodoCreateResponse,
status_code=status.HTTP_201_CREATED,
)
async def create_todo(todo: TodoCreate):
todo_id = max(todos.keys(), default=0) + 1
new_todo = {
"id": todo_id,
**todo.model_dump(),
"completed": False,
}
todos[todo_id] = new_todo</code></pre>
<div class="note">
<code>201 Created</code> 表示资源创建成功,比普通的 <code>200 OK</code> 更准确。
</div>
</section>
<section class="section">
<h2>PUT 和 PATCH</h2>
<div class="grid two">
<div class="item">
<strong><code>PUT</code>:整体替换</strong>
<span>适合客户端提交一份完整对象。没传的字段会按模型默认值处理,例如 <code>description</code> 可能变成 <code>null</code>。</span>
</div>
<div class="item">
<strong><code>PATCH</code>:局部修改</strong>
<span>适合只改一个或几个字段。比如只传 <code>{"completed": true}</code> 来标记完成。</span>
</div>
</div>
<pre><code>stored_todo = get_todo_or_404(todo_id)
update_data = todo.model_dump(exclude_unset=True)
updated_todo = {
**stored_todo,
**update_data,
}
todos[todo_id] = updated_todo</code></pre>
</section>
<section class="section">
<h2>exclude_unset=True 的区别</h2>
<p>本节最容易踩坑的是 <code>PATCH</code> 里的这一行:</p>
<pre><code>update_data = todo.model_dump(exclude_unset=True)</code></pre>
<p>如果请求体只传:</p>
<pre><code>{
"completed": true
}</code></pre>
<p>加了 <code>exclude_unset=True</code>,导出的数据只有真正传入的字段:</p>
<pre><code>{"completed": True}</code></pre>
<p>如果不写 <code>exclude_unset=True</code>,<code>TodoPatch</code> 里没传的字段也会带着默认值一起导出:</p>
<pre><code>{
"title": None,
"description": None,
"priority": None,
"completed": True
}</code></pre>
<div class="danger">
不写 <code>exclude_unset=True</code> 时,合并字典会把原来的 <code>title</code> 和 <code>priority</code> 覆盖成 <code>None</code>,局部更新就变成了误覆盖。
</div>
<div class="note">
<code>exclude_unset=True</code> 和 <code>exclude_none=True</code> 不一样。前者是不导出“没传”的字段;如果客户端明确传了 <code>{"description": null}</code>,仍然可以保留这个字段,用来主动清空说明。
</div>
</section>
<section class="section">
<h2>删除 Todo</h2>
<p><code>DELETE /todos/{todo_id}</code> 成功后返回 <code>204 No Content</code>。</p>
<pre><code>@app.delete(
"/todos/{todo_id}",
status_code=status.HTTP_204_NO_CONTENT,
)
async def delete_todo(todo_id: int):
get_todo_or_404(todo_id)
del todos[todo_id]
return Response(status_code=status.HTTP_204_NO_CONTENT)</code></pre>
<div class="warning">
<code>204</code> 的意思是成功但没有响应体。如果想返回 <code>{"message": "删除成功"}</code>,就不要继续用 <code>204</code>。
</div>
</section>
<section class="section">
<h2>响应模型过滤字段</h2>
<p>内存数据里有 <code>internal_note</code>,但 <code>TodoRead</code> 没有这个字段。</p>
<pre><code>class TodoRead(BaseModel):
id: int
title: str
description: Optional[str] = None
priority: int
completed: bool</code></pre>
<div class="success">
因为接口设置了 <code>response_model</code>,FastAPI 会按照响应模型过滤返回值,内部备注不会暴露给客户端。
</div>
</section>
<section class="section">
<h2>建议测试顺序</h2>
<ol class="steps">
<li>启动服务:<code>uvicorn my_day06.main:app --reload</code></li>
<li>打开文档:<code>http://127.0.0.1:8000/docs</code></li>
<li>运行 <code>GET /todos</code> 查看初始数据。</li>
<li>运行 <code>POST /todos</code> 新增一条 Todo。</li>
<li>运行 <code>PATCH /todos/{todo_id}</code>,只把 <code>completed</code> 改成 <code>true</code>。</li>
<li>运行 <code>PUT /todos/{todo_id}</code>,观察整体替换的效果。</li>
<li>运行 <code>DELETE /todos/{todo_id}</code>,确认返回 <code>204</code>。</li>
<li>再次查询被删除的 Todo,确认返回 <code>404</code>。</li>
</ol>
</section>
<section class="section">
<h2>今日练习</h2>
<ul class="checklist">
<li>给 <code>GET /todos</code> 增加 <code>max_priority</code> 查询参数。</li>
<li>给 <code>TodoCreate</code> 增加 <code>tag</code> 字段,表示 Todo 分类。</li>
<li>试试 <code>PATCH /todos/1</code> 传空 JSON <code>{}</code> 会发生什么。</li>
<li>把删除接口改成返回 JSON,并把状态码从 <code>204</code> 改成更合适的值。</li>
</ul>
</section>
<footer>
Day 6 重点:CRUD 不是新语法,而是一组稳定的接口设计习惯。
</footer>
</main>
</body>
</html>