LabHub
学习 学习路径 课程

FastAPI — 타입이 곧 계약이다 · 계약과 수명 · 实验

새는 필드와 멈추는 루프

在 LabHub 中继续学习

目标

亲手制造并修复 FastAPI 在实际工作中最常出现的两类问题。

规则

启动服务器

cd /root/work/apiuvicorn app:app --host 0.0.0.0 --port 8000 > /tmp/uv.log 2>&1 &curl -s localhost:8000/healthz

请勿使用 --reload。修改文件后,先执行 kill %1 再重新启动,
这样可以明确知道当前运行的是什么。

步骤

1. /healthz01-healthz.txt
2. Pydantic 验证、422 → 02-422.json
3. 故意泄露 → 03-leak.json
4. 使用 response_model 阻止泄露
5. HTTPException 404
6. Depends(get_store)
7. async def vs def07-block.txt · 07-unblock.txt
8. dependency_overrides 测试
9. 总结 → 09-notes.md

参考

不要手写验证代码。如果你正在使用 if not isinstance(...)
就说明你抢走了类型提示本应完成的工作。

9个步骤

  1. 启动服务器
  2. 拒绝无效输入
  3. 故意泄露敏感字段
  4. 使用输出模型阻止泄露
  5. 对不存在的资源返回 404
  6. 通过依赖项注入存储库
  7. 让事件循环停顿,然后修复它
  8. 替换依赖项进行测试
  9. 总结这两类事故