Browse Source

🌐 Update translations for zh (update-outdated)

pull/15177/head
github-actions[bot] 4 months ago
committed by Yurii Motov
parent
commit
dfecec2f86
  1. 266
      docs/zh/docs/_llm-test.md
  2. 62
      docs/zh/docs/alternatives.md
  3. 24
      docs/zh/docs/async.md
  4. 2
      docs/zh/docs/benchmarks.md
  5. 10
      docs/zh/docs/environment-variables.md
  6. 71
      docs/zh/docs/fastapi-cli.md
  7. 26
      docs/zh/docs/features.md
  8. 58
      docs/zh/docs/help-fastapi.md
  9. 12
      docs/zh/docs/history-design-future.md
  10. 118
      docs/zh/docs/index.md
  11. 2
      docs/zh/docs/project-generation.md
  12. 10
      docs/zh/docs/python-types.md
  13. 49
      docs/zh/docs/tutorial/bigger-applications.md
  14. 6
      docs/zh/docs/tutorial/body-updates.md
  15. 8
      docs/zh/docs/tutorial/cors.md
  16. 2
      docs/zh/docs/tutorial/debugging.md
  17. 4
      docs/zh/docs/tutorial/encoder.md
  18. 4
      docs/zh/docs/tutorial/extra-data-types.md
  19. 8
      docs/zh/docs/tutorial/extra-models.md
  20. 75
      docs/zh/docs/tutorial/first-steps.md
  21. 2
      docs/zh/docs/tutorial/handling-errors.md
  22. 14
      docs/zh/docs/tutorial/index.md
  23. 10
      docs/zh/docs/tutorial/middleware.md
  24. 16
      docs/zh/docs/tutorial/path-params.md
  25. 20
      docs/zh/docs/tutorial/query-params-str-validations.md
  26. 14
      docs/zh/docs/tutorial/query-params.md
  27. 8
      docs/zh/docs/tutorial/request-forms.md
  28. 9
      docs/zh/docs/tutorial/response-model.md
  29. 6
      docs/zh/docs/tutorial/response-status-code.md
  30. 30
      docs/zh/docs/virtual-environments.md

266
docs/zh/docs/_llm-test.md

@ -11,7 +11,7 @@
* 检查翻译是否正确。
* 如有需要,改进你的语言特定提示、通用提示,或英文文档。
* 然后手动修正翻译中剩余的问题,确保这是一个优秀的译文。
* 重新翻译,在已有的优秀译文基础上进行。理想情况是 LLM 不再对译文做任何更改。这意味着通用提示和你的语言特定提示已经尽可能完善(有时它仍会做一些看似随机的改动,原因是<a href="https://doublespeak.chat/#/handbook#deterministic-output" class="external-link" target="_blank">LLM 不是确定性算法</a>)。
* 重新翻译,在已有的优秀译文基础上进行。理想情况是 LLM 不再对译文做任何更改。这意味着通用提示和你的语言特定提示已经尽可能完善(有时它仍会做一些看似随机的改动,原因是[LLM 不是确定性算法](https://doublespeak.chat/#/handbook#deterministic-output))。
测试如下:
@ -169,15 +169,15 @@ Some text
链接文本应被翻译,链接地址应保持不变:
* [链接到上面的标题](#code-snippets)
* [内部链接](index.md#installation){.internal-link target=_blank}
* <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">外部链接</a>
* <a href="https://fastapi.tiangolo.com/css/styles.css" class="external-link" target="_blank">样式链接</a>
* <a href="https://fastapi.tiangolo.com/js/logic.js" class="external-link" target="_blank">脚本链接</a>
* <a href="https://fastapi.tiangolo.com/img/foo.jpg" class="external-link" target="_blank">图片链接</a>
* [内部链接](index.md#installation)
* [外部链接](https://sqlmodel.tiangolo.com/)
* [样式链接](https://fastapi.tiangolo.com/css/styles.css)
* [脚本链接](https://fastapi.tiangolo.com/js/logic.js)
* [图片链接](https://fastapi.tiangolo.com/img/foo.jpg)
链接文本应被翻译,且链接地址应指向对应的译文页面:
* <a href="https://fastapi.tiangolo.com/zh/" class="external-link" target="_blank">FastAPI 链接</a>
* [FastAPI 链接](https://fastapi.tiangolo.com/zh/)
////
@ -501,255 +501,3 @@ Hello again.
参见例如 `docs/de/llm-prompt.md` 中的 `### List of English terms and their preferred German translations` 部分。
////
////
翻译(术语)对照:
//// tab | 测试(译文)
* 你
* 你的
* 例如
* 等等
* 将 `foo` 作为 `int`
* 将 `bar` 作为 `str`
* 将 `baz` 作为 `list`
* 教程 - 用户指南
* 高级用户指南
* SQLModel 文档
* API 文档
* 自动文档
* 数据科学
* 深度学习
* 机器学习
* 依赖注入
* HTTP 基本认证
* HTTP 摘要认证
* ISO 格式
* JSON Schema 标准
* JSON 模式
* 模式定义
* 密码流
* 移动端
* 已弃用
* 设计的
* 无效
* 即时
* 标准的
* 默认的
* 区分大小写
* 不区分大小写
* 为应用提供服务
* 为页面提供服务
* 应用
* 应用程序
* 请求
* 响应
* 错误响应
* 路径操作
* 路径操作装饰器
* 路径操作函数
* 主体
* 请求体
* 响应体
* JSON 体
* 表单体
* 文件体
* 函数体
* 参数
* 请求体参数
* 路径参数
* 查询参数
* Cookie 参数
* Header 参数
* 表单参数
* 函数参数
* 事件
* 启动事件
* 服务器的启动
* 关闭事件
* 生命周期事件
* 处理器
* 事件处理器
* 异常处理器
* 处理
* 模型
* Pydantic 模型
* 数据模型
* 数据库模型
* 表单模型
* 模型对象
* 类
* 基类
* 父类
* 子类
* 子类
* 兄弟类
* 类方法
* 请求头
* 请求头
* 授权头
* `Authorization`
* 转发头
* 依赖注入系统
* 依赖
* 可依赖对象
* 依赖项
* I/O 受限
* CPU 受限
* 并发
* 并行
* 多进程
* 环境变量
* 环境变量
* `PATH`
* `PATH` 变量
* 认证
* 认证提供方
* 授权
* 授权表单
* 授权提供方
* 用户进行认证
* 系统对用户进行认证
* CLI
* 命令行界面
* 服务器
* 客户端
* 云服务提供商
* 云服务
* 开发
* 开发阶段
* dict
* 字典
* 枚举
* 枚举
* 枚举成员
* 编码器
* 解码器
* 编码
* 解码
* 异常
* 抛出
* 表达式
* 语句
* 前端
* 后端
* GitHub 讨论
* GitHub Issue
* 性能
* 性能优化
* 返回类型
* 返回值
* 安全
* 安全方案
* 任务
* 后台任务
* 任务函数
* 模板
* 模板引擎
* 类型注解
* 类型提示
* 服务器 worker
* Uvicorn worker
* Gunicorn worker
* worker 进程
* worker 类
* 工作负载
* 部署
* 部署
* SDK
* 软件开发工具包
* `APIRouter`
* `requirements.txt`
* Bearer Token
* 破坏性变更
* Bug
* 按钮
* 可调用对象
* 代码
* 提交
* 上下文管理器
* 协程
* 数据库会话
* 磁盘
* 域名
* 引擎
* 假 X
* HTTP GET 方法
* 项
* 库
* 生命周期
* 锁
* 中间件
* 移动应用
* 模块
* 挂载
* 网络
* 源
* 覆盖
* 负载
* 处理器
* 属性
* 代理
* Pull Request
* 查询
* RAM
* 远程机器
* 状态码
* 字符串
* 标签
* Web 框架
* 通配符
* 返回
* 校验
////
//// tab | 信息(译文)
此清单是不完整且非规范性的,列出(主要是)文档中出现的技术术语。它有助于提示词设计者确定哪些术语需要额外的指引。例如当 LLM 总是把更好的译法改回次优译法,或在你的语言中难以正确变形时。
也可参见 `docs/de/llm-prompt.md` 中的 `### List of English terms and their preferred German translations` 部分。
////

62
docs/zh/docs/alternatives.md

@ -14,7 +14,7 @@
## 先前的工具 { #previous-tools }
### <a href="https://www.djangoproject.com/" class="external-link" target="_blank">Django</a> { #django }
### [Django](https://www.djangoproject.com/) { #django }
它是最流行且被广泛信任的 Python 框架。被用于构建 Instagram 等系统。
@ -22,7 +22,7 @@
它最初用于在后端生成 HTML,而不是创建由现代前端(如 React、Vue.js、Angular)或与之通信的其他系统(如 <abbr title="Internet of Things - 物联网">IoT</abbr> 设备)使用的 API。
### <a href="https://www.django-rest-framework.org/" class="external-link" target="_blank">Django REST Framework</a> { #django-rest-framework }
### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
Django REST framework 作为一个灵活工具箱而创建,用于在底层使用 Django 构建 Web API,从而增强其 API 能力。
@ -42,7 +42,7 @@ Django REST Framework 由 Tom Christie 创建。他也是 Starlette 和 Uvicorn
///
### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a> { #flask }
### [Flask](https://flask.palletsprojects.com) { #flask }
Flask 是一个“微框架”,它不包含数据库集成,也没有像 Django 那样的许多默认内建功能。
@ -63,7 +63,7 @@ Flask 是一个“微框架”,它不包含数据库集成,也没有像 Djan
///
### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a> { #requests }
### [Requests](https://requests.readthedocs.io) { #requests }
**FastAPI** 实际上不是 **Requests** 的替代品。它们的作用范围完全不同。
@ -99,13 +99,13 @@ def read_url():
/// check | 启发 **FastAPI**
- 提供简单直观的 API。
- 直接、自然地使用 HTTP 方法名(操作)。
- 具备合理默认值,同时支持强大定制能力。
* 提供简单直观的 API。
* 直接、自然地使用 HTTP 方法名(操作)。
* 具备合理默认值,同时支持强大定制能力。
///
### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a> { #swagger-openapi }
### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
我想从 Django REST Framework 得到的主要特性之一是自动 API 文档。
@ -123,8 +123,8 @@ def read_url():
并集成基于标准的用户界面工具:
- <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
- <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
* [Swagger UI](https://github.com/swagger-api/swagger-ui)
* [ReDoc](https://github.com/Rebilly/ReDoc)
选择这两者是因为它们相当流行且稳定;但稍作搜索,你就能找到数十种 OpenAPI 的替代用户界面(都可以与 **FastAPI** 搭配使用)。
@ -134,7 +134,7 @@ def read_url():
有若干基于 Flask 的 REST 框架,但在投入时间精力深入调研后,我发现许多已停止维护或被弃用,并存在多处未解决问题,不太适合采用。
### <a href="https://marshmallow.readthedocs.io/en/stable/" class="external-link" target="_blank">Marshmallow</a> { #marshmallow }
### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
API 系统所需的主要特性之一是数据“<dfn title="也称为:编组、转换">序列化</dfn>”,即将代码(Python)中的数据转换为可通过网络发送的形式。例如,将包含数据库数据的对象转换为 JSON 对象、将 `datetime` 对象转换为字符串等。
@ -152,7 +152,7 @@ API 的另一个重要特性是数据校验,确保数据在给定约束下是
///
### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a> { #webargs }
### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
API 的另一个重要需求是从传入请求中<dfn title="读取并转换为 Python 数据">解析</dfn>数据。
@ -174,7 +174,7 @@ Webargs 由与 Marshmallow 相同的开发者创建。
///
### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a> { #apispec }
### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
Marshmallow 与 Webargs 通过插件提供了校验、解析与序列化。
@ -204,7 +204,7 @@ APISpec 由与 Marshmallow 相同的开发者创建。
///
### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a> { #flask-apispec }
### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
这是一个 Flask 插件,将 Webargs、Marshmallow 与 APISpec 结合在一起。
@ -218,11 +218,11 @@ APISpec 由与 Marshmallow 相同的开发者创建。
使用它促成了若干 Flask 全栈脚手架的诞生。以下是我(以及若干外部团队)至今使用的主要技术栈:
* <a href="https://github.com/tiangolo/full-stack" class="external-link" target="_blank">https://github.com/tiangolo/full-stack</a>
* <a href="https://github.com/tiangolo/full-stack-flask-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-flask-couchbase</a>
* <a href="https://github.com/tiangolo/full-stack-flask-couchdb" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-flask-couchdb</a>
* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
这些全栈脚手架也成为了[**FastAPI** 项目脚手架](project-generation.md){.internal-link target=_blank}的基础。
这些全栈脚手架也成为了[**FastAPI** 项目脚手架](project-generation.md)的基础。
/// info | 信息
@ -236,7 +236,7 @@ Flask-apispec 由与 Marshmallow 相同的开发者创建。
///
### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a>(以及 <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>) { #nestjs-and-angular }
### [NestJS](https://nestjs.com/)(以及 [Angular](https://angular.io/)) { #nestjs-and-angular }
这甚至不是 Python。NestJS 是一个 JavaScript(TypeScript)的 NodeJS 框架,受 Angular 启发。
@ -258,13 +258,13 @@ Flask-apispec 由与 Marshmallow 相同的开发者创建。
///
### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a> { #sanic }
### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
它是最早的一批基于 `asyncio` 的极速 Python 框架之一,且做得与 Flask 很相似。
/// note | 技术细节
它使用了 <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> 来替代 Python 默认的 `asyncio` 循环。这正是它如此之快的原因。
它使用了 [`uvloop`](https://github.com/MagicStack/uvloop) 来替代 Python 默认的 `asyncio` 循环。这正是它如此之快的原因。
它显然启发了 Uvicorn 和 Starlette;在公开的基准测试中,它们目前比 Sanic 更快。
@ -278,7 +278,7 @@ Flask-apispec 由与 Marshmallow 相同的开发者创建。
///
### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a> { #falcon }
### [Falcon](https://falconframework.org/) { #falcon }
Falcon 是另一个高性能 Python 框架,它被设计为精简且可作为 Hug 等其他框架的基础。
@ -294,7 +294,7 @@ Falcon 是另一个高性能 Python 框架,它被设计为精简且可作为 H
///
### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a> { #molten }
### [Molten](https://moltenframework.com/) { #molten }
我在构建 **FastAPI** 的早期阶段发现了 Molten。它有不少相似的想法:
@ -318,7 +318,7 @@ Falcon 是另一个高性能 Python 框架,它被设计为精简且可作为 H
///
### <a href="https://github.com/hugapi/hug" class="external-link" target="_blank">Hug</a> { #hug }
### [Hug](https://github.com/hugapi/hug) { #hug }
Hug 是最早使用 Python 类型提示来声明 API 参数类型的框架之一。这一绝妙想法也启发了其他工具。
@ -334,7 +334,7 @@ Hug 是最早使用 Python 类型提示来声明 API 参数类型的框架之一
/// info | 信息
Hug 由 Timothy Crosley 创建,他也是 <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a> 的作者,这是一个能自动排序 Python 文件中导入的优秀工具。
Hug 由 Timothy Crosley 创建,他也是 [`isort`](https://github.com/timothycrosley/isort) 的作者,这是一个能自动排序 Python 文件中导入的优秀工具。
///
@ -348,7 +348,7 @@ Hug 启发 **FastAPI** 在函数中声明 `response` 参数,用于设置 heade
///
### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5) { #apistar-0-5 }
### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }
就在决定动手构建 **FastAPI** 之前,我找到了 **APIStar** 服务器。它几乎具备我想要的一切,设计也很出色。
@ -398,7 +398,7 @@ APIStar 由 Tom Christie 创建。他还创建了:
## **FastAPI** 所使用的组件 { #used-by-fastapi }
### <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> { #pydantic }
### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
Pydantic 是一个基于 Python 类型提示来定义数据校验、序列化与文档(使用 JSON Schema)的库。
@ -414,7 +414,7 @@ Pydantic 是一个基于 Python 类型提示来定义数据校验、序列化与
///
### <a href="https://www.starlette.dev/" class="external-link" target="_blank">Starlette</a> { #starlette }
### [Starlette](https://www.starlette.dev/) { #starlette }
Starlette 是一个轻量级的 <dfn title="构建异步 Python Web 应用的新标准">ASGI</dfn> 框架/工具集,非常适合构建高性能的 asyncio 服务。
@ -459,7 +459,7 @@ ASGI 是由 Django 核心团队成员推动的新“标准”。它尚不是正
///
### <a href="https://www.uvicorn.dev/" class="external-link" target="_blank">Uvicorn</a> { #uvicorn }
### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
Uvicorn 是一个基于 uvloop 与 httptools 构建的极速 ASGI 服务器。
@ -473,10 +473,10 @@ Uvicorn 是一个基于 uvloop 与 httptools 构建的极速 ASGI 服务器。
你也可以使用 `--workers` 命令行选项以获得异步的多进程服务器。
更多细节见[部署](deployment/index.md){.internal-link target=_blank}一节。
更多细节见[部署](deployment/index.md)一节。
///
## 基准与速度 { #benchmarks-and-speed }
要理解、比较并查看 Uvicorn、Starlette 与 FastAPI 之间的差异,请查看[基准](benchmarks.md){.internal-link target=_blank}一节。
要理解、比较并查看 Uvicorn、Starlette 与 FastAPI 之间的差异,请查看[基准](benchmarks.md)一节。

24
docs/zh/docs/async.md

@ -141,7 +141,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
/// info | 信息
漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
漂亮的插画来自 [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot)。🎨
///
@ -207,7 +207,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
/// info | 信息
漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
漂亮的插画来自 [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot)。🎨
///
@ -251,7 +251,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
这与 **FastAPI** 的性能水平相同。
你可以同时拥有并行性和异步性,你可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言(<a href="https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1" class="external-link" target="_blank">全部归功于 Starlette</a>)。
你可以同时拥有并行性和异步性,你可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言([全部归功于 Starlette](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1))。
### 并发比并行好吗? { #is-concurrency-better-than-parallelism }
@ -298,7 +298,7 @@ CPU 密集型操作的常见示例是需要复杂的数学处理。
这一点,再加上 Python 是**数据科学**、机器学习(尤其是深度学习)的主要语言这一简单事实,使得 **FastAPI** 与数据科学/机器学习 Web API 和应用程序(以及其他许多应用程序)非常匹配。
了解如何在生产环境中实现这种并行性,可查看此文 [部署](deployment/index.md){.internal-link target=_blank}
了解如何在生产环境中实现这种并行性,可查看此文 [部署](deployment/index.md)。
## `async``await` { #async-and-await }
@ -363,13 +363,13 @@ async def read_burgers():
### 编写自己的异步代码 { #write-your-own-async-code }
Starlette (和 **FastAPI**) 是基于 <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a> 实现的,这使得它们可以兼容 Python 的标准库 <a href="https://docs.python.org/3/library/asyncio-task.html" class="external-link" target="_blank">asyncio</a><a href="https://trio.readthedocs.io/en/stable/" class="external-link" target="_blank">Trio</a>
Starlette (和 **FastAPI**) 是基于 [AnyIO](https://anyio.readthedocs.io/en/stable/) 实现的,这使得它们可以兼容 Python 的标准库 [asyncio](https://docs.python.org/3/library/asyncio-task.html) 和 [Trio](https://trio.readthedocs.io/en/stable/)
特别是,你可以直接使用 <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a> 来处理高级的并发用例,这些用例需要在自己的代码中使用更高级的模式。
特别是,你可以直接使用 [AnyIO](https://anyio.readthedocs.io/en/stable/) 来处理高级的并发用例,这些用例需要在自己的代码中使用更高级的模式。
即使你没有使用 **FastAPI**,你也可以使用 <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a> 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。
即使你没有使用 **FastAPI**,你也可以使用 [AnyIO](https://anyio.readthedocs.io/en/stable/) 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。
我基于 AnyIO 新建了一个库,作为一个轻量级的封装层,用来优化类型注解,同时提供了更好的**自动补全**、**内联错误提示**等功能。这个库还附带了一个友好的入门指南和教程,能帮助你**理解**并编写**自己的异步代码**:<a href="https://asyncer.tiangolo.com/" class="external-link" target="_blank">Asyncer</a>。如果你有**结合使用异步代码和常规**(阻塞/同步)代码的需求,这个库会特别有用。
我基于 AnyIO 新建了一个库,作为一个轻量级的封装层,用来优化类型注解,同时提供了更好的**自动补全**、**内联错误提示**等功能。这个库还附带了一个友好的入门指南和教程,能帮助你**理解**并编写**自己的异步代码**:[Asyncer](https://asyncer.tiangolo.com/)。如果你有**结合使用异步代码和常规**(阻塞/同步)代码的需求,这个库会特别有用。
### 其他形式的异步代码 { #other-forms-of-asynchronous-code }
@ -381,7 +381,7 @@ Starlette (和 **FastAPI**) 是基于 <a href="https://anyio.readthedocs.io/
但在此之前,处理异步代码非常复杂和困难。
在以前版本的 Python,你可以使用多线程或者 <a href="https://www.gevent.org/" class="external-link" target="_blank">Gevent</a>。但代码的理解、调试和思考都要复杂许多。
在以前版本的 Python,你可以使用多线程或者 [Gevent](https://www.gevent.org/)。但代码的理解、调试和思考都要复杂许多。
在以前版本的 NodeJS / 浏览器 JavaScript 中,你会使用"回调",因此也可能导致“回调地狱”。
@ -419,15 +419,15 @@ Starlette (和 **FastAPI**) 是基于 <a href="https://anyio.readthedocs.io/
如果你使用过另一个不以上述方式工作的异步框架,并且你习惯于用普通的 `def` 定义普通的仅计算路径操作函数,以获得微小的性能增益(大约100纳秒),请注意,在 FastAPI 中,效果将完全相反。在这些情况下,最好使用 `async def`,除非路径操作函数内使用执行阻塞 <abbr title="Input/Output - 输入/输出:磁盘读写,网络通信。">I/O</abbr> 的代码。
在这两种情况下,与你之前的框架相比,**FastAPI** 可能[仍然很快](index.md#performance){.internal-link target=_blank}
在这两种情况下,与你之前的框架相比,**FastAPI** 可能[仍然很快](index.md#performance)。
### 依赖 { #dependencies }
这同样适用于[依赖](tutorial/dependencies/index.md){.internal-link target=_blank}。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。
这同样适用于[依赖](tutorial/dependencies/index.md)。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。
### 子依赖 { #sub-dependencies }
你可以拥有多个相互依赖的依赖以及[子依赖](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。
你可以拥有多个相互依赖的依赖以及[子依赖](tutorial/dependencies/sub-dependencies.md) (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。
### 其他函数 { #other-utility-functions }

2
docs/zh/docs/benchmarks.md

@ -1,6 +1,6 @@
# 基准测试 { #benchmarks }
第三方机构 TechEmpower 的基准测试表明在 Uvicorn 下运行的 **FastAPI** 应用程序是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">可用的最快的 Python 框架之一</a>,仅次于 Starlette 和 Uvicorn 本身(由 FastAPI 内部使用)。
第三方机构 TechEmpower 的基准测试表明在 Uvicorn 下运行的 **FastAPI** 应用程序是 [可用的最快的 Python 框架之一](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7),仅次于 Starlette 和 Uvicorn 本身(由 FastAPI 内部使用)。
但是在查看基准得分和对比时,请注意以下几点。

10
docs/zh/docs/environment-variables.md

@ -65,7 +65,7 @@ print(f"Hello {name} from Python")
/// tip | 提示
第二个参数是 <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> 的默认返回值。
第二个参数是 [`os.getenv()`](https://docs.python.org/3.8/library/os.html#os.getenv) 的默认返回值。
如果没有提供,默认值为 `None`,这里我们提供 `"World"` 作为默认值。
@ -153,7 +153,7 @@ Hello World from Python
/// tip | 提示
你可以在 <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: 配置</a>中了解更多信息。
你可以在 [The Twelve-Factor App: 配置](https://12factor.net/config) 中了解更多信息。
///
@ -163,7 +163,7 @@ Hello World from Python
这意味着从环境变量中读取的**任何值**在 Python 中都将是一个 `str`,任何类型转换或验证都必须在代码中完成。
你将在[高级用户指南 - 设置和环境变量](./advanced/settings.md){.internal-link target=_blank}中了解更多关于使用环境变量处理**应用程序设置**的信息。
你将在[高级用户指南 - 设置和环境变量](./advanced/settings.md)中了解更多关于使用环境变量处理**应用程序设置**的信息。
## `PATH` 环境变量 { #path-environment-variable }
@ -285,13 +285,13 @@ $ C:\opt\custompython\bin\python
////
当学习[虚拟环境](virtual-environments.md){.internal-link target=_blank}时,这些信息将会很有用。
当学习[虚拟环境](virtual-environments.md)时,这些信息将会很有用。
## 结论 { #conclusion }
通过这个教程,你应该对**环境变量**是什么以及如何在 Python 中使用它们有了基本的了解。
你也可以在<a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">环境变量 - 维基百科</a>中了解更多关于它们的信息。
你也可以在[环境变量 - 维基百科](https://en.wikipedia.org/wiki/Environment_variable)中了解更多关于它们的信息。
在许多情况下,环境变量的用途和适用性并不是很明显。但是在开发过程中,它们会在许多不同的场景中出现,因此了解它们是很有必要的。

71
docs/zh/docs/fastapi-cli.md

@ -1,15 +1,15 @@
# FastAPI CLI { #fastapi-cli }
**FastAPI CLI** 是一个命令行程序,你可以用它来部署和运行你的 FastAPI 应用程序,管理你的 FastAPI 项目,等等。
**FastAPI <abbr title="command line interface - 命令行接口">CLI</abbr>** 是一个命令行程序,你可以用它来部署和运行你的 FastAPI 应用、管理 FastAPI 项目,等等。
当你安装 FastAPI(例如使用 `pip install "fastapi[standard]"`,会包含一个名为 `fastapi-cli` 的软件包,该软件包在终端中提供 `fastapi` 命令
当你安装 FastAPI(例如使用 `pip install "fastapi[standard]"`时,会附带一个可以在终端中运行的命令行程序
要在开发环境中运行你的 FastAPI 应用,可以使用 `fastapi dev` 命令:
要在开发环境中运行你的 FastAPI 应用,可以使用 `fastapi dev` 命令:
<div class="termy">
```console
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:solid">main.py</u>
$ <font color="#4E9A06">fastapi</font> dev
<span style="background-color:#009485"><font color="#D3D7CF"> FastAPI </font></span> Starting development server 🚀
@ -46,13 +46,66 @@ $ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:solid
</div>
该命令行程序 `fastapi` 就是 **FastAPI CLI**
/// tip | 提示
在生产环境中,你会使用 `fastapi run` 而不是 `fastapi dev`。🚀
///
在内部,**FastAPI CLI** 使用 [Uvicorn](https://www.uvicorn.dev),这是一个高性能、适用于生产环境的 ASGI 服务器。😎
`fastapi` CLI 会尝试自动检测要运行的 FastAPI 应用,默认假设它是文件 `main.py` 中名为 `app` 的对象(或少数其他变体)。
但你也可以显式配置要使用的应用。
## 在 `pyproject.toml` 中配置应用的 `entrypoint` { #configure-the-app-entrypoint-in-pyproject-toml }
你可以在 `pyproject.toml` 文件中配置应用的位置,例如:
```toml
[tool.fastapi]
entrypoint = "main:app"
```
这个 `entrypoint` 会告诉 `fastapi` 命令按如下方式导入应用:
```python
from main import app
```
FastAPI CLI 接收你的 Python 程序路径(例如 `main.py`),自动检测 `FastAPI` 实例(通常命名为 `app`),确定正确的导入方式,然后启动服务。
如果你的代码结构如下:
```
.
├── backend
│   ├── main.py
│   ├── __init__.py
```
那么你可以将 `entrypoint` 设置为:
```toml
[tool.fastapi]
entrypoint = "backend.main:app"
```
这等价于:
```python
from backend.main import app
```
### 带路径的 `fastapi dev` { #fastapi-dev-with-path }
你也可以把文件路径传给 `fastapi dev` 命令,它会猜测要使用的 FastAPI 应用对象:
```console
$ fastapi dev main.py
```
在生产环境中,你应该使用 `fastapi run` 命令。🚀
但每次运行 `fastapi` 命令都需要记得传入正确的路径。
在内部,**FastAPI CLI** 使用了 <a href="https://www.uvicorn.dev" class="external-link" target="_blank">Uvicorn</a>,这是一个高性能、适用于生产环境的 ASGI 服务器。😎
另外,其他工具可能找不到它,例如 [VS Code 扩展](editor-support.md) 或 [FastAPI Cloud](https://fastapicloud.com),因此推荐在 `pyproject.toml` 中使用 `entrypoint`
## `fastapi dev` { #fastapi-dev }
@ -70,6 +123,6 @@ FastAPI CLI 接收你的 Python 程序路径(例如 `main.py`),自动检
/// tip | 提示
你可以在[部署文档](deployment/index.md){.internal-link target=_blank}中了解更多。
你可以在[部署文档](deployment/index.md)中了解更多。
///

26
docs/zh/docs/features.md

@ -6,8 +6,8 @@
### 基于开放标准 { #based-on-open-standards }
* 用于创建 API 的 <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a>,包含对<dfn title="也称为:端点、路由">路径</dfn> <dfn title="也称为 HTTP 方法,如 POST、GET、PUT、DELETE">操作</dfn>、参数、请求体、安全等的声明。
* 使用 <a href="https://json-schema.org/" class="external-link" target="_blank"><strong>JSON Schema</strong></a> 自动生成数据模型文档(因为 OpenAPI 本身就是基于 JSON Schema 的)。
* [**OpenAPI**](https://github.com/OAI/OpenAPI-Specification) 用于创建 API,包含对<dfn title="也称为:端点、路由">路径</dfn> <dfn title="也称为 HTTP 方法,如 POST、GET、PUT、DELETE">操作</dfn>、参数、请求体、安全等的声明。
* 使用 [**JSON Schema**](https://json-schema.org/) 自动生成数据模型文档(因为 OpenAPI 本身就是基于 JSON Schema 的)。
* 经过了缜密的研究后围绕这些标准而设计。并非狗尾续貂。
* 这也允许了在很多语言中自动**生成客户端代码**。
@ -15,11 +15,11 @@
交互式 API 文档以及具探索性 web 界面。因为该框架是基于 OpenAPI,所以有很多可选项,FastAPI 默认自带两个交互式 API 文档。
* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank"><strong>Swagger UI</strong></a>,可交互式操作,能在浏览器中直接调用和测试你的 API。
* [**Swagger UI**](https://github.com/swagger-api/swagger-ui),可交互式操作,能在浏览器中直接调用和测试你的 API。
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)
* 另外的 API 文档:<a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank"><strong>ReDoc</strong></a>
* 另外的 API 文档:[**ReDoc**](https://github.com/Rebilly/ReDoc)
![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)
@ -27,7 +27,7 @@
全部都基于标准的 **Python 类型** 声明(感谢 Pydantic)。没有新的语法需要学习。只需要标准的现代 Python。
如果你需要2分钟来学习如何使用 Python 类型(即使你不使用 FastAPI),看看这个简短的教程:[Python Types](python-types.md){.internal-link target=_blank}
如果你需要2分钟来学习如何使用 Python 类型(即使你不使用 FastAPI),看看这个简短的教程:[Python 类型](python-types.md)
编写带有类型标注的标准 Python:
@ -76,7 +76,7 @@ my_second_user: User = User(**second_user_data)
整个框架都被设计得易于使用且直观,所有的决定都在开发之前就在多个编辑器上进行了测试,来确保最佳的开发体验。
最近的 Python 开发者调查中,我们能看到 <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">被使用最多的功能是“自动补全”</a>
Python 开发者调查中,我们能看到[被使用最多的功能之一是“自动补全”](https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features)
整个 **FastAPI** 框架就是基于这一点的。任何地方都可以进行自动补全。
@ -84,11 +84,11 @@ my_second_user: User = User(**second_user_data)
在这里,你的编辑器可能会这样帮助你:
* 在 <a href="https://code.visualstudio.com/" class="external-link" target="_blank">Visual Studio Code</a> 中:
* 在 [Visual Studio Code](https://code.visualstudio.com/) 中:
![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)
* 在 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> 中:
* 在 [PyCharm](https://www.jetbrains.com/pycharm/) 中:
![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png)
@ -125,7 +125,7 @@ my_second_user: User = User(**second_user_data)
OpenAPI 中定义的安全模式,包括:
* HTTP 基本认证。
* **OAuth2**(也使用 **JWT tokens**)。在 [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}查看教程。
* **OAuth2**(也使用 **JWT tokens**)。在 [使用 JWT 的 OAuth2](tutorial/security/oauth2-jwt.md) 查看教程。
* API 密钥,在:
* 请求头。
* 查询参数。
@ -142,7 +142,7 @@ FastAPI 有一个使用非常简单,但是非常强大的<dfn title='也称为
* 甚至依赖也可以有依赖,创建一个层级或者**“图”依赖**。
* 所有**自动化处理**都由框架完成。
* 所有的依赖关系都可以从请求中获取数据,并且**增加了路径操作**约束和自动文档生成。
* 即使在依赖项中被定义的*路径操作* 也会**自动验证**。
* 即使是在依赖项中定义的路径操作参数也会**自动验证**。
* 支持复杂的用户身份认证系统,**数据库连接**等等。
* **不依赖**数据库,前端等。但是和它们集成很简单。
@ -160,11 +160,11 @@ FastAPI 有一个使用非常简单,但是非常强大的<dfn title='也称为
## Starlette 特性 { #starlette-features }
**FastAPI** 和 <a href="https://www.starlette.dev/" class="external-link" target="_blank"><strong>Starlette</strong></a> 完全兼容(并基于)。所以,你有的其他的 Starlette 代码也能正常工作。`FastAPI` 实际上是 `Starlette` 的一个子类。所以,如果你已经知道或者使用 Starlette,大部分的功能会以相同的方式工作。
**FastAPI** 和 [**Starlette**](https://www.starlette.dev/) 完全兼容(并基于)。所以,你有的其他的 Starlette 代码也能正常工作。`FastAPI` 实际上是 `Starlette` 的一个子类。所以,如果你已经知道或者使用 Starlette,大部分的功能会以相同的方式工作。
通过 **FastAPI** 你可以获得所有 **Starlette** 的特性(FastAPI 就像加强版的 Starlette):
* 令人惊叹的性能。它是 <a href="https://github.com/encode/starlette#performance" class="external-link" target="_blank">Python 可用的最快的框架之一,和 **NodeJS****Go** 相当</a>
* 令人惊叹的性能。它是[Python 可用的最快的框架之一,和 **NodeJS****Go** 相当](https://github.com/encode/starlette#performance)
* **支持 WebSocket**
* 进程内后台任务。
* Startup 和 shutdown 事件。
@ -176,7 +176,7 @@ FastAPI 有一个使用非常简单,但是非常强大的<dfn title='也称为
## Pydantic 特性 { #pydantic-features }
**FastAPI** 和 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"><strong>Pydantic</strong></a> 完全兼容(并基于)。所以,你有的其他的 Pydantic 代码也能正常工作。
**FastAPI** 和 [**Pydantic**](https://docs.pydantic.dev/) 完全兼容(并基于)。所以,你有的其他的 Pydantic 代码也能正常工作。
兼容包括基于 Pydantic 的外部库,例如用于数据库的 <abbr title="Object-Relational Mapper - 对象关系映射">ORM</abbr>s、<abbr title="Object-Document Mapper - 对象文档映射">ODM</abbr>s。

58
docs/zh/docs/help-fastapi.md

@ -12,7 +12,7 @@
## 订阅新闻邮件 { #subscribe-to-the-newsletter }
你可以订阅(不频繁的)[**FastAPI and friends** 新闻邮件](newsletter.md){.internal-link target=_blank},获取如下更新:
你可以订阅(不频繁的)[**FastAPI and friends** 新闻邮件](newsletter.md),获取如下更新:
* FastAPI 及其小伙伴的新闻 🚀
* 指南 📝
@ -22,17 +22,17 @@
## 在 X (Twitter) 上关注 FastAPI { #follow-fastapi-on-x-twitter }
<a href="https://x.com/fastapi" class="external-link" target="_blank">**X (Twitter)** 上关注 @fastapi</a> 获取 **FastAPI** 的最新动态。🐦
[在 **X (Twitter)** 上关注 @fastapi](https://x.com/fastapi) 获取 **FastAPI** 的最新动态。🐦
## 在 GitHub 上为 **FastAPI** 加星 { #star-fastapi-in-github }
你可以在 GitHub 上为 FastAPI 点亮「星标」(点击右上角的星形按钮):<a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>。⭐️
你可以在 GitHub 上为 FastAPI 点亮「星标」(点击右上角的星形按钮):[https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi)。⭐️
点亮星标后,其他用户更容易发现它,并看到它已经对许多人有帮助。
## 关注 GitHub 资源库的版本发布 { #watch-the-github-repository-for-releases }
你可以在 GitHub 上「关注」FastAPI(点击右上角的「watch」按钮):<a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>。👀
你可以在 GitHub 上「关注」FastAPI(点击右上角的「watch」按钮):[https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi)。👀
在那里你可以选择「Releases only」。
@ -40,45 +40,45 @@
## 联系作者 { #connect-with-the-author }
你可以联系<a href="https://tiangolo.com" class="external-link" target="_blank">我(Sebastián Ramírez / `tiangolo`</a>,作者本人。
你可以联系[我(Sebastián Ramírez / `tiangolo`)](https://tiangolo.com),作者本人。
你可以:
* <a href="https://github.com/tiangolo" class="external-link" target="_blank">**GitHub** 上关注我</a>
* [在 **GitHub** 上关注我](https://github.com/tiangolo)
* 了解我创建的其他开源项目,也许对你有帮助。
* 关注我何时创建新的开源项目。
* 关注我在 <a href="https://x.com/tiangolo" class="external-link" target="_blank">**X (Twitter)**</a><a href="https://fosstodon.org/@tiangolo" class="external-link" target="_blank">Mastodon</a>
* 关注我在 [**X (Twitter)**](https://x.com/tiangolo) 或 [Mastodon](https://fosstodon.org/@tiangolo)
* 告诉我你如何使用 FastAPI(我很喜欢听这些)。
* 获取我发布公告或新工具的消息。
* 你也可以<a href="https://x.com/fastapi" class="external-link" target="_blank">关注 @fastapi on X (Twitter)</a>(独立账号)。
* <a href="https://www.linkedin.com/in/tiangolo/" class="external-link" target="_blank">**LinkedIn** 上关注我</a>
* 你也可以[在 X (Twitter) 上关注 @fastapi](https://x.com/fastapi)(独立账号)。
* [在 **LinkedIn** 上关注我](https://www.linkedin.com/in/tiangolo/)
* 获取我发布公告或新工具的消息(不过我更常用 X (Twitter) 🤷‍♂)。
* 阅读我在 <a href="https://dev.to/tiangolo" class="external-link" target="_blank">**Dev.to**</a><a href="https://medium.com/@tiangolo" class="external-link" target="_blank">**Medium**</a> 上的文章(或关注我)。
* 阅读我在 [**Dev.to**](https://dev.to/tiangolo) 或 [**Medium**](https://medium.com/@tiangolo) 上的文章(或关注我)。
* 阅读我的其他想法、文章,以及我创建的工具。
* 关注我,这样当我发布新文章时你会第一时间看到。
## 发推谈谈 **FastAPI** { #tweet-about-fastapi }
<a href="https://x.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi" class="external-link" target="_blank">发推谈谈 **FastAPI**</a>,告诉我和大家你为什么喜欢它。🎉
[发推谈谈 **FastAPI**](https://x.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi),告诉我和大家你为什么喜欢它。🎉
我很高兴听到 **FastAPI** 的使用情况、你喜欢它的哪些点、你在哪个项目/公司使用它,等等。
## 为 FastAPI 投票 { #vote-for-fastapi }
* <a href="https://www.slant.co/options/34241/~fastapi-review" class="external-link" target="_blank">在 Slant 上为 **FastAPI** 投票</a>
* <a href="https://alternativeto.net/software/fastapi/about/" class="external-link" target="_blank">在 AlternativeTo 上为 **FastAPI** 投票</a>
* <a href="https://stackshare.io/pypi-fastapi" class="external-link" target="_blank">在 StackShare 上标注你在用 **FastAPI**</a>
* [在 Slant 上为 **FastAPI** 投票](https://www.slant.co/options/34241/~fastapi-review)
* [在 AlternativeTo 上为 **FastAPI** 投票](https://alternativeto.net/software/fastapi/about/)
* [在 StackShare 上标注你在用 **FastAPI**](https://stackshare.io/pypi-fastapi)
## 在 GitHub 上帮别人解答问题 { #help-others-with-questions-in-github }
你可以尝试在以下地方帮助他人解答问题:
* <a href="https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">GitHub Discussions</a>
* <a href="https://github.com/fastapi/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">GitHub Issues</a>
* [GitHub Discussions](https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered)
* [GitHub Issues](https://github.com/fastapi/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+)
很多情况下,你也许已经知道这些问题的答案了。🤓
如果你帮助了很多人解答问题,你会成为官方的 [FastAPI 专家](fastapi-people.md#fastapi-experts){.internal-link target=_blank}。🎉
如果你帮助了很多人解答问题,你会成为官方的 [FastAPI 专家](fastapi-people.md#fastapi-experts)。🎉
只要记住,最重要的一点是:尽量友善。人们带着挫败感而来,很多时候他们的提问方式并不理想,但请尽你所能地友好对待。🤗
@ -104,7 +104,7 @@
很多时候他们只会粘贴一小段代码,但这不足以**复现问题**。
* 你可以请他们提供一个<a href="https://stackoverflow.com/help/minimal-reproducible-example" class="external-link" target="_blank">可最小复现的示例</a>,你可以**复制粘贴**并在本地运行,看到与他们相同的错误或行为,或者更好地理解他们的用例。
* 你可以请他们提供一个[可最小复现的示例](https://stackoverflow.com/help/minimal-reproducible-example),你可以**复制粘贴**并在本地运行,看到与他们相同的错误或行为,或者更好地理解他们的用例。
* 如果你非常热心,你也可以尝试仅根据问题描述自己**构造一个示例**。不过要记住,这可能会花很多时间,通常先请他们澄清问题会更好。
@ -124,7 +124,7 @@
## 关注 GitHub 资源库 { #watch-the-github-repository }
你可以在 GitHub 上「关注」FastAPI(点击右上角的「watch」按钮):<a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">https://github.com/fastapi/fastapi</a>。👀
你可以在 GitHub 上「关注」FastAPI(点击右上角的「watch」按钮):[https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi)。👀
如果你选择「Watching」而非「Releases only」,当有人创建新的 issue 或问题时你会收到通知。你也可以指定只通知新 issues、discussions、PR 等。
@ -132,7 +132,7 @@
## 提问 { #ask-questions }
你可以在 GitHub 资源库中<a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">创建一个新问题(Question)</a>,例如:
你可以在 GitHub 资源库中[创建一个新问题(Question)](https://github.com/fastapi/fastapi/discussions/new?category=questions),例如:
* 提出一个**问题**或关于某个**问题**的求助。
* 建议一个新的**功能**。
@ -195,12 +195,12 @@
## 创建 Pull Request { #create-a-pull-request }
你可以通过 Pull Request 为源代码[做贡献](contributing.md){.internal-link target=_blank},例如:
你可以通过 Pull Request 为源代码[做贡献](contributing.md),例如:
* 修正文档中的一个错别字。
* 通过<a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">编辑这个文件</a>分享你创建或发现的关于 FastAPI 的文章、视频或播客。
* 通过[编辑这个文件](https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml)分享你创建或发现的关于 FastAPI 的文章、视频或播客。
* 请确保把你的链接添加到相应区块的开头。
* 帮助把[文档翻译](contributing.md#translations){.internal-link target=_blank}成你的语言。
* 帮助把[文档翻译](contributing.md#translations)成你的语言。
* 你也可以审阅他人创建的翻译。
* 提议新增文档章节。
* 修复现有 issue/bug。
@ -217,8 +217,8 @@
你现在就能做的主要事情有:
* [在 GitHub 上帮别人解答问题](#help-others-with-questions-in-github){.internal-link target=_blank}(见上面的章节)。
* [审阅 Pull Request](#review-pull-requests){.internal-link target=_blank}(见上面的章节)。
* [在 GitHub 上帮别人解答问题](#help-others-with-questions-in-github)(见上面的章节)。
* [审阅 Pull Request](#review-pull-requests)(见上面的章节)。
这两项工作是**最耗时**的。这也是维护 FastAPI 的主要工作。
@ -226,11 +226,11 @@
## 加入聊天 { #join-the-chat }
加入 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord 聊天服务器</a> 👥,和 FastAPI 社区的小伙伴们一起交流。
加入 👥 [Discord 聊天服务器](https://discord.gg/VQjSZaeJmf) 👥,和 FastAPI 社区的小伙伴们一起交流。
/// tip | 提示
关于提问,请在 <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a> 中发布,这样更有机会得到 [FastAPI 专家](fastapi-people.md#fastapi-experts){.internal-link target=_blank} 的帮助。
关于提问,请在 [GitHub Discussions](https://github.com/fastapi/fastapi/discussions/new?category=questions) 中发布,这样更有机会得到 [FastAPI 专家](fastapi-people.md#fastapi-experts) 的帮助。
聊天仅用于其他日常交流。
@ -242,13 +242,13 @@
在 GitHub 中,模板会引导你写出恰当的问题,从而更容易获得好的回答,甚至在提问之前就能自己解决。而且在 GitHub 里,我能尽量确保最终回复每个问题,即使这需要一些时间。对聊天系统来说,我个人做不到这一点。😅
聊天系统中的对话也不像 GitHub 那样容易搜索,因此问答可能在聊天中淹没。而且只有在 GitHub 中的问答才会计入成为 [FastAPI 专家](fastapi-people.md#fastapi-experts){.internal-link target=_blank} 的贡献,所以你在 GitHub 上更可能获得关注。
聊天系统中的对话也不像 GitHub 那样容易搜索,因此问答可能在聊天中淹没。而且只有在 GitHub 中的问答才会计入成为 [FastAPI 专家](fastapi-people.md#fastapi-experts) 的贡献,所以你在 GitHub 上更可能获得关注。
另一方面,聊天系统里有成千上万的用户,你几乎随时都能在那里找到聊得来的人。😄
## 赞助作者 { #sponsor-the-author }
如果你的**产品/公司**依赖或与 **FastAPI** 相关,并且你想触达它的用户,你可以通过 <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub sponsors</a> 赞助作者(我)。根据赞助层级,你还可能获得一些额外福利,比如在文档中展示徽章。🎁
如果你的**产品/公司**依赖或与 **FastAPI** 相关,并且你想触达它的用户,你可以通过 [GitHub sponsors](https://github.com/sponsors/tiangolo) 赞助作者(我)。根据赞助层级,你还可能获得一些额外福利,比如在文档中展示徽章。🎁
---

12
docs/zh/docs/history-design-future.md

@ -1,6 +1,6 @@
# 历史、设计、未来 { #history-design-and-future }
不久前,<a href="https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920" class="external-link" target="_blank">曾有 **FastAPI** 用户问过</a>
不久前,[曾有 **FastAPI** 用户问过](https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920)
> 这个项目有怎样的历史?好像它只用了几周就从默默无闻变得众所周知...
@ -14,7 +14,7 @@
**FastAPI** 其实只是延续了这些前辈的历史。
正如[备选方案](alternatives.md){.internal-link target=_blank}一章所述:
正如[备选方案](alternatives.md)一章所述:
<blockquote markdown="1">
没有大家之前所做的工作,**FastAPI** 就不会存在。
@ -42,7 +42,7 @@
同时,我还在最流行的 Python 代码编辑器中测试了很多思路,包括 PyCharm、VS Code、基于 Jedi 的编辑器。
根据最新 <a href="https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools" class="external-link" target="_blank">Python 开发者调研报告</a>显示,这几种编辑器覆盖了约 80% 的用户。
根据最新 [Python 开发者调研报告](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools)显示,这几种编辑器覆盖了约 80% 的用户。
也就是说,**FastAPI** 针对差不多 80% 的 Python 开发者使用的编辑器进行了测试,而且其它大多数编辑器的工作方式也与之类似,因此,**FastAPI** 的优势几乎能在所有编辑器上体现。
@ -52,11 +52,11 @@
## 需求项 { #requirements }
经过测试多种备选方案,我最终决定使用 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">**Pydantic**</a>,并充分利用它的优势。
经过测试多种备选方案,我最终决定使用 [**Pydantic**](https://docs.pydantic.dev/),并充分利用它的优势。
我甚至为它做了不少贡献,让它完美兼容了 JSON Schema,支持多种方式定义约束声明,并基于多个编辑器,改进了它对编辑器支持(类型检查、自动补全)。
在开发期间,我还为 <a href="https://www.starlette.dev/" class="external-link" target="_blank">**Starlette**</a> 做了不少贡献,这是另一个关键需求项。
在开发期间,我还为 [**Starlette**](https://www.starlette.dev/) 做了不少贡献,这是另一个关键需求项。
## 开发 { #development }
@ -74,4 +74,4 @@
**FastAPI** 前景光明。
在此,我们衷心感谢[您的帮助](help-fastapi.md){.internal-link target=_blank}
在此,我们衷心感谢[你的帮助](help-fastapi.md)

118
docs/zh/docs/index.md

@ -11,25 +11,25 @@
<em>FastAPI 框架,高性能,易于学习,高效编码,生产可用</em>
</p>
<p align="center">
<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank">
<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster">
<img src="https://github.com/fastapi/fastapi/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Test">
</a>
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi" target="_blank">
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi">
<img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="Coverage">
</a>
<a href="https://pypi.org/project/fastapi" target="_blank">
<a href="https://pypi.org/project/fastapi">
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
</a>
<a href="https://pypi.org/project/fastapi" target="_blank">
<a href="https://pypi.org/project/fastapi">
<img src="https://img.shields.io/pypi/pyversions/fastapi.svg?color=%2334D058" alt="Supported Python versions">
</a>
</p>
---
**文档**: <a href="https://fastapi.tiangolo.com/zh" target="_blank">https://fastapi.tiangolo.com</a>
**文档**: [https://fastapi.tiangolo.com/zh](https://fastapi.tiangolo.com/zh)
**源码**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a>
**源码**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi)
---
@ -44,7 +44,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框
* **易用**:为易用和易学而设计。更少的文档阅读时间。
* **简短**:最小化代码重复。一次参数声明即可获得多种功能。更少的 bug。
* **健壮**:生产可用级代码。并带有自动生成的交互式文档。
* **标准化**:基于(并完全兼容)API 的开放标准:<a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a>(以前称为 Swagger)和 <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>
* **标准化**:基于(并完全兼容)API 的开放标准:[OpenAPI](https://github.com/OAI/OpenAPI-Specification)(以前称为 Swagger)和 [JSON Schema](https://json-schema.org/)
<small>* 基于某内部开发团队在构建生产应用时的测试估算。</small>
@ -55,51 +55,51 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框
### Keystone 赞助商 { #keystone-sponsor }
{% for sponsor in sponsors.keystone -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
<a href="{{ sponsor.url }}" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
### 金牌和银牌赞助商 { #gold-and-silver-sponsors }
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
<a href="{{ sponsor.url }}" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
<a href="{{ sponsor.url }}" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
<!-- /sponsors -->
<a href="https://fastapi.tiangolo.com/zh/fastapi-people/#sponsors" class="external-link" target="_blank">其他赞助商</a>
[其他赞助商](https://fastapi.tiangolo.com/zh/fastapi-people/#sponsors)
## 评价 { #opinions }
「_[...] 最近我大量使用 **FastAPI**。[...] 我实际上计划把它用于我团队在 **微软** 的所有 **机器学习服务**。其中一些正在集成进核心 **Windows** 产品以及一些 **Office** 产品。_」
<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div>
<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26"><small>(ref)</small></a></div>
---
「_我们采用 **FastAPI** 来构建可查询以获取**预测结果**的 **REST** 服务器。[用于 Ludwig]_」
<div style="text-align: right; margin-right: 10%;">Piero Molino,Yaroslav Dudin,Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(ref)</small></a></div>
<div style="text-align: right; margin-right: 10%;">Piero Molino,Yaroslav Dudin,Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/"><small>(ref)</small></a></div>
---
「_**Netflix** 很高兴宣布开源我们的**危机管理**编排框架:**Dispatch**![使用 **FastAPI** 构建]_」
<div style="text-align: right; margin-right: 10%;">Kevin Glisson,Marc Vilanova,Forest Monsen - <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" target="_blank"><small>(ref)</small></a></div>
<div style="text-align: right; margin-right: 10%;">Kevin Glisson,Marc Vilanova,Forest Monsen - <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072"><small>(ref)</small></a></div>
---
「_我对 **FastAPI** 兴奋到飞起。它太有趣了!_」
<div style="text-align: right; margin-right: 10%;">Brian Okken - <strong><a href="https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855" target="_blank">Python Bytes</a> 播客主持人</strong> <a href="https://x.com/brianokken/status/1112220079972728832" target="_blank"><small>(ref)</small></a></div>
<div style="text-align: right; margin-right: 10%;">Brian Okken - <strong>[Python Bytes](https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855) 播客主持人</strong> <a href="https://x.com/brianokken/status/1112220079972728832"><small>(ref)</small></a></div>
---
「_老实说,你构建的东西非常稳健而且打磨得很好。从很多方面看,这就是我想让 **Hug** 成为的样子 —— 看到有人把它做出来真的很鼓舞人心。_」
<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong><a href="https://github.com/hugapi/hug" target="_blank">Hug</a> 作者</strong> <a href="https://news.ycombinator.com/item?id=19455465" target="_blank"><small>(ref)</small></a></div>
<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong>[Hug](https://github.com/hugapi/hug) 作者</strong> <a href="https://news.ycombinator.com/item?id=19455465"><small>(ref)</small></a></div>
---
@ -107,27 +107,27 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框
「_我们已经把我们的 **API** 切换到 **FastAPI** [...] 我想你会喜欢它 [...]_」
<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong><a href="https://explosion.ai" target="_blank">Explosion AI</a> 创始人 - <a href="https://spacy.io" target="_blank">spaCy</a> 作者</strong> <a href="https://x.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(ref)</small></a> - <a href="https://x.com/honnibal/status/1144031421859655680" target="_blank"><small>(ref)</small></a></div>
<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong>[Explosion AI](https://explosion.ai) 创始人 - [spaCy](https://spacy.io) 作者</strong> <a href="https://x.com/_inesmontani/status/1144173225322143744"><small>(ref)</small></a> - <a href="https://x.com/honnibal/status/1144031421859655680"><small>(ref)</small></a></div>
---
「_如果有人正在构建生产级的 Python API,我强烈推荐 **FastAPI**。它**设计优雅**、**使用简单**且**高度可扩展**,已经成为我们 API 优先开发战略中的**关键组件**,并驱动了许多自动化和服务,比如我们的 Virtual TAC Engineer。_」
<div style="text-align: right; margin-right: 10%;">Deon Pillsbury - <strong>Cisco</strong> <a href="https://www.linkedin.com/posts/deonpillsbury_cisco-cx-python-activity-6963242628536487936-trAp/" target="_blank"><small>(ref)</small></a></div>
<div style="text-align: right; margin-right: 10%;">Deon Pillsbury - <strong>Cisco</strong> <a href="https://www.linkedin.com/posts/deonpillsbury_cisco-cx-python-activity-6963242628536487936-trAp/"><small>(ref)</small></a></div>
---
## FastAPI 迷你纪录片 { #fastapi-mini-documentary }
在 2025 年末发布了一部<a href="https://www.youtube.com/watch?v=mpR8ngthqiE" class="external-link" target="_blank">FastAPI 迷你纪录片</a>,你可以在线观看:
在 2025 年末发布了一部 [FastAPI 迷你纪录片](https://www.youtube.com/watch?v=mpR8ngthqiE),你可以在线观看:
<a href="https://www.youtube.com/watch?v=mpR8ngthqiE" target="_blank"><img src="https://fastapi.tiangolo.com/img/fastapi-documentary.jpg" alt="FastAPI Mini Documentary"></a>
<a href="https://www.youtube.com/watch?v=mpR8ngthqiE"><img src="https://fastapi.tiangolo.com/img/fastapi-documentary.jpg" alt="FastAPI Mini Documentary"></a>
## **Typer**,命令行中的 FastAPI { #typer-the-fastapi-of-clis }
<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>
<a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>
如果你要开发一个用于终端的 <abbr title="Command Line Interface">命令行</abbr>应用而不是 Web API,看看 <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>
如果你要开发一个用于终端的 <abbr title="Command Line Interface - 命令行界面">命令行</abbr>应用而不是 Web API,看看 [**Typer**](https://typer.tiangolo.com/)
**Typer** 是 FastAPI 的小同胞。它的目标是成为**命令行中的 FastAPI**。⌨️ 🚀
@ -135,12 +135,12 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框
FastAPI 站在巨人的肩膀之上:
* <a href="https://www.starlette.dev/" class="external-link" target="_blank">Starlette</a> 负责 Web 部分。
* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 负责数据部分。
* [Starlette](https://www.starlette.dev/) 负责 Web 部分。
* [Pydantic](https://docs.pydantic.dev/) 负责数据部分。
## 安装 { #installation }
创建并激活一个<a href="https://fastapi.tiangolo.com/zh/virtual-environments/" class="external-link" target="_blank">虚拟环境</a>,然后安装 FastAPI:
创建并激活一个 [虚拟环境](https://fastapi.tiangolo.com/zh/virtual-environments/),然后安装 FastAPI:
<div class="termy">
@ -199,7 +199,7 @@ async def read_item(item_id: int, q: str | None = None):
**Note**:
如果你不确定,请查看文档中 _"In a hurry?"_ 章节的<a href="https://fastapi.tiangolo.com/zh/async/#in-a-hurry" target="_blank">`async` 和 `await`</a>部分。
如果你不确定,请查看文档中 _"In a hurry?"_ 章节的 [`async` 和 `await`](https://fastapi.tiangolo.com/zh/async/#in-a-hurry) 部分。
</details>
@ -210,7 +210,7 @@ async def read_item(item_id: int, q: str | None = None):
<div class="termy">
```console
$ fastapi dev main.py
$ fastapi dev
╭────────── FastAPI CLI - Development mode ───────────╮
│ │
@ -235,19 +235,19 @@ INFO: Application startup complete.
</div>
<details markdown="1">
<summary>关于命令 <code>fastapi dev main.py</code>...</summary>
<summary>关于命令 <code>fastapi dev</code>...</summary>
`fastapi dev` 命令会读取你的 `main.py` 文件,检测其中的 **FastAPI** 应用,并使用 <a href="https://www.uvicorn.dev" class="external-link" target="_blank">Uvicorn</a> 启动服务器。
`fastapi dev` 命令会读取你的 `main.py` 文件,检测其中的 **FastAPI** 应用,并使用 [Uvicorn](https://www.uvicorn.dev) 启动服务器。
默认情况下,`fastapi dev` 会在本地开发时启用自动重载。
你可以在 <a href="https://fastapi.tiangolo.com/zh/fastapi-cli/" target="_blank">FastAPI CLI 文档</a>中了解更多。
你可以在 [FastAPI CLI 文档](https://fastapi.tiangolo.com/zh/fastapi-cli/) 中了解更多。
</details>
### 检查 { #check-it }
用浏览器打开 <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>
用浏览器打开 [http://127.0.0.1:8000/items/5?q=somequery](http://127.0.0.1:8000/items/5?q=somequery)
你会看到如下 JSON 响应:
@ -264,17 +264,17 @@ INFO: Application startup complete.
### 交互式 API 文档 { #interactive-api-docs }
现在访问 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>
现在访问 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
你会看到自动生成的交互式 API 文档(由 <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> 提供):
你会看到自动生成的交互式 API 文档(由 [Swagger UI](https://github.com/swagger-api/swagger-ui) 提供):
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
### 可选的 API 文档 { #alternative-api-docs }
然后访问 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>
然后访问 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)
你会看到另一个自动生成的文档(由 <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> 提供):
你会看到另一个自动生成的文档(由 [ReDoc](https://github.com/Rebilly/ReDoc) 提供):
![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
@ -316,7 +316,7 @@ def update_item(item_id: int, item: Item):
### 交互式 API 文档升级 { #interactive-api-docs-upgrade }
现在访问 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>
现在访问 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
* 交互式 API 文档会自动更新,并包含新的请求体:
@ -332,7 +332,7 @@ def update_item(item_id: int, item: Item):
### 可选文档升级 { #alternative-api-docs-upgrade }
再访问 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>
再访问 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)
* 可选文档同样会体现新的查询参数和请求体:
@ -442,7 +442,7 @@ item: Item
* 功能强大且易用的 **<dfn title="也被称为:组件、资源、提供者、服务、可注入项">依赖注入</dfn>** 系统。
* 安全与认证,包括对 **OAuth2**、**JWT tokens** 和 **HTTP Basic** 认证的支持。
* 更高级(但同样简单)的 **多层嵌套 JSON 模型** 声明技巧(得益于 Pydantic)。
* 通过 <a href="https://strawberry.rocks" class="external-link" target="_blank">Strawberry</a> 等库进行 **GraphQL** 集成。
* 通过 [Strawberry](https://strawberry.rocks) 等库进行 **GraphQL** 集成。
* 许多额外特性(归功于 Starlette),例如:
* **WebSockets**
* 基于 HTTPX 和 `pytest` 的极其简单的测试
@ -452,24 +452,10 @@ item: Item
### 部署你的应用(可选) { #deploy-your-app-optional }
你可以选择把 FastAPI 应用部署到 <a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>,如果还没有的话去加入候补名单吧。🚀
你可以选择把 FastAPI 应用部署到 [FastAPI Cloud](https://fastapicloud.com),如果还没有的话去加入候补名单吧。🚀
如果你已经有 **FastAPI Cloud** 账号(我们从候补名单邀请了你 😉),你可以用一个命令部署你的应用。
部署前,先确认已登录:
<div class="termy">
```console
$ fastapi login
You are logged in to FastAPI Cloud 🚀
```
</div>
然后部署你的应用:
<div class="termy">
```console
@ -488,7 +474,7 @@ Deploying to FastAPI Cloud...
#### 关于 FastAPI Cloud { #about-fastapi-cloud }
**<a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>** 由 **FastAPI** 的同一位作者和团队打造。
**[FastAPI Cloud](https://fastapicloud.com)** 由 **FastAPI** 的同一位作者和团队打造。
它让你以最小的工作量就能**构建**、**部署**并**访问**一个 API。
@ -504,9 +490,9 @@ FastAPI 是开源且基于标准的。你可以部署 FastAPI 应用到你选择
## 性能 { #performance }
独立机构 TechEmpower 的基准测试显示,运行在 Uvicorn 下的 **FastAPI** 应用是<a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">最快的 Python 框架之一</a>,仅次于 Starlette 和 Uvicorn 本身(FastAPI 内部使用它们)。(*)
独立机构 TechEmpower 的基准测试显示,运行在 Uvicorn 下的 **FastAPI** 应用是 [最快的 Python 框架之一](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7),仅次于 Starlette 和 Uvicorn 本身(FastAPI 内部使用它们)。(*)
想了解更多,请参阅<a href="https://fastapi.tiangolo.com/zh/benchmarks/" class="internal-link" target="_blank">基准测试</a>章节。
想了解更多,请参阅 [基准测试](https://fastapi.tiangolo.com/zh/benchmarks/) 章节。
## 依赖项 { #dependencies }
@ -518,19 +504,19 @@ FastAPI 依赖 Pydantic 和 Starlette。
Pydantic 使用:
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - 用于 email 校验。
* [`email-validator`](https://github.com/JoshData/python-email-validator) - 用于 email 校验。
Starlette 使用:
* <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - 使用 `TestClient` 时需要。
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - 使用默认模板配置时需要。
* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - 使用 `request.form()` 支持表单<dfn title="将 HTTP 请求中的字符串转换为 Python 数据">「解析」</dfn>时需要。
* [`httpx`](https://www.python-httpx.org) - 使用 `TestClient` 时需要。
* [`jinja2`](https://jinja.palletsprojects.com) - 使用默认模板配置时需要。
* [`python-multipart`](https://github.com/Kludex/python-multipart) - 使用 `request.form()` 支持表单<dfn title="将 HTTP 请求中的字符串转换为 Python 数据">「解析」</dfn>时需要。
FastAPI 使用:
* <a href="https://www.uvicorn.dev" target="_blank"><code>uvicorn</code></a> - 加载并提供你的应用的服务器。包含 `uvicorn[standard]`,其中包含高性能服务所需的一些依赖(例如 `uvloop`)。
* [`uvicorn`](https://www.uvicorn.dev) - 加载并提供你的应用的服务器。包含 `uvicorn[standard]`,其中包含高性能服务所需的一些依赖(例如 `uvloop`)。
* `fastapi-cli[standard]` - 提供 `fastapi` 命令。
* 其中包含 `fastapi-cloud-cli`,它允许你将 FastAPI 应用部署到 <a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>
* 其中包含 `fastapi-cloud-cli`,它允许你将 FastAPI 应用部署到 [FastAPI Cloud](https://fastapicloud.com)
### 不包含 `standard` 依赖 { #without-standard-dependencies }
@ -546,13 +532,13 @@ FastAPI 使用:
额外的 Pydantic 可选依赖:
* <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - 用于配置管理。
* <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - 用于在 Pydantic 中使用的额外类型。
* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - 用于配置管理。
* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - 用于在 Pydantic 中使用的额外类型。
额外的 FastAPI 可选依赖:
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - 使用 `ORJSONResponse` 时需要。
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - 使用 `UJSONResponse` 时需要。
* [`orjson`](https://github.com/ijl/orjson) - 使用 `ORJSONResponse` 时需要。
* [`ujson`](https://github.com/esnme/ultrajson) - 使用 `UJSONResponse` 时需要。
## 许可协议 { #license }

2
docs/zh/docs/project-generation.md

@ -4,7 +4,7 @@
你可以使用此模板开始,它已经为你完成了大量的初始设置、安全性、数据库以及一些 API 端点。
GitHub 仓库: <a href="https://github.com/tiangolo/full-stack-fastapi-template" class="external-link" target="_blank">Full Stack FastAPI Template</a>
GitHub 仓库:[Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template)
## FastAPI全栈模板 - 技术栈和特性 { #full-stack-fastapi-template-technology-stack-and-features }

10
docs/zh/docs/python-types.md

@ -269,7 +269,7 @@ def some_function(data: Any):
## Pydantic 模型 { #pydantic-models }
<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 是一个用于执行数据校验的 Python 库。
[Pydantic](https://docs.pydantic.dev/) 是一个用于执行数据校验的 Python 库。
你将数据的“结构”声明为带有属性的类。
@ -285,13 +285,13 @@ def some_function(data: Any):
/// info | 信息
想了解更多关于 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic 的信息,请查看其文档</a>
想了解更多关于 [Pydantic](https://docs.pydantic.dev/) 的信息,请查看其文档
///
**FastAPI** 完全建立在 Pydantic 之上。
你会在[教程 - 用户指南](tutorial/index.md){.internal-link target=_blank}中看到更多的实战示例。
你会在[教程 - 用户指南](tutorial/index.md)中看到更多的实战示例。
## 带元数据注解的类型提示 { #type-hints-with-metadata-annotations }
@ -337,12 +337,12 @@ Python 本身不会对这个 `Annotated` 做任何处理。对于编辑器和其
* 使用 OpenAPI 记录 API:
* 然后用于自动生成交互式文档界面。
这些听起来可能有点抽象。别担心。你会在[教程 - 用户指南](tutorial/index.md){.internal-link target=_blank}中看到所有这些的实际效果。
这些听起来可能有点抽象。别担心。你会在[教程 - 用户指南](tutorial/index.md)中看到所有这些的实际效果。
重要的是,通过使用标准的 Python 类型,而且只在一个地方声明(而不是添加更多类、装饰器等),**FastAPI** 会为你完成大量工作。
/// info | 信息
如果你已经读完所有教程,又回来想进一步了解类型,一个不错的资源是 <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy` 的“速查表”</a>
如果你已经读完所有教程,又回来想进一步了解类型,一个不错的资源是 [`mypy` 的“速查表”](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)
///

49
docs/zh/docs/tutorial/bigger-applications.md

@ -123,7 +123,7 @@ from app.routers import items
我们正在使用虚构的请求首部来简化此示例。
但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。
但在实际情况下,使用集成的[安全性实用工具](security/index.md)会得到更好的效果。
///
@ -169,7 +169,7 @@ async def read_item(item_id: str):
/// tip | 提示
请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。
请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md)很类似,没有值会被传递给你的*路径操作函数*。
///
@ -185,8 +185,8 @@ async def read_item(item_id: str):
* 所有的路径操作都将包含预定义的 `responses`
* 所有的这些*路径操作*都将在自身之前计算/执行 `dependencies` 列表。
* 如果你还在一个具体的*路径操作*中声明了依赖项,**它们也会被执行**。
* 路由器的依赖项最先执行,然后是[装饰器中的 `dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank},再然后是普通的参数依赖项。
* 你还可以添加[具有 `scopes``Security` 依赖项](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}
* 路由器的依赖项最先执行,然后是[装饰器中的 `dependencies`](dependencies/dependencies-in-path-operation-decorators.md),再然后是普通的参数依赖项。
* 你还可以添加[具有 `scopes``Security` 依赖项](../advanced/security/oauth2-scopes.md)。
/// tip | 提示
@ -303,7 +303,7 @@ from ...dependencies import get_token_header
你可以像平常一样导入并创建一个 `FastAPI` 类。
我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起:
我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md),它会和每个 `APIRouter` 的依赖项组合在一起:
{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
@ -353,7 +353,7 @@ from .routers import items, users
from app.routers import items, users
```
要了解有关 Python 包和模块的更多信息,请查阅<a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">关于 Modules 的 Python 官方文档</a>
要了解有关 Python 包和模块的更多信息,请查阅[关于 Modules 的 Python 官方文档](https://docs.python.org/3/tutorial/modules.html)
///
@ -451,7 +451,7 @@ from .routers.users import router
它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。
/// info | 特别的技术细节
/// info | 非常技术细节
**注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。
@ -465,6 +465,37 @@ from .routers.users import router
///
## 在 `pyproject.toml` 中配置 `entrypoint` { #configure-the-entrypoint-in-pyproject-toml }
因为你的 FastAPI `app` 对象位于 `app/main.py` 中,你可以在 `pyproject.toml` 中这样配置 `entrypoint`
```toml
[tool.fastapi]
entrypoint = "app.main:app"
```
等价于像这样导入:
```python
from app.main import app
```
这样 `fastapi` 命令就知道到哪里去找到你的应用了。
/// Note | 注意
你也可以把路径传给命令,比如:
```console
$ fastapi dev app/main.py
```
但是每次调用 `fastapi` 命令时,你都需要记得传入正确的路径。
另外,其他工具可能找不到它,比如 [VS Code 扩展](../editor-support.md) 或 [FastAPI Cloud](https://fastapicloud.com),因此推荐在 `pyproject.toml` 中使用 `entrypoint`
///
## 查看自动化的 API 文档 { #check-the-automatic-api-docs }
现在,运行你的应用:
@ -472,14 +503,14 @@ from .routers.users import router
<div class="termy">
```console
$ fastapi dev app/main.py
$ fastapi dev
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
然后打开位于 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a> 的文档。
然后打开位于 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) 的文档。
你将看到使用了正确路径(和前缀)和正确标签的自动化 API 文档,包括了来自所有子模块的路径:

6
docs/zh/docs/tutorial/body-updates.md

@ -2,7 +2,7 @@
## 用 `PUT` 替换式更新 { #update-replacing-with-put }
更新数据可以使用 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT" class="external-link" target="_blank">HTTP `PUT`</a> 操作。
更新数据可以使用 [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) 操作。
把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`
@ -28,7 +28,7 @@
## 用 `PATCH` 进行部分更新 { #partial-updates-with-patch }
也可以使用 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH" class="external-link" target="_blank">HTTP `PATCH`</a> 操作对数据进行*部分*更新。
也可以使用 [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) 操作对数据进行*部分*更新。
也就是说,你只需发送想要更新的数据,其余数据保持不变。
@ -95,6 +95,6 @@
因此,如果希望接收的部分更新可以省略所有属性,则需要一个所有属性都标记为可选(带默认值或 `None`)的模型。
为了区分用于**更新**(全部可选)和用于**创建**(必填)的模型,可以参考[更多模型](extra-models.md){.internal-link target=_blank} 中介绍的思路。
为了区分用于**更新**(全部可选)和用于**创建**(必填)的模型,可以参考[更多模型](extra-models.md) 中介绍的思路。
///

8
docs/zh/docs/tutorial/cors.md

@ -1,6 +1,6 @@
# CORS(跨域资源共享) { #cors-cross-origin-resource-sharing }
<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">CORS 或者「跨域资源共享」</a> 指浏览器中运行的前端拥有与后端通信的 JavaScript 代码,而后端处于与前端不同的「源」的情况。
[CORS 或者「跨域资源共享」](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) 指浏览器中运行的前端拥有与后端通信的 JavaScript 代码,而后端处于与前端不同的「源」的情况。
## 源 { #origin }
@ -55,10 +55,10 @@
* `allow_origins` - 一个允许跨域请求的源列表。例如 `['https://example.org', 'https://www.example.org']`。你可以使用 `['*']` 允许任何源。
* `allow_origin_regex` - 一个正则表达式字符串,匹配的源允许跨域请求。例如 `'https://.*\.example\.org'`
* `allow_methods` - 一个允许跨域请求的 HTTP 方法列表。默认为 `['GET']`。你可以使用 `['*']` 来允许所有标准方法。
* `allow_headers` - 一个允许跨域请求的 HTTP 请求头列表。默认为 `[]`。你可以使用 `['*']` 允许所有的请求头。`Accept`、`Accept-Language`、`Content-Language` 以及 `Content-Type` 这几个请求头在<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests" class="external-link" rel="noopener" target="_blank">简单 CORS 请求</a>中总是被允许。
* `allow_headers` - 一个允许跨域请求的 HTTP 请求头列表。默认为 `[]`。你可以使用 `['*']` 允许所有的请求头。`Accept`、`Accept-Language`、`Content-Language` 以及 `Content-Type` 这几个请求头在[简单 CORS 请求](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests)中总是被允许。
* `allow_credentials` - 指示跨域请求支持 cookies。默认是 `False`
`allow_credentials` 设为 `True` 时,`allow_origins`、`allow_methods` 和 `allow_headers` 都不能设为 `['*']`。它们必须<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#credentialed_requests_and_wildcards" class="external-link" rel="noopener" target="_blank">显式指定</a>
`allow_credentials` 设为 `True` 时,`allow_origins`、`allow_methods` 和 `allow_headers` 都不能设为 `['*']`。它们必须[显式指定](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#credentialed_requests_and_wildcards)
* `expose_headers` - 指示可以被浏览器访问的响应头。默认为 `[]`
* `max_age` - 设定浏览器缓存 CORS 响应的最长时间,单位是秒。默认为 `600`
@ -77,7 +77,7 @@
## 更多信息 { #more-info }
更多关于 <abbr title="Cross-Origin Resource Sharing - 跨域资源共享">CORS</abbr> 的信息,请查看 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS 文档</a>
更多关于 <abbr title="Cross-Origin Resource Sharing - 跨域资源共享">CORS</abbr> 的信息,请查看 [Mozilla CORS 文档](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
/// note | 技术细节

2
docs/zh/docs/tutorial/debugging.md

@ -70,7 +70,7 @@ from myapp import app
/// info | 信息
更多信息请检查 <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">Python 官方文档</a>.
更多信息请检查 [Python 官方文档](https://docs.python.org/3/library/__main__.html).
///

4
docs/zh/docs/tutorial/encoder.md

@ -12,7 +12,7 @@
例如,它不接收`datetime`这类的对象,因为这些对象与JSON不兼容。
因此,`datetime`对象必须转换为包含<a href="https://en.wikipedia.org/wiki/ISO_8601" class="external-link" target="_blank">ISO 格式</a>的`str`类型对象。
因此,`datetime`对象必须转换为包含[ISO 格式](https://en.wikipedia.org/wiki/ISO_8601)的`str`类型对象。
同样,这个数据库也不会接收Pydantic模型(带有属性的对象),而只接收`dict`。
@ -24,7 +24,7 @@
在这个例子中,它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。
调用它的结果后就可以使用Python标准编码中的<a href="https://docs.python.org/3/library/json.html#json.dumps" class="external-link" target="_blank">`json.dumps()`</a>
调用它的结果后就可以使用Python标准编码中的[`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps)。
这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。

4
docs/zh/docs/tutorial/extra-data-types.md

@ -36,7 +36,7 @@
* `datetime.timedelta`:
* 一个 Python `datetime.timedelta`.
* 在请求和响应中将表示为 `float` 代表总秒数。
* Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", <a href="https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers" class="external-link" target="_blank">查看文档了解更多信息</a>
* Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", [查看文档了解更多信息](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers)
* `frozenset`:
* 在请求和响应中,作为 `set` 对待:
* 在请求中,列表将被读取,消除重复,并将其转换为一个 `set`
@ -49,7 +49,7 @@
* `Decimal`:
* 标准的 Python `Decimal`
* 在请求和响应中被当做 `float` 一样处理。
* 您可以在这里检查所有有效的 Pydantic 数据类型: <a href="https://docs.pydantic.dev/latest/usage/types/types/" class="external-link" target="_blank">Pydantic data types</a>.
* 您可以在这里检查所有有效的 Pydantic 数据类型: [Pydantic data types](https://docs.pydantic.dev/latest/usage/types/types/)。
## 例子 { #example }

8
docs/zh/docs/tutorial/extra-models.md

@ -108,7 +108,7 @@ UserInDB(**user_dict)
UserInDB(**user_in.model_dump())
```
……因为 `user_in.model_dump()``dict`,在传递给 `UserInDB` 时,把 `**` 加在 `user_in.model_dump()` 前,可以让 Python 进行解包。
...因为 `user_in.model_dump()``dict`,在传递给 `UserInDB` 时,把 `**` 加在 `user_in.model_dump()` 前,可以让 Python 进行解包。
这样,就可以用其它 Pydantic 模型中的数据生成 Pydantic 模型。
@ -120,7 +120,7 @@ UserInDB(**user_in.model_dump())
UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
```
……输出结果如下:
...输出结果如下:
```Python
UserInDB(
@ -162,11 +162,11 @@ UserInDB(
在 OpenAPI 中会用 `anyOf` 表示。
为此,请使用 Python 标准类型提示 <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>
为此,请使用 Python 标准类型提示 [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union)
/// note | 注意
定义 <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a> 类型时,要把更具体的类型写在前面,然后是不太具体的类型。下例中,更具体的 `PlaneItem` 位于 `Union[PlaneItem, CarItem]` 中的 `CarItem` 之前。
定义 [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions) 类型时,要把更具体的类型写在前面,然后是不太具体的类型。下例中,更具体的 `PlaneItem` 位于 `Union[PlaneItem, CarItem]` 中的 `CarItem` 之前。
///

75
docs/zh/docs/tutorial/first-steps.md

@ -11,7 +11,7 @@
<div class="termy">
```console
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:solid">main.py</u>
$ <font color="#4E9A06">fastapi</font> dev
<span style="background-color:#009485"><font color="#D3D7CF"> FastAPI </font></span> Starting development server 🚀
@ -58,7 +58,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
### 查看 { #check-it }
打开浏览器访问 <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000</a>
打开浏览器访问 [http://127.0.0.1:8000](http://127.0.0.1:8000)
你将看到如下的 JSON 响应:
@ -68,17 +68,17 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
### 交互式 API 文档 { #interactive-api-docs }
跳转到 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>
跳转到 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
你将会看到自动生成的交互式 API 文档(由 <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> 提供):
你将会看到自动生成的交互式 API 文档(由 [Swagger UI](https://github.com/swagger-api/swagger-ui) 提供):
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
### 可选的 API 文档 { #alternative-api-docs }
前往 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>
前往 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)
你将会看到可选的自动生成文档 (由 <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> 提供):
你将会看到可选的自动生成文档 (由 [ReDoc](https://github.com/Rebilly/ReDoc) 提供):
![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
@ -92,7 +92,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
#### API「模式」 { #api-schema }
在这种场景下,<a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> 是一种规定如何定义 API 模式的规范。
在这种场景下,[OpenAPI](https://github.com/OAI/OpenAPI-Specification) 是一种规定如何定义 API 模式的规范。
「模式」的定义包括你的 API 路径,以及它们可能使用的参数等等。
@ -110,7 +110,7 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送
如果你对原始的 OpenAPI 模式长什么样子感到好奇,FastAPI 自动生成了包含所有 API 描述的 JSON(模式)。
你可以直接在:<a href="http://127.0.0.1:8000/openapi.json" class="external-link" target="_blank">http://127.0.0.1:8000/openapi.json</a> 看到它。
你可以直接在:[http://127.0.0.1:8000/openapi.json](http://127.0.0.1:8000/openapi.json) 看到它。
它将显示以如下内容开头的 JSON:
@ -143,9 +143,58 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送
你还可以使用它自动生成与你的 API 进行通信的客户端代码。例如 web 前端,移动端或物联网嵌入程序。
### 在 `pyproject.toml` 中配置应用 `entrypoint` { #configure-the-app-entrypoint-in-pyproject-toml }
你可以在 `pyproject.toml` 文件中配置应用的位置,例如:
```toml
[tool.fastapi]
entrypoint = "main:app"
```
`entrypoint` 会告诉 `fastapi` 命令按如下方式导入应用:
```python
from main import app
```
如果你的代码结构如下:
```
.
├── backend
│   ├── main.py
│   ├── __init__.py
```
那么你可以将 `entrypoint` 设置为:
```toml
[tool.fastapi]
entrypoint = "backend.main:app"
```
这等价于:
```python
from backend.main import app
```
### `fastapi dev` 带路径 { #fastapi-dev-with-path }
你也可以把文件路径传给 `fastapi dev` 命令,它会尝试推断要使用的 FastAPI 应用对象:
```console
$ fastapi dev main.py
```
但这样每次调用 `fastapi` 命令时都需要记得传入正确的路径。
另外,其他工具可能无法找到它,例如 [VS Code 扩展](../editor-support.md) 或 [FastAPI Cloud](https://fastapicloud.com),因此推荐在 `pyproject.toml` 中使用 `entrypoint`
### 部署你的应用(可选) { #deploy-your-app-optional }
你可以选择将 FastAPI 应用部署到 <a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>,如果还没有,先去加入候补名单。🚀
你可以选择将 FastAPI 应用部署到 [FastAPI Cloud](https://fastapicloud.com),如果还没有,先去加入候补名单。🚀
如果你已经拥有 **FastAPI Cloud** 账户(我们从候补名单邀请了你 😉),你可以用一条命令部署应用。
@ -191,7 +240,7 @@ Deploying to FastAPI Cloud...
`FastAPI` 是直接从 `Starlette` 继承的类。
你可以通过 `FastAPI` 使用所有的 <a href="https://www.starlette.dev/" class="external-link" target="_blank">Starlette</a> 的功能。
你可以通过 `FastAPI` 使用所有的 [Starlette](https://www.starlette.dev/) 的功能。
///
@ -273,7 +322,7 @@ https://example.com/items/foo
* 请求路径为 `/`
* 使用 <dfn title="一种 HTTP GET 方法"><code>get</code> 操作</dfn>
/// info | `@decorator` Info
/// info | `@decorator` 信息
`@something` 语法在 Python 中被称为「装饰器」。
@ -352,11 +401,11 @@ https://example.com/items/foo
### 步骤 6:部署 { #step-6-deploy-it }
用一条命令将你的应用部署到 **<a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>**:`fastapi deploy`。🎉
用一条命令将你的应用部署到 **[FastAPI Cloud](https://fastapicloud.com)**:`fastapi deploy`。🎉
#### 关于 FastAPI Cloud { #about-fastapi-cloud }
**<a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>** 由 **FastAPI** 的作者和团队打造。
**[FastAPI Cloud](https://fastapicloud.com)** 由 **FastAPI** 的作者和团队打造。
它以最小的投入简化了 **构建**、**部署** 和 **访问** API 的流程。

2
docs/zh/docs/tutorial/handling-errors.md

@ -81,7 +81,7 @@
## 安装自定义异常处理器 { #install-custom-exception-handlers }
可以使用<a href="https://www.starlette.dev/exceptions/" class="external-link" target="_blank">与 Starlette 相同的异常处理工具</a>添加自定义异常处理器。
可以使用[与 Starlette 相同的异常处理工具](https://www.starlette.dev/exceptions/)添加自定义异常处理器。
假设有一个自定义异常 `UnicornException`(你自己或你使用的库可能会 `raise` 它)。

14
docs/zh/docs/tutorial/index.md

@ -10,12 +10,12 @@
所有代码片段都可以复制后直接使用(它们实际上是经过测试的 Python 文件)。
要运行任何示例,请将代码复制到 `main.py` 文件中,然后使用以下命令启动 `fastapi dev`
要运行任何示例,请将代码复制到 `main.py` 文件中,然后启动 `fastapi dev`
<div class="termy">
```console
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:solid">main.py</u>
$ <font color="#4E9A06">fastapi</font> dev
<span style="background-color:#009485"><font color="#D3D7CF"> FastAPI </font></span> Starting development server 🚀
@ -62,7 +62,7 @@ $ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:solid
第一个步骤是安装 FastAPI.
请确保您创建并激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后**安装 FastAPI**:
请确保您创建并激活一个[虚拟环境](../virtual-environments.md),然后**安装 FastAPI**:
<div class="termy">
@ -76,7 +76,7 @@ $ pip install "fastapi[standard]"
/// note | 注意
当您使用 `pip install "fastapi[standard]"` 安装时,它会附带一些默认的可选标准依赖项,其中包括 `fastapi-cloud-cli`,它可以让您部署到 <a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>
当您使用 `pip install "fastapi[standard]"` 安装时,它会附带一些默认的可选标准依赖项,其中包括 `fastapi-cloud-cli`,它可以让您部署到 [FastAPI Cloud](https://fastapicloud.com)
如果您不想安装这些可选依赖,可以选择安装 `pip install fastapi`
@ -84,6 +84,12 @@ $ pip install "fastapi[standard]"
///
/// tip | 提示
FastAPI 提供了一个[VS Code 官方扩展](https://marketplace.visualstudio.com/items?itemName=FastAPILabs.fastapi-vscode)(也支持 Cursor),包含众多功能,例如路径操作浏览器、路径操作搜索、测试中的 CodeLens 导航(从测试跳转到定义),以及从编辑器内进行 FastAPI Cloud 部署和查看日志。
///
## 进阶用户指南 { #advanced-user-guide }
在本**教程-用户指南**之后,您可以阅读**进阶用户指南**。

10
docs/zh/docs/tutorial/middleware.md

@ -15,7 +15,7 @@
如果你有使用 `yield` 的依赖,依赖中的退出代码会在中间件之后运行。
如果有任何后台任务(会在[后台任务](background-tasks.md){.internal-link target=_blank}一节中介绍,你稍后会看到),它们会在所有中间件之后运行。
如果有任何后台任务(会在[后台任务](background-tasks.md)一节中介绍,你稍后会看到),它们会在所有中间件之后运行。
///
@ -35,9 +35,9 @@
/// tip
请记住可以<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">使用 `X-` 前缀</a>添加专有自定义请求头。
请记住可以[使用 `X-` 前缀](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)添加专有自定义请求头。
但是如果你有希望让浏览器中的客户端可见的自定义请求头,你需要把它们加到你的 CORS 配置([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})的 `expose_headers` 参数中,参见 <a href="https://www.starlette.dev/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette 的 CORS 文档</a>
但是如果你有希望让浏览器中的客户端可见的自定义请求头,你需要把它们加到你的 CORS 配置([CORS(跨域资源共享)](cors.md))的 `expose_headers` 参数中,参见 [Starlette 的 CORS 文档](https://www.starlette.dev/middleware/#corsmiddleware)
///
@ -61,7 +61,7 @@
/// tip
这里我们使用 <a href="https://docs.python.org/3/library/time.html#time.perf_counter" class="external-link" target="_blank">`time.perf_counter()`</a> 而不是 `time.time()`,因为在这类场景中它可能更精确。🤓
这里我们使用 [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) 而不是 `time.time()`,因为在这类场景中它可能更精确。🤓
///
@ -90,6 +90,6 @@ app.add_middleware(MiddlewareB)
## 其他中间件 { #other-middlewares }
你可以稍后在[高级用户指南:高级中间件](../advanced/middleware.md){.internal-link target=_blank}中阅读更多关于其他中间件的内容。
你可以稍后在[高级用户指南:高级中间件](../advanced/middleware.md)中阅读更多关于其他中间件的内容。
你将在下一节中了解如何使用中间件处理 <abbr title="Cross-Origin Resource Sharing - 跨域资源共享">CORS</abbr>

16
docs/zh/docs/tutorial/path-params.md

@ -6,7 +6,7 @@
路径参数 `item_id` 的值会作为参数 `item_id` 传递给你的函数。
运行示例并访问 <a href="http://127.0.0.1:8000/items/foo" class="external-link" target="_blank">http://127.0.0.1:8000/items/foo</a>,可获得如下响应:
运行示例并访问 [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo),可获得如下响应:
```JSON
{"item_id":"foo"}
@ -28,7 +28,7 @@
## 数据<dfn title="也称为:序列化、解析、编组">转换</dfn> { #data-conversion }
运行示例并访问 <a href="http://127.0.0.1:8000/items/3" class="external-link" target="_blank">http://127.0.0.1:8000/items/3</a>,返回的响应如下:
运行示例并访问 [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3),返回的响应如下:
```JSON
{"item_id":3}
@ -44,7 +44,7 @@
## 数据校验 { #data-validation }
通过浏览器访问 <a href="http://127.0.0.1:8000/items/foo" class="external-link" target="_blank">http://127.0.0.1:8000/items/foo</a>,接收如下 HTTP 错误信息:
通过浏览器访问 [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo),接收如下 HTTP 错误信息:
```JSON
{
@ -64,7 +64,7 @@
这是因为路径参数 `item_id` 的值(`"foo"`)的类型不是 `int`
值的类型不是 `int` 而是浮点数(`float`)时也会显示同样的错误,比如: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>
值的类型不是 `int` 而是浮点数(`float`)时也会显示同样的错误,比如: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
/// check | 检查
@ -78,7 +78,7 @@
## 文档 { #documentation }
访问 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>,查看自动生成的交互式 API 文档:
访问 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs),查看自动生成的交互式 API 文档:
<img src="/img/tutorial/path-params/image01.png">
@ -92,9 +92,9 @@
## 基于标准的好处,备选文档 { #standards-based-benefits-alternative-documentation }
**FastAPI** 使用 <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md" class="external-link" target="_blank">OpenAPI</a> 生成概图,所以能兼容很多工具。
**FastAPI** 使用 [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md) 生成概图,所以能兼容很多工具。
因此,**FastAPI** 还内置了 ReDoc 生成的备选 API 文档,可在此查看 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>
因此,**FastAPI** 还内置了 ReDoc 生成的备选 API 文档,可在此查看 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)
<img src="/img/tutorial/path-params/image02.png">
@ -102,7 +102,7 @@
## Pydantic { #pydantic }
FastAPI 充分地利用了 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 的优势,用它在后台校验数据。众所周知,Pydantic 擅长的就是数据校验。
FastAPI 充分地利用了 [Pydantic](https://docs.pydantic.dev/) 的优势,用它在后台校验数据。众所周知,Pydantic 擅长的就是数据校验。
同样,`str`、`float`、`bool` 以及很多复合数据类型都可以使用类型声明。

20
docs/zh/docs/tutorial/query-params-str-validations.md

@ -35,13 +35,13 @@ FastAPI 在 0.95.0 版本中添加了对 `Annotated` 的支持(并开始推荐
如果你的版本更旧,使用 `Annotated` 会报错。
在使用 `Annotated` 之前,请确保先[升级 FastAPI 版本](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}到至少 0.95.1。
在使用 `Annotated` 之前,请确保先[升级 FastAPI 版本](../deployment/versions.md#upgrading-the-fastapi-versions)到至少 0.95.1。
///
## 在 `q` 参数的类型中使用 `Annotated` { #use-annotated-in-the-type-for-the-q-parameter }
还记得我之前在[Python 类型简介](../python-types.md#type-hints-with-metadata-annotations){.internal-link target=_blank}中说过可以用 `Annotated` 给参数添加元数据吗?
还记得我之前在[Python 类型简介](../python-types.md#type-hints-with-metadata-annotations)中说过可以用 `Annotated` 给参数添加元数据吗?
现在正是与 FastAPI 搭配使用它的时候。🚀
@ -105,7 +105,7 @@ FastAPI 现在会:
q: str | None = Query(default=None)
```
……会让参数变成可选,默认值为 `None`,等同于:
...会让参数变成可选,默认值为 `None`,等同于:
```Python
q: str | None = None
@ -133,7 +133,7 @@ q: str | None = Query(default=None, max_length=50)
q: Annotated[str, Query(default="rick")] = "morty"
```
……因为不清楚默认值应该是 `"rick"` 还是 `"morty"`
...因为不清楚默认值应该是 `"rick"` 还是 `"morty"`
因此,你应该这样用(推荐):
@ -141,7 +141,7 @@ q: Annotated[str, Query(default="rick")] = "morty"
q: Annotated[str, Query()] = "rick"
```
……或者在旧代码库中你会见到:
...或者在旧代码库中你会见到:
```Python
q: str = Query(default="rick")
@ -157,7 +157,7 @@ q: str = Query(default="rick")
当你不使用 `Annotated` 而是使用**(旧的)默认值风格**时,如果你在**其他地方**不通过 FastAPI 调用该函数,你必须**记得**给函数传参,否则得到的值会和预期不同(例如得到 `QueryInfo` 之类的对象而不是 `str`)。而你的编辑器不会报错,Python 也不会在调用时报错,只有在函数内部的操作出错时才会暴露问题。
由于 `Annotated` 可以包含多个元数据标注,你甚至可以用同一个函数与其他工具配合,例如 <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">Typer</a>。🚀
由于 `Annotated` 可以包含多个元数据标注,你甚至可以用同一个函数与其他工具配合,例如 [Typer](https://typer.tiangolo.com/)。🚀
## 添加更多校验 { #add-more-validations }
@ -337,7 +337,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
最接近的有效名称是 `item_query`
但你仍然需要它在 URL 中就是 `item-query`……
但你仍然需要它在 URL 中就是 `item-query`...
这时可以用 `alias` 参数声明一个别名,FastAPI 会用该别名在 URL 中查找参数值:
@ -369,11 +369,11 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
在这些情况下,你可以使用**自定义校验函数**,该函数会在正常校验之后应用(例如,在先校验值是 `str` 之后)。
你可以在 `Annotated` 中使用 <a href="https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator" class="external-link" target="_blank">Pydantic 的 `AfterValidator`</a> 来实现。
你可以在 `Annotated` 中使用 [Pydantic 的 `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) 来实现。
/// tip | 提示
Pydantic 还有 <a href="https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator" class="external-link" target="_blank">`BeforeValidator`</a> 等。🤓
Pydantic 还有 [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) 等。🤓
///
@ -421,7 +421,7 @@ Pydantic 还有 <a href="https://docs.pydantic.dev/latest/concepts/validators/#f
所以,即使用户没有提供条目 ID,他们仍然会收到一个随机推荐。
……而我们把这些都放在**一行简单的代码**里完成。🤯 你不爱 Python 吗?🐍
...而我们把这些都放在**一行简单的代码**里完成。🤯 你不爱 Python 吗?🐍
{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}

14
docs/zh/docs/tutorial/query-params.md

@ -1,6 +1,6 @@
# 查询参数 { #query-parameters }
声明的参数不是路径参数时,路径操作函数会把该参数自动解释为**查询**参数。
声明的参数不是路径参数时,路径操作函数会把该参数自动解释为“查询”参数。
{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
@ -17,7 +17,7 @@ http://127.0.0.1:8000/items/?skip=0&limit=10
* `skip`:值为 `0`
* `limit`:值为 `10`
这些值都是 URL 的组成部分,因此,它们的类型**本应**是字符串。
这些值都是 URL 的组成部分,因此,它们的类型“本应”是字符串。
但声明 Python 类型(上例中为 `int`)之后,这些值就会转换为声明的类型,并进行类型校验。
@ -59,7 +59,7 @@ http://127.0.0.1:8000/items/?skip=20
## 可选参数 { #optional-parameters }
同理,把默认值设为 `None` 即可声明**可选的**查询参数:
同理,把默认值设为 `None` 即可声明可选的查询参数:
{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
@ -122,11 +122,11 @@ FastAPI 通过参数名进行检测:
## 必选查询参数 { #required-query-parameters }
为不是路径参数的参数声明默认值(至此,仅有查询参数),该参数就**不是必选**的了。
为不是路径参数的参数声明默认值(至此,仅有查询参数),该参数就不是必选的了。
如果只想把参数设为**可选**,但又不想指定参数的值,则要把默认值设为 `None`
如果只想把参数设为可选,但又不想指定参数的值,则要把默认值设为 `None`
如果要把查询参数设置为**必选**,就不要声明默认值:
如果要把查询参数设置为必选,就不要声明默认值:
{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
@ -183,6 +183,6 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
/// tip | 提示
还可以像在[路径参数](path-params.md#predefined-values){.internal-link target=_blank} 中那样使用 `Enum`
还可以像在[路径参数](path-params.md#predefined-values)中那样使用 `Enum`
///

8
docs/zh/docs/tutorial/request-forms.md

@ -4,9 +4,9 @@
/// info
要使用表单,首先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>
要使用表单,首先安装 [`python-multipart`](https://github.com/Kludex/python-multipart)
请先创建并激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后再进行安装,例如:
请先创建并激活一个[虚拟环境](../virtual-environments.md),然后再进行安装,例如:
```console
$ pip install python-multipart
@ -28,7 +28,7 @@ $ pip install python-multipart
例如,在 OAuth2 规范的一种使用方式(称为“密码流”)中,要求将 `username``password` 作为表单字段发送。
<dfn title="规范">规范</dfn> 要求这些字段必须精确命名为 `username``password`,并且作为表单字段发送,而不是 JSON。
<dfn title="规范">规范</dfn>要求这些字段必须精确命名为 `username``password`,并且作为表单字段发送,而不是 JSON。
使用 `Form` 可以像使用 `Body`(以及 `Query`、`Path`、`Cookie`)一样声明相同的配置,包括校验、示例、别名(例如将 `username` 写成 `user-name`)等。
@ -56,7 +56,7 @@ HTML 表单(`<form></form>`)向服务器发送数据时通常会对数据使
但当表单包含文件时,会编码为 `multipart/form-data`。你将在下一章阅读如何处理文件。
如果你想了解更多关于这些编码和表单字段的信息,请参阅 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network - Mozilla 开发者网络">MDN</abbr> Web 文档的 <code>POST</code></a>
如果你想了解更多关于这些编码和表单字段的信息,请参阅 [<abbr title="Mozilla Developer Network - Mozilla 开发者网络">MDN</abbr> Web 文档的 `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)
///

9
docs/zh/docs/tutorial/response-model.md

@ -13,6 +13,7 @@ FastAPI 会使用这个返回类型来:
* 在 OpenAPI 的*路径操作*中为响应添加**JSON Schema**。
* 它会被**自动文档**使用。
* 它也会被自动客户端代码生成工具使用。
* 使用 Pydantic 将返回数据**序列化**为 JSON。Pydantic 使用**Rust**编写,因此会**快很多**。
但更重要的是:
@ -73,9 +74,9 @@ FastAPI 会使用这个 `response_model` 来完成数据文档、校验等,并
/// info | 信息
要使用 `EmailStr`,首先安装 <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email-validator`</a>
要使用 `EmailStr`,首先安装 [`email-validator`](https://github.com/JoshData/python-email-validator)
请先创建并激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后安装,例如:
请先创建并激活一个[虚拟环境](../virtual-environments.md),然后安装,例如:
```console
$ pip install email-validator
@ -181,7 +182,7 @@ FastAPI 在内部配合 Pydantic 做了多项处理,确保不会把类继承
### 直接返回 Response { #return-a-response-directly }
最常见的情况是[直接返回 Response,详见进阶文档](../advanced/response-directly.md){.internal-link target=_blank}
最常见的情况是[直接返回 Response,详见进阶文档](../advanced/response-directly.md)。
{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
@ -257,7 +258,7 @@ FastAPI 在内部配合 Pydantic 做了多项处理,确保不会把类继承
* `response_model_exclude_defaults=True`
* `response_model_exclude_none=True`
详见 <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydantic 文档</a>中对 `exclude_defaults``exclude_none` 的说明。
详见 [Pydantic 文档](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict)中对 `exclude_defaults``exclude_none` 的说明。
///

6
docs/zh/docs/tutorial/response-status-code.md

@ -20,7 +20,7 @@
/// info | 信息
`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>
`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus)
///
@ -66,7 +66,7 @@ FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
/// tip | 提示
状态码及适用场景的详情,请参阅 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network - Mozilla 开发者网络">MDN</abbr> 的 HTTP 状态码文档</a>
想了解每个状态码的更多信息以及适用场景,请参阅 [<abbr title="Mozilla Developer Network - Mozilla 开发者网络">MDN</abbr> 的 HTTP 状态码文档](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
///
@ -98,4 +98,4 @@ FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
## 更改默认状态码 { #changing-the-default }
[高级用户指南](../advanced/response-change-status-code.md){.internal-link target=_blank}中,将介绍如何返回与在此声明的默认状态码不同的状态码。
稍后在[高级用户指南](../advanced/response-change-status-code.md)中,你将看到如何返回与此处声明的默认状态码不同的状态码。

30
docs/zh/docs/virtual-environments.md

@ -22,7 +22,7 @@
这个页面将教你如何使用**虚拟环境**以及了解它们的工作原理。
如果你计划使用一个**可以为你管理一切的工具**(包括安装 Python),试试 <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a>
如果你计划使用一个**可以为你管理一切的工具**(包括安装 Python),试试 [uv](https://github.com/astral-sh/uv)
///
@ -86,7 +86,7 @@ $ python -m venv .venv
//// tab | `uv`
如果你安装了 <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>,你也可以使用它来创建一个虚拟环境。
如果你安装了 [`uv`](https://github.com/astral-sh/uv),你也可以使用它来创建一个虚拟环境。
<div class="termy">
@ -150,7 +150,7 @@ $ .venv\Scripts\Activate.ps1
//// tab | Windows Bash
或者,如果你在 Windows 上使用 Bash(例如 <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
或者,如果你在 Windows 上使用 Bash(例如 [Git Bash](https://gitforwindows.org/)):
<div class="termy">
@ -216,7 +216,7 @@ C:\Users\user\code\awesome-project\.venv\Scripts\python
/// tip | 提示
如果你使用 <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> 来安装内容,而不是 `pip`,那么你就不需要升级 `pip`。😎
如果你使用 [`uv`](https://github.com/astral-sh/uv) 来安装内容,而不是 `pip`,那么你就不需要升级 `pip`。😎
///
@ -268,7 +268,7 @@ $ python -m ensurepip --upgrade
/// tip | 提示
如果你使用 <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> 来创建虚拟环境,它会自动为你完成这个操作,你可以跳过这一步。😎
如果你使用 [`uv`](https://github.com/astral-sh/uv) 来创建虚拟环境,它会自动为你完成这个操作,你可以跳过这一步。😎
///
@ -340,7 +340,7 @@ $ pip install "fastapi[standard]"
//// tab | `uv`
如果你有 <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>:
如果你有 [`uv`](https://github.com/astral-sh/uv):
<div class="termy">
@ -372,7 +372,7 @@ $ pip install -r requirements.txt
//// tab | `uv`
如果你有 <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>:
如果你有 [`uv`](https://github.com/astral-sh/uv):
<div class="termy">
@ -416,8 +416,8 @@ Hello World
例如:
* <a href="https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment" class="external-link" target="_blank">VS Code</a>
* <a href="https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html" class="external-link" target="_blank">PyCharm</a>
* [VS Code](https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment)
* [PyCharm](https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html)
/// tip | 提示
@ -455,7 +455,7 @@ $ deactivate
## 为什么要使用虚拟环境 { #why-virtual-environments }
你需要安装 <a href="https://www.python.org/" class="external-link" target="_blank">Python</a> 才能使用 FastAPI。
你需要安装 [Python](https://www.python.org/) 才能使用 FastAPI。
之后,你需要**安装** FastAPI 和你想要使用的任何其他**软件包**。
@ -564,7 +564,7 @@ $ pip install "fastapi[standard]"
</div>
这将会从 <a href="https://pypi.org/project/fastapi/" class="external-link" target="_blank">PyPI</a> 下载一个压缩文件,其中包含 FastAPI 代码。
这将会从 [PyPI](https://pypi.org/project/fastapi/) 下载一个压缩文件,其中包含 FastAPI 代码。
它还会**下载** FastAPI 依赖的其他软件包的文件。
@ -627,7 +627,7 @@ $ .venv\Scripts\Activate.ps1
//// tab | Windows Bash
或者如果你在 Windows 上使用 Bash(例如 <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
或者如果你在 Windows 上使用 Bash(例如 [Git Bash](https://gitforwindows.org/)):
<div class="termy">
@ -639,13 +639,13 @@ $ source .venv/Scripts/activate
////
这个命令会创建或修改一些[环境变量](environment-variables.md){.internal-link target=_blank},这些环境变量将在接下来的命令中可用。
这个命令会创建或修改一些[环境变量](environment-variables.md),这些环境变量将在接下来的命令中可用。
其中之一是 `PATH` 变量。
/// tip | 提示
你可以在 [环境变量](environment-variables.md#path-environment-variable){.internal-link target=_blank} 部分了解更多关于 `PATH` 环境变量的内容。
你可以在 [环境变量](environment-variables.md#path-environment-variable) 部分了解更多关于 `PATH` 环境变量的内容。
///
@ -846,7 +846,7 @@ I solemnly swear 🐺
有许多**替代方案**来管理虚拟环境、包依赖(requirements)、工程。
一旦你准备好并想要使用一个工具来**管理整个工程**、包依赖、虚拟环境等,建议你尝试 <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a>
一旦你准备好并想要使用一个工具来**管理整个工程**、包依赖、虚拟环境等,建议你尝试 [uv](https://github.com/astral-sh/uv)
`uv` 可以做很多事情,它可以:

Loading…
Cancel
Save