diff --git a/docs/zh/docs/_llm-test.md b/docs/zh/docs/_llm-test.md index 05c512e99b..2e9e7816e0 100644 --- a/docs/zh/docs/_llm-test.md +++ b/docs/zh/docs/_llm-test.md @@ -11,7 +11,7 @@ * 检查翻译是否正确。 * 如有需要,改进你的语言特定提示、通用提示,或英文文档。 * 然后手动修正翻译中剩余的问题,确保这是一个优秀的译文。 -* 重新翻译,在已有的优秀译文基础上进行。理想情况是 LLM 不再对译文做任何更改。这意味着通用提示和你的语言特定提示已经尽可能完善(有时它仍会做一些看似随机的改动,原因是LLM 不是确定性算法)。 +* 重新翻译,在已有的优秀译文基础上进行。理想情况是 LLM 不再对译文做任何更改。这意味着通用提示和你的语言特定提示已经尽可能完善(有时它仍会做一些看似随机的改动,原因是[LLM 不是确定性算法](https://doublespeak.chat/#/handbook#deterministic-output))。 测试如下: @@ -169,15 +169,15 @@ Some text 链接文本应被翻译,链接地址应保持不变: * [链接到上面的标题](#code-snippets) -* [内部链接](index.md#installation){.internal-link target=_blank} -* 外部链接 -* 样式链接 -* 脚本链接 -* 图片链接 +* [内部链接](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) 链接文本应被翻译,且链接地址应指向对应的译文页面: -* FastAPI 链接 +* [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` 部分。 - -//// diff --git a/docs/zh/docs/alternatives.md b/docs/zh/docs/alternatives.md index 8a552c91d4..fe7aa98698 100644 --- a/docs/zh/docs/alternatives.md +++ b/docs/zh/docs/alternatives.md @@ -14,7 +14,7 @@ ## 先前的工具 { #previous-tools } -### Django { #django } +### [Django](https://www.djangoproject.com/) { #django } 它是最流行且被广泛信任的 Python 框架。被用于构建 Instagram 等系统。 @@ -22,7 +22,7 @@ 它最初用于在后端生成 HTML,而不是创建由现代前端(如 React、Vue.js、Angular)或与之通信的其他系统(如 IoT 设备)使用的 API。 -### Django REST Framework { #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 /// -### Flask { #flask } +### [Flask](https://flask.palletsprojects.com) { #flask } Flask 是一个“微框架”,它不包含数据库集成,也没有像 Django 那样的许多默认内建功能。 @@ -63,7 +63,7 @@ Flask 是一个“微框架”,它不包含数据库集成,也没有像 Djan /// -### Requests { #requests } +### [Requests](https://requests.readthedocs.io) { #requests } **FastAPI** 实际上不是 **Requests** 的替代品。它们的作用范围完全不同。 @@ -99,13 +99,13 @@ def read_url(): /// check | 启发 **FastAPI**: -- 提供简单直观的 API。 -- 直接、自然地使用 HTTP 方法名(操作)。 -- 具备合理默认值,同时支持强大定制能力。 +* 提供简单直观的 API。 +* 直接、自然地使用 HTTP 方法名(操作)。 +* 具备合理默认值,同时支持强大定制能力。 /// -### Swagger / OpenAPI { #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(): 并集成基于标准的用户界面工具: -- Swagger UI -- ReDoc +* [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 框架,但在投入时间精力深入调研后,我发现许多已停止维护或被弃用,并存在多处未解决问题,不太适合采用。 -### Marshmallow { #marshmallow } +### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow } API 系统所需的主要特性之一是数据“序列化”,即将代码(Python)中的数据转换为可通过网络发送的形式。例如,将包含数据库数据的对象转换为 JSON 对象、将 `datetime` 对象转换为字符串等。 @@ -152,7 +152,7 @@ API 的另一个重要特性是数据校验,确保数据在给定约束下是 /// -### Webargs { #webargs } +### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs } API 的另一个重要需求是从传入请求中解析数据。 @@ -174,7 +174,7 @@ Webargs 由与 Marshmallow 相同的开发者创建。 /// -### APISpec { #apispec } +### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec } Marshmallow 与 Webargs 通过插件提供了校验、解析与序列化。 @@ -204,7 +204,7 @@ APISpec 由与 Marshmallow 相同的开发者创建。 /// -### Flask-apispec { #flask-apispec } +### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec } 这是一个 Flask 插件,将 Webargs、Marshmallow 与 APISpec 结合在一起。 @@ -218,11 +218,11 @@ APISpec 由与 Marshmallow 相同的开发者创建。 使用它促成了若干 Flask 全栈脚手架的诞生。以下是我(以及若干外部团队)至今使用的主要技术栈: -* https://github.com/tiangolo/full-stack -* https://github.com/tiangolo/full-stack-flask-couchbase -* https://github.com/tiangolo/full-stack-flask-couchdb +* [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 相同的开发者创建。 /// -### NestJS(以及 Angular) { #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 相同的开发者创建。 /// -### Sanic { #sanic } +### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic } 它是最早的一批基于 `asyncio` 的极速 Python 框架之一,且做得与 Flask 很相似。 /// note | 技术细节 -它使用了 `uvloop` 来替代 Python 默认的 `asyncio` 循环。这正是它如此之快的原因。 +它使用了 [`uvloop`](https://github.com/MagicStack/uvloop) 来替代 Python 默认的 `asyncio` 循环。这正是它如此之快的原因。 它显然启发了 Uvicorn 和 Starlette;在公开的基准测试中,它们目前比 Sanic 更快。 @@ -278,7 +278,7 @@ Flask-apispec 由与 Marshmallow 相同的开发者创建。 /// -### Falcon { #falcon } +### [Falcon](https://falconframework.org/) { #falcon } Falcon 是另一个高性能 Python 框架,它被设计为精简且可作为 Hug 等其他框架的基础。 @@ -294,7 +294,7 @@ Falcon 是另一个高性能 Python 框架,它被设计为精简且可作为 H /// -### Molten { #molten } +### [Molten](https://moltenframework.com/) { #molten } 我在构建 **FastAPI** 的早期阶段发现了 Molten。它有不少相似的想法: @@ -318,7 +318,7 @@ Falcon 是另一个高性能 Python 框架,它被设计为精简且可作为 H /// -### Hug { #hug } +### [Hug](https://github.com/hugapi/hug) { #hug } Hug 是最早使用 Python 类型提示来声明 API 参数类型的框架之一。这一绝妙想法也启发了其他工具。 @@ -334,7 +334,7 @@ Hug 是最早使用 Python 类型提示来声明 API 参数类型的框架之一 /// info | 信息 -Hug 由 Timothy Crosley 创建,他也是 `isort` 的作者,这是一个能自动排序 Python 文件中导入的优秀工具。 +Hug 由 Timothy Crosley 创建,他也是 [`isort`](https://github.com/timothycrosley/isort) 的作者,这是一个能自动排序 Python 文件中导入的优秀工具。 /// @@ -348,7 +348,7 @@ Hug 启发 **FastAPI** 在函数中声明 `response` 参数,用于设置 heade /// -### APIStar (<= 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 } -### Pydantic { #pydantic } +### [Pydantic](https://docs.pydantic.dev/) { #pydantic } Pydantic 是一个基于 Python 类型提示来定义数据校验、序列化与文档(使用 JSON Schema)的库。 @@ -414,7 +414,7 @@ Pydantic 是一个基于 Python 类型提示来定义数据校验、序列化与 /// -### Starlette { #starlette } +### [Starlette](https://www.starlette.dev/) { #starlette } Starlette 是一个轻量级的 ASGI 框架/工具集,非常适合构建高性能的 asyncio 服务。 @@ -459,7 +459,7 @@ ASGI 是由 Django 核心团队成员推动的新“标准”。它尚不是正 /// -### Uvicorn { #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)一节。 diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md index 36d875f515..92ee5ef22f 100644 --- a/docs/zh/docs/async.md +++ b/docs/zh/docs/async.md @@ -141,7 +141,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 /// info | 信息 -漂亮的插画来自 Ketrina Thompson. 🎨 +漂亮的插画来自 [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot)。🎨 /// @@ -207,7 +207,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 /// info | 信息 -漂亮的插画来自 Ketrina Thompson. 🎨 +漂亮的插画来自 [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot)。🎨 /// @@ -251,7 +251,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 这与 **FastAPI** 的性能水平相同。 -你可以同时拥有并行性和异步性,你可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言(全部归功于 Starlette)。 +你可以同时拥有并行性和异步性,你可以获得比大多数经过测试的 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**) 是基于 AnyIO 实现的,这使得它们可以兼容 Python 的标准库 asyncio 和 Trio。 +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/)。 -特别是,你可以直接使用 AnyIO 来处理高级的并发用例,这些用例需要在自己的代码中使用更高级的模式。 +特别是,你可以直接使用 [AnyIO](https://anyio.readthedocs.io/en/stable/) 来处理高级的并发用例,这些用例需要在自己的代码中使用更高级的模式。 -即使你没有使用 **FastAPI**,你也可以使用 AnyIO 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。 +即使你没有使用 **FastAPI**,你也可以使用 [AnyIO](https://anyio.readthedocs.io/en/stable/) 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。 -我基于 AnyIO 新建了一个库,作为一个轻量级的封装层,用来优化类型注解,同时提供了更好的**自动补全**、**内联错误提示**等功能。这个库还附带了一个友好的入门指南和教程,能帮助你**理解**并编写**自己的异步代码**:Asyncer。如果你有**结合使用异步代码和常规**(阻塞/同步)代码的需求,这个库会特别有用。 +我基于 AnyIO 新建了一个库,作为一个轻量级的封装层,用来优化类型注解,同时提供了更好的**自动补全**、**内联错误提示**等功能。这个库还附带了一个友好的入门指南和教程,能帮助你**理解**并编写**自己的异步代码**:[Asyncer](https://asyncer.tiangolo.com/)。如果你有**结合使用异步代码和常规**(阻塞/同步)代码的需求,这个库会特别有用。 ### 其他形式的异步代码 { #other-forms-of-asynchronous-code } @@ -381,7 +381,7 @@ Starlette (和 **FastAPI**) 是基于 Gevent。但代码的理解、调试和思考都要复杂许多。 +在以前版本的 Python,你可以使用多线程或者 [Gevent](https://www.gevent.org/)。但代码的理解、调试和思考都要复杂许多。 在以前版本的 NodeJS / 浏览器 JavaScript 中,你会使用"回调",因此也可能导致“回调地狱”。 @@ -419,15 +419,15 @@ Starlette (和 **FastAPI**) 是基于 I/O 的代码。 -在这两种情况下,与你之前的框架相比,**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 } diff --git a/docs/zh/docs/benchmarks.md b/docs/zh/docs/benchmarks.md index a6e706dfaa..d98d3de593 100644 --- a/docs/zh/docs/benchmarks.md +++ b/docs/zh/docs/benchmarks.md @@ -1,6 +1,6 @@ # 基准测试 { #benchmarks } -第三方机构 TechEmpower 的基准测试表明在 Uvicorn 下运行的 **FastAPI** 应用程序是 可用的最快的 Python 框架之一,仅次于 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 内部使用)。 但是在查看基准得分和对比时,请注意以下几点。 diff --git a/docs/zh/docs/environment-variables.md b/docs/zh/docs/environment-variables.md index 8729a6306a..3a90ecde62 100644 --- a/docs/zh/docs/environment-variables.md +++ b/docs/zh/docs/environment-variables.md @@ -65,7 +65,7 @@ print(f"Hello {name} from Python") /// tip | 提示 -第二个参数是 `os.getenv()` 的默认返回值。 +第二个参数是 [`os.getenv()`](https://docs.python.org/3.8/library/os.html#os.getenv) 的默认返回值。 如果没有提供,默认值为 `None`,这里我们提供 `"World"` 作为默认值。 @@ -153,7 +153,7 @@ Hello World from Python /// tip | 提示 -你可以在 The Twelve-Factor App: 配置中了解更多信息。 +你可以在 [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 中使用它们有了基本的了解。 -你也可以在环境变量 - 维基百科中了解更多关于它们的信息。 +你也可以在[环境变量 - 维基百科](https://en.wikipedia.org/wiki/Environment_variable)中了解更多关于它们的信息。 在许多情况下,环境变量的用途和适用性并不是很明显。但是在开发过程中,它们会在许多不同的场景中出现,因此了解它们是很有必要的。 diff --git a/docs/zh/docs/fastapi-cli.md b/docs/zh/docs/fastapi-cli.md index 4d3b51a57a..151b7e61ec 100644 --- a/docs/zh/docs/fastapi-cli.md +++ b/docs/zh/docs/fastapi-cli.md @@ -1,15 +1,15 @@ # FastAPI CLI { #fastapi-cli } -**FastAPI CLI** 是一个命令行程序,你可以用它来部署和运行你的 FastAPI 应用程序,管理你的 FastAPI 项目,等等。 +**FastAPI CLI** 是一个命令行程序,你可以用它来部署和运行你的 FastAPI 应用、管理 FastAPI 项目,等等。 -当你安装 FastAPI 时(例如使用 `pip install "fastapi[standard]"`),会包含一个名为 `fastapi-cli` 的软件包,该软件包在终端中提供 `fastapi` 命令。 +当你安装 FastAPI(例如使用 `pip install "fastapi[standard]"`)时,会附带一个可以在终端中运行的命令行程序。 -要在开发环境中运行你的 FastAPI 应用,你可以使用 `fastapi dev` 命令: +要在开发环境中运行你的 FastAPI 应用,可以使用 `fastapi dev` 命令:
没有大家之前所做的工作,**FastAPI** 就不会存在。 @@ -42,7 +42,7 @@ 同时,我还在最流行的 Python 代码编辑器中测试了很多思路,包括 PyCharm、VS Code、基于 Jedi 的编辑器。 -根据最新 Python 开发者调研报告显示,这几种编辑器覆盖了约 80% 的用户。 +根据最新 [Python 开发者调研报告](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools)显示,这几种编辑器覆盖了约 80% 的用户。 也就是说,**FastAPI** 针对差不多 80% 的 Python 开发者使用的编辑器进行了测试,而且其它大多数编辑器的工作方式也与之类似,因此,**FastAPI** 的优势几乎能在所有编辑器上体现。 @@ -52,11 +52,11 @@ ## 需求项 { #requirements } -经过测试多种备选方案,我最终决定使用 **Pydantic**,并充分利用它的优势。 +经过测试多种备选方案,我最终决定使用 [**Pydantic**](https://docs.pydantic.dev/),并充分利用它的优势。 我甚至为它做了不少贡献,让它完美兼容了 JSON Schema,支持多种方式定义约束声明,并基于多个编辑器,改进了它对编辑器支持(类型检查、自动补全)。 -在开发期间,我还为 **Starlette** 做了不少贡献,这是另一个关键需求项。 +在开发期间,我还为 [**Starlette**](https://www.starlette.dev/) 做了不少贡献,这是另一个关键需求项。 ## 开发 { #development } @@ -74,4 +74,4 @@ **FastAPI** 前景光明。 -在此,我们衷心感谢[您的帮助](help-fastapi.md){.internal-link target=_blank}。 +在此,我们衷心感谢[你的帮助](help-fastapi.md)。 diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index 38e128bf14..a88c25efb1 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -11,25 +11,25 @@ FastAPI 框架,高性能,易于学习,高效编码,生产可用 --- -**文档**: https://fastapi.tiangolo.com +**文档**: [https://fastapi.tiangolo.com/zh](https://fastapi.tiangolo.com/zh) -**源码**: https://github.com/fastapi/fastapi +**源码**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) --- @@ -44,7 +44,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框 * **易用**:为易用和易学而设计。更少的文档阅读时间。 * **简短**:最小化代码重复。一次参数声明即可获得多种功能。更少的 bug。 * **健壮**:生产可用级代码。并带有自动生成的交互式文档。 -* **标准化**:基于(并完全兼容)API 的开放标准:OpenAPI(以前称为 Swagger)和 JSON Schema。 +* **标准化**:基于(并完全兼容)API 的开放标准:[OpenAPI](https://github.com/OAI/OpenAPI-Specification)(以前称为 Swagger)和 [JSON Schema](https://json-schema.org/)。 * 基于某内部开发团队在构建生产应用时的测试估算。 @@ -55,51 +55,51 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框 ### Keystone 赞助商 { #keystone-sponsor } {% for sponsor in sponsors.keystone -%} -+
{% endfor -%} ### 金牌和银牌赞助商 { #gold-and-silver-sponsors } {% for sponsor in sponsors.gold -%} -
+
{% endfor -%} {%- for sponsor in sponsors.silver -%} -
+
{% endfor %} -其他赞助商 +[其他赞助商](https://fastapi.tiangolo.com/zh/fastapi-people/#sponsors) ## 评价 { #opinions } 「_[...] 最近我大量使用 **FastAPI**。[...] 我实际上计划把它用于我团队在 **微软** 的所有 **机器学习服务**。其中一些正在集成进核心 **Windows** 产品以及一些 **Office** 产品。_」 -
Kabir Khan - Microsoft (ref)+Kabir Khan - Microsoft (ref)--- 「_我们采用 **FastAPI** 来构建可查询以获取**预测结果**的 **REST** 服务器。[用于 Ludwig]_」 -Piero Molino,Yaroslav Dudin,Sai Sumanth Miryala - Uber (ref)+Piero Molino,Yaroslav Dudin,Sai Sumanth Miryala - Uber (ref)--- 「_**Netflix** 很高兴宣布开源我们的**危机管理**编排框架:**Dispatch**![使用 **FastAPI** 构建]_」 -Kevin Glisson,Marc Vilanova,Forest Monsen - Netflix (ref)+Kevin Glisson,Marc Vilanova,Forest Monsen - Netflix (ref)--- 「_我对 **FastAPI** 兴奋到飞起。它太有趣了!_」 -Brian Okken - Python Bytes 播客主持人 (ref)+Brian Okken - [Python Bytes](https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855) 播客主持人 (ref)--- 「_老实说,你构建的东西非常稳健而且打磨得很好。从很多方面看,这就是我想让 **Hug** 成为的样子 —— 看到有人把它做出来真的很鼓舞人心。_」 - +Timothy Crosley - [Hug](https://github.com/hugapi/hug) 作者 (ref)--- @@ -107,27 +107,27 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框 「_我们已经把我们的 **API** 切换到 **FastAPI** [...] 我想你会喜欢它 [...]_」 - +Ines Montani - Matthew Honnibal - [Explosion AI](https://explosion.ai) 创始人 - [spaCy](https://spacy.io) 作者 (ref) - (ref)--- 「_如果有人正在构建生产级的 Python API,我强烈推荐 **FastAPI**。它**设计优雅**、**使用简单**且**高度可扩展**,已经成为我们 API 优先开发战略中的**关键组件**,并驱动了许多自动化和服务,比如我们的 Virtual TAC Engineer。_」 -Deon Pillsbury - Cisco (ref)+Deon Pillsbury - Cisco (ref)--- ## FastAPI 迷你纪录片 { #fastapi-mini-documentary } -在 2025 年末发布了一部FastAPI 迷你纪录片,你可以在线观看: +在 2025 年末发布了一部 [FastAPI 迷你纪录片](https://www.youtube.com/watch?v=mpR8ngthqiE),你可以在线观看: -+
## **Typer**,命令行中的 FastAPI { #typer-the-fastapi-of-clis } -
+
-如果你要开发一个用于终端的 命令行应用而不是 Web API,看看 **Typer**。 +如果你要开发一个用于终端的 命令行应用而不是 Web API,看看 [**Typer**](https://typer.tiangolo.com/)。 **Typer** 是 FastAPI 的小同胞。它的目标是成为**命令行中的 FastAPI**。⌨️ 🚀 @@ -135,12 +135,12 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框 FastAPI 站在巨人的肩膀之上: -* Starlette 负责 Web 部分。 -* Pydantic 负责数据部分。 +* [Starlette](https://www.starlette.dev/) 负责 Web 部分。 +* [Pydantic](https://docs.pydantic.dev/) 负责数据部分。 ## 安装 { #installation } -创建并激活一个虚拟环境,然后安装 FastAPI: +创建并激活一个 [虚拟环境](https://fastapi.tiangolo.com/zh/virtual-environments/),然后安装 FastAPI:
@@ -199,7 +199,7 @@ async def read_item(item_id: int, q: str | None = None): **Note**: -如果你不确定,请查看文档中 _"In a hurry?"_ 章节的`async` 和 `await`部分。 +如果你不确定,请查看文档中 _"In a hurry?"_ 章节的 [`async` 和 `await`](https://fastapi.tiangolo.com/zh/async/#in-a-hurry) 部分。 @@ -210,7 +210,7 @@ async def read_item(item_id: int, q: str | None = None):```console -$ fastapi dev main.py +$ fastapi dev ╭────────── FastAPI CLI - Development mode ───────────╮ │ │ @@ -235,19 +235,19 @@ INFO: Application startup complete.-### 检查 { #check-it } -用浏览器打开 http://127.0.0.1:8000/items/5?q=somequery。 +用浏览器打开 [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 } -现在访问 http://127.0.0.1:8000/docs。 +现在访问 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)。 -你会看到自动生成的交互式 API 文档(由 Swagger UI 提供): +你会看到自动生成的交互式 API 文档(由 [Swagger UI](https://github.com/swagger-api/swagger-ui) 提供):  ### 可选的 API 文档 { #alternative-api-docs } -然后访问 http://127.0.0.1:8000/redoc。 +然后访问 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)。 -你会看到另一个自动生成的文档(由 ReDoc 提供): +你会看到另一个自动生成的文档(由 [ReDoc](https://github.com/Rebilly/ReDoc) 提供):  @@ -316,7 +316,7 @@ def update_item(item_id: int, item: Item): ### 交互式 API 文档升级 { #interactive-api-docs-upgrade } -现在访问 http://127.0.0.1:8000/docs。 +现在访问 [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 } -再访问 http://127.0.0.1:8000/redoc。 +再访问 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)。 * 可选文档同样会体现新的查询参数和请求体: @@ -442,7 +442,7 @@ item: Item * 功能强大且易用的 **依赖注入** 系统。 * 安全与认证,包括对 **OAuth2**、**JWT tokens** 和 **HTTP Basic** 认证的支持。 * 更高级(但同样简单)的 **多层嵌套 JSON 模型** 声明技巧(得益于 Pydantic)。 -* 通过 Strawberry 等库进行 **GraphQL** 集成。 +* 通过 [Strawberry](https://strawberry.rocks) 等库进行 **GraphQL** 集成。 * 许多额外特性(归功于 Starlette),例如: * **WebSockets** * 基于 HTTPX 和 `pytest` 的极其简单的测试 @@ -452,24 +452,10 @@ item: Item ### 部署你的应用(可选) { #deploy-your-app-optional } -你可以选择把 FastAPI 应用部署到 FastAPI Cloud,如果还没有的话去加入候补名单吧。🚀 +你可以选择把 FastAPI 应用部署到 [FastAPI Cloud](https://fastapicloud.com),如果还没有的话去加入候补名单吧。🚀 如果你已经有 **FastAPI Cloud** 账号(我们从候补名单邀请了你 😉),你可以用一个命令部署你的应用。 -部署前,先确认已登录: - -关于命令
+fastapi dev main.py...关于命令
-`fastapi dev` 命令会读取你的 `main.py` 文件,检测其中的 **FastAPI** 应用,并使用 Uvicorn 启动服务器。 +`fastapi dev` 命令会读取你的 `main.py` 文件,检测其中的 **FastAPI** 应用,并使用 [Uvicorn](https://www.uvicorn.dev) 启动服务器。 默认情况下,`fastapi dev` 会在本地开发时启用自动重载。 -你可以在 FastAPI CLI 文档中了解更多。 +你可以在 [FastAPI CLI 文档](https://fastapi.tiangolo.com/zh/fastapi-cli/) 中了解更多。fastapi dev...- -```console -$ fastapi login - -You are logged in to FastAPI Cloud 🚀 -``` - -- -然后部署你的应用: -```console @@ -488,7 +474,7 @@ Deploying to FastAPI Cloud... #### 关于 FastAPI Cloud { #about-fastapi-cloud } -**FastAPI Cloud** 由 **FastAPI** 的同一位作者和团队打造。 +**[FastAPI Cloud](https://fastapicloud.com)** 由 **FastAPI** 的同一位作者和团队打造。 它让你以最小的工作量就能**构建**、**部署**并**访问**一个 API。 @@ -504,9 +490,9 @@ FastAPI 是开源且基于标准的。你可以部署 FastAPI 应用到你选择 ## 性能 { #performance } -独立机构 TechEmpower 的基准测试显示,运行在 Uvicorn 下的 **FastAPI** 应用是最快的 Python 框架之一,仅次于 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 内部使用它们)。(*) -想了解更多,请参阅基准测试章节。 +想了解更多,请参阅 [基准测试](https://fastapi.tiangolo.com/zh/benchmarks/) 章节。 ## 依赖项 { #dependencies } @@ -518,19 +504,19 @@ FastAPI 依赖 Pydantic 和 Starlette。 Pydantic 使用: -*email-validator- 用于 email 校验。 +* [`email-validator`](https://github.com/JoshData/python-email-validator) - 用于 email 校验。 Starlette 使用: -*httpx- 使用 `TestClient` 时需要。 -*jinja2- 使用默认模板配置时需要。 -*python-multipart- 使用 `request.form()` 支持表单「解析」时需要。 +* [`httpx`](https://www.python-httpx.org) - 使用 `TestClient` 时需要。 +* [`jinja2`](https://jinja.palletsprojects.com) - 使用默认模板配置时需要。 +* [`python-multipart`](https://github.com/Kludex/python-multipart) - 使用 `request.form()` 支持表单「解析」时需要。 FastAPI 使用: -*uvicorn- 加载并提供你的应用的服务器。包含 `uvicorn[standard]`,其中包含高性能服务所需的一些依赖(例如 `uvloop`)。 +* [`uvicorn`](https://www.uvicorn.dev) - 加载并提供你的应用的服务器。包含 `uvicorn[standard]`,其中包含高性能服务所需的一些依赖(例如 `uvloop`)。 * `fastapi-cli[standard]` - 提供 `fastapi` 命令。 - * 其中包含 `fastapi-cloud-cli`,它允许你将 FastAPI 应用部署到 FastAPI Cloud。 + * 其中包含 `fastapi-cloud-cli`,它允许你将 FastAPI 应用部署到 [FastAPI Cloud](https://fastapicloud.com)。 ### 不包含 `standard` 依赖 { #without-standard-dependencies } @@ -546,13 +532,13 @@ FastAPI 使用: 额外的 Pydantic 可选依赖: -*pydantic-settings- 用于配置管理。 -*pydantic-extra-types- 用于在 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 可选依赖: -*orjson- 使用 `ORJSONResponse` 时需要。 -*ujson- 使用 `UJSONResponse` 时需要。 +* [`orjson`](https://github.com/ijl/orjson) - 使用 `ORJSONResponse` 时需要。 +* [`ujson`](https://github.com/esnme/ultrajson) - 使用 `UJSONResponse` 时需要。 ## 许可协议 { #license } diff --git a/docs/zh/docs/project-generation.md b/docs/zh/docs/project-generation.md index a6ad9f94ac..8cc50c0963 100644 --- a/docs/zh/docs/project-generation.md +++ b/docs/zh/docs/project-generation.md @@ -4,7 +4,7 @@ 你可以使用此模板开始,它已经为你完成了大量的初始设置、安全性、数据库以及一些 API 端点。 -GitHub 仓库: Full Stack FastAPI Template +GitHub 仓库:[Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template) ## FastAPI全栈模板 - 技术栈和特性 { #full-stack-fastapi-template-technology-stack-and-features } diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index 4824b7558d..9b2fceb98e 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -269,7 +269,7 @@ def some_function(data: Any): ## Pydantic 模型 { #pydantic-models } -Pydantic 是一个用于执行数据校验的 Python 库。 +[Pydantic](https://docs.pydantic.dev/) 是一个用于执行数据校验的 Python 库。 你将数据的“结构”声明为带有属性的类。 @@ -285,13 +285,13 @@ def some_function(data: Any): /// info | 信息 -想了解更多关于 Pydantic 的信息,请查看其文档。 +想了解更多关于 [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 | 信息 -如果你已经读完所有教程,又回来想进一步了解类型,一个不错的资源是 `mypy` 的“速查表”。 +如果你已经读完所有教程,又回来想进一步了解类型,一个不错的资源是 [`mypy` 的“速查表”](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)。 /// diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index a667d596f8..74522f8384 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/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 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。 +要了解有关 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```console -$ fastapi dev app/main.py +$ fastapi dev INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ```-然后打开位于 http://127.0.0.1:8000/docs 的文档。 +然后打开位于 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) 的文档。 你将看到使用了正确路径(和前缀)和正确标签的自动化 API 文档,包括了来自所有子模块的路径: diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index 000201de99..5b181642cb 100644 --- a/docs/zh/docs/tutorial/body-updates.md +++ b/docs/zh/docs/tutorial/body-updates.md @@ -2,7 +2,7 @@ ## 用 `PUT` 替换式更新 { #update-replacing-with-put } -更新数据可以使用 HTTP `PUT` 操作。 +更新数据可以使用 [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 } -也可以使用 HTTP `PATCH` 操作对数据进行*部分*更新。 +也可以使用 [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) 中介绍的思路。 /// diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md index 2e271ec758..ebea43edba 100644 --- a/docs/zh/docs/tutorial/cors.md +++ b/docs/zh/docs/tutorial/cors.md @@ -1,6 +1,6 @@ # CORS(跨域资源共享) { #cors-cross-origin-resource-sharing } -CORS 或者「跨域资源共享」 指浏览器中运行的前端拥有与后端通信的 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` 这几个请求头在简单 CORS 请求中总是被允许。 +* `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` 都不能设为 `['*']`。它们必须显式指定。 + 当 `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 } -更多关于 CORS 的信息,请查看 Mozilla CORS 文档。 +更多关于 CORS 的信息,请查看 [Mozilla CORS 文档](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)。 /// note | 技术细节 diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md index 1ff7d61275..19e6f8a612 100644 --- a/docs/zh/docs/tutorial/debugging.md +++ b/docs/zh/docs/tutorial/debugging.md @@ -70,7 +70,7 @@ from myapp import app /// info | 信息 -更多信息请检查 Python 官方文档. +更多信息请检查 [Python 官方文档](https://docs.python.org/3/library/__main__.html). /// diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md index 88be497493..8327ab6c7c 100644 --- a/docs/zh/docs/tutorial/encoder.md +++ b/docs/zh/docs/tutorial/encoder.md @@ -12,7 +12,7 @@ 例如,它不接收`datetime`这类的对象,因为这些对象与JSON不兼容。 -因此,`datetime`对象必须转换为包含ISO 格式的`str`类型对象。 +因此,`datetime`对象必须转换为包含[ISO 格式](https://en.wikipedia.org/wiki/ISO_8601)的`str`类型对象。 同样,这个数据库也不会接收Pydantic模型(带有属性的对象),而只接收`dict`。 @@ -24,7 +24,7 @@ 在这个例子中,它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。 -调用它的结果后就可以使用Python标准编码中的`json.dumps()`。 +调用它的结果后就可以使用Python标准编码中的[`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps)。 这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。 diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md index 2cefd163d3..76748a7a38 100644 --- a/docs/zh/docs/tutorial/extra-data-types.md +++ b/docs/zh/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * 一个 Python `datetime.timedelta`. * 在请求和响应中将表示为 `float` 代表总秒数。 - * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", 查看文档了解更多信息。 + * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", [查看文档了解更多信息](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers)。 * `frozenset`: * 在请求和响应中,作为 `set` 对待: * 在请求中,列表将被读取,消除重复,并将其转换为一个 `set`。 @@ -49,7 +49,7 @@ * `Decimal`: * 标准的 Python `Decimal`。 * 在请求和响应中被当做 `float` 一样处理。 -* 您可以在这里检查所有有效的 Pydantic 数据类型: Pydantic data types. +* 您可以在这里检查所有有效的 Pydantic 数据类型: [Pydantic data types](https://docs.pydantic.dev/latest/usage/types/types/)。 ## 例子 { #example } diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md index 09baa47319..8b6b790b8e 100644 --- a/docs/zh/docs/tutorial/extra-models.md +++ b/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 标准类型提示 `typing.Union`: +为此,请使用 Python 标准类型提示 [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union): /// note | 注意 -定义 `Union` 类型时,要把更具体的类型写在前面,然后是不太具体的类型。下例中,更具体的 `PlaneItem` 位于 `Union[PlaneItem, CarItem]` 中的 `CarItem` 之前。 +定义 [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions) 类型时,要把更具体的类型写在前面,然后是不太具体的类型。下例中,更具体的 `PlaneItem` 位于 `Union[PlaneItem, CarItem]` 中的 `CarItem` 之前。 /// diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md index 4c23807b8f..3fbab4d9b3 100644 --- a/docs/zh/docs/tutorial/first-steps.md +++ b/docs/zh/docs/tutorial/first-steps.md @@ -11,7 +11,7 @@```console -$ fastapi dev main.py +$ fastapi dev FastAPI Starting development server 🚀 @@ -58,7 +58,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 查看 { #check-it } -打开浏览器访问 http://127.0.0.1:8000。 +打开浏览器访问 [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 } -跳转到 http://127.0.0.1:8000/docs。 +跳转到 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)。 -你将会看到自动生成的交互式 API 文档(由 Swagger UI 提供): +你将会看到自动生成的交互式 API 文档(由 [Swagger UI](https://github.com/swagger-api/swagger-ui) 提供):  ### 可选的 API 文档 { #alternative-api-docs } -前往 http://127.0.0.1:8000/redoc。 +前往 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)。 -你将会看到可选的自动生成文档 (由 ReDoc 提供): +你将会看到可选的自动生成文档 (由 [ReDoc](https://github.com/Rebilly/ReDoc) 提供):  @@ -92,7 +92,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) #### API「模式」 { #api-schema } -在这种场景下,OpenAPI 是一种规定如何定义 API 模式的规范。 +在这种场景下,[OpenAPI](https://github.com/OAI/OpenAPI-Specification) 是一种规定如何定义 API 模式的规范。 「模式」的定义包括你的 API 路径,以及它们可能使用的参数等等。 @@ -110,7 +110,7 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 如果你对原始的 OpenAPI 模式长什么样子感到好奇,FastAPI 自动生成了包含所有 API 描述的 JSON(模式)。 -你可以直接在:http://127.0.0.1:8000/openapi.json 看到它。 +你可以直接在:[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 应用部署到 FastAPI Cloud,如果还没有,先去加入候补名单。🚀 +你可以选择将 FastAPI 应用部署到 [FastAPI Cloud](https://fastapicloud.com),如果还没有,先去加入候补名单。🚀 如果你已经拥有 **FastAPI Cloud** 账户(我们从候补名单邀请了你 😉),你可以用一条命令部署应用。 @@ -191,7 +240,7 @@ Deploying to FastAPI Cloud... `FastAPI` 是直接从 `Starlette` 继承的类。 -你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 +你可以通过 `FastAPI` 使用所有的 [Starlette](https://www.starlette.dev/) 的功能。 /// @@ -273,7 +322,7 @@ https://example.com/items/foo * 请求路径为 `/` * 使用get操作 -/// info | `@decorator` Info +/// info | `@decorator` 信息 `@something` 语法在 Python 中被称为「装饰器」。 @@ -352,11 +401,11 @@ https://example.com/items/foo ### 步骤 6:部署 { #step-6-deploy-it } -用一条命令将你的应用部署到 **FastAPI Cloud**:`fastapi deploy`。🎉 +用一条命令将你的应用部署到 **[FastAPI Cloud](https://fastapicloud.com)**:`fastapi deploy`。🎉 #### 关于 FastAPI Cloud { #about-fastapi-cloud } -**FastAPI Cloud** 由 **FastAPI** 的作者和团队打造。 +**[FastAPI Cloud](https://fastapicloud.com)** 由 **FastAPI** 的作者和团队打造。 它以最小的投入简化了 **构建**、**部署** 和 **访问** API 的流程。 diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md index 9782f3d225..f3a23fab0a 100644 --- a/docs/zh/docs/tutorial/handling-errors.md +++ b/docs/zh/docs/tutorial/handling-errors.md @@ -81,7 +81,7 @@ ## 安装自定义异常处理器 { #install-custom-exception-handlers } -可以使用与 Starlette 相同的异常处理工具添加自定义异常处理器。 +可以使用[与 Starlette 相同的异常处理工具](https://www.starlette.dev/exceptions/)添加自定义异常处理器。 假设有一个自定义异常 `UnicornException`(你自己或你使用的库可能会 `raise` 它)。 diff --git a/docs/zh/docs/tutorial/index.md b/docs/zh/docs/tutorial/index.md index 7934583023..8d6cbc7a6d 100644 --- a/docs/zh/docs/tutorial/index.md +++ b/docs/zh/docs/tutorial/index.md @@ -10,12 +10,12 @@ 所有代码片段都可以复制后直接使用(它们实际上是经过测试的 Python 文件)。 -要运行任何示例,请将代码复制到 `main.py` 文件中,然后使用以下命令启动 `fastapi dev`: +要运行任何示例,请将代码复制到 `main.py` 文件中,然后启动 `fastapi dev`:```console -$ fastapi dev main.py +$ fastapi dev FastAPI Starting development server 🚀 @@ -62,7 +62,7 @@ $ fastapi dev @@ -76,7 +76,7 @@ $ pip install "fastapi[standard]" /// note | 注意 -当您使用 `pip install "fastapi[standard]"` 安装时,它会附带一些默认的可选标准依赖项,其中包括 `fastapi-cloud-cli`,它可以让您部署到 FastAPI Cloud。 +当您使用 `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 } 在本**教程-用户指南**之后,您可以阅读**进阶用户指南**。 diff --git a/docs/zh/docs/tutorial/middleware.md b/docs/zh/docs/tutorial/middleware.md index a211a63bdf..e7586132f2 100644 --- a/docs/zh/docs/tutorial/middleware.md +++ b/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 -请记住可以使用 `X-` 前缀添加专有自定义请求头。 +请记住可以[使用 `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` 参数中,参见 Starlette 的 CORS 文档。 +但是如果你有希望让浏览器中的客户端可见的自定义请求头,你需要把它们加到你的 CORS 配置([CORS(跨域资源共享)](cors.md))的 `expose_headers` 参数中,参见 [Starlette 的 CORS 文档](https://www.starlette.dev/middleware/#corsmiddleware)。 /// @@ -61,7 +61,7 @@ /// tip -这里我们使用 `time.perf_counter()` 而不是 `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)中阅读更多关于其他中间件的内容。 你将在下一节中了解如何使用中间件处理 CORS。 diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md index 06a9f1b442..df9210673c 100644 --- a/docs/zh/docs/tutorial/path-params.md +++ b/docs/zh/docs/tutorial/path-params.md @@ -6,7 +6,7 @@ 路径参数 `item_id` 的值会作为参数 `item_id` 传递给你的函数。 -运行示例并访问 http://127.0.0.1:8000/items/foo,可获得如下响应: +运行示例并访问 [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo),可获得如下响应: ```JSON {"item_id":"foo"} @@ -28,7 +28,7 @@ ## 数据转换 { #data-conversion } -运行示例并访问 http://127.0.0.1:8000/items/3,返回的响应如下: +运行示例并访问 [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 } -通过浏览器访问 http://127.0.0.1:8000/items/foo,接收如下 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`)时也会显示同样的错误,比如: http://127.0.0.1:8000/items/4.2 +值的类型不是 `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 } -访问 http://127.0.0.1:8000/docs,查看自动生成的交互式 API 文档: +访问 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs),查看自动生成的交互式 API 文档:@@ -92,9 +92,9 @@ ## 基于标准的好处,备选文档 { #standards-based-benefits-alternative-documentation } -**FastAPI** 使用 OpenAPI 生成概图,所以能兼容很多工具。 +**FastAPI** 使用 [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md) 生成概图,所以能兼容很多工具。 -因此,**FastAPI** 还内置了 ReDoc 生成的备选 API 文档,可在此查看 http://127.0.0.1:8000/redoc: +因此,**FastAPI** 还内置了 ReDoc 生成的备选 API 文档,可在此查看 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc):
@@ -102,7 +102,7 @@ ## Pydantic { #pydantic } -FastAPI 充分地利用了 Pydantic 的优势,用它在后台校验数据。众所周知,Pydantic 擅长的就是数据校验。 +FastAPI 充分地利用了 [Pydantic](https://docs.pydantic.dev/) 的优势,用它在后台校验数据。众所周知,Pydantic 擅长的就是数据校验。 同样,`str`、`float`、`bool` 以及很多复合数据类型都可以使用类型声明。 diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md index d41f302267..67a5b40008 100644 --- a/docs/zh/docs/tutorial/query-params-str-validations.md +++ b/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` 可以包含多个元数据标注,你甚至可以用同一个函数与其他工具配合,例如 Typer。🚀 +由于 `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` 中使用 Pydantic 的 `AfterValidator` 来实现。 +你可以在 `Annotated` 中使用 [Pydantic 的 `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) 来实现。 /// tip | 提示 -Pydantic 还有 `BeforeValidator` 等。🤓 +Pydantic 还有 [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) 等。🤓 /// @@ -421,7 +421,7 @@ Pydantic 还有 `python-multipart`。 +要使用表单,首先安装 [`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` 作为表单字段发送。 -规范 要求这些字段必须精确命名为 `username` 和 `password`,并且作为表单字段发送,而不是 JSON。 +规范要求这些字段必须精确命名为 `username` 和 `password`,并且作为表单字段发送,而不是 JSON。 使用 `Form` 可以像使用 `Body`(以及 `Query`、`Path`、`Cookie`)一样声明相同的配置,包括校验、示例、别名(例如将 `username` 写成 `user-name`)等。 @@ -56,7 +56,7 @@ HTML 表单(``)向服务器发送数据时通常会对数据使 但当表单包含文件时,会编码为 `multipart/form-data`。你将在下一章阅读如何处理文件。 -如果你想了解更多关于这些编码和表单字段的信息,请参阅 MDN Web 文档的
POST。 +如果你想了解更多关于这些编码和表单字段的信息,请参阅 [MDN Web 文档的 `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)。 /// diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md index df0afa66f8..9b4e0382e9 100644 --- a/docs/zh/docs/tutorial/response-model.md +++ b/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`,首先安装 `email-validator`。 +要使用 `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` -详见 Pydantic 文档中对 `exclude_defaults` 和 `exclude_none` 的说明。 +详见 [Pydantic 文档](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict)中对 `exclude_defaults` 和 `exclude_none` 的说明。 /// diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md index 266f919ba1..e57c0e5937 100644 --- a/docs/zh/docs/tutorial/response-status-code.md +++ b/docs/zh/docs/tutorial/response-status-code.md @@ -20,7 +20,7 @@ /// info | 信息 -`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。 +`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus)。 /// @@ -66,7 +66,7 @@ FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 /// tip | 提示 -状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。 +想了解每个状态码的更多信息以及适用场景,请参阅 [MDN 的 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)中,你将看到如何返回与此处声明的默认状态码不同的状态码。 diff --git a/docs/zh/docs/virtual-environments.md b/docs/zh/docs/virtual-environments.md index 60fb9e23f6..14ee538639 100644 --- a/docs/zh/docs/virtual-environments.md +++ b/docs/zh/docs/virtual-environments.md @@ -22,7 +22,7 @@ 这个页面将教你如何使用**虚拟环境**以及了解它们的工作原理。 -如果你计划使用一个**可以为你管理一切的工具**(包括安装 Python),试试 uv。 +如果你计划使用一个**可以为你管理一切的工具**(包括安装 Python),试试 [uv](https://github.com/astral-sh/uv)。 /// @@ -86,7 +86,7 @@ $ python -m venv .venv //// tab | `uv` -如果你安装了 `uv`,你也可以使用它来创建一个虚拟环境。 +如果你安装了 [`uv`](https://github.com/astral-sh/uv),你也可以使用它来创建一个虚拟环境。@@ -150,7 +150,7 @@ $ .venv\Scripts\Activate.ps1 //// tab | Windows Bash -或者,如果你在 Windows 上使用 Bash(例如 Git Bash): +或者,如果你在 Windows 上使用 Bash(例如 [Git Bash](https://gitforwindows.org/)):@@ -216,7 +216,7 @@ C:\Users\user\code\awesome-project\.venv\Scripts\python /// tip | 提示 -如果你使用 `uv` 来安装内容,而不是 `pip`,那么你就不需要升级 `pip`。😎 +如果你使用 [`uv`](https://github.com/astral-sh/uv) 来安装内容,而不是 `pip`,那么你就不需要升级 `pip`。😎 /// @@ -268,7 +268,7 @@ $ python -m ensurepip --upgrade /// tip | 提示 -如果你使用 `uv` 来创建虚拟环境,它会自动为你完成这个操作,你可以跳过这一步。😎 +如果你使用 [`uv`](https://github.com/astral-sh/uv) 来创建虚拟环境,它会自动为你完成这个操作,你可以跳过这一步。😎 /// @@ -340,7 +340,7 @@ $ pip install "fastapi[standard]" //// tab | `uv` -如果你有 `uv`: +如果你有 [`uv`](https://github.com/astral-sh/uv):@@ -372,7 +372,7 @@ $ pip install -r requirements.txt //// tab | `uv` -如果你有 `uv`: +如果你有 [`uv`](https://github.com/astral-sh/uv):@@ -416,8 +416,8 @@ Hello World 例如: -* VS Code -* PyCharm +* [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 } -你需要安装 Python 才能使用 FastAPI。 +你需要安装 [Python](https://www.python.org/) 才能使用 FastAPI。 之后,你需要**安装** FastAPI 和你想要使用的任何其他**软件包**。 @@ -564,7 +564,7 @@ $ pip install "fastapi[standard]"-这将会从 PyPI 下载一个压缩文件,其中包含 FastAPI 代码。 +这将会从 [PyPI](https://pypi.org/project/fastapi/) 下载一个压缩文件,其中包含 FastAPI 代码。 它还会**下载** FastAPI 依赖的其他软件包的文件。 @@ -627,7 +627,7 @@ $ .venv\Scripts\Activate.ps1 //// tab | Windows Bash -或者如果你在 Windows 上使用 Bash(例如 Git Bash): +或者如果你在 Windows 上使用 Bash(例如 [Git Bash](https://gitforwindows.org/)):@@ -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)、工程。 -一旦你准备好并想要使用一个工具来**管理整个工程**、包依赖、虚拟环境等,建议你尝试 uv。 +一旦你准备好并想要使用一个工具来**管理整个工程**、包依赖、虚拟环境等,建议你尝试 [uv](https://github.com/astral-sh/uv)。 `uv` 可以做很多事情,它可以: