lessons.json 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  1. [
  2. {
  3. "id": "01",
  4. "group": "起步与 HTTP",
  5. "title": "启动第一个 FastAPI 服务",
  6. "summary": "建立 api-lab 项目,让 /health 返回 JSON,并通过交互文档发出第一次请求。",
  7. "objectives": [
  8. "为项目创建独立的 Python 环境",
  9. "解释 main:app、端口与 --reload 的作用",
  10. "分别在浏览器和 /docs 验证同一个接口"
  11. ],
  12. "concepts": [
  13. {
  14. "title": "服务进程与路由函数",
  15. "body": "普通脚本运行结束后会退出。API 服务由 Uvicorn 持续监听本机端口,收到 HTTP 请求后调用 FastAPI 中匹配的方法与路径。@app.get('/health') 注册的是 GET /health;函数的返回值会被序列化为 JSON 响应。"
  16. },
  17. {
  18. "title": "虚拟环境决定从哪里导入依赖",
  19. "body": "同一台电脑可以有多个 Python。虚拟环境把当前项目的解释器入口和第三方包放在 .venv 中。用 python -m pip 安装,能使 pip 与当前 python 指向同一环境;编辑器也应选择 .venv 中的解释器。"
  20. },
  21. {
  22. "title": "开发服务器的几个参数",
  23. "body": "main:app 表示从当前目录的 main.py 导入 app 对象。127.0.0.1 是本机地址,8000 是默认端口。--reload 会在代码变化后重启开发进程,重启也会清空之后课程中的内存数据。"
  24. }
  25. ],
  26. "steps": [
  27. {
  28. "title": "建立目录和虚拟环境",
  29. "body": "准备 Python 3.11 或更新版本。以下两组命令按系统选择一组。激活只影响当前终端;以后重新打开终端时,要先切换到 api-lab 再激活。",
  30. "lang": "bash",
  31. "code": "# Windows PowerShell\nmkdir api-lab\ncd api-lab\npy -3 -m venv .venv\n.\\.venv\\Scripts\\Activate.ps1\n\n# macOS / Linux\nmkdir api-lab\ncd api-lab\npython3 -m venv .venv\nsource .venv/bin/activate\n\n# 激活后检查解释器路径,结果应包含 api-lab/.venv\npython -c \"import sys; print(sys.executable)\""
  32. },
  33. {
  34. "title": "安装依赖并记录环境",
  35. "body": "创建 requirements.txt,写入下面三行。然后在激活后的终端运行 python -m pip install -r requirements.txt。本模块使用 Pydantic v2 的 model_dump() 写法。安装成功后运行 python -m pip freeze > requirements-lock.txt,保留当前环境实际使用的版本;另一个环境可从这个锁定文件安装。 如果直接运行下载包,请使用包内已经锁定版本的 requirements.txt。",
  36. "filename": "requirements.txt",
  37. "lang": "bash",
  38. "code": "fastapi>=0.115,<1\nuvicorn[standard]>=0.30,<1\npydantic>=2,<3"
  39. },
  40. {
  41. "title": "编写健康检查接口",
  42. "body": "在 api-lab 根目录创建 main.py。FastAPI 实例只创建一次。路由装饰器紧接在函数定义上方,返回值使用 Python 字典,JSON 编码由框架完成。",
  43. "filename": "main.py",
  44. "lang": "python",
  45. "code": "from fastapi import FastAPI\n\napp = FastAPI(title=\"API Lab\", version=\"0.1.0\")\n\n@app.get(\"/health\", tags=[\"system\"])\ndef health():\n return {\"status\": \"ok\"}"
  46. },
  47. {
  48. "title": "启动服务并观察终端",
  49. "body": "在 main.py 所在目录运行以下命令。终端保持运行状态是正常现象;看到 Application startup complete 后再访问浏览器。服务运行期间用另一个终端执行请求,停止服务使用 Ctrl+C。",
  50. "lang": "bash",
  51. "code": "python -m uvicorn main:app --reload\n# 默认访问地址:http://127.0.0.1:8000\n# 8000 被占用时,可加 --port 8001"
  52. },
  53. {
  54. "title": "通过浏览器和交互文档验收",
  55. "body": "先打开 http://127.0.0.1:8000/health,确认显示 {\"status\":\"ok\"}。再打开 /docs,展开 GET /health → Try it out → Execute,查看状态码、响应头和响应体。最后把 main.py 中的 ok 改为 ready 并保存,观察终端重载日志和新响应,完成后改回 ok。",
  56. "lang": "http",
  57. "code": "GET /health HTTP/1.1\nHost: 127.0.0.1:8000\n\nHTTP/1.1 200 OK\nContent-Type: application/json\n\n{\"status\":\"ok\"}"
  58. }
  59. ],
  60. "checks": [
  61. "终端的 sys.executable 路径包含 api-lab/.venv。",
  62. "GET /health 返回 200 和 {\"status\":\"ok\"};访问未定义的 / 返回 404,这不表示服务未启动。",
  63. "/docs 中出现 GET /health,点击 Execute 后能看到真实响应。"
  64. ],
  65. "pitfalls": [
  66. {
  67. "symptom": "ModuleNotFoundError: No module named 'fastapi'",
  68. "cause": "安装依赖和启动服务使用了不同解释器。",
  69. "fix": "激活 .venv,检查 sys.executable,再执行 python -m pip install -r requirements.txt。"
  70. },
  71. {
  72. "symptom": "Could not import module 'main'",
  73. "cause": "当前目录没有 main.py,或者文件中存在语法错误。",
  74. "fix": "切换到 api-lab 根目录,确认文件名为 main.py,阅读终端中最早出现的 Python 错误。"
  75. },
  76. {
  77. "symptom": "PowerShell 阻止 Activate.ps1 运行",
  78. "cause": "当前执行策略限制脚本运行。",
  79. "fix": "无需修改全局策略,可直接使用 .\\.venv\\Scripts\\python.exe -m pip install -r requirements.txt,以及 .\\.venv\\Scripts\\python.exe -m uvicorn main:app --reload。"
  80. }
  81. ],
  82. "exercise": {
  83. "task": "添加 GET /version,返回 {\"service\":\"api-lab\",\"version\":\"0.1.0\"},并在 /docs 中执行一次。",
  84. "hint": "保留已有 app,在另一个函数上方注册新的 GET 路由。",
  85. "answer": "在 main.py 末尾添加:\n@app.get('/version')\ndef version():\n return {'service': 'api-lab', 'version': '0.1.0'}\n\n保存后访问 /version,应返回 200;刷新 /docs 后应同时看到 /health 与 /version。"
  86. },
  87. "refs": [
  88. {
  89. "label": "Python:venv",
  90. "url": "https://docs.python.org/3/library/venv.html"
  91. },
  92. {
  93. "label": "FastAPI:First Steps",
  94. "url": "https://fastapi.tiangolo.com/tutorial/first-steps/"
  95. },
  96. {
  97. "label": "FastAPI:手动运行服务器",
  98. "url": "https://fastapi.tiangolo.com/deployment/manually/"
  99. }
  100. ]
  101. },
  102. {
  103. "id": "02",
  104. "group": "起步与 HTTP",
  105. "title": "读懂一次 HTTP 请求与响应",
  106. "summary": "拆开方法、路径、查询参数、请求头和请求体,亲手发送 GET 与 POST。",
  107. "demo": "http",
  108. "objectives": [
  109. "在请求中指出方法、URL、请求头和请求体的位置",
  110. "区分 Content-Type、Accept 与 HTTP 状态码",
  111. "用 /docs 和命令行复现同一条请求"
  112. ],
  113. "concepts": [
  114. {
  115. "title": "请求由几个独立部分组成",
  116. "body": "以 POST /notes?source=lesson 为例:POST 是方法,/notes 是路径,source=lesson 是查询参数。请求头携带内容类型等元信息,请求体携带笔记数据。下面的 HTTP/1.1 文本用于辨认字段;浏览器也可能使用其他 HTTP 版本,业务含义一致。"
  117. },
  118. {
  119. "title": "Content-Type 描述实际内容",
  120. "body": "请求头 Content-Type: application/json 表示请求体按 JSON 编码;Accept: application/json 表示客户端期望的响应格式。服务器仍按接口定义产生响应,并非只改 Accept 就会自动得到另一种格式。JSON 键和字符串使用双引号,布尔值使用 true / false。"
  121. },
  122. {
  123. "title": "响应状态与业务字段分开读取",
  124. "body": "响应先给出 HTTP 状态码,再给出响应头和响应体。200 表示本次 HTTP 操作成功,422 表示请求数据未通过当前接口校验。把 {\"code\":404} 放在一个 200 响应里,不会把 HTTP 状态变成 404。"
  125. }
  126. ],
  127. "steps": [
  128. {
  129. "title": "观察最小 GET 请求",
  130. "body": "保持第 01 课服务运行。在 /docs 执行 /health,同时查看本页的请求拆解演示。把方法、路径、Host 和响应体分别定位;GET /health 不需要请求体。",
  131. "lang": "http",
  132. "code": "GET /health HTTP/1.1\nHost: 127.0.0.1:8000\nAccept: application/json\n\nHTTP/1.1 200 OK\nContent-Type: application/json\n\n{\"status\":\"ok\"}"
  133. },
  134. {
  135. "title": "添加临时的 POST 回显接口",
  136. "body": "把以下代码追加到 main.py。这个临时接口只读取请求体并返回,不保存笔记,也不宣称创建成功。第 03 课会用带类型的模型替换它。这里先借助 Request 观察 HTTP 数据,异步语法在后续课程集中练习。",
  137. "filename": "main.py",
  138. "lang": "python",
  139. "code": "from fastapi import Request\n\n@app.post(\"/notes\")\nasync def inspect_note(request: Request):\n data = await request.json()\n return {\"received\": data}"
  140. },
  141. {
  142. "title": "准备 JSON 文件并发送 POST",
  143. "body": "在 api-lab 中创建 note.json,使用 UTF-8 保存。macOS / Linux 执行 curl -i -X POST http://127.0.0.1:8000/notes -H \"Content-Type: application/json\" --data-binary @note.json;Windows PowerShell 使用 curl.exe,并把 @note.json 写成引号包围的 \"@note.json\"。-i 同时显示响应头。",
  144. "filename": "note.json",
  145. "lang": "json",
  146. "code": "{\n \"title\": \"first note\",\n \"content\": \"learn HTTP\",\n \"pinned\": false\n}"
  147. },
  148. {
  149. "title": "对照原始请求与服务器结果",
  150. "body": "命令行应返回 200 和 received 对象。改动 note.json 中的 title 后再次发送,确认响应随之变化。在浏览器开发者工具 Network 中展开 /docs 发出的请求,也能查看 Method、Request Headers、Payload 和 Response。",
  151. "lang": "http",
  152. "code": "POST /notes HTTP/1.1\nHost: 127.0.0.1:8000\nContent-Type: application/json\n\n{\"title\":\"first note\",\"content\":\"learn HTTP\",\"pinned\":false}\n\nHTTP/1.1 200 OK\nContent-Type: application/json\n\n{\"received\":{\"title\":\"first note\",\"content\":\"learn HTTP\",\"pinned\":false}}"
  153. }
  154. ],
  155. "checks": [
  156. "能说明查询参数属于 URL,请求体位于请求头之后,两者不是同一块数据。",
  157. "命令行 POST 返回 200,并在 received 中保留 note.json 的三个字段。",
  158. "浏览器直接打开 /notes 会发出 GET;当前只注册了 POST,因此应返回 405 Method Not Allowed。"
  159. ],
  160. "pitfalls": [
  161. {
  162. "symptom": "PowerShell 提示无法识别 -H 参数",
  163. "cause": "使用了旧版 PowerShell 的 curl 别名。",
  164. "fix": "明确执行 curl.exe;或者在 /docs 中操作。"
  165. },
  166. {
  167. "symptom": "请求体解析失败",
  168. "cause": "把 Python 字典写法当成 JSON,例如使用单引号或 False。",
  169. "fix": "使用 note.json 文件,字符串和字段名用双引号,布尔值写 true / false。"
  170. },
  171. {
  172. "symptom": "浏览器地址栏打不开 POST 接口",
  173. "cause": "地址栏导航通常发送 GET,没有发送预期的 POST 和 JSON 请求体。",
  174. "fix": "使用 curl、/docs 或能够配置 HTTP 方法的客户端。"
  175. }
  176. ],
  177. "exercise": {
  178. "task": "把请求体的 title 改成 second note,再发送一次。记录响应的 HTTP 状态码、Content-Type 和 received.title;最后说明 Accept 和 Content-Type 的区别。",
  179. "hint": "使用 -i 查看响应头,不要只看最后一行 JSON。",
  180. "answer": "状态码为 200;响应 Content-Type 为 application/json;received.title 为 second note。请求 Content-Type 描述这次发送的数据格式,Accept 描述客户端希望接收的格式。"
  181. },
  182. "refs": [
  183. {
  184. "label": "RFC 9110:HTTP 消息与内容语义",
  185. "url": "https://www.rfc-editor.org/rfc/rfc9110.html#section-6"
  186. },
  187. {
  188. "label": "RFC 8259:JSON 语法",
  189. "url": "https://www.rfc-editor.org/rfc/rfc8259"
  190. },
  191. {
  192. "label": "FastAPI:直接使用 Request",
  193. "url": "https://fastapi.tiangolo.com/advanced/using-request-directly/"
  194. }
  195. ]
  196. },
  197. {
  198. "id": "03",
  199. "group": "起步与 HTTP",
  200. "title": "从路径、查询参数和 JSON 中接收数据",
  201. "summary": "为笔记接口声明参数类型,让 FastAPI 完成解析、默认值填充和基础校验。",
  202. "objectives": [
  203. "将 note_id 放在路径中,将筛选条件放在查询参数中",
  204. "用 Pydantic 模型接收 JSON 请求体",
  205. "通过 422 响应定位错误参数"
  206. ],
  207. "concepts": [
  208. {
  209. "title": "路径标识对象,查询参数控制读取方式",
  210. "body": "/notes/12 中的 12 表示要操作的笔记;/notes?limit=10&pinned=true 中的参数表示读取条件。参数名出现在路由路径中时,FastAPI 将其识别为路径参数。未出现在路径中的简单类型参数通常来自查询字符串。"
  211. },
  212. {
  213. "title": "类型声明参与运行时解析",
  214. "body": "HTTP 路径和查询字符串首先都是文本。note_id: int 要求它能解析为整数;limit: int = 10 提供默认值。无法转换的值会在进入路由函数前产生 422 响应,因此函数里不用重复写 int() 和大量类型判断。"
  215. },
  216. {
  217. "title": "请求模型决定必填与默认值",
  218. "body": "继承 BaseModel 的 NoteCreate 声明 JSON 对象的结构。title 没有默认值,所以必须发送;content 默认空字符串,pinned 默认 false。str | None 表示允许 null,不自动表示可以省略;若要允许省略,还需写默认值,例如 = None。"
  219. }
  220. ],
  221. "steps": [
  222. {
  223. "title": "声明创建笔记的输入模型",
  224. "body": "在 main.py 的路由定义之前添加模型。删除第 02 课的 inspect_note 路由函数及其装饰器,随后用第 04 步的新 POST /notes 替换,避免同一方法和路径出现多个处理函数。",
  225. "filename": "main.py",
  226. "lang": "python",
  227. "code": "from pydantic import BaseModel\n\nclass NoteCreate(BaseModel):\n title: str\n content: str = \"\"\n pinned: bool = False"
  228. },
  229. {
  230. "title": "添加路径参数",
  231. "body": "添加 GET /notes/{note_id}。本节先回显解析后的编号,暂不查询存储。依次请求 /notes/12 与 /notes/abc,比较状态码;整数解析失败时,错误位置会包含 path 和 note_id。",
  232. "filename": "main.py",
  233. "lang": "python",
  234. "code": "@app.get(\"/notes/{note_id}\")\ndef inspect_note_id(note_id: int):\n return {\"note_id\": note_id}"
  235. },
  236. {
  237. "title": "添加查询参数和范围",
  238. "body": "添加 GET /notes。Annotated 把 Python 类型和 FastAPI 的参数规则写在一起。limit 默认为 10,只允许 1 到 100;pinned 未传时为 None,传 false 时是明确的 False,后续筛选中要区分这两种情况。",
  239. "filename": "main.py",
  240. "lang": "python",
  241. "code": "from typing import Annotated\nfrom fastapi import Query\n\n@app.get(\"/notes\")\ndef inspect_filters(\n limit: Annotated[int, Query(ge=1, le=100)] = 10,\n pinned: bool | None = None,\n):\n return {\"limit\": limit, \"pinned\": pinned}"
  242. },
  243. {
  244. "title": "用类型模型替换原始请求体",
  245. "body": "定义新的 POST /notes。在 /docs 中仅发送 {\"title\":\"first note\"},观察缺省字段被补齐。本节仍是参数练习,不写入存储。model_dump() 把 Pydantic 模型转换为 Python 字典。",
  246. "filename": "main.py",
  247. "lang": "python",
  248. "code": "@app.post(\"/notes\")\ndef inspect_note_body(note: NoteCreate):\n return note.model_dump()"
  249. },
  250. {
  251. "title": "建立有效值和无效值对照",
  252. "body": "在 /docs 连续完成以下四次调用,记录状态码与响应中的字段位置。缺少 title 的 POST 应在路由运行前失败。下一课会继续收紧 title 的长度与多余字段规则。",
  253. "lang": "http",
  254. "code": "GET /notes/12\n# 200: {\"note_id\":12}\n\nGET /notes?limit=5&pinned=false\n# 200: {\"limit\":5,\"pinned\":false}\n\nGET /notes?limit=0\n# 422,错误位置包含 [\"query\",\"limit\"]\n\nPOST /notes\nContent-Type: application/json\n\n{}\n# 422,错误位置包含 [\"body\",\"title\"]"
  255. }
  256. ],
  257. "checks": [
  258. "GET /notes/12 返回数字 12,/notes/abc 返回 422。",
  259. "GET /notes 返回 {\"limit\":10,\"pinned\":null};?pinned=false 返回 false。",
  260. "POST /notes 只传 title 时补齐 content 和 pinned;缺少 title 返回 422。"
  261. ],
  262. "pitfalls": [
  263. {
  264. "symptom": "把 note_id 放进查询字符串,得到列表而不是单条笔记",
  265. "cause": "GET /notes?note_id=12 匹配的是 GET /notes。本课列表路由没有声明 note_id,FastAPI 默认忽略这个额外查询参数,因此返回 200 和列表;它不会匹配 /notes/{note_id}。",
  266. "fix": "读取单条笔记时改为 GET /notes/12。先检查方法和路径,再检查查询参数;只有确实没有匹配路由或资源不存在时才会得到相应的 404。"
  267. },
  268. {
  269. "symptom": "写了 title: str | None 后,省略 title 仍然报错",
  270. "cause": "允许 null 和允许省略是两个条件。",
  271. "fix": "如果业务允许省略,显式写默认值 = None;本例 title 应保持必填字符串。"
  272. },
  273. {
  274. "symptom": "修改 POST /notes 后响应还像上一课",
  275. "cause": "旧路由没有移除,重复注册了相同方法和路径。",
  276. "fix": "搜索 @app.post('/notes'),只保留当前一个定义,保存并确认服务完成重载。"
  277. }
  278. ],
  279. "exercise": {
  280. "task": "为 GET /notes 添加 offset 查询参数,默认 0,只允许非负整数,并把解析结果加进响应。验证 offset=3 与 offset=-1。",
  281. "hint": "参考 limit 的 Annotated[int, Query(...)],使用 ge=0。",
  282. "answer": "在函数参数中加入 offset: Annotated[int, Query(ge=0)] = 0,并在返回字典中加入 'offset': offset。?offset=3 返回 200 且 offset 为 3;?offset=-1 返回 422,loc 包含 query、offset。"
  283. },
  284. "refs": [
  285. {
  286. "label": "FastAPI:路径参数",
  287. "url": "https://fastapi.tiangolo.com/tutorial/path-params/"
  288. },
  289. {
  290. "label": "FastAPI:查询参数",
  291. "url": "https://fastapi.tiangolo.com/tutorial/query-params/"
  292. },
  293. {
  294. "label": "FastAPI:请求体",
  295. "url": "https://fastapi.tiangolo.com/tutorial/body/"
  296. }
  297. ]
  298. },
  299. {
  300. "id": "04",
  301. "group": "起步与 HTTP",
  302. "title": "用 Pydantic 定义输入和输出契约",
  303. "summary": "限制标题长度、拒绝拼错的字段,并通过 response_model 控制客户端能看到的数据。",
  304. "objectives": [
  305. "用 Field 声明范围,用 extra='forbid' 发现字段拼写错误",
  306. "分开定义创建输入与接口输出模型",
  307. "区分请求校验失败与响应校验失败"
  308. ],
  309. "concepts": [
  310. {
  311. "title": "模型把接口规则放到一起",
  312. "body": "类型描述数据形状,Field 描述长度或数值约束。本例 title 的长度为 1 到 120。extra='forbid' 会拒绝模型中未声明的字段,能及时发现 pinnd 这样的拼写错误;Pydantic 默认会忽略多余字段,因此需要显式配置。"
  313. },
  314. {
  315. "title": "输入模型与输出模型承担不同职责",
  316. "body": "创建时客户端只提交 title、content、pinned;id 由服务端产生。NoteOut 在输入字段之外增加 id。response_model 会校验并筛选普通返回数据,未声明的内部字段不会进入响应;这也会出现在 /docs 的响应结构中。"
  317. },
  318. {
  319. "title": "校验成功不代表全部业务规则成立",
  320. "body": "长度为 1 的字符串可能只是一个空格,类型与长度规则不会自动决定标题是否有意义。输入校验失败通常返回 422;如果路由返回的数据不符合输出模型,例如漏掉 id,则属于服务端代码错误,默认返回 500,并在终端记录具体原因。"
  321. }
  322. ],
  323. "steps": [
  324. {
  325. "title": "收紧 NoteCreate 的输入规则",
  326. "body": "用下面定义替换原来的 NoteCreate,放在路由之前。保留其余路由。随后在 /docs 中分别发送空标题和拼错的 pinnd 字段,确认都得到 422。",
  327. "filename": "main.py",
  328. "lang": "python",
  329. "code": "from pydantic import BaseModel, ConfigDict, Field\n\nclass NoteCreate(BaseModel):\n model_config = ConfigDict(extra=\"forbid\")\n\n title: str = Field(min_length=1, max_length=120)\n content: str = \"\"\n pinned: bool = False"
  330. },
  331. {
  332. "title": "增加响应模型",
  333. "body": "在 NoteCreate 后添加 NoteOut。输出字段单独声明,避免把输入的 extra='forbid' 规则带入本节的输出过滤实验。id 在输出里必填;客户端创建时不能自行指定 id。",
  334. "filename": "main.py",
  335. "lang": "python",
  336. "code": "class NoteOut(BaseModel):\n id: int\n title: str\n content: str\n pinned: bool"
  337. },
  338. {
  339. "title": "用 response_model 约束 POST 响应",
  340. "body": "替换 POST /notes 的装饰器和函数。本节的 id=1 仍是演示值,下一阶段才生成真实编号。返回字典故意增加 internal_source,查看 HTTP 响应时该字段应被过滤。",
  341. "filename": "main.py",
  342. "lang": "python",
  343. "code": "@app.post(\"/notes\", response_model=NoteOut)\ndef inspect_note_body(note: NoteCreate):\n return {\n \"id\": 1,\n **note.model_dump(),\n \"internal_source\": \"validation-lesson\",\n }"
  344. },
  345. {
  346. "title": "分别制造输入与输出错误",
  347. "body": "先发送下面的空标题请求,确认 422 的错误位置包含 body、title。再临时删除返回字典中的 id,发送正常请求,观察 500 和终端中的响应校验异常。恢复 id 后再继续;不要把服务端输出错误改成客户端的 422。",
  348. "lang": "json",
  349. "code": "{\n \"title\": \"\",\n \"content\": \"title must not be empty\",\n \"pinned\": false\n}"
  350. },
  351. {
  352. "title": "检查文档中的契约",
  353. "body": "刷新 /docs。展开 POST /notes 的 Schema,检查 title 的 minLength、maxLength,以及 NoteOut 的 id。发送 {\"title\":\"schema check\"} 后应返回下面四个字段。保存一份响应作为后续 CRUD 的验收样本。",
  354. "lang": "json",
  355. "code": "{\n \"id\": 1,\n \"title\": \"schema check\",\n \"content\": \"\",\n \"pinned\": false\n}"
  356. }
  357. ],
  358. "checks": [
  359. "空 title 或额外 pinnd 字段均返回 422。",
  360. "正常创建演示返回 id、title、content、pinned 四个字段,不包含 internal_source。",
  361. "故意漏掉输出 id 时出现 500;恢复后为 200,当前尚未设置创建成功的 201。"
  362. ],
  363. "pitfalls": [
  364. {
  365. "symptom": "空格标题通过了 min_length=1",
  366. "cause": "空格也是字符串字符,长度校验不执行去空格。",
  367. "fix": "根据业务要求加入 strip_whitespace 或字段校验器,去空格后再检查是否为空。"
  368. },
  369. {
  370. "symptom": "response_model 没有过滤某个自定义响应",
  371. "cause": "直接返回 JSONResponse 等 Response 对象时,框架不会按普通返回值继续执行响应模型转换。",
  372. "fix": "本节返回字典或模型对象,让 FastAPI 使用 response_model 处理。"
  373. },
  374. {
  375. "symptom": "把模型直接拼到字典时提示类型不匹配",
  376. "cause": "Pydantic 模型对象不等于普通字典。",
  377. "fix": "需要字典时调用 note.model_dump();不要使用旧教材中的 .dict() 作为本模块标准写法。"
  378. }
  379. ],
  380. "exercise": {
  381. "task": "拒绝只有空白的标题,并将 ' first note ' 保存为 'first note'。保持 120 字符上限。",
  382. "hint": "为 title 添加 mode='before' 的 field_validator,先去除字符串两端空白,再交给 Field 长度校验。",
  383. "answer": "从 pydantic 导入 field_validator,在 NoteCreate 内添加:\n@field_validator('title', mode='before')\n@classmethod\ndef strip_title(cls, value):\n return value.strip() if isinstance(value, str) else value\n\n只含空格会变为空字符串并返回 422;' first note ' 经解析后为 'first note'。"
  384. },
  385. "refs": [
  386. {
  387. "label": "Pydantic:Field 与字段约束",
  388. "url": "https://docs.pydantic.dev/latest/concepts/fields/"
  389. },
  390. {
  391. "label": "Pydantic:验证器",
  392. "url": "https://docs.pydantic.dev/latest/concepts/validators/"
  393. },
  394. {
  395. "label": "FastAPI:响应模型",
  396. "url": "https://fastapi.tiangolo.com/tutorial/response-model/"
  397. }
  398. ]
  399. },
  400. {
  401. "id": "05",
  402. "group": "REST 接口",
  403. "title": "设计笔记资源与 HTTP 行为",
  404. "summary": "确定集合、单条资源、全量替换和删除的接口约定,再用请求验证方法与状态码。",
  405. "objectives": [
  406. "用资源路径表达笔记集合和单条笔记",
  407. "区分 POST、PUT、PATCH、DELETE 的语义",
  408. "解释 200、201、204、404、405、422 与幂等性"
  409. ],
  410. "concepts": [
  411. {
  412. "title": "先确定资源,再确定操作",
  413. "body": "本项目使用 /notes 表示笔记集合,/notes/{note_id} 表示一条笔记。读取用 GET,创建用 POST,完整替换用 PUT,删除用 DELETE。方法和路径共同确定接口,因此 GET /notes 与 POST /notes 可以共用路径。"
  414. },
  415. {
  416. "title": "PUT 的完整替换需要明确输入规则",
  417. "body": "本课程的 PUT 要求 title、content、pinned 全部出现,替换指定笔记可编辑字段,id 保持不变。PATCH 通常表达局部更新,本模块暂不实现。若把创建模型直接用于 PUT,省略 content 会触发默认空字符串,容易被误认为保留旧值。"
  418. },
  419. {
  420. "title": "幂等描述重复请求后的目标状态",
  421. "body": "重复相同 PUT,目标笔记应保持相同内容;重复 DELETE,目标笔记都处于不存在状态,第一次可以返回 204,第二次可以返回 404。幂等不要求每次响应完全相同。POST 创建通常每次产生新资源,不能假设自动重复发送不会多建一条。"
  422. },
  423. {
  424. "title": "状态码也是接口契约",
  425. "body": "读取与更新成功使用 200,创建成功使用 201,删除成功且无响应体使用 204。找不到资源使用 404,路径存在但方法不支持使用 405,输入校验失败使用 422。4xx、5xx 响应不能只靠 JSON 业务字段表达,HTTP 状态也必须正确。"
  426. }
  427. ],
  428. "steps": [
  429. {
  430. "title": "写下接口清单",
  431. "body": "以下是第 06 课要实现的目标契约。当前服务还处于参数练习阶段,不应把回显结果视为已保存。先在纸上或请求文件中列出方法、路径、输入和成功状态,后续逐项实现。",
  432. "filename": "notes-contract.http",
  433. "lang": "http",
  434. "code": "GET /notes # 查询集合,200,响应为数组\nPOST /notes # 创建,201,响应包含新 id\nGET /notes/{note_id} # 查询单条,200 或 404\nPUT /notes/{note_id} # 完整替换,200 或 404\nDELETE /notes/{note_id} # 删除,204 或 404"
  435. },
  436. {
  437. "title": "用已有服务区分 404 与 405",
  438. "body": "在 /docs 执行 GET /health,应返回 200。然后命令行发送 POST /health,应返回 405,并检查 Allow 响应头;再 GET /missing-path,应返回 404。Windows 将下面 curl 改为 curl.exe。这两类错误都与 JSON 字段校验无关。",
  439. "lang": "bash",
  440. "code": "curl -i http://127.0.0.1:8000/health\ncurl -i -X POST http://127.0.0.1:8000/health\ncurl -i http://127.0.0.1:8000/missing-path"
  441. },
  442. {
  443. "title": "为完整替换定义独立输入",
  444. "body": "在 main.py 的模型区添加 NoteReplace。三个字段均无默认值,确保调用方明确提交完整内容。在 Python 终端或单独脚本中使用下面示例验证;此时只定义模型,尚未注册 PUT 路由。",
  445. "filename": "main.py",
  446. "lang": "python",
  447. "code": "class NoteReplace(BaseModel):\n model_config = ConfigDict(extra=\"forbid\")\n\n title: str = Field(min_length=1, max_length=120)\n content: str\n pinned: bool\n\n# 在独立 Python 终端中测试:\n# from main import NoteReplace\n# NoteReplace(title=\"updated\", content=\"\", pinned=False) # 通过\n# NoteReplace(title=\"updated\") # ValidationError:缺少两项"
  448. },
  449. {
  450. "title": "准备替换与删除的验收请求",
  451. "body": "把完整请求体保存为 replace.json。下一课先创建一条笔记,记录真实 id,再执行两次同样 PUT 和两次 DELETE。不要写死假定 id 永远为 1;服务重载会影响当前内存。204 响应后不要继续解析 JSON。",
  452. "filename": "replace.json",
  453. "lang": "json",
  454. "code": "{\n \"title\": \"updated note\",\n \"content\": \"replace all editable fields\",\n \"pinned\": true\n}"
  455. }
  456. ],
  457. "checks": [
  458. "GET /health 是 200;POST /health 是 405;不存在的路径是 404。",
  459. "NoteReplace 缺少 content 或 pinned 时验证失败,空 content 和 false 本身都合法。",
  460. "能解释 DELETE 第二次返回 404 仍然满足幂等,以及 204 为什么不能带 {\"ok\":true}。"
  461. ],
  462. "pitfalls": [
  463. {
  464. "symptom": "PUT 请求只传 title,意外把 content 清空",
  465. "cause": "复用了带默认值的创建模型,未明确全量替换规则。",
  466. "fix": "使用所有可编辑字段均必填的 NoteReplace;如果需要局部更新,应另行设计 PATCH。"
  467. },
  468. {
  469. "symptom": "客户端对成功 DELETE 调用 response.json() 后报错",
  470. "cause": "204 响应没有响应体。",
  471. "fix": "先判断状态码;遇到 204 直接按成功处理,不执行 JSON 解码。"
  472. },
  473. {
  474. "symptom": "网络超时后重复 POST,出现两条笔记",
  475. "cause": "客户端没收到响应,并不等于服务器没创建资源。",
  476. "fix": "本地实验先查询列表核对;生产创建接口需根据业务设计幂等键等重复提交控制,不能直接假定 POST 可安全重试。"
  477. }
  478. ],
  479. "exercise": {
  480. "task": "评审三个接口:GET /delete-note?id=1、PUT /notes/1 只接收 pinned、DELETE /notes/1 返回 200 和 {\"deleted\":true}。给出本课程约定下的修改方案,并说明第三种设计是否违反 HTTP。",
  481. "hint": "分清 HTTP 协议允许的行为与课程选择的统一接口约定。",
  482. "answer": "第一种改为 DELETE /notes/1,GET 不用于用户请求的数据删除。第二种若只做局部修改应定义 PATCH,或者要求 PUT 传齐 title/content/pinned。第三种返回 200 和结果体在 HTTP 中可以成立;本课程统一选择 204 空体,因此需同时调整状态码和响应内容。"
  483. },
  484. "refs": [
  485. {
  486. "label": "RFC 9110:请求方法",
  487. "url": "https://www.rfc-editor.org/rfc/rfc9110.html#section-9"
  488. },
  489. {
  490. "label": "RFC 9110:204 No Content",
  491. "url": "https://www.rfc-editor.org/rfc/rfc9110.html#section-15.3.5"
  492. },
  493. {
  494. "label": "FastAPI:更新请求体",
  495. "url": "https://fastapi.tiangolo.com/tutorial/body-updates/"
  496. }
  497. ]
  498. },
  499. {
  500. "id": "06",
  501. "group": "REST 接口",
  502. "title": "完成内存版笔记 CRUD",
  503. "summary": "把接口契约变成可运行程序,按创建、查询、替换、删除的顺序完成一次完整操作。",
  504. "objectives": [
  505. "用字典保存笔记并生成不重复的进程内编号",
  506. "实现带校验与响应模型的笔记 REST 接口",
  507. "按真实创建结果串联后续请求并验证失败路径"
  508. ],
  509. "concepts": [
  510. {
  511. "title": "请求之间需要共享状态",
  512. "body": "局部变量在函数调用结束后不用于保存下一次请求的数据。这里用模块级 notes 字典,键为整数 id,值为笔记字段。它只存在于当前 Python 进程内;重启、重载都会清空,多个 worker 也不会共享这份字典。"
  513. },
  514. {
  515. "title": "编号与列表位置不是同一个概念",
  516. "body": "使用单独递增的 next_id 分配编号,删除笔记后不回退。不能用 len(notes)+1 生成 id,否则删掉中间一条后可能复用仍存在的编号。客户端应从创建响应读取 id,再构造单条资源路径。"
  517. },
  518. {
  519. "title": "演示存储的运行条件",
  520. "body": "本节路由使用 async def,内部没有 await,字典读写在一次事件循环执行段中完成。以单个 Uvicorn worker 运行本地实验;不要在更新共享状态的中间加入等待操作。异步函数与等待的细节将在后面的并发课程中单独演示。"
  521. }
  522. ],
  523. "steps": [
  524. {
  525. "title": "重建 main.py 的公共部分",
  526. "body": "先备份前几课的实验文件,再将 main.py 替换为本步骤代码,并按顺序追加第 2、3、4 步。不要同时保留临时回显路由。全部代码完成后再启动;本节不含 /version 等附加练习接口。",
  527. "filename": "main.py",
  528. "lang": "python",
  529. "code": "from typing import Annotated\n\nfrom fastapi import FastAPI, HTTPException, Query, Response\nfrom pydantic import BaseModel, ConfigDict, Field\n\napp = FastAPI(title=\"API Lab\")\n\nclass NoteCreate(BaseModel):\n model_config = ConfigDict(extra=\"forbid\")\n title: str = Field(min_length=1, max_length=120)\n content: str = \"\"\n pinned: bool = False\n\nclass NoteReplace(BaseModel):\n model_config = ConfigDict(extra=\"forbid\")\n title: str = Field(min_length=1, max_length=120)\n content: str\n pinned: bool\n\nclass NoteOut(BaseModel):\n id: int\n title: str\n content: str\n pinned: bool\n\nnotes: dict[int, dict] = {}\nnext_id = 1\n\n@app.get(\"/health\", tags=[\"system\"])\nasync def health():\n return {\"status\": \"ok\"}"
  530. },
  531. {
  532. "title": "实现列表与创建",
  533. "body": "追加两个集合路由。pinned is not None 保证 false 也会触发筛选。创建成功后返回 201,并通过 Location 响应头给出新资源路径。next_id 在当前进程递增,保存时写入所有输入字段。",
  534. "filename": "main.py",
  535. "lang": "python",
  536. "code": "@app.get(\"/notes\", response_model=list[NoteOut], tags=[\"notes\"])\nasync def list_notes(\n limit: Annotated[int, Query(ge=1, le=100)] = 10,\n pinned: bool | None = None,\n):\n rows = list(notes.values())\n if pinned is not None:\n rows = [row for row in rows if row[\"pinned\"] == pinned]\n return rows[:limit]\n\n@app.post(\"/notes\", response_model=NoteOut, status_code=201, tags=[\"notes\"])\nasync def create_note(note: NoteCreate, response: Response):\n global next_id\n note_id = next_id\n next_id += 1\n row = {\"id\": note_id, **note.model_dump()}\n notes[note_id] = row\n response.headers[\"Location\"] = f\"/notes/{note_id}\"\n return row"
  537. },
  538. {
  539. "title": "实现单条读取与全量替换",
  540. "body": "先定义统一查找函数。不存在时 raise HTTPException 会立即中断本次请求,下一课再统一其错误格式。PUT 创建全新的字段字典并保留路径 id,不把旧 content 或 pinned 合并进去。",
  541. "filename": "main.py",
  542. "lang": "python",
  543. "code": "def require_note(note_id: int) -> dict:\n if note_id not in notes:\n raise HTTPException(status_code=404, detail=\"笔记不存在\")\n return notes[note_id]\n\n@app.get(\"/notes/{note_id}\", response_model=NoteOut, tags=[\"notes\"])\nasync def get_note(note_id: int):\n return require_note(note_id)\n\n@app.put(\"/notes/{note_id}\", response_model=NoteOut, tags=[\"notes\"])\nasync def replace_note(note_id: int, note: NoteReplace):\n require_note(note_id)\n row = {\"id\": note_id, **note.model_dump()}\n notes[note_id] = row\n return row"
  544. },
  545. {
  546. "title": "实现无响应体的删除",
  547. "body": "删除前先检查是否存在;返回 Response(status_code=204) 明确表示空响应。全部代码写好后运行 python -m uvicorn main:app --reload,打开 /docs,确认一个健康检查加五个笔记操作,共六个路由方法。",
  548. "filename": "main.py",
  549. "lang": "python",
  550. "code": "@app.delete(\"/notes/{note_id}\", status_code=204, tags=[\"notes\"])\nasync def delete_note(note_id: int):\n require_note(note_id)\n del notes[note_id]\n return Response(status_code=204)"
  551. },
  552. {
  553. "title": "按顺序完成一轮 CRUD",
  554. "body": "使用 /docs:先 GET /notes 确認 [];POST 下列对象并记下实际 id;GET /notes/{id};PUT 提交 title='updated'、content=''、pinned=true;再 GET 确认内容已替换;DELETE 后再次 GET,确认 404。操作过程中不要修改代码触发重载。最后重新创建一条,检查编号没有因删除而回退。",
  555. "lang": "json",
  556. "code": "{\n \"title\": \"first CRUD\",\n \"content\": \"create, read, replace, delete\",\n \"pinned\": false\n}"
  557. }
  558. ],
  559. "checks": [
  560. "空列表返回 200 和 [];创建返回 201,响应含整数 id,Location 指向 /notes/{id}。",
  561. "PUT 传齐字段时返回 200,id 保持不变;仅传 title 时返回 422。",
  562. "删除返回 204 且响应体为空;再 GET 或 DELETE 相同 id 均返回 404。",
  563. "创建两条并删除其中一条后,再创建不会覆盖另一条;服务重启后列表重新为空。"
  564. ],
  565. "pitfalls": [
  566. {
  567. "symptom": "保存代码后刚创建的笔记找不到了",
  568. "cause": "--reload 重启了服务进程,内存字典被重新初始化。",
  569. "fix": "完成代码编辑后重新准备数据;验证一轮 CRUD 时不要中途保存服务端文件。"
  570. },
  571. {
  572. "symptom": "筛选 pinned=false 返回全部数据",
  573. "cause": "使用 if pinned 判断是否筛选,False 被当成未提供条件。",
  574. "fix": "使用 if pinned is not None,再比较字段的布尔值。"
  575. },
  576. {
  577. "symptom": "删除一条后,新笔记覆盖了旧笔记",
  578. "cause": "用 len(notes)+1 计算编号导致重复。",
  579. "fix": "独立维护递增 next_id,不因删除回退;本地练习保持单进程运行。"
  580. }
  581. ],
  582. "exercise": {
  583. "task": "在列表接口加入 offset>=0,先按 pinned 筛选,再返回 rows[offset:offset+limit]。创建三条笔记,第二条和第三条设为 pinned=true,验证 pinned=true&offset=1&limit=1 只返回第三条。",
  584. "hint": "分页应该作用在筛选后的结果上;把切片放在筛选后,limit 和 offset 均添加参数约束。",
  585. "answer": "添加 offset: Annotated[int, Query(ge=0)] = 0;保持 pinned 筛选顺序;把 return rows[:limit] 改为 return rows[offset:offset + limit]。按题目创建顺序,返回数组长度为 1,元素为第三条笔记;offset=-1 返回 422。"
  586. },
  587. "refs": [
  588. {
  589. "label": "FastAPI:响应状态码",
  590. "url": "https://fastapi.tiangolo.com/tutorial/response-status-code/"
  591. },
  592. {
  593. "label": "FastAPI:直接返回 Response",
  594. "url": "https://fastapi.tiangolo.com/advanced/response-directly/"
  595. },
  596. {
  597. "label": "FastAPI:处理错误",
  598. "url": "https://fastapi.tiangolo.com/tutorial/handling-errors/"
  599. }
  600. ]
  601. },
  602. {
  603. "id": "07",
  604. "group": "REST 接口",
  605. "title": "返回可定位、格式一致的错误",
  606. "summary": "用 HTTPException 表达已知失败,统一 404、405 与 422 的响应结构,并保留字段位置。",
  607. "objectives": [
  608. "在业务失败时抛出 HTTPException",
  609. "为 HTTPException 和 RequestValidationError 注册处理器",
  610. "保持 HTTP 状态码,同时返回稳定的错误结构"
  611. ],
  612. "concepts": [
  613. {
  614. "title": "已知失败应在对应位置结束请求",
  615. "body": "查不到笔记是可以预期的业务结果,用 raise HTTPException(status_code=404, detail='笔记不存在') 结束当前处理。return HTTPException(...) 只是在返回一个对象,不能表达相同控制流程。未知编程错误需要修复,不能一律包装成 200。"
  616. },
  617. {
  618. "title": "统一外层结构,保留不同错误的细节",
  619. "body": "本项目约定 {error:{code,message,details}}。HTTP 错误使用 code='http_error';请求校验使用 code='validation_error'。HTTP 状态码仍保留 404、405、422 等差异。details 中只返回定位所需的字段路径、错误类型和说明,不回显整个请求体。"
  620. },
  621. {
  622. "title": "校验失败可能发生在路由执行之前",
  623. "body": "参数解析失败会抛出 RequestValidationError,不会进入路由里的 try/except。因此在应用级处理器统一处理。注册 Starlette 的 HTTPException 基类还能覆盖路由不存在和方法不支持等框架错误;处理时保留 Allow 等原有响应头。"
  624. }
  625. ],
  626. "steps": [
  627. {
  628. "title": "确认已有业务错误入口",
  629. "body": "保留第 06 课代码,找到 require_note。确认它使用 raise 而非 return。请求一个不存在的 id,此时默认响应通常为 {\"detail\":\"笔记不存在\"},接下来统一其外层结构。",
  630. "filename": "main.py",
  631. "lang": "python",
  632. "code": "def require_note(note_id: int) -> dict:\n if note_id not in notes:\n raise HTTPException(status_code=404, detail=\"笔记不存在\")\n return notes[note_id]"
  633. },
  634. {
  635. "title": "统一 HTTP 错误处理",
  636. "body": "在 main.py 中添加导入与处理器。这里演示业务 detail 为字符串;若后续传入字典,应单独约定字段映射,不把任意内部对象直接返回。保留 exc.headers,确保例如 405 的 Allow 头仍然存在。",
  637. "filename": "main.py",
  638. "lang": "python",
  639. "code": "from fastapi import Request\nfrom fastapi.responses import JSONResponse\nfrom starlette.exceptions import HTTPException as StarletteHTTPException\n\n@app.exception_handler(StarletteHTTPException)\nasync def handle_http_error(request: Request, exc: StarletteHTTPException):\n return JSONResponse(\n status_code=exc.status_code,\n headers=exc.headers,\n content={\n \"error\": {\n \"code\": \"http_error\",\n \"message\": str(exc.detail),\n \"details\": [],\n }\n },\n )"
  640. },
  641. {
  642. "title": "统一 422 并保留字段位置",
  643. "body": "添加请求校验处理器。不要直接把 exc.errors() 中的所有对象交给 JSON 序列化;自定义校验器的 ctx 可能包含异常对象。这里只提取 JSON 可序列化的 loc、type、msg,也避免在响应中回显原始输入。",
  644. "filename": "main.py",
  645. "lang": "python",
  646. "code": "from fastapi.exceptions import RequestValidationError\n\n@app.exception_handler(RequestValidationError)\nasync def handle_validation_error(request: Request, exc: RequestValidationError):\n details = [\n {\n \"loc\": list(error[\"loc\"]),\n \"type\": error[\"type\"],\n \"msg\": error[\"msg\"],\n }\n for error in exc.errors()\n ]\n return JSONResponse(\n status_code=422,\n content={\n \"error\": {\n \"code\": \"validation_error\",\n \"message\": \"请求参数不符合接口要求\",\n \"details\": details,\n }\n },\n )"
  647. },
  648. {
  649. "title": "用三类失败验证处理器",
  650. "body": "先 GET /notes/999999,确认 404 且 error.code='http_error'。再 GET /notes/abc 和 POST /notes 的空对象,确认 422;前者定位 path.note_id,后者定位 body.title。最后 POST /health,检查 405、http_error 以及 Allow 头。具体英文 msg 可能随依赖版本变化,客户端不要解析这段文本作业务判断。",
  651. "lang": "json",
  652. "code": "{\n \"error\": {\n \"code\": \"validation_error\",\n \"message\": \"请求参数不符合接口要求\",\n \"details\": [\n {\n \"loc\": [\"body\", \"title\"],\n \"type\": \"missing\",\n \"msg\": \"Field required\"\n }\n ]\n }\n}"
  653. }
  654. ],
  655. "checks": [
  656. "不存在的笔记返回 404、http_error 和“笔记不存在”。",
  657. "非法 note_id 与缺失 title 都返回 422、validation_error,details.loc 能指出不同位置。",
  658. "POST /health 仍返回 405,Allow 响应头被保留。",
  659. "成功的笔记响应不被包在 error 字段中;204 删除仍然没有响应体。"
  660. ],
  661. "pitfalls": [
  662. {
  663. "symptom": "错误响应有 message,但 HTTP 状态一直是 200",
  664. "cause": "只返回了错误字典,没有设置 JSONResponse 的 status_code。",
  665. "fix": "在异常处理器中显式设置对应状态,HTTP 错误使用 exc.status_code。"
  666. },
  667. {
  668. "symptom": "注册 HTTPException 处理器后,未知路径仍是默认格式",
  669. "cause": "只处理 FastAPI 的异常子类,没有覆盖框架抛出的 Starlette 基类异常。",
  670. "fix": "导入并为 StarletteHTTPException 注册处理器,路由仍可抛出 FastAPI 的 HTTPException。"
  671. },
  672. {
  673. "symptom": "自定义标题校验失败后出现 JSON 序列化异常",
  674. "cause": "把 exc.errors() 的 ctx 异常对象直接放进 JSONResponse。",
  675. "fix": "只提取 loc、type、msg 等必要字段,不直接返回任意异常对象或原始请求内容。"
  676. }
  677. ],
  678. "exercise": {
  679. "task": "对 GET /notes?limit=0、GET /notes/abc、POST /notes 的 {} 逐一记录 status、error.code 和第一条 details.loc,写出客户端应如何定位表单或请求参数错误。",
  680. "hint": "三次都是 422,但错误位置的来源不同:query、path、body。",
  681. "answer": "三次 status 都是 422,code 都是 validation_error。loc 分别为 ['query','limit']、['path','note_id']、['body','title']。客户端先按 status/code 判断错误类别,再用 loc 映射对应输入位置;msg 用于显示,不作为稳定的判断条件。"
  682. },
  683. "refs": [
  684. {
  685. "label": "FastAPI:覆盖异常处理器",
  686. "url": "https://fastapi.tiangolo.com/tutorial/handling-errors/"
  687. },
  688. {
  689. "label": "Starlette:Exceptions",
  690. "url": "https://github.com/Kludex/starlette/blob/main/docs/exceptions.md"
  691. },
  692. {
  693. "label": "Pydantic:错误处理",
  694. "url": "https://docs.pydantic.dev/latest/errors/errors/"
  695. }
  696. ]
  697. },
  698. {
  699. "id": "08",
  700. "group": "REST 接口",
  701. "title": "复用依赖与拆分路由文件",
  702. "summary": "用 X-API-Key 练习依赖执行顺序,把 /private 放入独立 APIRouter,并通过环境变量配置课堂密钥。",
  703. "objectives": [
  704. "用 Depends 在路由执行前完成可复用校验",
  705. "从请求头读取 X-API-Key,从环境变量读取预期值",
  706. "用 APIRouter 拆分文件并注册到同一个应用"
  707. ],
  708. "concepts": [
  709. {
  710. "title": "Depends 声明请求处理的前置步骤",
  711. "body": "FastAPI 收到请求后先解析依赖需要的参数,执行依赖函数,再进入路由。依赖抛出 HTTPException 时,路由不会执行。同一套校验可以挂在多个接口或整个 APIRouter 上,避免每个路由重复读取请求头。"
  712. },
  713. {
  714. "title": "Header 与查询参数的来源不同",
  715. "body": "x_api_key: str 这种普通参数默认会作为查询参数。使用 Header(alias='X-API-Key') 才从请求头读取。这里给缺失值默认 None,再由依赖统一返回课堂约定的 401;缺少请求头不会先变成默认必填参数的 422。401 响应携带 WWW-Authenticate: APIKey,说明本实验使用的凭据类型。"
  716. },
  717. {
  718. "title": "配置值与身份系统分开理解",
  719. "body": "DEMO_API_KEY 从启动终端的环境变量读取,网页教程中的 classroom-key 仅用于本地实验。这个共享字符串只演示请求校验,不能区分用户,也没有密钥轮换或权限管理。本节只保护 /private,公开的笔记接口用于本地练习。"
  720. },
  721. {
  722. "title": "APIRouter 负责组织,不会自动启动服务",
  723. "body": "独立文件创建 router 并注册其路由,主入口再 app.include_router(router)。依赖模块不导入 main,避免循环导入。多个文件最终仍组成同一个 FastAPI 应用,共享第 07 课注册的异常处理器。"
  724. }
  725. ],
  726. "steps": [
  727. {
  728. "title": "建立依赖函数文件",
  729. "body": "在 api-lab 根目录新增 dependencies.py,不修改前面的笔记接口。用 secrets.compare_digest 比较字符串。未配置环境变量返回 503,缺失或错误请求头返回 401,这两种失败帮助区分服务配置和调用参数。",
  730. "filename": "dependencies.py",
  731. "lang": "python",
  732. "code": "import os\nimport secrets\nfrom typing import Annotated\n\nfrom fastapi import Header, HTTPException\n\ndef require_demo_key(\n x_api_key: Annotated[str | None, Header(alias=\"X-API-Key\")] = None,\n) -> None:\n expected = os.getenv(\"DEMO_API_KEY\")\n if not expected:\n raise HTTPException(status_code=503, detail=\"服务未配置 DEMO_API_KEY\")\n if x_api_key is None or not secrets.compare_digest(\n x_api_key.encode(\"utf-8\"), expected.encode(\"utf-8\")\n ):\n raise HTTPException(\n status_code=401,\n detail=\"X-API-Key 无效\",\n headers={\"WWW-Authenticate\": \"APIKey\"},\n )"
  733. },
  734. {
  735. "title": "创建独立的私有路由",
  736. "body": "新增 routers 目录,其中创建空的 __init__.py 和下面的 private.py。把依赖挂在 APIRouter 上,当前文件中的接口都会执行相同校验。装饰器使用 @router.get,路径保持 /private。",
  737. "filename": "routers/private.py",
  738. "lang": "python",
  739. "code": "from fastapi import APIRouter, Depends\n\nfrom dependencies import require_demo_key\n\nrouter = APIRouter(\n tags=[\"private\"],\n dependencies=[Depends(require_demo_key)],\n)\n\n@router.get(\"/private\")\ndef read_private():\n return {\"message\": \"API key accepted\"}"
  740. },
  741. {
  742. "title": "在主入口注册 router",
  743. "body": "在 main.py 导入路由模块,并在 app 创建之后调用 include_router。保留原有 /health、笔记路由和两个异常处理器。刷新 /docs,确认出现 private 分组及 X-API-Key 参数;如果没有出现,先检查是否真正注册。",
  744. "filename": "main.py",
  745. "lang": "python",
  746. "code": "from routers import private\n\n# 放在 app = FastAPI(...) 之后\napp.include_router(private.router)\n\n# 目录结构\n# api-lab/\n# main.py\n# dependencies.py\n# routers/\n# __init__.py\n# private.py"
  747. },
  748. {
  749. "title": "设置当前终端环境并重新启动",
  750. "body": "先 Ctrl+C 停止旧服务,在同一个终端按系统选择一组命令。新启动的进程继承该终端环境;在另一窗口设置变量不会修改正在运行的服务。classroom-key 是公开教学校验值。",
  751. "lang": "bash",
  752. "code": "# Windows PowerShell\n$env:DEMO_API_KEY = \"classroom-key\"\npython -m uvicorn main:app --reload\n\n# macOS / Linux\nexport DEMO_API_KEY=\"classroom-key\"\npython -m uvicorn main:app --reload"
  753. },
  754. {
  755. "title": "验证缺失、错误与正确密钥",
  756. "body": "在 /docs 连续执行 GET /private:不填写头部、填写 wrong-key、填写 classroom-key。前两次返回 401,第三次返回 200。第 07 课错误处理器会把失败转换为统一 error 对象。再访问 /notes,确认该本地练习接口未要求密钥。",
  757. "lang": "bash",
  758. "code": "# macOS / Linux;Windows PowerShell 使用 curl.exe\ncurl -i http://127.0.0.1:8000/private\ncurl -i http://127.0.0.1:8000/private -H \"X-API-Key: wrong-key\"\ncurl -i http://127.0.0.1:8000/private -H \"X-API-Key: classroom-key\""
  759. }
  760. ],
  761. "checks": [
  762. "/docs 显示 /private 和 X-API-Key 请求头输入项。",
  763. "配置环境变量后,缺失或错误密钥返回 401 和 http_error;正确密钥返回 200 和 {\"message\":\"API key accepted\"}。",
  764. "未设置 DEMO_API_KEY 的新服务进程返回 503,而不会因为请求头与配置都为空而通过。",
  765. "拆分文件后 /health、原有笔记 CRUD 与错误结构仍然可用。"
  766. ],
  767. "pitfalls": [
  768. {
  769. "symptom": "已在客户端写 X-API-Key,却显示密钥无效",
  770. "cause": "服务读取的头部来源声明不正确,或者客户端把值放到了查询字符串。",
  771. "fix": "依赖明确使用 Header(alias='X-API-Key');在 Network 或 curl 输出中核对 Request Headers。"
  772. },
  773. {
  774. "symptom": "环境变量已设置,接口仍返回 503",
  775. "cause": "变量设置在另一个终端,或者旧服务进程没有重启。",
  776. "fix": "在设置变量的同一个终端停止并重启 Uvicorn。"
  777. },
  778. {
  779. "symptom": "新增 private.py 后 /private 返回 404",
  780. "cause": "只创建了 router,没有在主 app 上 include_router,或启动时目录不正确。",
  781. "fix": "确认 main.py 注册 private.router,并从 api-lab 根目录启动 main:app。"
  782. }
  783. ],
  784. "exercise": {
  785. "task": "在 routers/private.py 中新增 GET /private/status,返回 {\"enabled\":true}。复用 router 上的依赖,分别验证无头部与正确头部。再说明为什么这仍不能判断是哪位学生发出的请求。",
  786. "hint": "只添加 @router.get('/private/status') 的函数,不必复制校验代码。",
  787. "answer": "添加:\n@router.get('/private/status')\ndef private_status():\n return {'enabled': True}\n\n无 X-API-Key 返回 401;classroom-key 返回 200 和 {'enabled':true}。两个接口自动复用 router 依赖。所有人使用同一公开密钥,服务只能判断是否匹配,无法识别具体用户。"
  788. },
  789. "refs": [
  790. {
  791. "label": "FastAPI:依赖注入",
  792. "url": "https://fastapi.tiangolo.com/tutorial/dependencies/"
  793. },
  794. {
  795. "label": "FastAPI:Header 参数",
  796. "url": "https://fastapi.tiangolo.com/tutorial/header-params/"
  797. },
  798. {
  799. "label": "FastAPI:多文件应用",
  800. "url": "https://fastapi.tiangolo.com/tutorial/bigger-applications/"
  801. },
  802. {
  803. "label": "Python:compare_digest",
  804. "url": "https://docs.python.org/3/library/secrets.html#secrets.compare_digest"
  805. }
  806. ]
  807. },
  808. {
  809. "id": "09",
  810. "group": "异步与调用",
  811. "title": "使用 async / await 处理 I/O 等待",
  812. "summary": "用两个并发请求复现阻塞,掌握 async / await 在接口中的实际作用。",
  813. "objectives": [
  814. "写出不阻塞事件循环的 /slow 接口",
  815. "测量串行与并发请求的耗时差异",
  816. "判断同步 I/O 应改用异步客户端,还是移交线程"
  817. ],
  818. "concepts": [
  819. {
  820. "title": "async def 定义协程函数",
  821. "body": "调用后得到可等待对象;await 等待结果,并在操作尚未完成时让出执行机会。仅给函数添加 async 不会把内部的阻塞代码变为异步。"
  822. },
  823. {
  824. "title": "等待与计算分开判断",
  825. "body": "网络响应、磁盘访问属于 I/O;大量 Python 计算属于 CPU 工作。异步可以交错等待,本课不通过 async 加速计算,也不在接口里引入后台任务队列。"
  826. },
  827. {
  828. "title": "FastAPI 的执行位置",
  829. "body": "FastAPI 调用普通 def 路由时使用线程池;async def 路由在事件循环中执行。你在 async def 内直接调用普通辅助函数时,FastAPI 不会自动把辅助函数移到线程。"
  830. }
  831. ],
  832. "steps": [
  833. {
  834. "title": "增加一个可测量的等待接口",
  835. "body": "开始前,在已激活的虚拟环境中运行 python -m pip install \"httpx>=0.27,<1\",第 09 节的客户端脚本会导入它。下载包的 requirements.txt 已包含此依赖。\n\n在 api-lab 的应用中加入路由。delay 限制在 0–5 秒,避免误输很大数值;运行单个服务进程进行本课实验。",
  836. "code": "import asyncio\nfrom fastapi import Query\n\n@app.get(\"/slow\")\nasync def slow(delay: float = Query(default=1, ge=0, le=5)):\n await asyncio.sleep(delay)\n return {\"delay\": delay}",
  837. "lang": "python",
  838. "filename": "main.py"
  839. },
  840. {
  841. "title": "同时发出两次请求",
  842. "body": "新建脚本,保持服务已启动后执行 python concurrent_check.py。先建立一个客户端,再让两次请求同时等待;打印状态码和总耗时。页面演示是浏览器模拟,真实耗时以此脚本为准。",
  843. "code": "import asyncio\nfrom time import perf_counter\nimport httpx\n\nasync def main():\n async with httpx.AsyncClient(base_url=\"http://127.0.0.1:8000\") as client:\n started = perf_counter()\n results = await asyncio.gather(\n client.get(\"/slow\", params={\"delay\": 1}),\n client.get(\"/slow\", params={\"delay\": 1}),\n )\n print([r.status_code for r in results])\n print(f\"elapsed={perf_counter() - started:.2f}s\")\n\nasyncio.run(main())",
  844. "lang": "python",
  845. "filename": "concurrent_check.py"
  846. },
  847. {
  848. "title": "复现阻塞,再恢复",
  849. "body": "暂时把 await asyncio.sleep(delay) 换成 time.sleep(delay),并 import time。保存后等服务完成重载,再运行相同脚本。单进程时两次等待通常接近 2 秒;恢复 async sleep 后通常接近 1 秒。另开终端访问 /health,观察阻塞时它也要等待。结果会受机器和调度开销影响,不以毫秒误差判断对错。",
  850. "code": "curl.exe \"http://127.0.0.1:8000/health\"",
  851. "lang": "bash"
  852. },
  853. {
  854. "title": "为无法替换的同步 I/O 选择线程",
  855. "body": "优先使用库提供的异步方法;若必须在 async def 路由中调用同步 I/O,用 asyncio.to_thread。此处 slow_sync 用 sleep 模拟同步 I/O,实际替换为该库的函数;线程不是本课 CPU 计算加速方案。",
  856. "code": "import time\n\ndef slow_sync(delay: float):\n time.sleep(delay)\n return {\"delay\": delay}\n\n# 放在 async def 路由内:\n# result = await asyncio.to_thread(slow_sync, delay)\n# return result",
  857. "lang": "python"
  858. }
  859. ],
  860. "checks": [
  861. "异步版本两个 delay=1 请求均返回 200,总耗时通常接近 1 秒。",
  862. "阻塞版本在单进程下耗时明显增加,恢复后 /health 不再等待 slow 的 sleep 结束。",
  863. "/slow?delay=-1 与 /slow?delay=6 都返回 422。"
  864. ],
  865. "pitfalls": [
  866. {
  867. "symptom": "写了 async def,其他请求仍卡住",
  868. "cause": "路由内使用 time.sleep、同步 HTTP 客户端或长时间计算,占住事件循环。",
  869. "fix": "定位耗时调用;I/O 改用 await 支持的 API,必要时把同步 I/O 放到线程。"
  870. },
  871. {
  872. "symptom": "两次 await 请求仍耗时约 2 秒",
  873. "cause": "先 await 第一次,再创建第二次,代码仍是串行等待。",
  874. "fix": "用 asyncio.gather 同时调度两个请求,再比较结果。"
  875. },
  876. {
  877. "symptom": "出现 coroutine was never awaited",
  878. "cause": "调用异步函数但没有 await,也没有交给任务调度。",
  879. "fix": "在 async 函数内 await 结果;脚本最外层用 asyncio.run(main())。"
  880. }
  881. ],
  882. "exercise": {
  883. "task": "把脚本改成同时请求 3 个 delay=1 的 /slow,再增加一次 /health,记录总耗时及各状态码。",
  884. "hint": "把第三个 /slow 和 /health 一并放进 gather;不要依次 await。",
  885. "answer": "四个请求应全部返回 200。使用非阻塞等待时,总耗时通常仍接近最长的一次等待,即约 1 秒;若接近 3 秒,先检查服务是否恢复了 asyncio.sleep。"
  886. },
  887. "refs": [
  888. {
  889. "label": "FastAPI:并发与 async / await",
  890. "url": "https://fastapi.tiangolo.com/async/"
  891. },
  892. {
  893. "label": "Python:协程、gather 与 to_thread",
  894. "url": "https://docs.python.org/3/library/asyncio-task.html"
  895. }
  896. ],
  897. "demo": "async"
  898. },
  899. {
  900. "id": "10",
  901. "group": "异步与调用",
  902. "title": "使用 HTTPX 调用服务与调试 CORS",
  903. "summary": "复用 HTTPX 客户端,处理超时与上游错误,并定位浏览器跨域问题。",
  904. "objectives": [
  905. "在应用生命周期中创建和关闭 AsyncClient",
  906. "区分超时、连接失败和非成功状态码",
  907. "说明为什么 curl 正常而浏览器请求失败"
  908. ],
  909. "concepts": [
  910. {
  911. "title": "一次请求有两个方向",
  912. "body": "浏览器到 FastAPI 是入站请求;FastAPI 到另一个服务是出站请求。调用失败时,先确定错误发生在哪一段。"
  913. },
  914. {
  915. "title": "客户端与连接池",
  916. "body": "AsyncClient 可以复用连接。应用启动时创建,退出时关闭;不要在每次高频请求内重新创建客户端。connect、read、write、pool 是不同阶段的超时,read 通常是等待下一块数据的上限,不是请求总时限。"
  917. },
  918. {
  919. "title": "CORS 由浏览器检查",
  920. "body": "Origin 由协议、主机和端口组成。http://localhost:5500 与 http://127.0.0.1:5500 是两个来源;curl 和服务端 HTTPX 不执行浏览器的 CORS 检查。CORS 也不替代 API 认证。"
  921. }
  922. ],
  923. "steps": [
  924. {
  925. "title": "把客户端交给 lifespan 管理",
  926. "body": "安装 httpx。把现有 FastAPI() 初始化改为使用 lifespan;若应用已有 lifespan,把下面的客户端管理合并进去,不要再创建第二个 app。上游使用本机已完成的 /slow,让超时实验不依赖公网。",
  927. "code": "from contextlib import asynccontextmanager\nimport httpx\nfrom fastapi import FastAPI\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n timeout = httpx.Timeout(3.0, connect=1.0)\n async with httpx.AsyncClient(\n base_url=\"http://127.0.0.1:8000\", timeout=timeout\n ) as client:\n app.state.http = client\n yield\n\napp = FastAPI(lifespan=lifespan)",
  928. "lang": "python",
  929. "filename": "main.py"
  930. },
  931. {
  932. "title": "把出站失败转换为可判断的响应",
  933. "body": "增加 /upstream-demo。默认 delay=1 会成功,delay=4 超过 read 超时。这里调用本机接口只是本地实验;正式业务中使用服务方的固定地址,避免让用户任意指定出站 URL。raise_for_status 会把非 2xx 响应转为 HTTPStatusError。",
  934. "code": "from fastapi import HTTPException, Query, Request\n\n@app.get(\"/upstream-demo\")\nasync def upstream_demo(\n request: Request,\n delay: float = Query(default=1, ge=0, le=5),\n):\n try:\n response = await request.app.state.http.get(\n \"/slow\", params={\"delay\": delay}\n )\n response.raise_for_status()\n return {\"upstream\": response.json()}\n except httpx.TimeoutException as exc:\n raise HTTPException(504, \"上游响应超时\") from exc\n except httpx.HTTPStatusError as exc:\n raise HTTPException(502, \"上游返回非成功状态\") from exc\n except httpx.RequestError as exc:\n raise HTTPException(502, \"无法连接上游服务\") from exc",
  935. "lang": "python",
  936. "filename": "main.py"
  937. },
  938. {
  939. "title": "在两个页面来源之间复现 CORS",
  940. "body": "API 保持运行在 8000 端口。把下面中间件加入现有 app;已有 CORSMiddleware 时修改原配置,不要重复添加。本实验只允许 http://127.0.0.1:5500。如果使用下载的参考项目,先暂时从 allow_origins 中移除 http://localhost:5500,才能复现后面来源不匹配的情况。",
  941. "code": "from fastapi.middleware.cors import CORSMiddleware\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"http://127.0.0.1:5500\"],\n allow_credentials=False,\n allow_methods=[\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n allow_headers=[\"Content-Type\", \"X-API-Key\"],\n)",
  942. "lang": "python",
  943. "filename": "main.py"
  944. },
  945. {
  946. "title": "建立前端页面并从 5500 访问 API",
  947. "body": "在 api-lab 中新建 cors-demo.html,粘贴下面内容。另开一个终端,在 api-lab 目录执行 python -m http.server 5500,保留 API 的 8000 终端。打开 http://127.0.0.1:5500/cors-demo.html 并点击按钮,在 Network 中观察 OPTIONS 预检和 POST;JSON 的 Content-Type 会触发本次跨域预检。再通过 http://localhost:5500/cors-demo.html 打开同一文件,对照来源不匹配时的浏览器错误。此时简单的 GET /health 不一定产生 OPTIONS。",
  948. "code": "<!doctype html>\n<html lang=\"zh-CN\">\n<meta charset=\"utf-8\">\n<title>CORS 实验</title>\n<button id=\"send\">向 API 创建笔记</button>\n<pre id=\"result\"></pre>\n<script>\ndocument.querySelector(\"#send\").onclick = async () => {\n const output = document.querySelector(\"#result\");\n try {\n const response = await fetch(\"http://127.0.0.1:8000/notes\", {\n method: \"POST\",\n headers: {\"Content-Type\": \"application/json\"},\n body: JSON.stringify({title: \"CORS 实验\"}),\n });\n output.textContent = response.status + \"\\n\" + await response.text();\n } catch (error) {\n output.textContent = \"浏览器未能读取响应;检查 Network 和 Console:\" + error.message;\n }\n};\n</script>\n</html>",
  949. "lang": "html",
  950. "filename": "cors-demo.html"
  951. },
  952. {
  953. "title": "读预检请求和响应头",
  954. "body": "在浏览器 Network 面板查看 Origin、OPTIONS 和 Access-Control-Allow-Origin。curl.exe 可手动查看预检响应,但它不会替浏览器决定是否允许页面读取响应。把来源改为 localhost:5500 后复现不匹配,再恢复准确来源。 macOS / Linux 把 curl.exe 改为 curl。实验完成后,如需同时使用两个前端域名,再把 localhost:5500 加回白名单。",
  955. "code": "curl.exe -i -X OPTIONS \"http://127.0.0.1:8000/notes\" -H \"Origin: http://127.0.0.1:5500\" -H \"Access-Control-Request-Method: POST\" -H \"Access-Control-Request-Headers: content-type\"\ncurl.exe -i \"http://127.0.0.1:8000/upstream-demo?delay=4\"",
  956. "lang": "bash"
  957. }
  958. ],
  959. "checks": [
  960. "/upstream-demo?delay=1 返回 200,包含上游的 delay 字段。",
  961. "/upstream-demo?delay=4 返回 504;把上游地址临时改为未监听端口可观察 502,随后恢复。",
  962. "允许来源的预检响应包含 Access-Control-Allow-Origin: http://127.0.0.1:5500,浏览器可以读取响应。"
  963. ],
  964. "pitfalls": [
  965. {
  966. "symptom": "上游返回 404,接口却继续执行正常处理",
  967. "cause": "HTTP 请求收到响应不等于业务成功,代码没有检查状态。",
  968. "fix": "调用 raise_for_status 并单独处理 HTTPStatusError。"
  969. },
  970. {
  971. "symptom": "curl 成功,网页报 CORS 错误",
  972. "cause": "浏览器页面来源与 allow_origins 不匹配,或预检方法、请求头未被允许。",
  973. "fix": "逐项核对 Origin、方法和自定义请求头,再看浏览器 Network 中的 OPTIONS 响应。"
  974. },
  975. {
  976. "symptom": "用 timeout=3 就以为整个请求最多 3 秒",
  977. "cause": "把阶段性超时误认为总请求截止时间,流式响应每次及时发送数据时可能持续更久。",
  978. "fix": "先明确要限制连接、块间等待还是总耗时;本课实验只验证读超时。"
  979. }
  980. ],
  981. "exercise": {
  982. "task": "让 /upstream-demo 在等待超过 0.2 秒时返回 504,同时保持直接访问 /slow?delay=1 能正常返回。",
  983. "hint": "只覆盖 client.get 的 timeout 参数,保留异步 /slow。",
  984. "answer": "给该次请求设置 timeout=httpx.Timeout(0.2, connect=1.0)。请求 /upstream-demo?delay=1 会在等待上游数据时触发超时;直接请求 /slow?delay=1 仍约 1 秒后返回 200。"
  985. },
  986. "refs": [
  987. {
  988. "label": "HTTPX:异步客户端",
  989. "url": "https://www.python-httpx.org/async/"
  990. },
  991. {
  992. "label": "HTTPX:超时阶段",
  993. "url": "https://www.python-httpx.org/advanced/timeouts/"
  994. },
  995. {
  996. "label": "HTTPX:状态码与异常",
  997. "url": "https://www.python-httpx.org/quickstart/"
  998. },
  999. {
  1000. "label": "FastAPI:lifespan",
  1001. "url": "https://fastapi.tiangolo.com/advanced/events/"
  1002. },
  1003. {
  1004. "label": "FastAPI:CORS",
  1005. "url": "https://fastapi.tiangolo.com/tutorial/cors/"
  1006. }
  1007. ]
  1008. },
  1009. {
  1010. "id": "11",
  1011. "group": "流式与实时通信",
  1012. "title": "完整响应、流式响应、SSE 与 WebSocket",
  1013. "summary": "从通信方向与消息格式选择接口形态,用同一份文本比较接收过程。",
  1014. "objectives": [
  1015. "分清 REST 风格、HTTP 响应方式和 WebSocket 协议",
  1016. "根据发送方向与数据频率选择实现",
  1017. "观察首段到达时间与全部完成时间"
  1018. ],
  1019. "concepts": [
  1020. {
  1021. "title": "REST 不规定必须一次返回全部数据",
  1022. "body": "REST 主要讨论资源及 HTTP 操作方式。普通 JSON 响应先得到完整结果再返回;HTTP 流式响应逐段发送同一个响应体。流式发送不自动定义每段的业务含义。"
  1023. },
  1024. {
  1025. "title": "SSE 为文本流定义事件边界",
  1026. "body": "SSE 在 HTTP 响应体中使用 text/event-stream,以空行分隔事件。连接内数据由服务端推向客户端;浏览器可用 EventSource 解析。SSE 是 HTTP 流式响应的一种约定。"
  1027. },
  1028. {
  1029. "title": "WebSocket 保持双向通信",
  1030. "body": "连接建立后,双方可以独立发送消息,不必每条消息新建 HTTP 请求。业务仍需定义消息类型、结束、错误与连接关闭后的行为。"
  1031. }
  1032. ],
  1033. "steps": [
  1034. {
  1035. "title": "先跑一次完整结果接口",
  1036. "body": "用延时代表逐步产生内容,POST /generate 等待全部内容完成后返回一个 JSON 对象。PromptIn 限制长度,本课使用固定文本拼接,便于观察协议而不引入模型服务。",
  1037. "code": "import asyncio\nfrom pydantic import BaseModel, Field\n\nclass PromptIn(BaseModel):\n prompt: str = Field(min_length=1, max_length=200)\n\n@app.post(\"/generate\")\nasync def generate(payload: PromptIn):\n parts = []\n for text in [\"收到:\", payload.prompt, \"。处理完成。\"]:\n await asyncio.sleep(0.4)\n parts.append(text)\n return {\"text\": \"\".join(parts)}",
  1038. "lang": "python",
  1039. "filename": "main.py"
  1040. },
  1041. {
  1042. "title": "记录完整响应的等待",
  1043. "body": "在 /docs 对 POST /generate 输入下面 JSON。结果约在所有步骤完成后出现。区分响应头到达与可用业务内容到达;观察何时收到第一段内容。",
  1044. "code": "{\"prompt\":\"hello\"}",
  1045. "lang": "json"
  1046. },
  1047. {
  1048. "title": "对照三条连接过程",
  1049. "body": "在本页协议演示中依次选择完整 HTTP、SSE、WebSocket:完整响应在完成后显示文本;SSE 逐条显示 token 事件;WebSocket 可在连接保持期间发送新消息。此交互是浏览器模拟;第 12–15 课会用 api-lab 进行真实收发验证。"
  1050. },
  1051. {
  1052. "title": "把场景写成协议选择题",
  1053. "body": "保存笔记通常使用 HTTP 的 POST /notes;一段处理结果要边产生边显示,可使用 HTTP 流式响应,文本事件采用 SSE;前后端要频繁互发消息,可使用 WebSocket。若只需偶尔查询状态,也可以定期 HTTP 查询,不需要先维护长连接。"
  1054. }
  1055. ],
  1056. "checks": [
  1057. "能说清 SSE 使用 HTTP,且不是 WebSocket 的别名。",
  1058. "/generate 返回单个 {text:...} 对象;不会在每个步骤结束时返回一个新 HTTP 响应。",
  1059. "能为保存笔记、逐步显示文本、双向实时消息分别选择方案并说明原因。"
  1060. ],
  1061. "pitfalls": [
  1062. {
  1063. "symptom": "为了逐字显示文字,直接把所有接口都改成 WebSocket",
  1064. "cause": "把流式接收和双向消息通信混为一谈。",
  1065. "fix": "先确定客户端是否需要在同一条连接上持续主动发送;单向文本结果通常先考虑 HTTP 流式响应。"
  1066. },
  1067. {
  1068. "symptom": "把服务器 yield 的次数当成客户端 read 的次数",
  1069. "cause": "网络、服务器和浏览器可能合并或拆开数据块。",
  1070. "fix": "依赖协议的事件分隔符解析消息,不依赖网络块边界。"
  1071. }
  1072. ],
  1073. "exercise": {
  1074. "task": "用户提交一次短文本后只接收生成结果,偶尔点击“停止”。是否必须使用 WebSocket?",
  1075. "hint": "思考取消 HTTP 请求是否已经满足停止读取的需要。",
  1076. "answer": "不必须。可以提交 HTTP 请求并读取流式响应,通过取消请求停止读取;服务端同时处理断开并释放资源。如果还需要在同一会话持续双向发送独立消息,再评估 WebSocket。"
  1077. },
  1078. "refs": [
  1079. {
  1080. "label": "FastAPI:StreamingResponse",
  1081. "url": "https://fastapi.tiangolo.com/advanced/custom-response/"
  1082. },
  1083. {
  1084. "label": "MDN:SSE 事件流",
  1085. "url": "https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events"
  1086. },
  1087. {
  1088. "label": "FastAPI:WebSocket",
  1089. "url": "https://fastapi.tiangolo.com/advanced/websockets/"
  1090. }
  1091. ],
  1092. "demo": "protocol"
  1093. },
  1094. {
  1095. "id": "12",
  1096. "group": "流式与实时通信",
  1097. "title": "用 StreamingResponse 输出 SSE 事件",
  1098. "summary": "实现有限长度文本流,定义 token / done 事件,并处理客户端断开。",
  1099. "objectives": [
  1100. "用异步生成器逐段发送 text/event-stream",
  1101. "使用 JSON 编码 data 字段并保留空行边界",
  1102. "区分正常完成、连接断开和流内错误"
  1103. ],
  1104. "concepts": [
  1105. {
  1106. "title": "yield 交出一段响应体",
  1107. "body": "异步生成器可在产生下一段数据前 await。StreamingResponse 消费生成器并发送响应体;生成器必须有明确的正常结束条件。"
  1108. },
  1109. {
  1110. "title": "消息格式属于双方约定",
  1111. "body": "本课每个 token 事件的 data 是 {text:...},最后发送 done 事件且 data 为 {}。JSON 编码处理引号和换行,空行负责分隔事件。不能直接把任意用户输入拼接成 SSE 行。"
  1112. },
  1113. {
  1114. "title": "响应开始后不能改写 HTTP 状态",
  1115. "body": "参数验证应在开始流式响应前完成。发送响应头后若处理中断,应通过约定的流内错误事件或连接结束通知客户端;不能再把已经开始的 200 改成 500。"
  1116. }
  1117. ],
  1118. "steps": [
  1119. {
  1120. "title": "定义一处统一的事件编码",
  1121. "body": "把事件名限制为代码中定义的固定值;用 json.dumps 编码数据。返回字符串末尾是两个换行字符,即一个空行。ensure_ascii=False 保留中文可读性。",
  1122. "code": "import json\n\ndef encode_sse(event: str, data: dict) -> str:\n payload = json.dumps(data, ensure_ascii=False)\n return f\"event: {event}\\ndata: {payload}\\n\\n\"",
  1123. "lang": "python",
  1124. "filename": "main.py"
  1125. },
  1126. {
  1127. "title": "产生有限长度 token 流",
  1128. "body": "每隔约 0.4 秒发送一个 token,完成后发 done。使用 finally 观察连接关闭后的清理路径;真实上游迭代器、文件等资源应在这里或上下文管理器内关闭。不要吞掉取消异常。",
  1129. "code": "import asyncio\nfrom fastapi import Request\n\nasync def token_events(request: Request, prompt: str):\n try:\n for text in [\"收到:\", prompt, \"。处理完成。\"]:\n await asyncio.sleep(0.4)\n if await request.is_disconnected():\n return\n yield encode_sse(\"token\", {\"text\": text})\n yield encode_sse(\"done\", {})\n finally:\n print(\"stream closed\")",
  1130. "lang": "python",
  1131. "filename": "main.py"
  1132. },
  1133. {
  1134. "title": "在 /stream 返回 StreamingResponse",
  1135. "body": "GET 查询参数适合 EventSource 演示;不要在 URL 中传密钥或敏感正文。prompt 先经过长度验证,再进入生成器。已有相同路由时替换定义,避免重复注册。",
  1136. "code": "from fastapi import Query\nfrom fastapi.responses import StreamingResponse\n\n@app.get(\"/stream\")\nasync def stream(\n request: Request,\n prompt: str = Query(default=\"hello\", min_length=1, max_length=200),\n):\n return StreamingResponse(\n token_events(request, prompt),\n media_type=\"text/event-stream\",\n headers={\"Cache-Control\": \"no-cache\"},\n )",
  1137. "lang": "python",
  1138. "filename": "main.py"
  1139. },
  1140. {
  1141. "title": "从终端逐段观察,再主动取消",
  1142. "body": "使用 curl.exe 的 -N 禁用它自己的输出缓冲。应先后看到三条 token 与一条 done,每条后有空行。第二次请求在生成中按 Ctrl+C,服务端最终应打印 stream closed;断开通常通过取消路径或断开检查被观察到。",
  1143. "code": "curl.exe -N -i \"http://127.0.0.1:8000/stream?prompt=hello\"",
  1144. "lang": "bash"
  1145. },
  1146. {
  1147. "title": "核对线上实际字节格式",
  1148. "body": "以下是事件体格式展示,其中空行是协议的一部分。data 内的 JSON 字符串若有换行,应由 JSON 编码为转义序列,不能破坏事件边界。",
  1149. "code": "event: token\ndata: {\"text\": \"hello\"}\n\nevent: done\ndata: {}\n\n",
  1150. "lang": "http"
  1151. }
  1152. ],
  1153. "checks": [
  1154. "响应 Content-Type 以 text/event-stream 开头;终端能在流结束前看到 token。",
  1155. "正常结束只有一个 done,三个 token 的 text 拼接后与 /generate 的 text 相同。",
  1156. "prompt 为空返回 422;请求中途取消后清理日志出现,服务仍能处理 /health。"
  1157. ],
  1158. "pitfalls": [
  1159. {
  1160. "symptom": "客户端一直等不到事件回调",
  1161. "cause": "发送了 data 行却漏了事件末尾的空行。",
  1162. "fix": "每条事件统一通过 encode_sse 编码,并确认末尾为 \\n\\n。"
  1163. },
  1164. {
  1165. "symptom": "输入含换行后事件解析失败",
  1166. "cause": "手工拼接 JSON 或把原始输入直接放进 data 行。",
  1167. "fix": "先 json.dumps,再写入 SSE data 字段。"
  1168. },
  1169. {
  1170. "symptom": "断开后仍持续执行,或者没有清理资源",
  1171. "cause": "无限循环未处理断开、没有 await 让取消生效,或遗漏 finally 清理。",
  1172. "fix": "在迭代中检查断开,使用可等待的 I/O,并在 finally 中释放资源;保持本课生成器有限长度。"
  1173. }
  1174. ],
  1175. "exercise": {
  1176. "task": "在三个 token 后、done 前增加一个 stats 事件,返回 token_count:3;保持已有客户端仍能完成。",
  1177. "hint": "stats 是独立事件类型,不需要把它伪装成 token。",
  1178. "answer": "在 done 前增加 yield encode_sse(\"stats\", {\"token_count\": 3})。原客户端只监听 token 和 done 时会忽略 stats;新增监听器后可以显示统计值。"
  1179. },
  1180. "refs": [
  1181. {
  1182. "label": "FastAPI:自定义与流式响应",
  1183. "url": "https://fastapi.tiangolo.com/advanced/custom-response/"
  1184. },
  1185. {
  1186. "label": "MDN:SSE 消息格式",
  1187. "url": "https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events"
  1188. },
  1189. {
  1190. "label": "FastAPI:Request 类与断开检查",
  1191. "url": "https://fastapi.tiangolo.com/reference/request/"
  1192. }
  1193. ]
  1194. },
  1195. {
  1196. "id": "13",
  1197. "group": "流式与实时通信",
  1198. "title": "在浏览器中读取流,并在中途停止",
  1199. "summary": "分别使用 EventSource 与 fetch,处理 UTF-8 分块、事件边界和取消请求。",
  1200. "objectives": [
  1201. "用 EventSource 监听命名事件并主动关闭",
  1202. "用 ReadableStream 解析可能被拆开的 SSE 数据",
  1203. "通过 AbortController 停止请求并区分取消与错误"
  1204. ],
  1205. "concepts": [
  1206. {
  1207. "title": "EventSource 简单,但请求形态有限",
  1208. "body": "原生 EventSource 发起 GET 请求,自动解析 SSE 并具备重连行为;构造参数不能任意设置请求体和自定义请求头。收到本课有限流的 done 后应主动 close,防止结束后重新请求。"
  1209. },
  1210. {
  1211. "title": "fetch 能发送 POST,再读取响应流",
  1212. "body": "POST 请求不妨碍响应逐段返回。需要 JSON 请求体或自定义头时可用 fetch,但必须自己解析响应体。调用 response.json() 或 response.text() 会等到响应体读完。"
  1213. },
  1214. {
  1215. "title": "网络块不等于事件",
  1216. "body": "一个中文字符的 UTF-8 字节、一个 JSON 或空行都可能跨越两次 read;一次 read 也可能包含多条事件。先连续解码字节,再缓存文本并按事件边界提取。"
  1217. }
  1218. ],
  1219. "steps": [
  1220. {
  1221. "title": "先用 EventSource 接收命名事件",
  1222. "body": "打开本地 http://127.0.0.1:8000/docs,在开发者工具 Console 运行。URL 与页面同源,先排除 CORS 干扰。控制台应逐条输出文本,done 后主动关闭;本课把网络失败也关闭,避免自动重连重复执行。",
  1223. "code": "{\n const source = new EventSource(\"/stream?prompt=hello\");\n source.addEventListener(\"token\", (event) => {\n console.log(JSON.parse(event.data).text);\n });\n source.addEventListener(\"done\", () => {\n console.log(\"完成\");\n source.close();\n });\n source.onerror = () => {\n console.error(\"流连接失败,已停止\");\n source.close();\n };\n window.stopSse = () => source.close();\n}",
  1224. "lang": "javascript",
  1225. "filename": "浏览器 Console"
  1226. },
  1227. {
  1228. "title": "把事件解析与网络读取分开",
  1229. "body": "先在 Console 定义解析函数。它为本课 LF / CRLF 事件格式处理跨块与多条 data 行,且要求正常收到 done;不实现完整 EventSource 的 id、retry 与自动重连功能。TextDecoder 的 stream:true 会暂存未完整的 UTF-8 字节,最后再刷新。",
  1230. "code": "async function consumeSse(response, onEvent) {\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n if (!response.headers.get(\"content-type\")?.includes(\"text/event-stream\")) {\n throw new Error(\"响应不是 SSE\");\n }\n if (!response.body) throw new Error(\"没有响应体\");\n const reader = response.body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n let buffer = \"\";\n let completed = false;\n try {\n while (!completed) {\n const { value, done } = await reader.read();\n buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n let boundary;\n while ((boundary = /\\r?\\n\\r?\\n/.exec(buffer)) !== null) {\n const block = buffer.slice(0, boundary.index);\n buffer = buffer.slice(boundary.index + boundary[0].length);\n const lines = block.split(/\\r?\\n/);\n const name = lines.find(line => line.startsWith(\"event:\"))\n ?.slice(6).trim() || \"message\";\n const data = lines.filter(line => line.startsWith(\"data:\"))\n .map(line => line.slice(5).replace(/^ /, \"\")).join(\"\\n\");\n if (data) onEvent(name, JSON.parse(data));\n if (name === \"done\") { completed = true; break; }\n }\n if (done && !completed) throw new Error(\"连接结束,但没有收到 done\");\n }\n await reader.cancel();\n } catch (error) {\n await reader.cancel().catch(() => {});\n throw error;\n } finally {\n reader.releaseLock();\n }\n}",
  1231. "lang": "javascript",
  1232. "filename": "浏览器 Console"
  1233. },
  1234. {
  1235. "title": "用 fetch 读取同一个 GET 接口",
  1236. "body": "在同一 Console 定义 startStream,然后执行 startStream()。紧接着执行 stopStream() 可中途取消;AbortError 代表用户主动取消,不应显示为服务故障。新的请求使用新的 AbortController。",
  1237. "code": "async function startStream() {\n const controller = new AbortController();\n window.stopStream = () => controller.abort();\n try {\n const response = await fetch(\"/stream?prompt=hello\", {\n signal: controller.signal,\n });\n await consumeSse(response, (name, data) => {\n if (name === \"token\") console.log(data.text);\n if (name === \"done\") console.log(\"完成\");\n });\n } catch (error) {\n if (error.name === \"AbortError\") console.log(\"已取消\");\n else console.error(error);\n }\n}\nstartStream();",
  1238. "lang": "javascript",
  1239. "filename": "浏览器 Console"
  1240. },
  1241. {
  1242. "title": "扩展:需要 POST 请求体时",
  1243. "body": "先在 main.py 额外加入以下 POST /stream 路由,复用第 11 课 PromptIn 与第 12 课 token_events。然后把上一步 fetch 的 URL 改为 /stream,并在配置对象中加入 method:\"POST\"、headers:{\"Content-Type\":\"application/json\"}、body:JSON.stringify({prompt:\"hello\"});保留 signal。POST /generate 仍返回完整 JSON,不可拿它套用 SSE 解析函数。",
  1244. "code": "@app.post(\"/stream\")\nasync def stream_post(request: Request, payload: PromptIn):\n return StreamingResponse(\n token_events(request, payload.prompt),\n media_type=\"text/event-stream\",\n headers={\"Cache-Control\": \"no-cache\"},\n )",
  1245. "lang": "python",
  1246. "filename": "main.py"
  1247. },
  1248. {
  1249. "title": "核对流为什么没有逐段显示",
  1250. "body": "先用 curl.exe -N 直连本地 API。若本地逐段到达但页面一次出现,检查是否调用了 response.text/json,或渲染是否缓存了结果。若只有经过中间服务才一次出现,再检查中间服务的响应缓冲;本课只定位差异,具体代理配置留到部署模块。"
  1251. }
  1252. ],
  1253. "checks": [
  1254. "EventSource 收到三次 token 和一次 done 后关闭,不会周期性重新发起 /stream。",
  1255. "fetch 版本能正常显示中文;主动 stopStream 后输出“已取消”。",
  1256. "扩展 POST /stream 返回 SSE;POST /generate 仍返回 application/json。"
  1257. ],
  1258. "pitfalls": [
  1259. {
  1260. "symptom": "偶发 JSON.parse 错误,或中文出现替换字符",
  1261. "cause": "直接对每次 read 的内容解码和解析,忽略了字符、事件可能跨块。",
  1262. "fix": "保持同一 TextDecoder 并设置 stream:true,再缓存到完整空行边界后解析。"
  1263. },
  1264. {
  1265. "symptom": "一次成功结束后又出现同样文本",
  1266. "cause": "有限 SSE 结束后 EventSource 自动重连,客户端没有处理 done。",
  1267. "fix": "监听 done 调用 close;真实恢复能力需要单独定义,不默认重复执行。"
  1268. },
  1269. {
  1270. "symptom": "点击停止后仍把状态改成失败",
  1271. "cause": "把所有 fetch 异常都当成网络故障。",
  1272. "fix": "单独识别 AbortError,并同步把页面状态改为已取消。"
  1273. }
  1274. ],
  1275. "exercise": {
  1276. "task": "把一条包含“你好”的 SSE 消息拆成逐个字节的 ReadableStream,验证解析函数仍得到完整中文和 done。",
  1277. "hint": "用 TextEncoder 生成字节,再通过 Response 包装本地 ReadableStream;这只是解析器实验,不是 API 网络测试。",
  1278. "answer": "构造文本 'event: token\\ndata: {\"text\":\"你好\"}\\n\\nevent: done\\ndata: {}\\n\\n';对 TextEncoder().encode(text) 的每个字节调用 controller.enqueue(new Uint8Array([byte])),最后 close。用 new Response(stream,{headers:{\"Content-Type\":\"text/event-stream\"}}) 传入 consumeSse,回调应只收到完整 token 和 done。"
  1279. },
  1280. "refs": [
  1281. {
  1282. "label": "MDN:EventSource",
  1283. "url": "https://developer.mozilla.org/en-US/docs/Web/API/EventSource"
  1284. },
  1285. {
  1286. "label": "MDN:读取 ReadableStream",
  1287. "url": "https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams"
  1288. },
  1289. {
  1290. "label": "MDN:TextDecoder.decode",
  1291. "url": "https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder/decode"
  1292. },
  1293. {
  1294. "label": "MDN:AbortController",
  1295. "url": "https://developer.mozilla.org/en-US/docs/Web/API/AbortController"
  1296. }
  1297. ]
  1298. },
  1299. {
  1300. "id": "14",
  1301. "group": "流式与实时通信",
  1302. "title": "建立第一条 WebSocket 双向连接",
  1303. "summary": "实现 /ws 回显,观察建立、发送、接收和关闭的完整过程。",
  1304. "objectives": [
  1305. "使用 accept、receive_text 和 send_json 完成回显",
  1306. "在浏览器连接打开后发送消息",
  1307. "捕获断开并释放连接相关资源"
  1308. ],
  1309. "concepts": [
  1310. {
  1311. "title": "连接先建立,消息再发送",
  1312. "body": "服务端 accept 后进入收发阶段;浏览器 WebSocket 从 CONNECTING 转为 OPEN 后才能发送。send 只表示数据进入发送流程,不证明对方已经处理。"
  1313. },
  1314. {
  1315. "title": "一条连接,多条消息",
  1316. "body": "本课客户端发送文本,服务端回复 JSON。普通文本对应 type:echo;文本 ping 对应 type:pong。双方必须约定数据格式,不能把 HTTP 路由的返回值当作 WebSocket 消息发送。"
  1317. },
  1318. {
  1319. "title": "断开是正常生命周期",
  1320. "body": "用户关页、主动关闭和网络中断都可能结束连接。receive_text 在断开时会抛出 WebSocketDisconnect;在 finally 中清理该连接持有的资源。"
  1321. }
  1322. ],
  1323. "steps": [
  1324. {
  1325. "title": "在 main.py 插入 /ws 路由",
  1326. "body": "接受连接后循环读取消息。回复必须调用 send_json,而不是 return 一个字典。这个本地练习只接收文本消息,不实现用户身份或消息保存。",
  1327. "code": "from fastapi import WebSocket, WebSocketDisconnect\n\n@app.websocket(\"/ws\")\nasync def websocket_echo(websocket: WebSocket):\n await websocket.accept()\n try:\n while True:\n text = await websocket.receive_text()\n if text == \"ping\":\n await websocket.send_json({\"type\": \"pong\"})\n else:\n await websocket.send_json({\"type\": \"echo\", \"text\": text})\n except WebSocketDisconnect:\n pass\n finally:\n print(\"websocket closed\")",
  1328. "lang": "python",
  1329. "filename": "main.py"
  1330. },
  1331. {
  1332. "title": "从浏览器建立连接",
  1333. "body": "打开本地 http://127.0.0.1:8000/docs,在 Console 运行。代码把连接保留到 window.echoSocket,方便随后发送和关闭。open、message、close 的日志对应三个不同阶段。",
  1334. "code": "{\n const socket = new WebSocket(\"ws://127.0.0.1:8000/ws\");\n window.echoSocket = socket;\n socket.onopen = () => console.log(\"连接已打开\");\n socket.onmessage = event => console.log(\"收到\", JSON.parse(event.data));\n socket.onerror = () => console.error(\"连接发生错误\");\n socket.onclose = event => console.log(\"已关闭\", event.code, event.reason);\n}",
  1335. "lang": "javascript",
  1336. "filename": "浏览器 Console"
  1337. },
  1338. {
  1339. "title": "在 OPEN 状态发送两种消息",
  1340. "body": "等“连接已打开”出现后,执行下列代码。在 Network 面板选择 WS 请求并查看消息列表,区分客户端发出的原始文本与服务端返回的 JSON。WebSocket 请求不使用 /docs 的 HTTP Execute 按钮测试。",
  1341. "code": "if (echoSocket.readyState === WebSocket.OPEN) {\n echoSocket.send(\"hello\");\n echoSocket.send(\"ping\");\n}",
  1342. "lang": "javascript",
  1343. "filename": "浏览器 Console"
  1344. },
  1345. {
  1346. "title": "主动关闭并确认生命周期结束",
  1347. "body": "调用 close 后,浏览器输出关闭事件,服务端输出清理日志。关闭后不能复用旧 socket 继续发送;需要新建 WebSocket。重新连接并再发送一次 hello,确认服务仍可用。",
  1348. "code": "echoSocket.close(1000, \"lesson finished\");",
  1349. "lang": "javascript",
  1350. "filename": "浏览器 Console"
  1351. }
  1352. ],
  1353. "checks": [
  1354. "浏览器先收到 open,发送 hello 后收到 {type:'echo',text:'hello'}。",
  1355. "发送 ping 后收到 {type:'pong'};同一连接可重复收发。",
  1356. "主动关闭后收到 close,服务端清理日志出现,重新连接仍正常。"
  1357. ],
  1358. "pitfalls": [
  1359. {
  1360. "symptom": "调用 send 报连接尚未建立",
  1361. "cause": "new WebSocket 返回时握手仍在进行。",
  1362. "fix": "在 open 回调中发送,或先检查 readyState === WebSocket.OPEN。"
  1363. },
  1364. {
  1365. "symptom": "浏览器无任何回复,路由却 return 了字典",
  1366. "cause": "WebSocket 消息不会像 HTTP 响应一样自动序列化返回。",
  1367. "fix": "在连接内 await websocket.send_json(...)。"
  1368. },
  1369. {
  1370. "symptom": "把 WebSocket 地址粘到普通地址栏后得到 404",
  1371. "cause": "使用 HTTP GET 测试了 WebSocket 端点,没有进行 WebSocket 握手。",
  1372. "fix": "通过浏览器 WebSocket API 或支持 WS 的客户端测试,使用 ws:// 地址。"
  1373. }
  1374. ],
  1375. "exercise": {
  1376. "task": "增加一个文本命令 upper:hello,让服务端回复 {type:'upper',text:'HELLO'},其他消息保持回显。",
  1377. "hint": "把 startswith('upper:') 分支放在默认 echo 分支之前。",
  1378. "answer": "在 echo 的 else 之前加入 elif text.startswith(\"upper:\"): await websocket.send_json({\"type\":\"upper\",\"text\":text.removeprefix(\"upper:\").upper()})。浏览器收到的 JSON type 应为 upper。"
  1379. },
  1380. "refs": [
  1381. {
  1382. "label": "FastAPI:WebSocket 收发与断开",
  1383. "url": "https://fastapi.tiangolo.com/advanced/websockets/"
  1384. },
  1385. {
  1386. "label": "MDN:编写 WebSocket 客户端",
  1387. "url": "https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications"
  1388. }
  1389. ]
  1390. },
  1391. {
  1392. "id": "15",
  1393. "group": "流式与实时通信",
  1394. "title": "连接断开后:重连、心跳与取消",
  1395. "summary": "给 WebSocket 加上有限重试和定时器清理,验证停止后不会自行恢复。",
  1396. "objectives": [
  1397. "在异常关闭后用指数退避重新连接",
  1398. "通过应用层 ping / pong 检测连接是否仍可用",
  1399. "清理重连和心跳定时器,不自动重发未确认消息"
  1400. ],
  1401. "concepts": [
  1402. {
  1403. "title": "重连创建一条新连接",
  1404. "body": "新连接不会自动恢复旧连接内的执行状态,也不保证断开期间消息送达。本课不缓存、不重发业务消息;需要可靠恢复时,必须另行设计消息编号、确认和服务端去重。"
  1405. },
  1406. {
  1407. "title": "退避限制重试频率",
  1408. "body": "连续失败时逐渐延长等待,并加少量随机抖动,避免同时快速请求。设置最大次数;用户主动停止后取消待执行重连。"
  1409. },
  1410. {
  1411. "title": "心跳与页面状态",
  1412. "body": "这里的 ping 是普通文本消息,pong 是业务 JSON,属于应用层心跳。浏览器 WebSocket API 不提供主动发送协议级 Ping 帧的方法。计时器会受后台页面节流影响,超时阈值需要按场景调整。"
  1413. }
  1414. ],
  1415. "steps": [
  1416. {
  1417. "title": "先定义连接状态与定时器清理",
  1418. "body": "在本地 /docs 的 Console 按步骤运行。先关闭上一课 echoSocket,避免同时观察两条连接。下面状态只属于本次练习;刷新页面可重新开始。",
  1419. "code": "let wsSocket = null;\nlet retryTimer = null;\nlet heartbeatTimer = null;\nlet pongTimer = null;\nlet wsStopped = true;\nlet retryCount = 0;\n\nfunction clearHeartbeat() {\n clearInterval(heartbeatTimer);\n clearTimeout(pongTimer);\n heartbeatTimer = null;\n pongTimer = null;\n}",
  1420. "lang": "javascript",
  1421. "filename": "浏览器 Console"
  1422. },
  1423. {
  1424. "title": "加入应用层心跳",
  1425. "body": "每 5 秒发送一次 ping,3 秒内没有 pong 就关闭连接,让同一条关闭处理路径决定是否重连。收到 pong 时取消对应超时。这里只允许一个等待中的心跳。",
  1426. "code": "function startHeartbeat(socket) {\n clearHeartbeat();\n heartbeatTimer = setInterval(() => {\n if (socket.readyState !== WebSocket.OPEN) return;\n socket.send(\"ping\");\n pongTimer = setTimeout(() => {\n socket.close(4000, \"heartbeat timeout\");\n }, 3000);\n }, 5000);\n}",
  1427. "lang": "javascript",
  1428. "filename": "浏览器 Console"
  1429. },
  1430. {
  1431. "title": "把重连集中在 close 事件中",
  1432. "body": "首次失败约 0.5 秒后重连,随后约 1、2、4、8 秒,另加少量随机抖动;最多连续重试 5 次。error 只记录,避免 error 和 close 各重试一次。收到服务端有效消息后清零连续失败计数。",
  1433. "code": "function connectWs() {\n if (wsStopped) return;\n const socket = new WebSocket(\"ws://127.0.0.1:8000/ws\");\n wsSocket = socket;\n socket.onopen = () => {\n if (wsStopped || wsSocket !== socket) { socket.close(); return; }\n console.log(\"已连接\");\n startHeartbeat(socket);\n };\n socket.onmessage = event => {\n if (wsSocket !== socket) return;\n const message = JSON.parse(event.data);\n retryCount = 0;\n if (message.type === \"pong\") {\n clearTimeout(pongTimer);\n pongTimer = null;\n } else {\n console.log(\"收到\", message);\n }\n };\n socket.onerror = () => console.log(\"连接错误,等待 close\");\n socket.onclose = () => {\n if (wsSocket !== socket) return;\n clearHeartbeat();\n if (wsStopped) return;\n if (retryCount >= 5) {\n wsStopped = true;\n console.log(\"连续重试已达上限,请手动开始\");\n return;\n }\n const delay = Math.min(8000, 500 * 2 ** retryCount) + Math.random() * 200;\n retryCount += 1;\n console.log(`第 ${retryCount} 次重试,等待 ${Math.round(delay)}ms`);\n retryTimer = setTimeout(connectWs, delay);\n };\n}",
  1434. "lang": "javascript",
  1435. "filename": "浏览器 Console"
  1436. },
  1437. {
  1438. "title": "实现开始、发送与停止",
  1439. "body": "开始函数防止重复创建连接;发送函数在未连接时明确拒绝;停止函数先记录主动停止,再清理所有计时器和连接。stopWs 同时可供页面关闭时调用。",
  1440. "code": "function startWs() {\n if (!wsStopped) return;\n wsStopped = false;\n retryCount = 0;\n connectWs();\n}\nfunction sendWs(text) {\n if (wsSocket?.readyState !== WebSocket.OPEN) {\n console.log(\"尚未连接,本条消息未发送\");\n return;\n }\n wsSocket.send(text);\n}\nfunction stopWs() {\n wsStopped = true;\n clearTimeout(retryTimer);\n clearHeartbeat();\n wsSocket?.close(1000, \"user stopped\");\n wsSocket = null;\n console.log(\"已停止\");\n}\nwindow.addEventListener(\"pagehide\", stopWs);\nstartWs();",
  1441. "lang": "javascript",
  1442. "filename": "浏览器 Console"
  1443. },
  1444. {
  1445. "title": "执行三组失败实验",
  1446. "body": "正常连接后用 sendWs('hello') 验证回显。接着停止本地服务,观察逐渐延长的重试间隔,重启服务后确认新连接可收发。最后在下一次重试前调用 stopWs(),等待超过 9 秒,确认没有新建 WS 请求。断线期间尝试发送的消息不能在重连后自动出现。"
  1447. }
  1448. ],
  1449. "checks": [
  1450. "服务停止时重连间隔逐步增加,连续失败达到 5 次重试后停止。",
  1451. "服务恢复后能建立新连接并再次收到 echo,心跳 ping 对应 pong。",
  1452. "stopWs 后超过 9 秒没有新连接;未连接时调用 sendWs 不会排队重发。"
  1453. ],
  1454. "pitfalls": [
  1455. {
  1456. "symptom": "每次断线都会产生两条新连接",
  1457. "cause": "在 error 和 close 中分别启动重试,或开始按钮允许重复创建。",
  1458. "fix": "只在 close 调度重试;开始前检查当前是否已经运行。"
  1459. },
  1460. {
  1461. "symptom": "点停止后几秒钟又自动连上",
  1462. "cause": "只关闭 socket,没有取消已经安排的 setTimeout。",
  1463. "fix": "先设置主动停止标记,再清理重试、心跳和 pong 超时定时器。"
  1464. },
  1465. {
  1466. "symptom": "重连后重复执行了一条操作",
  1467. "cause": "客户端自动重发消息,但无法确定服务端在断开前是否已经执行。",
  1468. "fix": "本课不自动重发;需要重试业务操作时另行加入确认、操作编号与幂等处理。"
  1469. }
  1470. ],
  1471. "exercise": {
  1472. "task": "把连续重试上限改为 3 次,并验证用户手动 startWs() 后可以开始新一轮连接。",
  1473. "hint": "更改重试边界,保留达到上限时 wsStopped=true,以及开始时 retryCount=0。",
  1474. "answer": "把 if (retryCount >= 5) 改为 >= 3。连续失败后控制台打印到达上限;随后调用 startWs() 重置次数并重新连接,若服务已恢复即可继续回显。"
  1475. },
  1476. "refs": [
  1477. {
  1478. "label": "MDN:WebSocket 客户端生命周期",
  1479. "url": "https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications"
  1480. },
  1481. {
  1482. "label": "MDN:WebSocket.close",
  1483. "url": "https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close"
  1484. },
  1485. {
  1486. "label": "RFC 6455:异常关闭后的恢复建议",
  1487. "url": "https://www.rfc-editor.org/rfc/rfc6455#section-7.2.3"
  1488. }
  1489. ]
  1490. },
  1491. {
  1492. "id": "16",
  1493. "group": "联调与验收",
  1494. "title": "把能运行的接口变成可重复验收的服务",
  1495. "summary": "用 pytest 检查 CRUD、错误、认证、SSE 和 WebSocket,再完成一次真实浏览器联调。",
  1496. "objectives": [
  1497. "使用 TestClient 在测试中运行 FastAPI 应用",
  1498. "为正常路径和 401 / 404 / 422 写出明确断言",
  1499. "区分接口逻辑验收与真实网络流式验证"
  1500. ],
  1501. "concepts": [
  1502. {
  1503. "title": "断言检查可观察结果",
  1504. "body": "测试应检查状态码、响应字段与操作后结果,而不是只确认请求没报异常。每个测试创建自己的数据,通过返回 id 继续操作,避免假设某条笔记固定为 id=1。"
  1505. },
  1506. {
  1507. "title": "TestClient 不等同于浏览器",
  1508. "body": "TestClient 基于 HTTPX,可在进程内调用应用,不必先启动 Uvicorn。用 with 管理客户端才会执行 lifespan;它不验证浏览器 CORS,也不能证明真实网络按预期逐段到达。"
  1509. },
  1510. {
  1511. "title": "错误与正常结束分别验收",
  1512. "body": "422 验证输入约束;401 验证 /private 的 API Key;404 验证资源不存在。SSE 既检查事件数据,也检查 done;WebSocket 检查来回消息并关闭会话。"
  1513. }
  1514. ],
  1515. "steps": [
  1516. {
  1517. "title": "建立测试客户端",
  1518. "body": "在 api-lab 新建 tests/test_acceptance.py;以下第 1–4 步代码依次放入同一文件。先运行 python -m pip install pytest httpx。monkeypatch 只在测试期间设置演示 Key,测试结束自动恢复;导入入口为根目录 main.py。",
  1519. "code": "import json\nfrom uuid import uuid4\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom main import app\n\n@pytest.fixture\ndef client(monkeypatch):\n monkeypatch.setenv(\"DEMO_API_KEY\", \"classroom-key\")\n with TestClient(app) as test_client:\n yield test_client\n\ndef test_health(client):\n response = client.get(\"/health\")\n assert response.status_code == 200",
  1520. "lang": "python",
  1521. "filename": "tests/test_acceptance.py"
  1522. },
  1523. {
  1524. "title": "验证创建、查询、更新与删除",
  1525. "body": "从 POST 返回值提取 id,再验证默认值、列表、PUT 完整替换和 DELETE 后 404。PUT 必须包含 title、content、pinned 三个可写字段。DELETE 204 响应体应为空,不能再对它调用 json()。",
  1526. "code": "def test_note_lifecycle(client):\n title = f\"acceptance-{uuid4()}\"\n created = client.post(\"/notes\", json={\"title\": title})\n assert created.status_code == 201\n note = created.json()\n note_id = note[\"id\"]\n assert note[\"content\"] == \"\"\n assert note[\"pinned\"] is False\n assert client.get(f\"/notes/{note_id}\").json() == note\n\n listed = client.get(\"/notes\", params={\"q\": title, \"limit\": 100})\n assert listed.status_code == 200\n assert any(item[\"id\"] == note_id for item in listed.json())\n\n replacement = {\"title\": \"更新后\", \"content\": \"测试正文\", \"pinned\": True}\n updated = client.put(f\"/notes/{note_id}\", json=replacement)\n assert updated.status_code == 200\n assert updated.json() == {\"id\": note_id, **replacement}\n assert client.get(f\"/notes/{note_id}\").json() == updated.json()\n\n deleted = client.delete(f\"/notes/{note_id}\")\n assert deleted.status_code == 204\n assert deleted.content == b\"\"\n missing = client.get(f\"/notes/{note_id}\")\n assert missing.status_code == 404\n assert missing.json()[\"error\"][\"code\"] == \"http_error\"",
  1527. "lang": "python",
  1528. "filename": "tests/test_acceptance.py"
  1529. },
  1530. {
  1531. "title": "验证输入错误与受保护接口",
  1532. "body": "空标题应被输入校验拒绝。只有 /private 在本地样例中需要 X-API-Key;不要把笔记的公开练习路由与认证演示混在一起。错误体沿用前面课程的统一结构 error.code / message / details。",
  1533. "code": "def test_validation(client):\n invalid = client.post(\"/notes\", json={\"title\": \"\"})\n assert invalid.status_code == 422\n assert invalid.json()[\"error\"][\"code\"] == \"validation_error\"\n assert client.get(\"/slow\", params={\"delay\": -1}).status_code == 422\n\n\ndef test_api_key(client):\n assert client.get(\"/private\").status_code == 401\n wrong = client.get(\"/private\", headers={\"X-API-Key\": \"wrong-key\"})\n assert wrong.status_code == 401\n assert wrong.json()[\"error\"][\"code\"] == \"http_error\"\n valid = client.get(\"/private\", headers={\"X-API-Key\": \"classroom-key\"})\n assert valid.status_code == 200",
  1534. "lang": "python",
  1535. "filename": "tests/test_acceptance.py"
  1536. },
  1537. {
  1538. "title": "验证 SSE 内容和 WebSocket 来回消息",
  1539. "body": "TestClient 读取有限 SSE 的完整响应后检查协议内容;该测试不用于断言首段到达时间。WebSocket 使用上下文管理器,离开时关闭连接。 如果完成了第 12 课的 stats 扩展,测试允许保留该事件,只对 token/done 的主线顺序和内容断言;done 仍必须是最后一个事件。",
  1540. "code": "def test_stream_matches_complete_result(client):\n complete = client.post(\"/generate\", json={\"prompt\": \"hello\"})\n assert complete.status_code == 200\n response = client.get(\"/stream\", params={\"prompt\": \"hello\"})\n assert response.status_code == 200\n assert response.headers[\"content-type\"].startswith(\"text/event-stream\")\n events = []\n for block in response.text.replace(\"\\r\\n\", \"\\n\").strip().split(\"\\n\\n\"):\n fields = {}\n for line in block.split(\"\\n\"):\n name, value = line.split(\":\", 1)\n fields[name] = value.lstrip(\" \")\n events.append((fields[\"event\"], json.loads(fields[\"data\"])))\n assert [name for name, _ in events if name != \"stats\"] == [\"token\", \"token\", \"token\", \"done\"]\n text = \"\".join(data[\"text\"] for name, data in events if name == \"token\")\n assert text == complete.json()[\"text\"]\n assert events[-1] == (\"done\", {})\n\n\ndef test_websocket(client):\n with client.websocket_connect(\"/ws\") as socket:\n socket.send_text(\"hello\")\n assert socket.receive_json() == {\"type\": \"echo\", \"text\": \"hello\"}\n socket.send_text(\"ping\")\n assert socket.receive_json() == {\"type\": \"pong\"}",
  1541. "lang": "python",
  1542. "filename": "tests/test_acceptance.py"
  1543. },
  1544. {
  1545. "title": "运行自动验收,再测真实网络",
  1546. "body": "在 api-lab 执行 python -m pytest -q tests/test_acceptance.py。通过后另开终端运行 python -m uvicorn main:app --reload,再运行下面脚本。SSE 的 data 行应分批出现,时间通常约为 0.4、0.8、1.2 秒,而非都等到最后。最后在浏览器完成 CORS、主动停止流、WebSocket 断开重连三个场景。",
  1547. "code": "from time import perf_counter\nimport httpx\n\nwith httpx.Client(base_url=\"http://127.0.0.1:8000\", timeout=5.0) as client:\n started = perf_counter()\n with client.stream(\"GET\", \"/stream\", params={\"prompt\": \"hello\"}) as response:\n response.raise_for_status()\n for line in response.iter_lines():\n if line.startswith(\"data:\"):\n print(f\"{perf_counter() - started:.2f}s {line}\", flush=True)",
  1548. "lang": "python",
  1549. "filename": "verify_stream_network.py"
  1550. }
  1551. ],
  1552. "checks": [
  1553. "自动测试覆盖健康检查、完整 CRUD、422 校验、401 认证、删除后 404、SSE 与 WebSocket,运行结果全部通过。",
  1554. "真实 HTTPX / curl 客户端在响应结束前接收到 token,浏览器停止读取后服务端执行清理。",
  1555. "允许来源的浏览器能够调用 API;未允许来源不能读取响应;WebSocket 主动停止后不再重连。"
  1556. ],
  1557. "pitfalls": [
  1558. {
  1559. "symptom": "单个测试能过,整套测试偶尔失败",
  1560. "cause": "多个测试假定相同 id 或依赖前一个测试创建的数据。",
  1561. "fix": "每个测试自行创建记录,用返回 id 操作,并在生命周期测试中删除。"
  1562. },
  1563. {
  1564. "symptom": "测试里 app.state.http 不存在",
  1565. "cause": "没有通过 with TestClient(app) 启动 lifespan,或代码未正确注册 lifespan。",
  1566. "fix": "在 fixture 的上下文中创建客户端,并核对 FastAPI(lifespan=lifespan)。"
  1567. },
  1568. {
  1569. "symptom": "SSE 测试通过,网页仍一次显示全部内容",
  1570. "cause": "进程内测试只检查完整内容,没有经过浏览器、真实网络和中间服务。",
  1571. "fix": "用真实 Uvicorn 配合 httpx.stream / curl -N 观察时间,再检查浏览器读取与渲染。"
  1572. }
  1573. ],
  1574. "exercise": {
  1575. "task": "增加一个测试:创建笔记后,PUT 只发送 title 应返回 422,随后 GET 仍返回原来的完整内容。",
  1576. "hint": "输入不合法时不能发生部分更新;先保存创建响应,再比较读取结果。",
  1577. "answer": "创建笔记并保存 note;使用 client.put(f'/notes/{note[\"id\"]}', json={\"title\":\"修改\"}),断言 422;再次 GET 并断言等于 note,最后 DELETE 清理。这个测试同时检查完整替换约定和校验失败不写入的行为。"
  1578. },
  1579. "refs": [
  1580. {
  1581. "label": "FastAPI:TestClient 与 pytest",
  1582. "url": "https://fastapi.tiangolo.com/tutorial/testing/"
  1583. },
  1584. {
  1585. "label": "FastAPI:测试 lifespan",
  1586. "url": "https://fastapi.tiangolo.com/advanced/testing-events/"
  1587. },
  1588. {
  1589. "label": "FastAPI:测试 WebSocket",
  1590. "url": "https://fastapi.tiangolo.com/advanced/testing-websockets/"
  1591. },
  1592. {
  1593. "label": "pytest:fixtures",
  1594. "url": "https://docs.pytest.org/en/stable/how-to/fixtures.html"
  1595. },
  1596. {
  1597. "label": "pytest:临时环境变量",
  1598. "url": "https://docs.pytest.org/en/stable/how-to/monkeypatch.html"
  1599. },
  1600. {
  1601. "label": "HTTPX:流式响应",
  1602. "url": "https://www.python-httpx.org/quickstart/"
  1603. }
  1604. ]
  1605. }
  1606. ]