From 2e170b9585fbbf57120598632cd7e13a11028c57 Mon Sep 17 00:00:00 2001
From: Rayyan oumlil
- Фреймворк FastAPI: висока продуктивність, легко вивчати, швидко писати код, готовий до продакшину + Фреймворк FastAPI - це висока продуктивність, легко вивчати, швидко писати код, готовий до продакшину
@@ -33,14 +33,14 @@
---
-FastAPI — це сучасний, швидкий (високопродуктивний) вебфреймворк для створення API за допомогою Python, що базується на стандартних підказках типів Python.
+FastAPI - це сучасний, швидкий (високопродуктивний) вебфреймворк для створення API за допомогою Python, що базується на стандартних підказках типів Python.
Ключові особливості:
* **Швидкий**: дуже висока продуктивність, на рівні з **NodeJS** та **Go** (завдяки Starlette та Pydantic). [Один із найшвидших Python-фреймворків](#performance).
* **Швидке написання коду**: пришвидшує розробку функціоналу приблизно на 200%–300%. *
* **Менше помилок**: зменшує приблизно на 40% кількість помилок, спричинених людиною (розробником). *
-* **Інтуїтивний**: чудова підтримка редакторами коду. Автодоповнення всюди. Менше часу на налагодження.
+* **Інтуїтивний**: чудова підтримка редакторами коду. Автодоповнення всюди. Менше часу на налагодження.
* **Простий**: спроєктований так, щоб бути простим у використанні та вивченні. Менше часу на читання документації.
* **Короткий**: мінімізує дублювання коду. Кілька можливостей з кожного оголошення параметра. Менше помилок.
* **Надійний**: ви отримуєте код, готовий до продакшину. З автоматичною інтерактивною документацією.
@@ -127,9 +127,9 @@ FastAPI — це сучасний, швидкий (високопродукти
FastAPI 框架,高效能,易於學習,快速開發,適用於生產環境
@@ -21,138 +27,140 @@
---
-**文件**: https://fastapi.tiangolo.com
+**文件**: https://fastapi.tiangolo.com/zh-hant
**程式碼**: https://github.com/fastapi/fastapi
---
-FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 並採用標準 Python 型別提示。
+FastAPI 是一個現代、快速(高效能)的 Web 框架,用於以 Python 並基於標準的 Python 型別提示來構建 API。
主要特點包含:
-- **快速**: 非常高的效能,可與 **NodeJS** 和 **Go** 效能相當 (歸功於 Starlette and Pydantic)。 [FastAPI 是最快的 Python web 框架之一](#performance)。
-- **極速開發**: 提高開發功能的速度約 200% 至 300%。 \*
-- **更少的 Bug**: 減少約 40% 的人為(開發者)導致的錯誤。 \*
-- **直覺**: 具有出色的編輯器支援,處處都有自動補全以減少偵錯時間。
-- **簡單**: 設計上易於使用和學習,大幅減少閱讀文件的時間。
-- **簡潔**: 最小化程式碼重複性。可以通過不同的參數聲明來實現更豐富的功能,和更少的錯誤。
-- **穩健**: 立即獲得生產級可用的程式碼,還有自動生成互動式文件。
-- **標準化**: 基於 (且完全相容於) OpenAPIs 的相關標準:OpenAPI(之前被稱為 Swagger)和JSON Schema。
+* **快速**:非常高的效能,可與 **NodeJS** 和 **Go** 相當(歸功於 Starlette 和 Pydantic)。[最快的 Python 框架之一](#performance)。
+* **極速開發**:開發功能的速度可提升約 200% 至 300%。*
+* **更少的 Bug**:減少約 40% 的人為(開發者)錯誤。*
+* **直覺**:具有出色的編輯器支援,處處都有 自動補全。更少的偵錯時間。
+* **簡單**:設計上易於使用與學習。更少的讀文件時間。
+* **簡潔**:最小化程式碼重複性。每個參數宣告可帶來多個功能。更少的錯誤。
+* **穩健**:立即獲得可投入生產的程式碼,並自動生成互動式文件。
+* **標準化**:基於(且完全相容於)API 的開放標準:OpenAPI(之前稱為 Swagger)和 JSON Schema。
-\* 基於內部開發團隊在建立生產應用程式時的測試預估。
+* 基於內部開發團隊在建立生產應用程式時的測試預估。
-## 贊助
+## 贊助 { #sponsors }
-{% if sponsors %}
+### 基石贊助商 { #keystone-sponsor }
+
+{% for sponsor in sponsors.keystone -%}
+
Framework FastAPI, haute performance, facile à apprendre, rapide à coder, prêt pour la production
@@ -27,7 +27,7 @@
---
-**Documentation** : https://fastapi.tiangolo.com
+**Documentation** : https://fastapi.tiangolo.com/fr
**Code Source** : https://github.com/fastapi/fastapi
@@ -37,128 +37,130 @@ FastAPI est un framework web moderne et rapide (haute performance) pour la créa
Les principales fonctionnalités sont :
-* **Rapidité** : De très hautes performances, au niveau de **NodeJS** et **Go** (grâce à Starlette et Pydantic). [L'un des frameworks Python les plus rapides](#performance).
-* **Rapide à coder** : Augmente la vitesse de développement des fonctionnalités d'environ 200 % à 300 %. *
-* **Moins de bugs** : Réduit d'environ 40 % les erreurs induites par le développeur. *
-* **Intuitif** : Excellente compatibilité avec les IDE. Complétion complète. Moins de temps passé à déboguer.
-* **Facile** : Conçu pour être facile à utiliser et à apprendre. Moins de temps passé à lire la documentation.
-* **Concis** : Diminue la duplication de code. De nombreuses fonctionnalités liées à la déclaration de chaque paramètre. Moins de bugs.
-* **Robuste** : Obtenez un code prêt pour la production. Avec une documentation interactive automatique.
-* **Basé sur des normes** : Basé sur (et entièrement compatible avec) les standards ouverts pour les APIs : OpenAPI (précédemment connu sous le nom de Swagger) et JSON Schema.
+* **Rapide** : très hautes performances, au niveau de **NodeJS** et **Go** (grâce à Starlette et Pydantic). [L'un des frameworks Python les plus rapides](#performance).
+* **Rapide à coder** : augmente la vitesse de développement des fonctionnalités d'environ 200 % à 300 %. *
+* **Moins de bugs** : réduit d'environ 40 % les erreurs induites par le développeur. *
+* **Intuitif** : excellente compatibilité avec les éditeurs. Autocomplétion partout. Moins de temps passé à déboguer.
+* **Facile** : conçu pour être facile à utiliser et à apprendre. Moins de temps passé à lire les documents.
+* **Concis** : diminue la duplication de code. Plusieurs fonctionnalités à partir de chaque déclaration de paramètre. Moins de bugs.
+* **Robuste** : obtenez un code prêt pour la production. Avec une documentation interactive automatique.
+* **Basé sur des normes** : basé sur (et entièrement compatible avec) les standards ouverts pour les APIs : OpenAPI (précédemment connu sous le nom de Swagger) et JSON Schema.
* estimation basée sur des tests d'une équipe de développement interne, construisant des applications de production.
-## Sponsors
+## Sponsors { #sponsors }
-{% if sponsors %}
+### Sponsor clé de voûte { #keystone-sponsor }
+
+{% for sponsor in sponsors.keystone -%}
+
FastAPI 框架,高性能,易于学习,高效编码,生产可用
@@ -27,135 +27,140 @@
---
-**文档**: https://fastapi.tiangolo.com
+**文档**: https://fastapi.tiangolo.com
**源码**: https://github.com/fastapi/fastapi
---
-FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 并基于标准的 Python 类型提示。
+FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框架,使用 Python 并基于标准的 Python 类型提示。
-关键特性:
+关键特性:
-* **快速**:可与 **NodeJS** 和 **Go** 并肩的极高性能(归功于 Starlette 和 Pydantic)。[最快的 Python web 框架之一](#_11)。
+* **快速**:极高性能,可与 **NodeJS** 和 **Go** 并肩(归功于 Starlette 和 Pydantic)。[最快的 Python 框架之一](#performance)。
+* **高效编码**:功能开发速度提升约 200% ~ 300%。*
+* **更少 bug**:人为(开发者)错误减少约 40%。*
+* **直观**:极佳的编辑器支持。处处皆可自动补全。更少的调试时间。
+* **易用**:为易用和易学而设计。更少的文档阅读时间。
+* **简短**:最小化代码重复。一次参数声明即可获得多种功能。更少的 bug。
+* **健壮**:生产可用级代码。并带有自动生成的交互式文档。
+* **标准化**:基于(并完全兼容)API 的开放标准:OpenAPI(以前称为 Swagger)和 JSON Schema。
-* **高效编码**:提高功能开发速度约 200% 至 300%。*
-* **更少 bug**:减少约 40% 的人为(开发者)导致错误。*
-* **智能**:极佳的编辑器支持。处处皆可自动补全,减少调试时间。
-* **简单**:设计的易于使用和学习,阅读文档的时间更短。
-* **简短**:使代码重复最小化。通过不同的参数声明实现丰富功能。bug 更少。
-* **健壮**:生产可用级别的代码。还有自动生成的交互式文档。
-* **标准化**:基于(并完全兼容)API 的相关开放标准:OpenAPI (以前被称为 Swagger) 和 JSON Schema。
+* 基于某内部开发团队在构建生产应用时的测试估算。
-* 根据对某个构建线上应用的内部开发团队所进行的测试估算得出。
-
-## Sponsors
+## 赞助商 { #sponsors }
-{% if sponsors %}
+### Keystone 赞助商 { #keystone-sponsor }
+
+{% for sponsor in sponsors.keystone -%}
+
+ FastAPI framework, high performance, easy to learn, fast to code, ready for production
+ fXlZ7+Kb`iLCx;T#CO9DA(NdHAyK%heZ?N97Z?$t@qDO
zuB1T@M`)ENE05Yqdd?%2@exv6rX;&n3WHrTjd>~*#YIJ0x(TOr5oyq?Q6XPp{6c6^
zW4;jtgvShcJ?Z6DO*CY=soCeP1X7&`&L#0j2d%$%w%byrXrzTGY5r<9RN=+Nr-zEZ
z7VZVB7GAR}*wCBu13Au@*wSH4ZitFWqn2=SBjsX;g^?4R*_Z^9pLBv5X`>+I^yPu|
z3~6ey4De4&)cs()MoP2O$_c6wzj$*R(~_zaL^r2cEYjr!HY+D%8+u!p5GQ43HB
zT%M)E2*G+iU{sDIW~4Rk)?}frYH4QRwLqefpK_d#u)wl{gua))j+dLCKqU)qGDh9g
zFNN6!`^eu>ehxP>Lz<-J4og`v*zRk?hcIKJW{6w#ZskExbv6^(oT`J5)XA+3pgFlV
zIYEJnPg6}dCcfiahvMxE-Z`NROowy!k*;)uLj$XJVoQC)c)QqCopdF;66U1WgGJF2
z^8DqT)#WvVs!af@G9HSYEGk|7+-}Z&>j84S=)Rkf?i0td6T!rpgVWgPHp4 5g)qwNM3IJi4l )p?EyW#R5VZLu3MI^
zXgQq1!a`i)voz@eQH;xZPoz3Nz6rY3IJBO1y^Eoe;}ax6zkJCA?cdf+_h!nXhmg@{
z{D4z_*vW|-Y?WhS*_Xski+p27lT^!y%(ENrJO6p>s8tyyKSl3|(srN7@BK
-Якщо ви створюєте застосунок CLI для використання в терміналі замість веб-API, зверніть увагу на **Typer**.
+Якщо ви створюєте застосунок CLI для використання в терміналі замість веб-API, зверніть увагу на **Typer**.
-**Typer** — молодший брат FastAPI. І його задумано як **FastAPI для CLI**. ⌨️ 🚀
+**Typer** - молодший брат FastAPI. І його задумано як **FastAPI для CLI**. ⌨️ 🚀
## Вимоги { #requirements }
@@ -161,8 +161,6 @@ $ pip install "fastapi[standard]"
Створіть файл `main.py` з:
```Python
-from typing import Union
-
from fastapi import FastAPI
app = FastAPI()
@@ -174,7 +172,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Union[str, None] = None):
+def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
```
@@ -183,9 +181,7 @@ def read_item(item_id: int, q: Union[str, None] = None):
Якщо ваш код використовує `async` / `await`, скористайтеся `async def`:
-```Python hl_lines="9 14"
-from typing import Union
-
+```Python hl_lines="7 12"
from fastapi import FastAPI
app = FastAPI()
@@ -197,7 +193,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Union[str, None] = None):
+async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
```
@@ -288,9 +284,7 @@ INFO: Application startup complete.
Оголосіть тіло, використовуючи стандартні типи Python, завдяки Pydantic.
-```Python hl_lines="4 9-12 25-27"
-from typing import Union
-
+```Python hl_lines="2 7-10 23-25"
from fastapi import FastAPI
from pydantic import BaseModel
@@ -300,7 +294,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Union[bool, None] = None
+ is_offer: bool | None = None
@app.get("/")
@@ -309,7 +303,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Union[str, None] = None):
+def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
@@ -374,7 +368,7 @@ item: Item
* Валідацію даних:
* Автоматичні та зрозумілі помилки, коли дані некоректні.
* Валідацію навіть для глибоко вкладених JSON-обʼєктів.
-* Перетворення вхідних даних: з мережі до даних і типів Python. Читання з:
+* Перетворення вхідних даних: з мережі до даних і типів Python. Читання з:
* JSON.
* Параметрів шляху.
* Параметрів запиту.
@@ -382,7 +376,7 @@ item: Item
* Headers.
* Forms.
* Files.
-* Перетворення вихідних даних: перетворення з даних і типів Python у мережеві дані (як JSON):
+* Перетворення вихідних даних: перетворення з даних і типів Python у мережеві дані (як JSON):
* Перетворення типів Python (`str`, `int`, `float`, `bool`, `list`, тощо).
* Обʼєктів `datetime`.
* Обʼєктів `UUID`.
@@ -439,9 +433,9 @@ item: Item

-Для більш повного прикладу, що включає більше можливостей, перегляньте Туторіал — Посібник користувача.
+Для більш повного прикладу, що включає більше можливостей, перегляньте Навчальний посібник - Посібник користувача.
-**Spoiler alert**: туторіал — посібник користувача містить:
+**Попередження про спойлер**: навчальний посібник - посібник користувача містить:
* Оголошення **параметрів** з інших різних місць, як-от: **headers**, **cookies**, **form fields** та **files**.
* Як встановлювати **обмеження валідації** як `maximum_length` або `regex`.
@@ -500,11 +494,11 @@ Deploying to FastAPI Cloud...
Він забезпечує той самий **developer experience** створення застосунків на FastAPI під час їх **розгортання** у хмарі. 🎉
-FastAPI Cloud — основний спонсор і джерело фінансування open source проєктів *FastAPI and friends*. ✨
+FastAPI Cloud - основний спонсор і джерело фінансування open source проєктів *FastAPI and friends*. ✨
#### Розгортання в інших хмарних провайдерів { #deploy-to-other-cloud-providers }
-FastAPI — open source і базується на стандартах. Ви можете розгортати застосунки FastAPI в будь-якому хмарному провайдері, який ви оберете.
+FastAPI - open source проект і базується на стандартах. Ви можете розгортати застосунки FastAPI в будь-якому хмарному провайдері, який ви оберете.
Дотримуйтеся інструкцій вашого хмарного провайдера, щоб розгорнути застосунки FastAPI у нього. 🤓
@@ -530,7 +524,7 @@ FastAPI залежить від Pydantic і Starlette.
*
httpx - потрібно, якщо ви хочете використовувати `TestClient`.
* jinja2 - потрібно, якщо ви хочете використовувати конфігурацію шаблонів за замовчуванням.
-* python-multipart - потрібно, якщо ви хочете підтримувати «parsing» форм за допомогою `request.form()`.
+* python-multipart - потрібно, якщо ви хочете підтримувати «parsing» форм за допомогою `request.form()`.
Використовується FastAPI:
diff --git a/docs/uk/docs/tutorial/body-multiple-params.md b/docs/uk/docs/tutorial/body-multiple-params.md
index dc9a768c3..f541beea7 100644
--- a/docs/uk/docs/tutorial/body-multiple-params.md
+++ b/docs/uk/docs/tutorial/body-multiple-params.md
@@ -102,15 +102,16 @@
Оскільки за замовчуванням одиничні значення інтерпретуються як параметри запиту, вам не потрібно явно додавати `Query`, ви можете просто зробити:
+```Python
+q: str | None = None
+```
+
+Або в Python 3.9:
+
```Python
q: Union[str, None] = None
```
-Або в Python 3.10 і вище:
-
-```Python
-q: str | None = None
-```
Наприклад:
@@ -129,7 +130,7 @@ q: str | None = None
За замовчуванням **FastAPI** очікуватиме його тіло безпосередньо.
-Але якщо ви хочете, щоб він очікував JSON з ключем `item`, а всередині нього — вміст моделі, як це відбувається, коли ви оголошуєте додаткові параметри тіла, ви можете використати спеціальний параметр `Body` — `embed`:
+Але якщо ви хочете, щоб він очікував JSON з ключем `item`, а всередині нього - вміст моделі, як це відбувається, коли ви оголошуєте додаткові параметри тіла, ви можете використати спеціальний параметр `Body` - `embed`:
```Python
item: Item = Body(embed=True)
From c00cebc5c68331046741f862359b83d0f428e518 Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
+{% endfor -%}
+
+### 金級與銀級贊助商 { #gold-and-silver-sponsors }
+
{% for sponsor in sponsors.gold -%}
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
{% endfor %}
-{% endif %}
-其他贊助商
+其他贊助商
-## 評價
+## 評價 { #opinions }
-"_[...] 近期大量的使用 **FastAPI**。 [...] 目前正在計畫在**微軟**團隊的**機器學習**服務中導入。其中一些正在整合到核心的 **Windows** 產品和一些 **Office** 產品。_"
+"_[...] 近期大量使用 **FastAPI**。[...] 我實際上打算在我在**微軟**團隊的所有**機器學習**服務上使用它。其中一些正在整合到核心的 **Windows** 產品,以及一些 **Office** 產品。_"
+
+## **Typer**,命令列的 FastAPI { #typer-the-fastapi-of-clis }
-如果你不是在開發網頁 API,而是正在開發一個在終端機中運行的命令列應用程式,不妨嘗試 **Typer**。
+如果你不是在做 Web API,而是要建立一個在終端機中使用的 CLI 應用程式,可以看看 **Typer**。
-**Typer** 是 FastAPI 的小兄弟。他立志成為命令列的 **FastAPI**。 ⌨️ 🚀
+**Typer** 是 FastAPI 的小老弟。他立志成為命令列世界的 **FastAPI**。⌨️ 🚀
-## 安裝需求
+## 需求 { #requirements }
FastAPI 是站在以下巨人的肩膀上:
-- Starlette 負責網頁的部分
-- Pydantic 負責資料的部分
+* Starlette 負責 Web 部分。
+* Pydantic 負責資料部分。
-## 安裝
+## 安裝 { #installation }
+
+建立並啟用一個虛擬環境,然後安裝 FastAPI:
或可以使用
+async def...或使用
-如果你的程式使用 `async` / `await`,請使用 `async def`:
-
-```Python hl_lines="9 14"
-from typing import Union
+如果你的程式碼使用 `async` / `await`,請使用 `async def`:
+```Python hl_lines="7 12"
from fastapi import FastAPI
app = FastAPI()
@@ -187,28 +193,41 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Union[str, None] = None):
+async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
```
**注意**:
-如果你不知道是否會用到,可以查看 _"In a hurry?"_ 章節中,關於 `async` 和 `await` 的部分。
+如果你不確定,請查看文件中 _"In a hurry?"_ 章節的 `async` 與 `await`。
async def...關於指令
+uvicorn main:app --reload...關於指令
-該指令 `uvicorn main:app` 指的是:
+指令 `fastapi dev` 會讀取你的 `main.py`,偵測其中的 **FastAPI** 應用,並使用 Uvicorn 啟動伺服器。
-- `main`:`main.py` 檔案(一個 python 的 "模組")。
-- `app`:在 `main.py` 檔案中,使用 `app = FastAPI()` 建立的物件。
-- `--reload`:程式碼更改後會自動重新啟動,請僅在開發時使用此參數。
+預設情況下,`fastapi dev` 會在本機開發時啟用自動重新載入。
+
+可在 FastAPI CLI 文件中閱讀更多資訊。
fastapi dev main.py...email-validator - 用於電子郵件驗證。
-- pydantic-settings - 用於設定管理。
-- pydantic-extra-types - 用於與 Pydantic 一起使用的額外型別。
+```console
+$ fastapi login
-用於 Starlette:
+You are logged in to FastAPI Cloud 🚀
+```
-- httpx - 使用 `TestClient`時必須安裝。
-- jinja2 - 使用預設的模板配置時必須安裝。
-- python-multipart - 需要使用 `request.form()` 對表單進行 "解析" 時安裝。
-- itsdangerous - 需要使用 `SessionMiddleware` 支援時安裝。
-- pyyaml - 用於支援 Starlette 的 `SchemaGenerator` (如果你使用 FastAPI,可能不需要它)。
+uvicorn - 用於加載和運行應用程式的服務器。
-- orjson - 使用 `ORJSONResponse`時必須安裝。
-- ujson - 使用 `UJSONResponse` 時必須安裝。
+email-validator - 用於電子郵件驗證。
+
+Starlette 會使用:
+
+* httpx - 若要使用 `TestClient` 必須安裝。
+* jinja2 - 若要使用預設的模板設定必須安裝。
+* python-multipart - 若要支援表單 "解析",搭配 `request.form()`。
+
+FastAPI 會使用:
+
+* uvicorn - 用於載入並服務你的應用的伺服器。這包含 `uvicorn[standard]`,其中含有一些高效能服務所需的依賴(例如 `uvloop`)。
+* `fastapi-cli[standard]` - 提供 `fastapi` 指令。
+ * 其中包含 `fastapi-cloud-cli`,可讓你將 FastAPI 應用部署到 FastAPI Cloud。
+
+### 不含 `standard` 依賴套件 { #without-standard-dependencies }
+
+如果你不想包含 `standard` 可選依賴,可以改用 `pip install fastapi`(而不是 `pip install "fastapi[standard]"`)。
+
+### 不含 `fastapi-cloud-cli` { #without-fastapi-cloud-cli }
+
+如果你想安裝帶有 standard 依賴、但不包含 `fastapi-cloud-cli`,可以使用 `pip install "fastapi[standard-no-fastapi-cloud-cli]"`。
+
+### 額外可選依賴套件 { #additional-optional-dependencies }
+
+有些額外依賴你可能也會想安裝。
+
+Pydantic 的額外可選依賴:
+
+* pydantic-settings - 設定管理。
+* pydantic-extra-types - 與 Pydantic 一起使用的額外型別。
+
+FastAPI 的額外可選依賴:
+
+* orjson - 若要使用 `ORJSONResponse` 必須安裝。
+* ujson - 若要使用 `UJSONResponse` 必須安裝。
+
+## 授權 { #license }
+
+本專案以 MIT 授權條款釋出。
diff --git a/docs/zh-hant/docs/learn/index.md b/docs/zh-hant/docs/learn/index.md
index eb7d7096a..43e4519a5 100644
--- a/docs/zh-hant/docs/learn/index.md
+++ b/docs/zh-hant/docs/learn/index.md
@@ -1,5 +1,5 @@
-# 學習
+# 學習 { #learn }
-以下是學習 FastAPI 的入門介紹和教學。
+以下是學習 **FastAPI** 的入門介紹和教學。
你可以將其視為一本**書籍**或一門**課程**,這是**官方**認可並推薦的 FastAPI 學習方式。 😎
diff --git a/docs/zh-hant/docs/resources/index.md b/docs/zh-hant/docs/resources/index.md
index f4c70a3a0..ea77cb728 100644
--- a/docs/zh-hant/docs/resources/index.md
+++ b/docs/zh-hant/docs/resources/index.md
@@ -1,3 +1,3 @@
-# 資源
+# 資源 { #resources }
-額外的資源、外部連結、文章等。 ✈️
+額外的資源、外部連結等。 ✈️
diff --git a/docs/zh-hant/docs/tutorial/first-steps.md b/docs/zh-hant/docs/tutorial/first-steps.md
index d6684bc51..6bcb453bf 100644
--- a/docs/zh-hant/docs/tutorial/first-steps.md
+++ b/docs/zh-hant/docs/tutorial/first-steps.md
@@ -1,8 +1,8 @@
-# 第一步
+# 第一步 { #first-steps }
最簡單的 FastAPI 檔案可能看起來像這樣:
-{* ../../docs_src/first_steps/tutorial001.py *}
+{* ../../docs_src/first_steps/tutorial001_py39.py *}
將其複製到一個名為 `main.py` 的文件中。
@@ -11,47 +11,39 @@
get操作
-/// info | `@decorator` Info
+/// info | `@decorator` 說明
Python 中的 `@something` 語法被稱為「裝飾器」。
@@ -253,7 +281,7 @@ Python 中的 `@something` 語法被稱為「裝飾器」。
一個「裝飾器」會對下面的函式做一些事情。
-在這種情況下,這個裝飾器告訴 **FastAPI** 那個函式對應於 **路徑** `/` 和 **操作** `get`.
+在這種情況下,這個裝飾器告訴 **FastAPI** 那個函式對應於 **路徑** `/` 和 **操作** `get`。
這就是「**路徑操作裝飾器**」。
@@ -284,27 +312,27 @@ Python 中的 `@something` 語法被稱為「裝飾器」。
///
-### 第四步:定義 **路徑操作函式**
+### 第四步:定義「路徑操作函式」 { #step-4-define-the-path-operation-function }
這是我們的「**路徑操作函式**」:
-* **path**: 是 `/`.
-* **operation**: 是 `get`.
-* **function**: 是裝飾器下面的函式(在 `@app.get("/")` 下面)。
+* **path**:是 `/`。
+* **operation**:是 `get`。
+* **function**:是裝飾器下面的函式(在 `@app.get("/")` 下面)。
-{* ../../docs_src/first_steps/tutorial001.py h1[7] *}
+{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
這就是一個 Python 函式。
-它將會在 **FastAPI** 收到一個請求時被呼叫,使用 `GET` 操作。
+它將會在 **FastAPI** 收到一個使用 `GET` 操作、網址為「`/`」的請求時被呼叫。
在這種情況下,它是一個 `async` 函式。
---
-你可以將它定義為一個正常的函式,而不是 `async def`:
+你也可以將它定義為一般函式,而不是 `async def`:
-{* ../../docs_src/first_steps/tutorial003.py h1[7] *}
+{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
/// note
@@ -312,9 +340,9 @@ Python 中的 `@something` 語法被稱為「裝飾器」。
///
-### 第五步:回傳內容
+### 第五步:回傳內容 { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001.py h1[8] *}
+{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
你可以返回一個 `dict`、`list`、單個值作為 `str`、`int` 等。
@@ -322,10 +350,31 @@ Python 中的 `@something` 語法被稱為「裝飾器」。
有很多其他物件和模型會自動轉換為 JSON(包括 ORMs,等等)。試用你最喜歡的,很有可能它們已經有支援。
-## 回顧
+### 第六步:部署 { #step-6-deploy-it }
-* 引入 `FastAPI`.
+用一行指令將你的應用程式部署到 **FastAPI Cloud**:`fastapi deploy`。🎉
+
+#### 關於 FastAPI Cloud { #about-fastapi-cloud }
+
+**FastAPI Cloud** 由 **FastAPI** 的作者與團隊打造。
+
+它讓你以最小的成本完成 API 的**建置**、**部署**與**存取**流程。
+
+它把用 FastAPI 開發應用的同樣**開發者體驗**帶到將應用**部署**到雲端的流程中。🎉
+
+FastAPI Cloud 也是「FastAPI 與其好友」這些開源專案的主要贊助與資金提供者。✨
+
+#### 部署到其他雲端供應商 { #deploy-to-other-cloud-providers }
+
+FastAPI 是開源並基於標準的。你可以把 FastAPI 應用部署到你選擇的任何雲端供應商。
+
+依照你的雲端供應商的指南部署 FastAPI 應用吧。🤓
+
+## 回顧 { #recap }
+
+* 引入 `FastAPI`。
* 建立一個 `app` 實例。
-* 寫一個 **路徑操作裝飾器** 使用裝飾器像 `@app.get("/")`。
-* 定義一個 **路徑操作函式**;例如,`def root(): ...`。
+* 寫一個「路徑操作裝飾器」,像是 `@app.get("/")`。
+* 定義一個「路徑操作函式」;例如,`def root(): ...`。
* 使用命令 `fastapi dev` 執行開發伺服器。
+* 可選:使用 `fastapi deploy` 部署你的應用程式。
diff --git a/docs/zh-hant/docs/tutorial/index.md b/docs/zh-hant/docs/tutorial/index.md
index ae0056f52..5e1961fd7 100644
--- a/docs/zh-hant/docs/tutorial/index.md
+++ b/docs/zh-hant/docs/tutorial/index.md
@@ -1,4 +1,4 @@
-# 教學 - 使用者指南
+# 教學 - 使用者指南 { #tutorial-user-guide }
本教學將一步一步展示如何使用 **FastAPI** 及其大多數功能。
@@ -6,7 +6,7 @@
它也被設計成可作為未來的參考,讓你隨時回來查看所需的內容。
-## 運行程式碼
+## 運行程式碼 { #run-the-code }
所有程式碼區塊都可以直接複製和使用(它們實際上是經過測試的 Python 檔案)。
@@ -15,48 +15,39 @@
-## 禁止額外的查詢參數
+## 禁止額外的查詢參數 { #forbid-extra-query-parameters }
在一些特殊的使用場景中(可能不是很常見),你可能希望**限制**你要收到的查詢參數。
@@ -57,7 +57,7 @@ https://example.com/items/?limit=10&tool=plumbus
}
```
-## 總結
+## 總結 { #summary }
你可以使用 **Pydantic 模型**在 **FastAPI** 中聲明**查詢參數**。😎
diff --git a/docs/zh-hant/docs/virtual-environments.md b/docs/zh-hant/docs/virtual-environments.md
index d8e31e08e..acd1d914e 100644
--- a/docs/zh-hant/docs/virtual-environments.md
+++ b/docs/zh-hant/docs/virtual-environments.md
@@ -1,4 +1,4 @@
-# 虛擬環境
+# 虛擬環境 { #virtual-environments }
當你在 Python 專案中工作時,你可能會需要使用一個**虛擬環境**(或類似的機制)來隔離你為每個專案安裝的套件。
@@ -26,7 +26,7 @@
///
-## 建立一個專案
+## 建立一個專案 { #create-a-project }
首先,為你的專案建立一個目錄。
@@ -51,7 +51,7 @@ $ cd awesome-project
-## 建立一個虛擬環境
+## 建立一個虛擬環境 { #create-a-virtual-environment }
在開始一個 Python 專案的**第一時間**,**在你的專案內部**建立一個虛擬環境。
@@ -114,7 +114,7 @@ $ uv venv
///
-## 啟動虛擬環境
+## 啟動虛擬環境 { #activate-the-virtual-environment }
啟動新的虛擬環境來確保你運行的任何 Python 指令或安裝的套件都能使用到它。
@@ -166,11 +166,11 @@ $ source .venv/Scripts/activate
每次你在這個環境中安裝一個**新的套件**時,都需要**重新啟動**這個環境。
-這麼做確保了當你使用一個由這個套件安裝的**終端(CLI)程式**時,你使用的是你的虛擬環境中的程式,而不是全域安裝、可能版本不同的程式。
+這麼做確保了當你使用一個由這個套件安裝的**終端(CLI)程式**時,你使用的是你的虛擬環境中的程式,而不是全域安裝、可能版本不同的程式。
///
-## 檢查虛擬環境是否啟動
+## 檢查虛擬環境是否啟動 { #check-the-virtual-environment-is-active }
檢查虛擬環境是否啟動(前面的指令是否生效)。
@@ -212,7 +212,7 @@ C:\Users\user\code\awesome-project\.venv\Scripts\python
////
-## 升級 `pip`
+## 升級 `pip` { #upgrade-pip }
/// tip
@@ -242,7 +242,27 @@ $ python -m pip install --upgrade pip
-## 加入 `.gitignore`
+/// tip | 注意
+
+有時你在嘗試升級 pip 時,可能會遇到 **`No module named pip`** 的錯誤。
+
+如果發生這種情況,請用下面的指令安裝並升級 pip:
+
+
-## Combinez les réponses prédéfinies et les réponses personnalisées
+## Combinez les réponses prédéfinies et les réponses personnalisées { #combine-predefined-responses-and-custom-ones }
-Vous voulez peut-être avoir des réponses prédéfinies qui s'appliquent à de nombreux *paramètre de chemin*, mais vous souhaitez les combiner avec des réponses personnalisées nécessaires à chaque *opération de chemin*.
+Vous voulez peut-être avoir des réponses prédéfinies qui s'appliquent à de nombreux *chemins d'accès*, mais vous souhaitez les combiner avec des réponses personnalisées nécessaires à chaque *chemin d'accès*.
-Dans ces cas, vous pouvez utiliser la technique Python "d'affection par décomposition" (appelé _unpacking_ en anglais) d'un `dict` avec `**dict_to_unpack` :
+Dans ces cas, vous pouvez utiliser la technique Python « unpacking » d'un `dict` avec `**dict_to_unpack` :
```Python
old_dict = {
@@ -233,15 +233,15 @@ Ici, `new_dict` contiendra toutes les paires clé-valeur de `old_dict` plus la n
}
```
-Vous pouvez utiliser cette technique pour réutiliser certaines réponses prédéfinies dans vos *paramètres de chemin* et les combiner avec des réponses personnalisées supplémentaires.
+Vous pouvez utiliser cette technique pour réutiliser certaines réponses prédéfinies dans vos *chemins d'accès* et les combiner avec des réponses personnalisées supplémentaires.
Par exemple:
-{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *}
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
-## Plus d'informations sur les réponses OpenAPI
+## Plus d'informations sur les réponses OpenAPI { #more-information-about-openapi-responses }
Pour voir exactement ce que vous pouvez inclure dans les réponses, vous pouvez consulter ces sections dans la spécification OpenAPI :
-* Objet Responses de OpenAPI , il inclut le `Response Object`.
-* Objet Response de OpenAPI , vous pouvez inclure n'importe quoi directement dans chaque réponse à l'intérieur de votre paramètre `responses`. Y compris `description`, `headers`, `content` (à l'intérieur de cela, vous déclarez différents types de médias et schémas JSON) et `links`.
+* Objet Responses de OpenAPI, il inclut le `Response Object`.
+* Objet Response de OpenAPI, vous pouvez inclure n'importe quoi directement dans chaque réponse à l'intérieur de votre paramètre `responses`. Y compris `description`, `headers`, `content` (à l'intérieur de cela, vous déclarez différents types de médias et schémas JSON) et `links`.
diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md
index dde6b9a63..b2befffa8 100644
--- a/docs/fr/docs/advanced/additional-status-codes.md
+++ b/docs/fr/docs/advanced/additional-status-codes.md
@@ -1,28 +1,28 @@
-# Codes HTTP supplémentaires
+# Codes HTTP supplémentaires { #additional-status-codes }
Par défaut, **FastAPI** renverra les réponses à l'aide d'une structure de données `JSONResponse`, en plaçant la réponse de votre *chemin d'accès* à l'intérieur de cette `JSONResponse`.
Il utilisera le code HTTP par défaut ou celui que vous avez défini dans votre *chemin d'accès*.
-## Codes HTTP supplémentaires
+## Codes HTTP supplémentaires { #additional-status-codes_1 }
Si vous souhaitez renvoyer des codes HTTP supplémentaires en plus du code principal, vous pouvez le faire en renvoyant directement une `Response`, comme une `JSONResponse`, et en définissant directement le code HTTP supplémentaire.
-Par exemple, disons que vous voulez avoir un *chemin d'accès* qui permet de mettre à jour les éléments et renvoie les codes HTTP 200 "OK" en cas de succès.
+Par exemple, disons que vous voulez avoir un *chemin d'accès* qui permet de mettre à jour les éléments et renvoie les codes HTTP 200 « OK » en cas de succès.
-Mais vous voulez aussi qu'il accepte de nouveaux éléments. Et lorsque les éléments n'existaient pas auparavant, il les crée et renvoie un code HTTP de 201 "Créé".
+Mais vous voulez aussi qu'il accepte de nouveaux éléments. Et lorsque les éléments n'existaient pas auparavant, il les crée et renvoie un code HTTP de 201 « Créé ».
Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu, en définissant le `status_code` que vous souhaitez :
-{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *}
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
-/// warning | Attention
+/// warning | Alertes
Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement.
Elle ne sera pas sérialisée avec un modèle.
-Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`).
+Assurez-vous qu'il contient les données souhaitées et que les valeurs sont dans un format JSON valide (si vous utilisez une `JSONResponse`).
///
@@ -30,12 +30,12 @@ Assurez-vous qu'il contient les données souhaitées et que les valeurs soient d
Vous pouvez également utiliser `from starlette.responses import JSONResponse`.
-Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`.
+Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec `status`.
///
-## Documents OpenAPI et API
+## Documents OpenAPI et API { #openapi-and-api-docs }
Si vous renvoyez directement des codes HTTP et des réponses supplémentaires, ils ne seront pas inclus dans le schéma OpenAPI (la documentation de l'API), car FastAPI n'a aucun moyen de savoir à l'avance ce que vous allez renvoyer.
-Mais vous pouvez documenter cela dans votre code, en utilisant : [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
+Mais vous pouvez documenter cela dans votre code, en utilisant : [Réponses supplémentaires](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md
index d9d8ad8e6..a2f9d3b1b 100644
--- a/docs/fr/docs/advanced/index.md
+++ b/docs/fr/docs/advanced/index.md
@@ -1,27 +1,21 @@
-# Guide de l'utilisateur avancé
+# Guide de l'utilisateur avancé { #advanced-user-guide }
-## Caractéristiques supplémentaires
+## Caractéristiques supplémentaires { #additional-features }
Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link target=_blank} devrait suffire à vous faire découvrir toutes les fonctionnalités principales de **FastAPI**.
Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires.
-/// note | Remarque
+/// tip | Astuce
-Les sections de ce chapitre ne sont **pas nécessairement "avancées"**.
+Les sections suivantes ne sont **pas nécessairement « avancées »**.
-Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux.
+Et il est possible que, pour votre cas d'utilisation, la solution se trouve dans l'une d'entre elles.
///
-## Lisez d'abord le didacticiel
+## Lire d'abord le tutoriel { #read-the-tutorial-first }
Vous pouvez utiliser la plupart des fonctionnalités de **FastAPI** grâce aux connaissances du [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link target=_blank}.
Et les sections suivantes supposent que vous l'avez lu et que vous en connaissez les idées principales.
-
-## Cours TestDriven.io
-
-Si vous souhaitez suivre un cours pour débutants avancés pour compléter cette section de la documentation, vous pouvez consulter : Développement piloté par les tests avec FastAPI et Docker par **TestDriven.io**.
-
-10 % de tous les bénéfices de ce cours sont reversés au développement de **FastAPI**. 🎉 😄
diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
index 7daf0fc65..fc88f3363 100644
--- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
@@ -1,106 +1,108 @@
-# Configuration avancée des paramètres de chemin
+# Configuration avancée des chemins d'accès { #path-operation-advanced-configuration }
-## ID d'opération OpenAPI
+## ID d’opération OpenAPI { #openapi-operationid }
-/// warning | Attention
+/// warning | Alertes
-Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin.
+Si vous n’êtes pas un « expert » d’OpenAPI, vous n’en avez probablement pas besoin.
///
-Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, exposées par votre API, et les opérations sont les méthodes HTTP utilisées pour manipuler ces chemins, telles que GET, POST ou DELETE. Les operationId sont des chaînes uniques facultatives utilisées pour identifier une opération d'un chemin. Vous pouvez définir l'OpenAPI `operationId` à utiliser dans votre *opération de chemin* avec le paramètre `operation_id`.
+Vous pouvez définir l’OpenAPI `operationId` à utiliser dans votre chemin d’accès avec le paramètre `operation_id`.
-Vous devez vous assurer qu'il est unique pour chaque opération.
+Vous devez vous assurer qu’il est unique pour chaque opération.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}
-### Utilisation du nom *path operation function* comme operationId
+### Utiliser le nom de la fonction de chemin d’accès comme operationId { #using-the-path-operation-function-name-as-the-operationid }
-Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`, vous pouvez les parcourir tous et remplacer chaque `operation_id` de l'*opération de chemin* en utilisant leur `APIRoute.name`.
+Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`, vous pouvez les parcourir tous et remplacer l’`operation_id` de chaque chemin d’accès en utilisant leur `APIRoute.name`.
-Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*.
+Vous devez le faire après avoir ajouté tous vos chemins d’accès.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py39.py hl[2, 12:21, 24] *}
/// tip | Astuce
-Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
+Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant cela.
///
-/// warning | Attention
+/// warning | Alertes
-Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique.
+Si vous faites cela, vous devez vous assurer que chacune de vos fonctions de chemin d’accès a un nom unique.
-Même s'ils se trouvent dans des modules différents (fichiers Python).
+Même si elles se trouvent dans des modules différents (fichiers Python).
///
-## Exclusion d'OpenAPI
+## Exclusion d’OpenAPI { #exclude-from-openapi }
-Pour exclure un *chemin* du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et assignez-lui la valeur `False` :
+Pour exclure un chemin d’accès du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et définissez-le à `False` :
-{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}
-## Description avancée de docstring
+## Description avancée depuis la docstring { #advanced-description-from-docstring }
-Vous pouvez limiter le texte utilisé de la docstring d'une *fonction de chemin* qui sera affiché sur OpenAPI.
+Vous pouvez limiter les lignes utilisées de la docstring d’une fonction de chemin d’accès pour OpenAPI.
-L'ajout d'un `\f` (un caractère d'échappement "form feed") va permettre à **FastAPI** de tronquer la sortie utilisée pour OpenAPI à ce stade.
+L’ajout d’un `\f` (un caractère « saut de page » échappé) amène **FastAPI** à tronquer la sortie utilisée pour OpenAPI à cet endroit.
-Il n'apparaîtra pas dans la documentation, mais d'autres outils (tel que Sphinx) pourront utiliser le reste.
+Cela n’apparaîtra pas dans la documentation, mais d’autres outils (comme Sphinx) pourront utiliser le reste.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
-## Réponses supplémentaires
+## Réponses supplémentaires { #additional-responses }
-Vous avez probablement vu comment déclarer le `response_model` et le `status_code` pour une *opération de chemin*.
+Vous avez probablement vu comment déclarer le `response_model` et le `status_code` pour un chemin d’accès.
-Cela définit les métadonnées sur la réponse principale d'une *opération de chemin*.
+Cela définit les métadonnées sur la réponse principale d’un chemin d’accès.
Vous pouvez également déclarer des réponses supplémentaires avec leurs modèles, codes de statut, etc.
-Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
+Il y a un chapitre entier dans la documentation à ce sujet, vous pouvez le lire dans [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
-## OpenAPI supplémentaire
+## OpenAPI supplémentaire { #openapi-extra }
-Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI.
+Lorsque vous déclarez un chemin d’accès dans votre application, **FastAPI** génère automatiquement les métadonnées pertinentes à propos de ce chemin d’accès à inclure dans le schéma OpenAPI.
/// note | Détails techniques
-La spécification OpenAPI appelle ces métadonnées des Objets d'opération.
+Dans la spécification OpenAPI, cela s’appelle l’objet Operation.
///
-Il contient toutes les informations sur le *chemin* et est utilisé pour générer automatiquement la documentation.
+Il contient toutes les informations sur le chemin d’accès et est utilisé pour générer la documentation automatique.
Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc.
-Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre.
+Ce schéma OpenAPI spécifique à un chemin d’accès est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l’étendre.
/// tip | Astuce
-Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
+Ceci est un point d’extension de bas niveau.
+
+Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d’utiliser [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
///
-Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`.
+Vous pouvez étendre le schéma OpenAPI pour un chemin d’accès en utilisant le paramètre `openapi_extra`.
-### Extensions OpenAPI
+### Extensions OpenAPI { #openapi-extensions }
-Cet `openapi_extra` peut être utile, par exemple, pour déclarer [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) :
+Cet `openapi_extra` peut être utile, par exemple, pour déclarer des [Extensions OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) :
-{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py39.py hl[6] *}
-Si vous ouvrez la documentation automatique de l'API, votre extension apparaîtra au bas du *chemin* spécifique.
+Si vous ouvrez la documentation automatique de l’API, votre extension apparaîtra en bas du chemin d’accès spécifique.
-Et dans le fichier openapi généré (`/openapi.json`), vous verrez également votre extension dans le cadre du *chemin* spécifique :
+Et si vous consultez l’OpenAPI résultant (à `/openapi.json` dans votre API), vous verrez également votre extension comme partie du chemin d’accès spécifique :
```JSON hl_lines="22"
{
- "openapi": "3.0.2",
+ "openapi": "3.1.0",
"info": {
"title": "FastAPI",
"version": "0.1.0"
@@ -127,44 +129,44 @@ Et dans le fichier openapi généré (`/openapi.json`), vous verrez également v
}
```
-### Personnalisation du Schéma OpenAPI pour un chemin
+### Personnaliser le schéma OpenAPI d’un chemin d’accès { #custom-openapi-path-operation-schema }
-Le dictionnaire contenu dans la variable `openapi_extra` sera fusionné avec le schéma OpenAPI généré automatiquement pour l'*opération de chemin*.
+Le dictionnaire dans `openapi_extra` sera fusionné en profondeur avec le schéma OpenAPI généré automatiquement pour le chemin d’accès.
Ainsi, vous pouvez ajouter des données supplémentaires au schéma généré automatiquement.
-Par exemple, vous pouvez décider de lire et de valider la requête avec votre propre code, sans utiliser les fonctionnalités automatiques de validation proposée par Pydantic, mais vous pouvez toujours définir la requête dans le schéma OpenAPI.
+Par exemple, vous pourriez décider de lire et de valider la requête avec votre propre code, sans utiliser les fonctionnalités automatiques de FastAPI avec Pydantic, mais vous pourriez tout de même vouloir définir la requête dans le schéma OpenAPI.
-Vous pouvez le faire avec `openapi_extra` :
+Vous pourriez le faire avec `openapi_extra` :
-{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py39.py hl[19:36, 39:40] *}
-Dans cet exemple, nous n'avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n'est même pas parsé en tant que JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargé de l'analyser d'une manière ou d'une autre.
+Dans cet exemple, nous n’avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n’est même pas parsé en JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargée de l’analyser d’une manière ou d’une autre.
Néanmoins, nous pouvons déclarer le schéma attendu pour le corps de la requête.
-### Type de contenu OpenAPI personnalisé
+### Type de contenu OpenAPI personnalisé { #custom-openapi-content-type }
-En utilisant cette même astuce, vous pouvez utiliser un modèle Pydantic pour définir le schéma JSON qui est ensuite inclus dans la section de schéma OpenAPI personnalisée pour le *chemin* concerné.
+En utilisant cette même astuce, vous pourriez utiliser un modèle Pydantic pour définir le JSON Schema qui est ensuite inclus dans la section de schéma OpenAPI personnalisée pour le chemin d’accès.
-Et vous pouvez le faire même si le type de données dans la requête n'est pas au format JSON.
+Et vous pourriez le faire même si le type de données dans la requête n’est pas du JSON.
-Dans cet exemple, nous n'utilisons pas les fonctionnalités de FastAPI pour extraire le schéma JSON des modèles Pydantic ni la validation automatique pour JSON. En fait, nous déclarons le type de contenu de la requête en tant que YAML, et non JSON :
+Par exemple, dans cette application nous n’utilisons pas la fonctionnalité intégrée de FastAPI pour extraire le JSON Schema des modèles Pydantic ni la validation automatique pour le JSON. En fait, nous déclarons le type de contenu de la requête comme YAML, pas JSON :
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[15:20, 22] *}
-Néanmoins, bien que nous n'utilisions pas la fonctionnalité par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le schéma JSON pour les données que nous souhaitons recevoir en YAML.
+Néanmoins, bien que nous n’utilisions pas la fonctionnalité intégrée par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le JSON Schema pour les données que nous souhaitons recevoir en YAML.
-Ensuite, nous utilisons directement la requête et extrayons son contenu en tant qu'octets. Cela signifie que FastAPI n'essaiera même pas d'analyser le payload de la requête en tant que JSON.
+Ensuite, nous utilisons directement la requête et extrayons le corps en tant que `bytes`. Cela signifie que FastAPI n’essaiera même pas d’analyser le payload de la requête en JSON.
-Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML :
+Ensuite, dans notre code, nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML :
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[24:31] *}
/// tip | Astuce
Ici, nous réutilisons le même modèle Pydantic.
-Mais nous aurions pu tout aussi bien pu le valider d'une autre manière.
+Mais de la même manière, nous aurions pu le valider autrement.
///
diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md
index 4ff883c77..f35c39c06 100644
--- a/docs/fr/docs/advanced/response-directly.md
+++ b/docs/fr/docs/advanced/response-directly.md
@@ -1,20 +1,20 @@
-# Renvoyer directement une réponse
+# Renvoyer directement une réponse { #return-a-response-directly }
-Lorsque vous créez une *opération de chemins* **FastAPI**, vous pouvez normalement retourner n'importe quelle donnée : un `dict`, une `list`, un modèle Pydantic, un modèle de base de données, etc.
+Lorsque vous créez un *chemin d'accès* **FastAPI**, vous pouvez normalement retourner n'importe quelle donnée : un `dict`, une `list`, un modèle Pydantic, un modèle de base de données, etc.
-Par défaut, **FastAPI** convertirait automatiquement cette valeur de retour en JSON en utilisant le `jsonable_encoder` expliqué dans [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}.
+Par défaut, **FastAPI** convertirait automatiquement cette valeur de retour en JSON en utilisant le `jsonable_encoder` expliqué dans [Encodeur compatible JSON](../tutorial/encoder.md){.internal-link target=_blank}.
Ensuite, en arrière-plan, il mettra ces données JSON-compatible (par exemple un `dict`) à l'intérieur d'un `JSONResponse` qui sera utilisé pour envoyer la réponse au client.
-Mais vous pouvez retourner une `JSONResponse` directement à partir de vos *opérations de chemin*.
+Mais vous pouvez retourner une `JSONResponse` directement à partir de vos *chemins d'accès*.
Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés ou des cookies.
-## Renvoyer une `Response`
+## Renvoyer une `Response` { #return-a-response }
En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci.
-/// note | Remarque
+/// tip | Astuce
`JSONResponse` est elle-même une sous-classe de `Response`.
@@ -24,27 +24,27 @@ Et quand vous retournez une `Response`, **FastAPI** la transmet directement.
Elle ne fera aucune conversion de données avec les modèles Pydantic, elle ne convertira pas le contenu en un type quelconque.
-Cela vous donne beaucoup de flexibilité. Vous pouvez retourner n'importe quel type de données, surcharger n'importe quelle déclaration ou validation de données.
+Cela vous donne beaucoup de flexibilité. Vous pouvez retourner n'importe quel type de données, surcharger n'importe quelle déclaration ou validation de données, etc.
-## Utiliser le `jsonable_encoder` dans une `Response`
+## Utiliser le `jsonable_encoder` dans une `Response` { #using-the-jsonable-encoder-in-a-response }
-Parce que **FastAPI** n'apporte aucune modification à une `Response` que vous retournez, vous devez vous assurer que son contenu est prêt à être utilisé (sérialisable).
+Parce que **FastAPI** n'apporte aucune modification à une `Response` que vous retournez, vous devez vous assurer que son contenu est prêt pour cela.
Par exemple, vous ne pouvez pas mettre un modèle Pydantic dans une `JSONResponse` sans d'abord le convertir en un `dict` avec tous les types de données (comme `datetime`, `UUID`, etc.) convertis en types compatibles avec JSON.
-Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convertir vos données avant de les passer à une réponse :
+Pour ces cas, vous pouvez utiliser le `jsonable_encoder` pour convertir vos données avant de les passer à une réponse :
-{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *}
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
/// note | Détails techniques
Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`.
-**FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+**FastAPI** fournit le même `starlette.responses` que `fastapi.responses` juste par commodité pour vous, le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
///
-## Renvoyer une `Response` personnalisée
+## Renvoyer une `Response` personnalisée { #returning-a-custom-response }
L'exemple ci-dessus montre toutes les parties dont vous avez besoin, mais il n'est pas encore très utile, car vous auriez pu retourner l'`item` directement, et **FastAPI** l'aurait mis dans une `JSONResponse` pour vous, en le convertissant en `dict`, etc. Tout cela par défaut.
@@ -54,9 +54,9 @@ Disons que vous voulez retourner une réponse étant l'un des frameworks Python les plus rapides disponibles, seulement inférieur à Starlette et Uvicorn (tous deux utilisés au cœur de FastAPI). (*)
+Les benchmarks indépendants de TechEmpower montrent que les applications **FastAPI** s’exécutant avec Uvicorn sont parmi les frameworks Python les plus rapides disponibles, seulement en dessous de Starlette et Uvicorn eux‑mêmes (tous deux utilisés en interne par FastAPI).
-Mais en prêtant attention aux tests de performance et aux comparaisons, il faut tenir compte de ce qu'il suit.
+Mais en prêtant attention aux tests de performance et aux comparaisons, vous devez tenir compte de ce qui suit.
-## Tests de performance et rapidité
+## Tests de performance et rapidité { #benchmarks-and-speed }
Lorsque vous vérifiez les tests de performance, il est commun de voir plusieurs outils de différents types comparés comme équivalents.
En particulier, on voit Uvicorn, Starlette et FastAPI comparés (parmi de nombreux autres outils).
-Plus le problème résolu par un outil est simple, mieux seront les performances obtenues. Et la plupart des tests de performance ne prennent pas en compte les fonctionnalités additionnelles fournies par les outils.
+Plus le problème résolu par un outil est simple, meilleures seront les performances obtenues. Et la plupart des tests de performance ne prennent pas en compte les fonctionnalités additionnelles fournies par les outils.
La hiérarchie est la suivante :
* **Uvicorn** : un serveur ASGI
- * **Starlette** : (utilise Uvicorn) un micro-framework web
- * **FastAPI**: (utilise Starlette) un micro-framework pour API disposant de fonctionnalités additionnelles pour la création d'API, avec la validation des données, etc.
+ * **Starlette** : (utilise Uvicorn) un microframework web
+ * **FastAPI**: (utilise Starlette) un microframework pour API disposant de fonctionnalités additionnelles pour la création d'API, avec la validation des données, etc.
* **Uvicorn** :
- * A les meilleures performances, étant donné qu'il n'a pas beaucoup de code mis-à-part le serveur en lui-même.
- * On n'écrit pas une application avec uniquement Uvicorn. Cela signifie que le code devrait inclure plus ou moins, au minimum, tout le code offert par Starlette (ou **FastAPI**). Et si on fait cela, l'application finale apportera les mêmes complications que si on avait utilisé un framework et que l'on avait minimisé la quantité de code et de bugs.
- * Si on compare Uvicorn, il faut le comparer à d'autre applications de serveurs comme Daphne, Hypercorn, uWSGI, etc.
+ * A les meilleures performances, étant donné qu'il n'a pas beaucoup de code mis à part le serveur en lui‑même.
+ * On n'écrit pas une application directement avec Uvicorn. Cela signifie que le code devrait inclure, au minimum, plus ou moins tout le code offert par Starlette (ou **FastAPI**). Et si on fait cela, l'application finale aura la même surcharge que si on avait utilisé un framework, tout en minimisant la quantité de code et les bugs.
+ * Si on compare Uvicorn, il faut le comparer à d'autres serveurs d'applications comme Daphne, Hypercorn, uWSGI, etc.
* **Starlette** :
- * A les seconde meilleures performances après Uvicorn. Starlette utilise en réalité Uvicorn. De ce fait, il ne peut qu’être plus "lent" qu'Uvicorn car il requiert l'exécution de plus de code.
- * Cependant il nous apporte les outils pour construire une application web simple, avec un routage basé sur des chemins, etc.
- * Si on compare Starlette, il faut le comparer à d'autres frameworks web (ou micorframework) comme Sanic, Flask, Django, etc.
+ * A les secondes meilleures performances après Uvicorn. En réalité, Starlette utilise Uvicorn. De ce fait, il ne peut qu’être plus « lent » qu'Uvicorn car il requiert l'exécution de plus de code.
+ * Cependant, il apporte les outils pour construire une application web simple, avec un routage basé sur des chemins, etc.
+ * Si on compare Starlette, il faut le comparer à d'autres frameworks web (ou microframeworks) comme Sanic, Flask, Django, etc.
* **FastAPI** :
- * Comme Starlette, FastAPI utilise Uvicorn et ne peut donc pas être plus rapide que ce dernier.
- * FastAPI apporte des fonctionnalités supplémentaires à Starlette. Des fonctionnalités qui sont nécessaires presque systématiquement lors de la création d'une API, comme la validation des données, la sérialisation. En utilisant FastAPI, on obtient une documentation automatiquement (qui ne requiert aucune manipulation pour être mise en place).
- * Si on n'utilisait pas FastAPI mais directement Starlette (ou un outil équivalent comme Sanic, Flask, Responder, etc) il faudrait implémenter la validation des données et la sérialisation par nous-même. Le résultat serait donc le même dans les deux cas mais du travail supplémentaire serait à réaliser avec Starlette, surtout en considérant que la validation des données et la sérialisation représentent la plus grande quantité de code à écrire dans une application.
- * De ce fait, en utilisant FastAPI on minimise le temps de développement, les bugs, le nombre de lignes de code, et on obtient les mêmes performances (si ce n'est de meilleurs performances) que l'on aurait pu avoir sans ce framework (en ayant à implémenter de nombreuses fonctionnalités importantes par nous-mêmes).
- * Si on compare FastAPI, il faut le comparer à d'autres frameworks web (ou ensemble d'outils) qui fournissent la validation des données, la sérialisation et la documentation, comme Flask-apispec, NestJS, Molten, etc.
+ * Comme Starlette utilise Uvicorn et ne peut donc pas être plus rapide que lui, **FastAPI** utilise Starlette et ne peut donc pas être plus rapide que lui.
+ * FastAPI apporte des fonctionnalités supplémentaires à Starlette. Des fonctionnalités dont vous avez presque toujours besoin lors de la création d'une API, comme la validation des données et la sérialisation. En l'utilisant, vous obtenez une documentation automatique « gratuitement » (la documentation automatique n'ajoute même pas de surcharge à l’exécution, elle est générée au démarrage).
+ * Si on n'utilisait pas FastAPI mais directement Starlette (ou un autre outil comme Sanic, Flask, Responder, etc.), il faudrait implémenter toute la validation des données et la sérialisation soi‑même. L'application finale aurait donc la même surcharge que si elle avait été construite avec FastAPI. Et dans de nombreux cas, cette validation des données et cette sérialisation représentent la plus grande quantité de code écrite dans les applications.
+ * De ce fait, en utilisant FastAPI on minimise le temps de développement, les bugs, le nombre de lignes de code, et on obtient probablement les mêmes performances (voire de meilleures performances) que l'on aurait pu avoir sans ce framework (car il aurait fallu tout implémenter dans votre code).
+ * Si on compare FastAPI, il faut le comparer à d'autres frameworks d’application web (ou ensembles d'outils) qui fournissent la validation des données, la sérialisation et la documentation, comme Flask-apispec, NestJS, Molten, etc. Des frameworks avec validation des données, sérialisation et documentation automatiques intégrées.
diff --git a/docs/fr/docs/deployment/docker.md b/docs/fr/docs/deployment/docker.md
index 05b597a2d..ec30f9607 100644
--- a/docs/fr/docs/deployment/docker.md
+++ b/docs/fr/docs/deployment/docker.md
@@ -1,75 +1,150 @@
-# Déployer avec Docker
+# FastAPI dans des conteneurs - Docker { #fastapi-in-containers-docker }
-Dans cette section, vous verrez des instructions et des liens vers des guides pour savoir comment :
+Lors du déploiement d'applications FastAPI, une approche courante consiste à construire une **image de conteneur Linux**. C'est généralement fait avec **Docker**. Vous pouvez ensuite déployer cette image de conteneur de plusieurs façons possibles.
-* Faire de votre application **FastAPI** une image/conteneur Docker avec une performance maximale. En environ **5 min**.
-* (Optionnellement) comprendre ce que vous, en tant que développeur, devez savoir sur HTTPS.
-* Configurer un cluster en mode Docker Swarm avec HTTPS automatique, même sur un simple serveur à 5 dollars US/mois. En environ **20 min**.
-* Générer et déployer une application **FastAPI** complète, en utilisant votre cluster Docker Swarm, avec HTTPS, etc. En environ **10 min**.
-
-Vous pouvez utiliser **Docker** pour le déploiement. Il présente plusieurs avantages comme la sécurité, la réplicabilité, la simplicité de développement, etc.
-
-Si vous utilisez Docker, vous pouvez utiliser l'image Docker officielle :
-
-## tiangolo/uvicorn-gunicorn-fastapi
-
-Cette image est dotée d'un mécanisme d'"auto-tuning", de sorte qu'il vous suffit d'ajouter votre code pour obtenir automatiquement des performances très élevées. Et sans faire de sacrifices.
-
-Mais vous pouvez toujours changer et mettre à jour toutes les configurations avec des variables d'environnement ou des fichiers de configuration.
+L'utilisation de conteneurs Linux présente plusieurs avantages, notamment la **sécurité**, la **réplicabilité**, la **simplicité**, entre autres.
/// tip | Astuce
-Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : tiangolo/uvicorn-gunicorn-fastapi.
+Vous êtes pressé et vous connaissez déjà tout ça ? Allez directement au [`Dockerfile` ci-dessous 👇](#build-a-docker-image-for-fastapi).
///
-## Créer un `Dockerfile`
-
-* Allez dans le répertoire de votre projet.
-* Créez un `Dockerfile` avec :
+Aperçu du Dockerfile 👀
```Dockerfile
-FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
+FROM python:3.9
-COPY ./app /app
+WORKDIR /code
+
+COPY ./requirements.txt /code/requirements.txt
+
+RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
+
+COPY ./app /code/app
+
+CMD ["fastapi", "run", "app/main.py", "--port", "80"]
+
+# Si vous exécutez derrière un proxy comme Nginx ou Traefik, ajoutez --proxy-headers
+# CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"]
```
-### Applications plus larges
+
+
+### Début de la négociation TLS (Handshake) { #tls-handshake-start }
+
+Le navigateur communiquerait ensuite avec cette adresse IP sur le **port 443** (le port HTTPS).
+
+La première partie de la communication consiste simplement à établir la connexion entre le client et le serveur et à décider des clés cryptographiques qu'ils utiliseront, etc.
+
+
+
+Cette interaction entre le client et le serveur pour établir la connexion TLS s'appelle la **négociation TLS (TLS handshake)**.
+
+### TLS avec l'extension SNI { #tls-with-sni-extension }
+
+**Un seul processus** sur le serveur peut écouter sur un **port** spécifique d'une **adresse IP** spécifique. Il pourrait y avoir d'autres processus écoutant sur d'autres ports de la même adresse IP, mais un seul pour chaque combinaison d'adresse IP et de port.
+
+TLS (HTTPS) utilise par défaut le port spécifique `443`. C'est donc le port dont nous aurions besoin.
+
+Comme un seul processus peut écouter sur ce port, le processus qui le ferait serait le **Proxy de terminaison TLS**.
+
+Le Proxy de terminaison TLS aurait accès à un ou plusieurs **certificats TLS** (certificats HTTPS).
+
+En utilisant l'**extension SNI** mentionnée plus haut, le Proxy de terminaison TLS vérifierait lequel des certificats TLS (HTTPS) disponibles il devrait utiliser pour cette connexion, en choisissant celui qui correspond au domaine attendu par le client.
+
+Dans ce cas, il utiliserait le certificat pour `someapp.example.com`.
+
+
+
+Le client **fait déjà confiance** à l'entité qui a généré ce certificat TLS (dans ce cas Let's Encrypt, mais nous y reviendrons plus tard), il peut donc **vérifier** que le certificat est valide.
+
+Ensuite, en utilisant le certificat, le client et le Proxy de terminaison TLS **décident comment chiffrer** le reste de la **communication TCP**. Cela termine la partie **négociation TLS**.
+
+Après cela, le client et le serveur disposent d'une **connexion TCP chiffrée**, c'est ce que fournit TLS. Ils peuvent alors utiliser cette connexion pour démarrer la **communication HTTP** proprement dite.
+
+Et c'est ce qu'est **HTTPS** : c'est simplement du **HTTP** à l'intérieur d'une **connexion TLS sécurisée** au lieu d'une connexion TCP pure (non chiffrée).
+
+/// tip | Astuce
+
+Remarquez que le cryptage de la communication se produit au **niveau TCP**, pas au niveau HTTP.
+
+///
+
+### Requête HTTPS { #https-request }
+
+Maintenant que le client et le serveur (spécifiquement le navigateur et le Proxy de terminaison TLS) ont une **connexion TCP chiffrée**, ils peuvent démarrer la **communication HTTP**.
+
+Ainsi, le client envoie une **requête HTTPS**. Ce n'est qu'une requête HTTP à travers une connexion TLS chiffrée.
+
+
+
+### Déchiffrer la requête { #decrypt-the-request }
+
+Le Proxy de terminaison TLS utiliserait le chiffrement convenu pour **déchiffrer la requête**, et transmettrait la **requête HTTP en clair (déchiffrée)** au processus exécutant l'application (par exemple un processus avec Uvicorn exécutant l'application FastAPI).
+
+
+
+### Réponse HTTP { #http-response }
+
+L'application traiterait la requête et enverrait une **réponse HTTP en clair (non chiffrée)** au Proxy de terminaison TLS.
+
+
+
+### Réponse HTTPS { #https-response }
+
+Le Proxy de terminaison TLS **chiffrerait ensuite la réponse** en utilisant la cryptographie convenue auparavant (qui a commencé avec le certificat pour `someapp.example.com`), et la renverrait au navigateur.
+
+Ensuite, le navigateur vérifierait que la réponse est valide et chiffrée avec la bonne clé cryptographique, etc. Il **déchiffrerait la réponse** et la traiterait.
+
+
+
+Le client (navigateur) saura que la réponse provient du bon serveur parce qu'elle utilise la cryptographie convenue auparavant à l'aide du **certificat HTTPS**.
+
+### Applications multiples { #multiple-applications }
+
+Sur le même serveur (ou les mêmes serveurs), il pourrait y avoir **plusieurs applications**, par exemple d'autres programmes d'API ou une base de données.
+
+Un seul processus peut gérer l'adresse IP et le port spécifiques (le Proxy de terminaison TLS dans notre exemple), mais les autres applications/processus peuvent également s'exécuter sur le ou les serveurs, tant qu'ils n'essaient pas d'utiliser la même **combinaison d'adresse IP publique et de port**.
+
+
+
+De cette façon, le Proxy de terminaison TLS pourrait gérer HTTPS et les certificats pour **plusieurs domaines**, pour plusieurs applications, puis transmettre les requêtes à la bonne application dans chaque cas.
+
+### Renouvellement des certificats { #certificate-renewal }
+
+À un moment donné dans le futur, chaque certificat **expirerait** (environ 3 mois après son acquisition).
+
+Ensuite, il y aurait un autre programme (dans certains cas c'est un autre programme, dans d'autres cas cela pourrait être le même Proxy de terminaison TLS) qui communiquerait avec Let's Encrypt et renouvellerait le ou les certificats.
+
+
+
+Les **certificats TLS** sont **associés à un nom de domaine**, pas à une adresse IP.
+
+Ainsi, pour renouveler les certificats, le programme de renouvellement doit **prouver** à l'autorité (Let's Encrypt) qu'il **« possède » et contrôle ce domaine**.
+
+Pour ce faire, et pour s'adapter aux différents besoins des applications, il existe plusieurs façons de procéder. Parmi les plus courantes :
+
+* **Modifier certains enregistrements DNS**.
+ * Pour cela, le programme de renouvellement doit prendre en charge les API du fournisseur DNS ; ainsi, selon le fournisseur DNS que vous utilisez, cela peut être ou non une option.
+* **S'exécuter comme un serveur** (au moins pendant le processus d'acquisition du certificat) sur l'adresse IP publique associée au domaine.
+ * Comme nous l'avons dit plus haut, un seul processus peut écouter sur une adresse IP et un port spécifiques.
+ * C'est l'une des raisons pour lesquelles il est très utile que le même Proxy de terminaison TLS prenne également en charge le processus de renouvellement des certificats.
+ * Sinon, vous pourriez avoir à arrêter le Proxy de terminaison TLS momentanément, démarrer le programme de renouvellement pour acquérir les certificats, puis les configurer avec le Proxy de terminaison TLS, et ensuite redémarrer le Proxy de terminaison TLS. Ce n'est pas idéal, car votre/vos application(s) ne seront pas disponibles pendant le temps où le Proxy de terminaison TLS est arrêté.
+
+Tout ce processus de renouvellement, tout en continuant à servir l'application, est l'une des principales raisons pour lesquelles vous voudriez avoir un **système séparé pour gérer HTTPS** avec un Proxy de terminaison TLS, au lieu d'utiliser directement les certificats TLS avec le serveur d'application (par exemple Uvicorn).
+
+## En-têtes Proxy Forwarded { #proxy-forwarded-headers }
+
+Lorsque vous utilisez un proxy pour gérer HTTPS, votre **serveur d'application** (par exemple Uvicorn via FastAPI CLI) ne connaît rien du processus HTTPS, il communique en HTTP en clair avec le **Proxy de terminaison TLS**.
+
+Ce **proxy** définirait normalement certains en-têtes HTTP à la volée avant de transmettre la requête au **serveur d'application**, pour informer le serveur d'application que la requête est **transmise** par le proxy.
+
+/// note | Détails techniques
+
+Les en-têtes du proxy sont :
+
+* X-Forwarded-For
+* X-Forwarded-Proto
+* X-Forwarded-Host
+
+///
+
+Néanmoins, comme le **serveur d'application** ne sait pas qu'il se trouve derrière un **proxy** de confiance, par défaut, il ne ferait pas confiance à ces en-têtes.
+
+Mais vous pouvez configurer le **serveur d'application** pour qu'il fasse confiance aux en-têtes transmis (*forwarded*) envoyés par le **proxy**. Si vous utilisez FastAPI CLI, vous pouvez utiliser l'*option CLI* `--forwarded-allow-ips` pour lui indiquer à partir de quelles IP il doit faire confiance à ces en-têtes transmis.
+
+Par exemple, si le **serveur d'application** ne reçoit des communications que du **proxy** de confiance, vous pouvez définir `--forwarded-allow-ips="*"` pour lui faire faire confiance à toutes les IP entrantes, puisqu'il ne recevra des requêtes que depuis l'IP utilisée par le **proxy**.
+
+De cette façon, l'application sera en mesure de savoir quelle est sa propre URL publique, si elle utilise HTTPS, le domaine, etc.
+
+Cela serait utile, par exemple, pour gérer correctement les redirections.
+
+/// tip | Astuce
+
+Vous pouvez en savoir plus dans la documentation [Derrière un proxy - Activer les en-têtes transmis par le proxy](../advanced/behind-a-proxy.md#enable-proxy-forwarded-headers){.internal-link target=_blank}
+
+///
+
+## Récapitulatif { #recap }
+
+Disposer de **HTTPS** est très important, et assez **critique** dans la plupart des cas. La majeure partie de l'effort que vous, en tant que développeur, devez fournir autour de HTTPS consiste simplement à **comprendre ces concepts** et leur fonctionnement.
+
+Mais une fois que vous connaissez les informations de base sur **HTTPS pour les développeurs**, vous pouvez facilement combiner et configurer différents outils pour vous aider à tout gérer simplement.
+
+Dans certains des prochains chapitres, je vous montrerai plusieurs exemples concrets de configuration de **HTTPS** pour des applications **FastAPI**. 🔒
diff --git a/docs/fr/docs/deployment/index.md b/docs/fr/docs/deployment/index.md
index e2014afe9..3b08e9af7 100644
--- a/docs/fr/docs/deployment/index.md
+++ b/docs/fr/docs/deployment/index.md
@@ -1,8 +1,8 @@
-# Déploiement
+# Déploiement { #deployment }
Le déploiement d'une application **FastAPI** est relativement simple.
-## Que signifie le déploiement
+## Que signifie le déploiement { #what-does-deployment-mean }
**Déployer** une application signifie effectuer les étapes nécessaires pour la rendre **disponible pour les
utilisateurs**.
@@ -14,7 +14,7 @@ l'application efficacement et sans interruption ni problème.
Ceci contraste avec les étapes de **développement**, où vous êtes constamment en train de modifier le code, de le casser
et de le réparer, d'arrêter et de redémarrer le serveur de développement, _etc._
-## Stratégies de déploiement
+## Stratégies de déploiement { #deployment-strategies }
Il existe plusieurs façons de procéder, en fonction de votre cas d'utilisation spécifique et des outils que vous
utilisez.
@@ -22,6 +22,8 @@ utilisez.
Vous pouvez **déployer un serveur** vous-même en utilisant une combinaison d'outils, vous pouvez utiliser un **service
cloud** qui fait une partie du travail pour vous, ou encore d'autres options possibles.
+Par exemple, nous, l'équipe derrière FastAPI, avons créé **FastAPI Cloud**, pour rendre le déploiement d'applications FastAPI dans le cloud aussi fluide que possible, avec la même expérience développeur que lorsque vous travaillez avec FastAPI.
+
Je vais vous montrer certains des principaux concepts que vous devriez probablement avoir à l'esprit lors du déploiement
d'une application **FastAPI** (bien que la plupart de ces concepts s'appliquent à tout autre type d'application web).
diff --git a/docs/fr/docs/deployment/versions.md b/docs/fr/docs/deployment/versions.md
index 9d84274e2..81794428f 100644
--- a/docs/fr/docs/deployment/versions.md
+++ b/docs/fr/docs/deployment/versions.md
@@ -1,101 +1,93 @@
-# À propos des versions de FastAPI
+# À propos des versions de FastAPI { #about-fastapi-versions }
-**FastAPI** est déjà utilisé en production dans de nombreuses applications et systèmes. Et la couverture de test est maintenue à 100 %. Mais son développement est toujours aussi rapide.
+**FastAPI** est déjà utilisé en production dans de nombreuses applications et de nombreux systèmes. Et la couverture de tests est maintenue à 100 %. Mais son développement avance toujours rapidement.
-De nouvelles fonctionnalités sont ajoutées fréquemment, des bogues sont corrigés régulièrement et le code est
-amélioré continuellement.
+De nouvelles fonctionnalités sont ajoutées fréquemment, des bogues sont corrigés régulièrement et le code s'améliore continuellement.
-C'est pourquoi les versions actuelles sont toujours `0.x.x`, cela reflète que chaque version peut potentiellement
-recevoir des changements non rétrocompatibles. Cela suit les conventions de versionnage sémantique.
+C'est pourquoi les versions actuelles sont toujours `0.x.x`, cela reflète que chaque version pourrait potentiellement comporter des changements non rétrocompatibles. Cela suit les conventions de versionnage sémantique.
Vous pouvez créer des applications de production avec **FastAPI** dès maintenant (et vous le faites probablement depuis un certain temps), vous devez juste vous assurer que vous utilisez une version qui fonctionne correctement avec le reste de votre code.
-## Épinglez votre version de `fastapi`
+## Épingler votre version de `fastapi` { #pin-your-fastapi-version }
-Tout d'abord il faut "épingler" la version de **FastAPI** que vous utilisez à la dernière version dont vous savez
-qu'elle fonctionne correctement pour votre application.
+La première chose que vous devez faire est « épingler » la version de **FastAPI** que vous utilisez à la dernière version spécifique dont vous savez qu’elle fonctionne correctement pour votre application.
-Par exemple, disons que vous utilisez la version `0.45.0` dans votre application.
+Par exemple, disons que vous utilisez la version `0.112.0` dans votre application.
-Si vous utilisez un fichier `requirements.txt`, vous pouvez spécifier la version avec :
+Si vous utilisez un fichier `requirements.txt`, vous pouvez spécifier la version avec :
```txt
-fastapi==0.45.0
+fastapi[standard]==0.112.0
```
-ce qui signifierait que vous utiliseriez exactement la version `0.45.0`.
+ce qui signifierait que vous utiliseriez exactement la version `0.112.0`.
-Ou vous pourriez aussi l'épingler avec :
+Ou vous pourriez aussi l'épingler avec :
```txt
-fastapi>=0.45.0,<0.46.0
+fastapi[standard]>=0.112.0,<0.113.0
```
-cela signifierait que vous utiliseriez les versions `0.45.0` ou supérieures, mais inférieures à `0.46.0`, par exemple, une version `0.45.2` serait toujours acceptée.
+cela signifierait que vous utiliseriez les versions `0.112.0` ou supérieures, mais inférieures à `0.113.0`, par exemple, une version `0.112.2` serait toujours acceptée.
-Si vous utilisez un autre outil pour gérer vos installations, comme Poetry, Pipenv, ou autres, ils ont tous un moyen que vous pouvez utiliser pour définir des versions spécifiques pour vos paquets.
+Si vous utilisez un autre outil pour gérer vos installations, comme `uv`, Poetry, Pipenv, ou autres, ils ont tous un moyen que vous pouvez utiliser pour définir des versions spécifiques pour vos paquets.
-## Versions disponibles
+## Versions disponibles { #available-versions }
Vous pouvez consulter les versions disponibles (par exemple, pour vérifier quelle est la dernière version en date) dans les [Notes de version](../release-notes.md){.internal-link target=_blank}.
-## À propos des versions
+## À propos des versions { #about-versions }
-Suivant les conventions de versionnage sémantique, toute version inférieure à `1.0.0` peut potentiellement ajouter
-des changements non rétrocompatibles.
+Suivant les conventions de versionnage sémantique, toute version inférieure à `1.0.0` peut potentiellement ajouter des changements non rétrocompatibles.
-FastAPI suit également la convention que tout changement de version "PATCH" est pour des corrections de bogues et
-des changements rétrocompatibles.
+FastAPI suit également la convention selon laquelle tout changement de version « PATCH » concerne des corrections de bogues et des changements rétrocompatibles.
/// tip | Astuce
-Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`.
+Le « PATCH » est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`.
///
-Donc, vous devriez être capable d'épingler une version comme suit :
+Donc, vous devriez être en mesure d'épingler une version comme suit :
```txt
fastapi>=0.45.0,<0.46.0
```
-Les changements non rétrocompatibles et les nouvelles fonctionnalités sont ajoutés dans les versions "MINOR".
+Les changements non rétrocompatibles et les nouvelles fonctionnalités sont ajoutés dans les versions « MINOR ».
/// tip | Astuce
-Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`.
+Le « MINOR » est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`.
///
-## Mise à jour des versions FastAPI
+## Mettre à niveau les versions de FastAPI { #upgrading-the-fastapi-versions }
-Vous devriez tester votre application.
+Vous devez ajouter des tests pour votre application.
-Avec **FastAPI** c'est très facile (merci à Starlette), consultez la documentation : [Testing](../tutorial/testing.md){.internal-link target=_blank}
+Avec **FastAPI** c'est très facile (merci à Starlette), consultez les documents : [Tests](../tutorial/testing.md){.internal-link target=_blank}
-Après avoir effectué des tests, vous pouvez mettre à jour la version **FastAPI** vers une version plus récente, et vous assurer que tout votre code fonctionne correctement en exécutant vos tests.
+Après avoir des tests, vous pouvez mettre à niveau la version de **FastAPI** vers une version plus récente et vous assurer que tout votre code fonctionne correctement en exécutant vos tests.
-Si tout fonctionne, ou après avoir fait les changements nécessaires, et que tous vos tests passent, vous pouvez
-épingler votre version de `fastapi` à cette nouvelle version récente.
+Si tout fonctionne, ou après avoir effectué les changements nécessaires, et que tous vos tests passent, vous pouvez alors épingler votre `fastapi` à cette nouvelle version récente.
-## À propos de Starlette
+## À propos de Starlette { #about-starlette }
-Vous ne devriez pas épingler la version de `starlette`.
+Vous ne devez pas épingler la version de `starlette`.
Différentes versions de **FastAPI** utiliseront une version spécifique plus récente de Starlette.
Ainsi, vous pouvez simplement laisser **FastAPI** utiliser la bonne version de Starlette.
-## À propos de Pydantic
+## À propos de Pydantic { #about-pydantic }
-Pydantic inclut des tests pour **FastAPI** avec ses propres tests, ainsi les nouvelles versions de Pydantic (au-dessus
-de `1.0.0`) sont toujours compatibles avec **FastAPI**.
+Pydantic inclut les tests pour **FastAPI** avec ses propres tests, ainsi les nouvelles versions de Pydantic (au-dessus de `1.0.0`) sont toujours compatibles avec FastAPI.
-Vous pouvez épingler Pydantic à toute version supérieure à `1.0.0` qui fonctionne pour vous et inférieure à `2.0.0`.
+Vous pouvez épingler Pydantic à toute version supérieure à `1.0.0` qui fonctionne pour vous.
-Par exemple :
+Par exemple :
```txt
-pydantic>=1.2.0,<2.0.0
+pydantic>=2.7.0,<3.0.0
```
diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md
index 99ea8dda1..2aeaa1c69 100644
--- a/docs/fr/docs/index.md
+++ b/docs/fr/docs/index.md
@@ -1,11 +1,11 @@
-# FastAPI
+# FastAPI { #fastapi }
+{% endfor -%}
+
+### Sponsors Or et Argent { #gold-and-silver-sponsors }
+
{% for sponsor in sponsors.gold -%}
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
{% endfor %}
-{% endif %}
-Other sponsors
+Autres sponsors
-## Opinions
+## Opinions { #opinions }
-"_[...] J'utilise beaucoup **FastAPI** ces derniers temps. [...] Je prévois de l'utiliser dans mon équipe pour tous les **services de ML chez Microsoft**. Certains d'entre eux seront intégrés dans le coeur de **Windows** et dans certains produits **Office**._"
+« _[...] J'utilise beaucoup **FastAPI** ces derniers temps. [...] Je prévois de l'utiliser dans mon équipe pour tous les **services de ML chez Microsoft**. Certains d'entre eux sont intégrés au cœur de **Windows** et à certains produits **Office**._ »
+
+## **Typer**, le FastAPI des CLIs { #typer-the-fastapi-of-clis }
-Si vous souhaitez construire une application CLI utilisable dans un terminal au lieu d'une API web, regardez **Typer**.
+Si vous construisez une application CLI à utiliser dans un terminal au lieu d'une API web, regardez **Typer**.
-**Typer** est le petit frère de FastAPI. Et il est destiné à être le **FastAPI des CLI**. ⌨️ 🚀
+**Typer** est le petit frère de FastAPI. Et il est destiné à être le **FastAPI des CLIs**. ⌨️ 🚀
-## Prérequis
+## Prérequis { #requirements }
FastAPI repose sur les épaules de géants :
* Starlette pour les parties web.
* Pydantic pour les parties données.
-## Installation
+## Installation { #installation }
+
+Créez et activez un environnement virtuel puis installez FastAPI :
Ou utilisez
+async def ...Ou utilisez
Si votre code utilise `async` / `await`, utilisez `async def` :
-```Python hl_lines="9 14"
-from typing import Union
-
+```Python hl_lines="7 12"
from fastapi import FastAPI
app = FastAPI()
@@ -193,28 +193,41 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Union[str, None] = None):
+async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
```
-**Note**
+**Remarque** :
-Si vous n'êtes pas familier avec cette notion, consultez la section _"Vous êtes pressés ?"_ à propos de `async` et `await` dans la documentation.
+Si vous ne savez pas, consultez la section « Vous êtes pressés ? » à propos de `async` et `await` dans la documentation.
async def...À propos de la commande
+uvicorn main:app --reload ...À propos de la commande
-La commande `uvicorn main:app` fait référence à :
+La commande `fastapi dev` lit votre fichier `main.py`, détecte l'application **FastAPI** qu'il contient et lance un serveur avec Uvicorn.
-* `main` : le fichier `main.py` (le "module" Python).
-* `app` : l'objet créé à l'intérieur de `main.py` avec la ligne `app = FastAPI()`.
-* `--reload` : fait redémarrer le serveur après des changements de code. À n'utiliser que pour le développement.
+Par défaut, `fastapi dev` démarre avec le rechargement automatique activé pour le développement local.
+
+Vous pouvez en savoir plus dans la documentation de la CLI FastAPI.
fastapi dev main.py...email-validator - pour la validation des adresses email.
+### Dépendances `standard` { #standard-dependencies }
+
+Lorsque vous installez FastAPI avec `pip install "fastapi[standard]"`, il inclut le groupe `standard` de dépendances optionnelles :
+
+Utilisées par Pydantic :
+
+* email-validator - pour la validation des adresses e-mail.
Utilisées par Starlette :
-* requests - Obligatoire si vous souhaitez utiliser `TestClient`.
+* httpx - Obligatoire si vous souhaitez utiliser le `TestClient`.
* jinja2 - Obligatoire si vous souhaitez utiliser la configuration de template par défaut.
-* python-multipart - Obligatoire si vous souhaitez supporter le "décodage" de formulaire avec `request.form()`.
-* itsdangerous - Obligatoire pour la prise en charge de `SessionMiddleware`.
-* pyyaml - Obligatoire pour le support `SchemaGenerator` de Starlette (vous n'en avez probablement pas besoin avec FastAPI).
+* python-multipart - Obligatoire si vous souhaitez prendre en charge l’« parsing » de formulaires avec `request.form()`.
-Utilisées par FastAPI / Starlette :
+Utilisées par FastAPI :
-* uvicorn - Pour le serveur qui charge et sert votre application.
-* orjson - Obligatoire si vous voulez utiliser `ORJSONResponse`.
+* uvicorn - pour le serveur qui charge et sert votre application. Cela inclut `uvicorn[standard]`, qui comprend certaines dépendances (par ex. `uvloop`) nécessaires pour une haute performance.
+* `fastapi-cli[standard]` - pour fournir la commande `fastapi`.
+ * Cela inclut `fastapi-cloud-cli`, qui vous permet de déployer votre application FastAPI sur FastAPI Cloud.
+
+### Sans les dépendances `standard` { #without-standard-dependencies }
+
+Si vous ne souhaitez pas inclure les dépendances optionnelles `standard`, vous pouvez installer avec `pip install fastapi` au lieu de `pip install "fastapi[standard]"`.
+
+### Sans `fastapi-cloud-cli` { #without-fastapi-cloud-cli }
+
+Si vous souhaitez installer FastAPI avec les dépendances standard mais sans `fastapi-cloud-cli`, vous pouvez installer avec `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
+
+### Dépendances optionnelles supplémentaires { #additional-optional-dependencies }
+
+Il existe des dépendances supplémentaires que vous pourriez vouloir installer.
+
+Dépendances optionnelles supplémentaires pour Pydantic :
+
+* pydantic-settings - pour la gestion des paramètres.
+* pydantic-extra-types - pour des types supplémentaires à utiliser avec Pydantic.
+
+Dépendances optionnelles supplémentaires pour FastAPI :
+
+* orjson - Obligatoire si vous souhaitez utiliser `ORJSONResponse`.
* ujson - Obligatoire si vous souhaitez utiliser `UJSONResponse`.
-Vous pouvez tout installer avec `pip install fastapi[all]`.
-
-## Licence
+## Licence { #license }
Ce projet est soumis aux termes de la licence MIT.
diff --git a/docs/fr/docs/learn/index.md b/docs/fr/docs/learn/index.md
index 46fc095dc..552687703 100644
--- a/docs/fr/docs/learn/index.md
+++ b/docs/fr/docs/learn/index.md
@@ -1,5 +1,5 @@
-# Apprendre
+# Apprendre { #learn }
Voici les sections introductives et les tutoriels pour apprendre **FastAPI**.
-Vous pouvez considérer ceci comme un **manuel**, un **cours**, la **méthode officielle** et recommandée pour appréhender FastAPI. 😎
+Vous pouvez considérer ceci comme un **livre**, un **cours**, la **méthode officielle** et recommandée pour apprendre FastAPI. 😎
diff --git a/docs/fr/docs/project-generation.md b/docs/fr/docs/project-generation.md
index 4c04dc167..f062ffecf 100644
--- a/docs/fr/docs/project-generation.md
+++ b/docs/fr/docs/project-generation.md
@@ -1,84 +1,28 @@
-# Génération de projets - Modèle
+# Modèle Full Stack FastAPI { #full-stack-fastapi-template }
-Vous pouvez utiliser un générateur de projet pour commencer, qui réalisera pour vous la mise en place de bases côté architecture globale, sécurité, base de données et premières routes d'API.
+Les modèles, bien qu'ils soient généralement livrés avec une configuration spécifique, sont conçus pour être flexibles et personnalisables. Cela vous permet de les modifier et de les adapter aux exigences de votre projet, ce qui en fait un excellent point de départ. 🏁
-Un générateur de projet fera toujours une mise en place très subjective que vous devriez modifier et adapter suivant vos besoins, mais cela reste un bon point de départ pour vos projets.
+Vous pouvez utiliser ce modèle pour démarrer, car il inclut une grande partie de la configuration initiale, la sécurité, la base de données et quelques endpoints d'API déjà prêts pour vous.
-## Full Stack FastAPI PostgreSQL
+Dépôt GitHub : Modèle Full Stack FastAPI
-GitHub : https://github.com/tiangolo/full-stack-fastapi-postgresql
+## Modèle Full Stack FastAPI - Pile technologique et fonctionnalités { #full-stack-fastapi-template-technology-stack-and-features }
-### Full Stack FastAPI PostgreSQL - Fonctionnalités
-
-* Intégration **Docker** complète (basée sur Docker).
-* Déploiement Docker en mode Swarm
-* Intégration **Docker Compose** et optimisation pour développement local.
-* Serveur web Python **prêt au déploiement** utilisant Uvicorn et Gunicorn.
-* Backend Python **FastAPI** :
- * **Rapide** : Très hautes performances, comparables à **NodeJS** ou **Go** (grâce à Starlette et Pydantic).
- * **Intuitif** : Excellent support des éditeurs. Complétion partout. Moins de temps passé à déboguer.
- * **Facile** : Fait pour être facile à utiliser et apprendre. Moins de temps passé à lire de la documentation.
- * **Concis** : Minimise la duplication de code. Plusieurs fonctionnalités à chaque déclaration de paramètre.
- * **Robuste** : Obtenez du code prêt pour être utilisé en production. Avec de la documentation automatique interactive.
- * **Basé sur des normes** : Basé sur (et totalement compatible avec) les normes ouvertes pour les APIs : OpenAPI et JSON Schema.
- * **Et bien d'autres fonctionnalités** comme la validation automatique, la sérialisation, l'authentification avec OAuth2 JWT tokens, etc.
-* Hashage de **mots de passe sécurisé** par défaut.
-* Authentification par **jetons JWT**.
-* Modèles **SQLAlchemy** (indépendants des extensions Flask, afin qu'ils puissent être utilisés directement avec des *workers* Celery).
-* Modèle de démarrages basiques pour les utilisateurs (à modifier et supprimer au besoin).
-* Migrations **Alembic**.
-* **CORS** (partage des ressources entre origines multiples, ou *Cross Origin Resource Sharing*).
-* *Worker* **Celery** pouvant importer et utiliser les modèles et le code du reste du backend.
-* Tests du backend REST basés sur **Pytest**, intégrés dans Docker, pour que vous puissiez tester toutes les interactions de l'API indépendamment de la base de données. Étant exécutés dans Docker, les tests peuvent utiliser un nouvel entrepôt de données créé de zéro à chaque fois (vous pouvez donc utiliser ElasticSearch, MongoDB, CouchDB, etc. et juste tester que l'API fonctionne).
-* Intégration Python facile avec **Jupyter Kernels** pour le développement à distance ou intra-Docker avec des extensions comme Atom Hydrogen ou Visual Studio Code Jupyter.
-* Frontend **Vue** :
- * Généré avec Vue CLI.
- * Gestion de l'**Authentification JWT**.
- * Page de connexion.
- * Après la connexion, page de tableau de bord principal.
- * Tableau de bord principal avec création et modification d'utilisateurs.
- * Modification de ses propres caractéristiques utilisateur.
- * **Vuex**.
- * **Vue-router**.
- * **Vuetify** pour de magnifiques composants *material design*.
- * **TypeScript**.
- * Serveur Docker basé sur **Nginx** (configuré pour être facilement manipulé avec Vue-router).
- * Utilisation de *Docker multi-stage building*, pour ne pas avoir besoin de sauvegarder ou *commit* du code compilé.
- * Tests frontend exécutés à la compilation (pouvant être désactivés).
- * Fait aussi modulable que possible, pour pouvoir fonctionner comme tel, tout en pouvant être utilisé qu'en partie grâce à Vue CLI.
-* **PGAdmin** pour les bases de données PostgreSQL, facilement modifiable pour utiliser PHPMYAdmin ou MySQL.
-* **Flower** pour la surveillance de tâches Celery.
-* Équilibrage de charge entre le frontend et le backend avec **Traefik**, afin de pouvoir avoir les deux sur le même domaine, séparés par chemins, mais servis par différents conteneurs.
-* Intégration Traefik, comprenant la génération automatique de certificat **HTTPS** Let's Encrypt.
-* GitLab **CI** (intégration continue), comprenant des tests pour le frontend et le backend.
-
-## Full Stack FastAPI Couchbase
-
-GitHub : https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-⚠️ **ATTENTION** ⚠️
-
-Si vous démarrez un nouveau projet de zéro, allez voir les alternatives au début de cette page.
-
-Par exemple, le générateur de projet Full Stack FastAPI PostgreSQL peut être une meilleure alternative, étant activement maintenu et utilisé et comprenant toutes les nouvelles fonctionnalités et améliorations.
-
-Vous êtes toujours libre d'utiliser le générateur basé sur Couchbase si vous le voulez, cela devrait probablement fonctionner correctement, et si vous avez déjà un projet généré en utilisant ce dernier, cela devrait fonctionner aussi (et vous l'avez déjà probablement mis à jour suivant vos besoins).
-
-Vous pouvez en apprendre plus dans la documentation du dépôt GithHub.
-
-## Full Stack FastAPI MongoDB
-
-...viendra surement plus tard, suivant le temps que j'ai. 😅 🎉
-
-## Modèles d'apprentissage automatique avec spaCy et FastAPI
-
-GitHub : https://github.com/microsoft/cookiecutter-spacy-fastapi
-
-## Modèles d'apprentissage automatique avec spaCy et FastAPI - Fonctionnalités
-
-* Intégration d'un modèle NER **spaCy**.
-* Formatage de requête pour **Azure Cognitive Search**.
-* Serveur Python web **prêt à utiliser en production** utilisant Uvicorn et Gunicorn.
-* Déploiement CI/CD Kubernetes pour **Azure DevOps** (AKS).
-* **Multilangues**. Choisissez facilement l'une des langues intégrées à spaCy durant la mise en place du projet.
-* **Facilement généralisable** à d'autres bibliothèques similaires (Pytorch, Tensorflow), et non juste spaCy.
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com/fr) pour l'API backend Python.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) pour les interactions avec la base de données SQL en Python (ORM).
+ - 🔍 [Pydantic](https://docs.pydantic.dev), utilisé par FastAPI, pour la validation des données et la gestion des paramètres.
+ - 💾 [PostgreSQL](https://www.postgresql.org) comme base de données SQL.
+- 🚀 [React](https://react.dev) pour le frontend.
+ - 💃 Utilisation de TypeScript, des hooks, de Vite et d'autres éléments d'un stack frontend moderne.
+ - 🎨 [Tailwind CSS](https://tailwindcss.com) et [shadcn/ui](https://ui.shadcn.com) pour les composants frontend.
+ - 🤖 Un client frontend généré automatiquement.
+ - 🧪 [Playwright](https://playwright.dev) pour les tests de bout en bout.
+ - 🦇 Prise en charge du mode sombre.
+- 🐋 [Docker Compose](https://www.docker.com) pour le développement et la production.
+- 🔒 Hachage sécurisé des mots de passe par défaut.
+- 🔑 Authentification JWT (JSON Web Token).
+- 📫 Récupération de mot de passe par e-mail.
+- ✅ Tests avec [Pytest](https://pytest.org).
+- 📞 [Traefik](https://traefik.io) comme proxy inverse / répartiteur de charge.
+- 🚢 Instructions de déploiement avec Docker Compose, y compris la configuration d'un proxy Traefik frontal pour gérer les certificats HTTPS automatiques.
+- 🏭 CI (intégration continue) et CD (déploiement continu) basés sur GitHub Actions.
diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md
index 99ca90827..f393b0f5c 100644
--- a/docs/fr/docs/python-types.md
+++ b/docs/fr/docs/python-types.md
@@ -1,70 +1,68 @@
-# Introduction aux Types Python
+# Introduction aux types Python { #python-types-intro }
-Python supporte des annotations de type (ou *type hints*) optionnelles.
+Python prend en charge des « type hints » (aussi appelées « annotations de type ») facultatives.
-Ces annotations de type constituent une syntaxe spéciale qui permet de déclarer le type d'une variable.
+Ces « type hints » ou annotations sont une syntaxe spéciale qui permet de déclarer le type d'une variable.
-En déclarant les types de vos variables, cela permet aux différents outils comme les éditeurs de texte d'offrir un meilleur support.
+En déclarant les types de vos variables, les éditeurs et outils peuvent vous offrir un meilleur support.
-Ce chapitre n'est qu'un **tutoriel rapide / rappel** sur les annotations de type Python.
-Seulement le minimum nécessaire pour les utiliser avec **FastAPI** sera couvert... ce qui est en réalité très peu.
+Ceci est un **tutoriel rapide / rappel** à propos des annotations de type Python. Il couvre uniquement le minimum nécessaire pour les utiliser avec **FastAPI** ... ce qui est en réalité très peu.
-**FastAPI** est totalement basé sur ces annotations de type, qui lui donnent de nombreux avantages.
+**FastAPI** est totalement basé sur ces annotations de type, elles lui donnent de nombreux avantages et bénéfices.
-Mais même si vous n'utilisez pas ou n'utiliserez jamais **FastAPI**, vous pourriez bénéficier d'apprendre quelques choses sur ces dernières.
+Mais même si vous n'utilisez jamais **FastAPI**, vous auriez intérêt à en apprendre un peu à leur sujet.
-/// note
+/// note | Remarque
-Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant.
+Si vous êtes un expert Python, et que vous savez déjà tout sur les annotations de type, passez au chapitre suivant.
///
-## Motivations
+## Motivation { #motivation }
-Prenons un exemple simple :
+Commençons par un exemple simple :
-{*../../docs_src/python_types/tutorial001.py*}
+{* ../../docs_src/python_types/tutorial001_py39.py *}
-Exécuter ce programe affiche :
+Exécuter ce programme affiche :
```
John Doe
```
-La fonction :
+La fonction fait ce qui suit :
* Prend un `first_name` et un `last_name`.
-* Convertit la première lettre de chaque paramètre en majuscules grâce à `title()`.
-* Concatène les résultats avec un espace entre les deux.
+* Convertit la première lettre de chacun en majuscule avec `title()`.
+* Concatène ces deux valeurs avec un espace au milieu.
-{*../../docs_src/python_types/tutorial001.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
-### Limitations
+### Modifier le code { #edit-it }
C'est un programme très simple.
Mais maintenant imaginez que vous l'écriviez de zéro.
-À un certain point vous auriez commencé la définition de la fonction, vous aviez les paramètres prêts.
+À un certain moment, vous auriez commencé la définition de la fonction, vous aviez les paramètres prêts ...
-Mais vous aviez besoin de "cette méthode qui convertit la première lettre en majuscule".
+Mais ensuite vous devez appeler « cette méthode qui convertit la première lettre en majuscule ».
-Était-ce `upper` ? `uppercase` ? `first_uppercase` ? `capitalize` ?
+Était-ce `upper` ? Était-ce `uppercase` ? `first_uppercase` ? `capitalize` ?
-Vous essayez donc d'utiliser le vieil ami du programmeur, l'auto-complétion de l'éditeur.
+Vous essayez alors avec l'ami de toujours des programmeurs, l'autocomplétion de l'éditeur.
-Vous écrivez le premier paramètre, `first_name`, puis un point (`.`) et appuyez sur `Ctrl+Espace` pour déclencher l'auto-complétion.
+Vous tapez le premier paramètre de la fonction, `first_name`, puis un point (`.`) et appuyez sur `Ctrl+Espace` pour déclencher l'autocomplétion.
-Mais malheureusement, rien d'utile n'en résulte :
+Mais, malheureusement, vous n'obtenez rien d'utile :
-### Ajouter des types
+### Ajouter des types { #add-types }
Modifions une seule ligne de la version précédente.
-Nous allons changer seulement cet extrait, les paramètres de la fonction, de :
-
+Nous allons changer exactement ce fragment, les paramètres de la fonction, de :
```Python
first_name, last_name
@@ -78,222 +76,389 @@ Nous allons changer seulement cet extrait, les paramètres de la fonction, de :
C'est tout.
-Ce sont des annotations de types :
+Ce sont les « annotations de type » :
-{*../../docs_src/python_types/tutorial002.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
-À ne pas confondre avec la déclaration de valeurs par défaut comme ici :
+Ce n'est pas la même chose que de déclarer des valeurs par défaut, ce qui serait :
```Python
first_name="john", last_name="doe"
```
-C'est une chose différente.
+C'est différent.
-On utilise un deux-points (`:`), et pas un égal (`=`).
+Nous utilisons des deux-points (`:`), pas des signes égal (`=`).
-Et ajouter des annotations de types ne crée normalement pas de différence avec le comportement qui aurait eu lieu si elles n'étaient pas là.
+Et ajouter des annotations de type ne change normalement pas ce qui se passe par rapport à ce qui se passerait sans elles.
-Maintenant, imaginez que vous êtes en train de créer cette fonction, mais avec des annotations de type cette fois.
+Mais maintenant, imaginez que vous êtes à nouveau en train de créer cette fonction, mais avec des annotations de type.
-Au même moment que durant l'exemple précédent, vous essayez de déclencher l'auto-complétion et vous voyez :
+Au même moment, vous essayez de déclencher l'autocomplétion avec `Ctrl+Espace` et vous voyez :
-Vous pouvez donc dérouler les options jusqu'à trouver la méthode à laquelle vous pensiez.
+Avec cela, vous pouvez faire défiler en voyant les options, jusqu'à trouver celle qui « vous dit quelque chose » :
-## Plus de motivations
+## Plus de motivation { #more-motivation }
-Cette fonction possède déjà des annotations de type :
+Regardez cette fonction, elle a déjà des annotations de type :
-{*../../docs_src/python_types/tutorial003.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
-Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'auto-complétion, mais aussi de la détection d'erreurs :
+Comme l'éditeur connaît les types des variables, vous n'obtenez pas seulement l'autocomplétion, vous obtenez aussi des vérifications d'erreurs :
-Maintenant que vous avez connaissance du problème, convertissez `age` en chaîne de caractères grâce à `str(age)` :
+Vous savez maintenant qu'il faut corriger, convertir `age` en chaîne avec `str(age)` :
-{*../../docs_src/python_types/tutorial004.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
-## Déclarer des types
+## Déclarer des types { #declaring-types }
-Vous venez de voir là où les types sont généralement déclarés : dans les paramètres de fonctions.
+Vous venez de voir l'endroit principal pour déclarer des annotations de type : dans les paramètres des fonctions.
-C'est aussi ici que vous les utiliseriez avec **FastAPI**.
+C'est aussi l'endroit principal où vous les utiliserez avec **FastAPI**.
-### Types simples
+### Types simples { #simple-types }
-Vous pouvez déclarer tous les types de Python, pas seulement `str`.
+Vous pouvez déclarer tous les types standards de Python, pas seulement `str`.
-Comme par exemple :
+Vous pouvez utiliser, par exemple :
* `int`
* `float`
* `bool`
* `bytes`
-{*../../docs_src/python_types/tutorial005.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
-### Types génériques avec des paramètres de types
+### Types génériques avec paramètres de type { #generic-types-with-type-parameters }
-Il existe certaines structures de données qui contiennent d'autres valeurs, comme `dict`, `list`, `set` et `tuple`. Et les valeurs internes peuvent elles aussi avoir leurs propres types.
+Il existe certaines structures de données qui peuvent contenir d'autres valeurs, comme `dict`, `list`, `set` et `tuple`. Et les valeurs internes peuvent aussi avoir leur propre type.
-Pour déclarer ces types et les types internes, on utilise le module standard de Python `typing`.
+Ces types qui ont des types internes sont appelés types « génériques ». Et il est possible de les déclarer, même avec leurs types internes.
-Il existe spécialement pour supporter ces annotations de types.
+Pour déclarer ces types et les types internes, vous pouvez utiliser le module standard Python `typing`. Il existe spécifiquement pour prendre en charge ces annotations de type.
-#### `List`
+#### Versions plus récentes de Python { #newer-versions-of-python }
-Par exemple, définissons une variable comme `list` de `str`.
+La syntaxe utilisant `typing` est compatible avec toutes les versions, de Python 3.6 aux plus récentes, y compris Python 3.9, Python 3.10, etc.
-Importez `List` (avec un `L` majuscule) depuis `typing`.
+Au fur et à mesure que Python évolue, les versions plus récentes apportent un meilleur support pour ces annotations de type et dans de nombreux cas vous n'aurez même pas besoin d'importer et d'utiliser le module `typing` pour les déclarer.
-{*../../docs_src/python_types/tutorial006.py hl[1] *}
+Si vous pouvez choisir une version plus récente de Python pour votre projet, vous pourrez profiter de cette simplicité supplémentaire.
-Déclarez la variable, en utilisant la syntaxe des deux-points (`:`).
+Dans toute la documentation, il y a des exemples compatibles avec chaque version de Python (lorsqu'il y a une différence).
-Et comme type, mettez `List`.
+Par exemple « Python 3.6+ » signifie que c'est compatible avec Python 3.6 ou supérieur (y compris 3.7, 3.8, 3.9, 3.10, etc.). Et « Python 3.9+ » signifie que c'est compatible avec Python 3.9 ou supérieur (y compris 3.10, etc).
-Les listes étant un type contenant des types internes, mettez ces derniers entre crochets (`[`, `]`) :
+Si vous pouvez utiliser les dernières versions de Python, utilisez les exemples pour la dernière version, ils auront la meilleure et la plus simple syntaxe, par exemple, « Python 3.10+ ».
-{*../../docs_src/python_types/tutorial006.py hl[4] *}
+#### Liste { #list }
-/// tip | Astuce
+Par exemple, définissons une variable comme une `list` de `str`.
-Ces types internes entre crochets sont appelés des "paramètres de type".
+Déclarez la variable, en utilisant la même syntaxe avec deux-points (`:`).
-Ici, `str` est un paramètre de type passé à `List`.
+Comme type, mettez `list`.
+
+Comme la liste est un type qui contient des types internes, mettez-les entre crochets :
+
+{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
+
+/// info
+
+Ces types internes entre crochets sont appelés « paramètres de type ».
+
+Dans ce cas, `str` est le paramètre de type passé à `list`.
///
-Ce qui signifie : "la variable `items` est une `list`, et chacun de ses éléments a pour type `str`.
+Cela signifie : « la variable `items` est une `list`, et chacun des éléments de cette liste est un `str` ».
-En faisant cela, votre éditeur pourra vous aider, même pendant que vous traitez des éléments de la liste.
+En faisant cela, votre éditeur peut vous fournir de l'aide même pendant le traitement des éléments de la liste :
Sans types, c'est presque impossible à réaliser.
-Vous remarquerez que la variable `item` n'est qu'un des éléments de la list `items`.
+Remarquez que la variable `item` est l'un des éléments de la liste `items`.
-Et pourtant, l'éditeur sait qu'elle est de type `str` et pourra donc vous aider à l'utiliser.
+Et pourtant, l'éditeur sait que c'est un `str` et fournit le support approprié.
-#### `Tuple` et `Set`
+#### Tuple et Set { #tuple-and-set }
-C'est le même fonctionnement pour déclarer un `tuple` ou un `set` :
+Vous feriez la même chose pour déclarer des `tuple` et des `set` :
-{*../../docs_src/python_types/tutorial007.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
-Dans cet exemple :
+Cela signifie :
-* La variable `items_t` est un `tuple` avec 3 éléments, un `int`, un deuxième `int`, et un `str`.
+* La variable `items_t` est un `tuple` avec 3 éléments, un `int`, un autre `int`, et un `str`.
* La variable `items_s` est un `set`, et chacun de ses éléments est de type `bytes`.
-#### `Dict`
+#### Dict { #dict }
-Pour définir un `dict`, il faut lui passer 2 paramètres, séparés par une virgule (`,`).
+Pour définir un `dict`, vous passez 2 paramètres de type, séparés par des virgules.
-Le premier paramètre de type est pour les clés et le second pour les valeurs du dictionnaire (`dict`).
+Le premier paramètre de type est pour les clés du `dict`.
-{*../../docs_src/python_types/tutorial008.py hl[1,4] *}
+Le second paramètre de type est pour les valeurs du `dict` :
-Dans cet exemple :
+{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
-* La variable `prices` est de type `dict` :
- * Les clés de ce dictionnaire sont de type `str`.
- * Les valeurs de ce dictionnaire sont de type `float`.
+Cela signifie :
-#### `Optional`
+* La variable `prices` est un `dict` :
+ * Les clés de ce `dict` sont de type `str` (disons, le nom de chaque article).
+ * Les valeurs de ce `dict` sont de type `float` (disons, le prix de chaque article).
-Vous pouvez aussi utiliser `Optional` pour déclarer qu'une variable a un type, comme `str` mais qu'il est "optionnel" signifiant qu'il pourrait aussi être `None`.
+#### Union { #union }
-{*../../docs_src/python_types/tutorial009.py hl[1,4] *}
+Vous pouvez déclarer qu'une variable peut être de plusieurs types, par exemple, un `int` ou un `str`.
-Utiliser `Optional[str]` plutôt que `str` permettra à l'éditeur de vous aider à détecter les erreurs où vous supposeriez qu'une valeur est toujours de type `str`, alors qu'elle pourrait aussi être `None`.
+Dans Python 3.6 et supérieur (y compris Python 3.10), vous pouvez utiliser le type `Union` de `typing` et mettre entre crochets les types possibles à accepter.
-#### Types génériques
+Dans Python 3.10, il existe aussi une nouvelle syntaxe où vous pouvez mettre les types possibles séparés par une barre verticale (`|`).
-Les types qui peuvent contenir des paramètres de types entre crochets, comme :
+//// tab | Python 3.10+
-* `List`
-* `Tuple`
-* `Set`
-* `Dict`
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b_py39.py!}
+```
+
+////
+
+Dans les deux cas, cela signifie que `item` peut être un `int` ou un `str`.
+
+#### Possiblement `None` { #possibly-none }
+
+Vous pouvez déclarer qu'une valeur peut avoir un type, comme `str`, mais qu'elle peut aussi être `None`.
+
+Dans Python 3.6 et supérieur (y compris Python 3.10), vous pouvez le déclarer en important et en utilisant `Optional` depuis le module `typing`.
+
+```Python hl_lines="1 4"
+{!../../docs_src/python_types/tutorial009_py39.py!}
+```
+
+Utiliser `Optional[str]` au lieu de simplement `str` permettra à l'éditeur de vous aider à détecter des erreurs où vous supposeriez qu'une valeur est toujours un `str`, alors qu'elle pourrait en fait aussi être `None`.
+
+`Optional[Something]` est en réalité un raccourci pour `Union[Something, None]`, ils sont équivalents.
+
+Cela signifie aussi que dans Python 3.10, vous pouvez utiliser `Something | None` :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009_py39.py!}
+```
+
+////
+
+//// tab | Python 3.9+ alternative
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b_py39.py!}
+```
+
+////
+
+#### Utiliser `Union` ou `Optional` { #using-union-or-optional }
+
+Si vous utilisez une version de Python inférieure à 3.10, voici un conseil de mon point de vue très **subjectif** :
+
+* 🚨 Évitez d'utiliser `Optional[SomeType]`
+* À la place ✨ **utilisez `Union[SomeType, None]`** ✨.
+
+Les deux sont équivalents et sous le capot ce sont les mêmes, mais je recommanderais `Union` plutôt que `Optional` parce que le mot « facultatif » semble impliquer que la valeur est optionnelle, alors que cela signifie en fait « elle peut être `None` », même si elle n'est pas facultative et est toujours requise.
+
+Je pense que `Union[SomeType, None]` est plus explicite sur ce que cela signifie.
+
+Il ne s'agit que des mots et des noms. Mais ces mots peuvent influencer la manière dont vous et vos coéquipiers pensez au code.
+
+Par exemple, prenons cette fonction :
+
+{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
+
+Le paramètre `name` est défini comme `Optional[str]`, mais il n'est pas facultatif, vous ne pouvez pas appeler la fonction sans le paramètre :
+
+```Python
+say_hi() # Oh non, cela lève une erreur ! 😱
+```
+
+Le paramètre `name` est toujours requis (pas « optionnel ») parce qu'il n'a pas de valeur par défaut. Néanmoins, `name` accepte `None` comme valeur :
+
+```Python
+say_hi(name=None) # Cela fonctionne, None est valide 🎉
+```
+
+La bonne nouvelle est que, dès que vous êtes sur Python 3.10, vous n'avez plus à vous en soucier, car vous pourrez simplement utiliser `|` pour définir des unions de types :
+
+{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
+
+Et alors vous n'aurez plus à vous soucier de noms comme `Optional` et `Union`. 😎
+
+#### Types génériques { #generic-types }
+
+Ces types qui prennent des paramètres de type entre crochets sont appelés des **types génériques** ou **Generics**, par exemple :
+
+//// tab | Python 3.10+
+
+Vous pouvez utiliser les mêmes types intégrés comme génériques (avec des crochets et des types à l'intérieur) :
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+Et, comme avec les versions précédentes de Python, depuis le module `typing` :
+
+* `Union`
* `Optional`
-* ...et d'autres.
+* ... et d'autres.
-sont appelés des **types génériques** ou **Generics**.
+Dans Python 3.10, comme alternative à l'utilisation des génériques `Union` et `Optional`, vous pouvez utiliser la barre verticale (`|`) pour déclarer des unions de types, c'est bien mieux et plus simple.
-### Classes en tant que types
+////
+
+//// tab | Python 3.9+
+
+Vous pouvez utiliser les mêmes types intégrés comme génériques (avec des crochets et des types à l'intérieur) :
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+Et des génériques depuis le module `typing` :
+
+* `Union`
+* `Optional`
+* ... et d'autres.
+
+////
+
+### Classes en tant que types { #classes-as-types }
Vous pouvez aussi déclarer une classe comme type d'une variable.
-Disons que vous avez une classe `Person`, avec une variable `name` :
-
-{*../../docs_src/python_types/tutorial010.py hl[1:3] *}
+Disons que vous avez une classe `Person`, avec un nom :
+{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
Vous pouvez ensuite déclarer une variable de type `Person` :
-{*../../docs_src/python_types/tutorial010.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
-Et vous aurez accès, encore une fois, au support complet offert par l'éditeur :
+Et là encore, vous obtenez tout le support de l'éditeur :
-## Les modèles Pydantic
+Remarquez que cela signifie « `one_person` est une instance de la classe `Person` ».
+
+Cela ne signifie pas « `one_person` est la classe appelée `Person` ».
+
+## Modèles Pydantic { #pydantic-models }
Pydantic est une bibliothèque Python pour effectuer de la validation de données.
-Vous déclarez la forme de la donnée avec des classes et des attributs.
+Vous déclarez la « forme » de la donnée sous forme de classes avec des attributs.
-Chaque attribut possède un type.
+Et chaque attribut a un type.
-Puis vous créez une instance de cette classe avec certaines valeurs et **Pydantic** validera les valeurs, les convertira dans le type adéquat (si c'est nécessaire et possible) et vous donnera un objet avec toute la donnée.
+Ensuite, vous créez une instance de cette classe avec certaines valeurs et elle validera les valeurs, les convertira dans le type approprié (le cas échéant) et vous donnera un objet avec toutes les données.
-Ainsi, votre éditeur vous offrira un support adapté pour l'objet résultant.
+Et vous obtenez tout le support de l'éditeur avec cet objet résultant.
-Extrait de la documentation officielle de **Pydantic** :
+Un exemple tiré de la documentation officielle de Pydantic :
-{*../../docs_src/python_types/tutorial011.py*}
+{* ../../docs_src/python_types/tutorial011_py310.py *}
/// info
-Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation.
+Pour en savoir plus à propos de Pydantic, consultez sa documentation.
///
-**FastAPI** est basé entièrement sur **Pydantic**.
+**FastAPI** est entièrement basé sur Pydantic.
-Vous verrez bien plus d'exemples de son utilisation dans [Tutoriel - Guide utilisateur](tutorial/index.md){.internal-link target=_blank}.
+Vous verrez beaucoup plus de tout cela en pratique dans le [Tutoriel - Guide utilisateur](tutorial/index.md){.internal-link target=_blank}.
-## Les annotations de type dans **FastAPI**
+/// tip | Astuce
-**FastAPI** utilise ces annotations pour faire différentes choses.
+Pydantic a un comportement spécial lorsque vous utilisez `Optional` ou `Union[Something, None]` sans valeur par défaut, vous pouvez en lire davantage dans la documentation de Pydantic à propos des champs Optionals requis.
-Avec **FastAPI**, vous déclarez des paramètres grâce aux annotations de types et vous obtenez :
+///
-* **du support de l'éditeur**
-* **de la vérification de types**
+## Annotations de type avec métadonnées { #type-hints-with-metadata-annotations }
-...et **FastAPI** utilise ces mêmes déclarations pour :
+Python dispose également d'une fonctionnalité qui permet de mettre des **métadonnées supplémentaires** dans ces annotations de type en utilisant `Annotated`.
-* **Définir les prérequis** : depuis les paramètres de chemins des requêtes, les entêtes, les corps, les dépendances, etc.
-* **Convertir des données** : depuis la requête vers les types requis.
-* **Valider des données** : venant de chaque requête :
- * Générant automatiquement des **erreurs** renvoyées au client quand la donnée est invalide.
+Depuis Python 3.9, `Annotated` fait partie de la bibliothèque standard, vous pouvez donc l'importer depuis `typing`.
+
+{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+
+Python lui-même ne fait rien avec ce `Annotated`. Et pour les éditeurs et autres outils, le type est toujours `str`.
+
+Mais vous pouvez utiliser cet espace dans `Annotated` pour fournir à **FastAPI** des métadonnées supplémentaires sur la façon dont vous voulez que votre application se comporte.
+
+L'important à retenir est que le premier paramètre de type que vous passez à `Annotated` est le type réel. Le reste n'est que des métadonnées pour d'autres outils.
+
+Pour l'instant, vous avez juste besoin de savoir que `Annotated` existe, et que c'est du Python standard. 😎
+
+Plus tard, vous verrez à quel point cela peut être puissant.
+
+/// tip | Astuce
+
+Le fait que ce soit du Python standard signifie que vous bénéficierez toujours de la meilleure expérience développeur possible dans votre éditeur, avec les outils que vous utilisez pour analyser et refactoriser votre code, etc. ✨
+
+Et aussi que votre code sera très compatible avec de nombreux autres outils et bibliothèques Python. 🚀
+
+///
+
+## Annotations de type dans **FastAPI** { #type-hints-in-fastapi }
+
+**FastAPI** tire parti de ces annotations de type pour faire plusieurs choses.
+
+Avec **FastAPI**, vous déclarez des paramètres avec des annotations de type et vous obtenez :
+
+* **Du support de l'éditeur**.
+* **Des vérifications de types**.
+
+... et **FastAPI** utilise les mêmes déclarations pour :
+
+* **Définir des prérequis** : à partir des paramètres de chemin de la requête, des paramètres de requête, des en-têtes, des corps, des dépendances, etc.
+* **Convertir des données** : de la requête vers le type requis.
+* **Valider des données** : provenant de chaque requête :
+ * En générant des **erreurs automatiques** renvoyées au client lorsque la donnée est invalide.
* **Documenter** l'API avec OpenAPI :
- * ce qui ensuite utilisé par les interfaces utilisateur automatiques de documentation interactive.
+ * ce qui est ensuite utilisé par les interfaces utilisateur de documentation interactive automatiques.
-Tout cela peut paraître bien abstrait, mais ne vous inquiétez pas, vous verrez tout ça en pratique dans [Tutoriel - Guide utilisateur](tutorial/index.md){.internal-link target=_blank}.
+Tout cela peut sembler abstrait. Ne vous inquiétez pas. Vous verrez tout cela en action dans le [Tutoriel - Guide utilisateur](tutorial/index.md){.internal-link target=_blank}.
-Ce qu'il faut retenir c'est qu'en utilisant les types standard de Python, à un seul endroit (plutôt que d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous.
+L'important est qu'en utilisant les types standards de Python, en un seul endroit (au lieu d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous.
/// info
-Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la "cheat sheet" de `mypy`.
+Si vous avez déjà parcouru tout le tutoriel et êtes revenu pour en voir plus sur les types, une bonne ressource est l'« aide-mémoire » de `mypy`.
///
diff --git a/docs/fr/docs/tutorial/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md
index 6efd16e07..ed7494669 100644
--- a/docs/fr/docs/tutorial/background-tasks.md
+++ b/docs/fr/docs/tutorial/background-tasks.md
@@ -1,4 +1,4 @@
-# Tâches d'arrière-plan
+# Tâches d'arrière-plan { #background-tasks }
Vous pouvez définir des tâches d'arrière-plan qui seront exécutées après avoir retourné une réponse.
@@ -7,20 +7,19 @@ Ceci est utile pour les opérations qui doivent avoir lieu après une requête,
Cela comprend, par exemple :
* Les notifications par email envoyées après l'exécution d'une action :
- * Étant donné que se connecter à un serveur et envoyer un email a tendance à être «lent» (plusieurs secondes), vous pouvez retourner la réponse directement et envoyer la notification en arrière-plan.
+ * Étant donné que se connecter à un serveur et envoyer un email a tendance à être « lent » (plusieurs secondes), vous pouvez retourner la réponse directement et envoyer la notification en arrière-plan.
* Traiter des données :
- * Par exemple, si vous recevez un fichier qui doit passer par un traitement lent, vous pouvez retourner une réponse «Accepted» (HTTP 202) puis faire le traitement en arrière-plan.
+ * Par exemple, si vous recevez un fichier qui doit passer par un traitement lent, vous pouvez retourner une réponse « Accepted » (HTTP 202) puis faire le traitement en arrière-plan.
+## Utiliser `BackgroundTasks` { #using-backgroundtasks }
-## Utiliser `BackgroundTasks`
+Pour commencer, importez `BackgroundTasks` et définissez un paramètre dans votre *fonction de chemin d'accès* avec `BackgroundTasks` comme type déclaré.
-Pour commencer, importez `BackgroundTasks` et définissez un paramètre dans votre *fonction de chemin* avec `BackgroundTasks` comme type déclaré.
-
-{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
**FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre.
-## Créer une fonction de tâche
+## Créer une fonction de tâche { #create-a-task-function }
Une fonction à exécuter comme tâche d'arrière-plan est juste une fonction standard qui peut recevoir des paramètres.
@@ -30,14 +29,13 @@ Dans cet exemple, la fonction de tâche écrira dans un fichier (afin de simuler
L'opération d'écriture n'utilisant ni `async` ni `await`, on définit la fonction avec un `def` normal.
-{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
-## Ajouter une tâche d'arrière-plan
+## Ajouter une tâche d'arrière-plan { #add-the-background-task }
-Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de type `BackgroundTasks` (`background_tasks` ici) grâce à la méthode `.add_task()` :
+Dans votre *fonction de chemin d'accès*, passez votre fonction de tâche à l'objet de type `BackgroundTasks` (`background_tasks` ici) grâce à la méthode `.add_task()` :
-
-{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
`.add_task()` reçoit comme arguments :
@@ -45,40 +43,40 @@ Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de t
* Les arguments positionnels à passer à la fonction de tâche dans l'ordre (`email`).
* Les arguments nommés à passer à la fonction de tâche (`message="some notification"`).
-## Injection de dépendances
+## Injection de dépendances { #dependency-injection }
-Utiliser `BackgroundTasks` fonctionne aussi avec le système d'injection de dépendances. Vous pouvez déclarer un paramètre de type `BackgroundTasks` à différents niveaux : dans une *fonction de chemin*, dans une dépendance, dans une sous-dépendance...
+Utiliser `BackgroundTasks` fonctionne aussi avec le système d'injection de dépendances. Vous pouvez déclarer un paramètre de type `BackgroundTasks` à différents niveaux : dans une *fonction de chemin d'accès*, dans une dépendance (dependable), dans une sous-dépendance, etc.
-**FastAPI** sait quoi faire dans chaque cas et comment réutiliser le même objet, afin que tous les paramètres de type `BackgroundTasks` soient fusionnés et que les tâches soient exécutées en arrière-plan :
+**FastAPI** sait quoi faire dans chaque cas et comment réutiliser le même objet, afin que toutes les tâches d'arrière-plan soient fusionnées et que les tâches soient ensuite exécutées en arrière-plan :
-{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *}
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée.
-S'il y avait une `query` (paramètre nommé `q`) dans la requête, alors elle sera écrite dans `log.txt` via une tâche d'arrière-plan.
+S'il y avait un paramètre de requête dans la requête, alors il sera écrit dans le journal via une tâche d'arrière-plan.
-Et ensuite une autre tâche d'arrière-plan (générée dans les paramètres de la *la fonction de chemin*) écrira un message dans `log.txt` comprenant le paramètre de chemin `email`.
+Et ensuite une autre tâche d'arrière-plan (générée dans la *fonction de chemin d'accès*) écrira un message comprenant le paramètre de chemin `email`.
-## Détails techniques
+## Détails techniques { #technical-details }
La classe `BackgroundTasks` provient directement de `starlette.background`.
Elle est importée/incluse directement dans **FastAPI** pour que vous puissiez l'importer depuis `fastapi` et éviter d'importer accidentellement `BackgroundTask` (sans `s` à la fin) depuis `starlette.background`.
-En utilisant seulement `BackgroundTasks` (et non `BackgroundTask`), il est possible de l'utiliser en tant que paramètre de *fonction de chemin* et de laisser **FastAPI** gérer le reste pour vous, comme en utilisant l'objet `Request` directement.
+En utilisant seulement `BackgroundTasks` (et non `BackgroundTask`), il est possible de l'utiliser en tant que paramètre de *fonction de chemin d'accès* et de laisser **FastAPI** gérer le reste pour vous, comme en utilisant l'objet `Request` directement.
Il est tout de même possible d'utiliser `BackgroundTask` seul dans **FastAPI**, mais dans ce cas il faut créer l'objet dans le code et renvoyer une `Response` Starlette l'incluant.
-Plus de détails sont disponibles dans la documentation officielle de Starlette sur les tâches d'arrière-plan (via leurs classes `BackgroundTasks`et `BackgroundTask`).
+Plus de détails sont disponibles dans la documentation officielle de Starlette sur les tâches d'arrière-plan.
-## Avertissement
+## Avertissement { #caveat }
Si vous avez besoin de réaliser des traitements lourds en tâche d'arrière-plan et que vous n'avez pas besoin que ces traitements aient lieu dans le même process (par exemple, pas besoin de partager la mémoire, les variables, etc.), il peut s'avérer profitable d'utiliser des outils plus importants tels que Celery.
-Ces outils nécessitent généralement des configurations plus complexes ainsi qu'un gestionnaire de queue de message, comme RabbitMQ ou Redis, mais ils permettent d'exécuter des tâches d'arrière-plan dans différents process, et potentiellement, sur plusieurs serveurs.
+Ces outils nécessitent généralement des configurations plus complexes ainsi qu'un gestionnaire de queue de message, comme RabbitMQ ou Redis, mais ils permettent d'exécuter des tâches d'arrière-plan dans différents process, et surtout, sur plusieurs serveurs.
Mais si vous avez besoin d'accéder aux variables et objets de la même application **FastAPI**, ou si vous avez besoin d'effectuer de petites tâches d'arrière-plan (comme envoyer des notifications par email), vous pouvez simplement vous contenter d'utiliser `BackgroundTasks`.
-## Résumé
+## Résumé { #recap }
-Importez et utilisez `BackgroundTasks` grâce aux paramètres de *fonction de chemin* et les dépendances pour ajouter des tâches d'arrière-plan.
+Importez et utilisez `BackgroundTasks` grâce aux paramètres de *fonction de chemin d'accès* et les dépendances pour ajouter des tâches d'arrière-plan.
diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md
index 0541acc74..9aed24e98 100644
--- a/docs/fr/docs/tutorial/body-multiple-params.md
+++ b/docs/fr/docs/tutorial/body-multiple-params.md
@@ -1,24 +1,24 @@
-# Body - Paramètres multiples
+# Body - Paramètres multiples { #body-multiple-parameters }
-Maintenant que nous avons vu comment manipuler `Path` et `Query`, voyons comment faire pour le corps d'une requête, communément désigné par le terme anglais "body".
+Maintenant que nous avons vu comment utiliser `Path` et `Query`, voyons des usages plus avancés des déclarations de paramètres du corps de la requête.
-## Mélanger les paramètres `Path`, `Query` et body
+## Mélanger les paramètres `Path`, `Query` et body { #mix-path-query-and-body-parameters }
-Tout d'abord, sachez que vous pouvez mélanger les déclarations des paramètres `Path`, `Query` et body, **FastAPI** saura quoi faire.
+Tout d'abord, sachez que vous pouvez mélanger librement les déclarations des paramètres `Path`, `Query` et du body, **FastAPI** saura quoi faire.
-Vous pouvez également déclarer des paramètres body comme étant optionnels, en leur assignant une valeur par défaut à `None` :
+Et vous pouvez également déclarer des paramètres du body comme étant optionnels, en leur assignant une valeur par défaut à `None` :
{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
-/// note
+/// note | Remarque
-Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`).
+Notez que, dans ce cas, l'élément `item` récupéré depuis le body est optionnel. Comme sa valeur par défaut est `None`.
///
-## Paramètres multiples du body
+## Paramètres multiples du body { #multiple-body-parameters }
-Dans l'exemple précédent, les opérations de routage attendaient un body JSON avec les attributs d'un `Item`, par exemple :
+Dans l'exemple précédent, les chemins d'accès attendraient un body JSON avec les attributs d'un `Item`, par exemple :
```JSON
{
@@ -29,13 +29,13 @@ Dans l'exemple précédent, les opérations de routage attendaient un body JSON
}
```
-Mais vous pouvez également déclarer plusieurs paramètres provenant de body, par exemple `item` et `user` simultanément :
+Mais vous pouvez également déclarer plusieurs paramètres provenant du body, par exemple `item` et `user` :
{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
-Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic).
+Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre du body dans la fonction (il y a deux paramètres qui sont des modèles Pydantic).
-Il utilisera alors les noms des paramètres comme clés, et s'attendra à recevoir quelque chose de semblable à :
+Il utilisera alors les noms des paramètres comme clés (noms de champs) dans le body, et s'attendra à recevoir un body semblable à :
```JSON
{
@@ -52,25 +52,25 @@ Il utilisera alors les noms des paramètres comme clés, et s'attendra à recevo
}
```
-/// note
+/// note | Remarque
-"Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`.
+Notez que, bien que `item` ait été déclaré de la même manière qu'auparavant, il est désormais attendu à l'intérieur du body sous la clé `item`.
///
-**FastAPI** effectue la conversion de la requête de façon transparente, de sorte que les objets `item` et `user` se trouvent correctement définis.
+**FastAPI** effectuera la conversion automatique depuis la requête, de sorte que le paramètre `item` reçoive son contenu spécifique, et de même pour `user`.
-Il effectue également la validation des données (même imbriquées les unes dans les autres), et permet de les documenter correctement (schéma OpenAPI et documentation auto-générée).
+Il effectuera la validation des données composées, et les documentera ainsi pour le schéma OpenAPI et la documentation automatique.
-## Valeurs scalaires dans le body
+## Valeurs singulières dans le body { #singular-values-in-body }
-De la même façon qu'il existe `Query` et `Path` pour définir des données supplémentaires pour les paramètres query et path, **FastAPI** fournit un équivalent `Body`.
+De la même façon qu'il existe `Query` et `Path` pour définir des données supplémentaires pour les paramètres de requête et de chemin, **FastAPI** fournit un équivalent `Body`.
-Par exemple, en étendant le modèle précédent, vous pouvez vouloir ajouter un paramètre `importance` dans le même body, en plus des paramètres `item` et `user`.
+Par exemple, en étendant le modèle précédent, vous pourriez décider d'avoir une autre clé `importance` dans le même body, en plus de `item` et `user`.
-Si vous le déclarez tel quel, comme c'est une valeur [scalaire](https://docs.github.com/fr/graphql/reference/scalars), **FastAPI** supposera qu'il s'agit d'un paramètre de requête (`Query`).
+Si vous le déclarez tel quel, comme c'est une valeur singulière, **FastAPI** supposera qu'il s'agit d'un paramètre de requête.
-Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de body en utilisant `Body` :
+Mais vous pouvez indiquer à **FastAPI** de la traiter comme une autre clé du body en utilisant `Body` :
{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
@@ -92,51 +92,51 @@ Dans ce cas, **FastAPI** s'attendra à un body semblable à :
}
```
-Encore une fois, cela convertira les types de données, les validera, permettra de générer la documentation, etc...
+Encore une fois, il convertira les types de données, validera, documentera, etc.
-## Paramètres multiples body et query
+## Paramètres multiples du body et paramètres de requête { #multiple-body-params-and-query }
-Bien entendu, vous pouvez déclarer autant de paramètres que vous le souhaitez, en plus des paramètres body déjà déclarés.
+Bien entendu, vous pouvez également déclarer des paramètres de requête supplémentaires quand vous en avez besoin, en plus de tout paramètre du body.
-Par défaut, les valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) sont interprétées comme des paramètres query, donc inutile d'ajouter explicitement `Query`. Vous pouvez juste écrire :
-
-```Python
-q: Union[str, None] = None
-```
-
-Ou bien, en Python 3.10 et supérieur :
+Comme, par défaut, les valeurs singulières sont interprétées comme des paramètres de requête, vous n'avez pas besoin d'ajouter explicitement `Query`, vous pouvez simplement écrire :
```Python
q: str | None = None
```
+Ou en Python 3.9 :
+
+```Python
+q: Union[str, None] = None
+```
+
Par exemple :
-{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *}
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
/// info
-`Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard.
+`Body` possède également les mêmes paramètres supplémentaires de validation et de métadonnées que `Query`, `Path` et d'autres que vous verrez plus tard.
///
-## Inclure un paramètre imbriqué dans le body
+## Intégrer un seul paramètre du body { #embed-a-single-body-parameter }
-Disons que vous avez seulement un paramètre `item` dans le body, correspondant à un modèle Pydantic `Item`.
+Supposons que vous n'ayez qu'un seul paramètre `item` dans le body, provenant d'un modèle Pydantic `Item`.
-Par défaut, **FastAPI** attendra sa déclaration directement dans le body.
+Par défaut, **FastAPI** attendra alors son contenu directement.
-Cependant, si vous souhaitez qu'il interprête correctement un JSON avec une clé `item` associée au contenu du modèle, comme cela serait le cas si vous déclariez des paramètres body additionnels, vous pouvez utiliser le paramètre spécial `embed` de `Body` :
+Mais si vous voulez qu'il attende un JSON avec une clé `item` contenant le contenu du modèle, comme lorsqu'on déclare des paramètres supplémentaires du body, vous pouvez utiliser le paramètre spécial `embed` de `Body` :
```Python
item: Item = Body(embed=True)
```
-Voici un exemple complet :
+comme dans :
{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
-Dans ce cas **FastAPI** attendra un body semblable à :
+Dans ce cas **FastAPI** s'attendra à un body semblable à :
```JSON hl_lines="2"
{
@@ -160,12 +160,12 @@ au lieu de :
}
```
-## Pour résumer
+## Récapitulatif { #recap }
-Vous pouvez ajouter plusieurs paramètres body dans votre fonction de routage, même si une requête ne peut avoir qu'un seul body.
+Vous pouvez ajouter plusieurs paramètres du body à votre fonction de chemin d'accès, même si une requête ne peut avoir qu'un seul body.
-Cependant, **FastAPI** se chargera de faire opérer sa magie, afin de toujours fournir à votre fonction des données correctes, les validera et documentera le schéma associé.
+Mais **FastAPI** s'en chargera, vous fournira les bonnes données dans votre fonction, et validera et documentera le schéma correct dans le chemin d'accès.
-Vous pouvez également déclarer des valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) à recevoir dans le body.
+Vous pouvez également déclarer des valeurs singulières à recevoir dans le body.
-Et vous pouvez indiquer à **FastAPI** d'inclure le body dans une autre variable, même lorsqu'un seul paramètre est déclaré.
+Et vous pouvez indiquer à **FastAPI** d'intégrer le body sous une clé même lorsqu'un seul paramètre est déclaré.
diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md
index 760b6d80a..ca115fabc 100644
--- a/docs/fr/docs/tutorial/body.md
+++ b/docs/fr/docs/tutorial/body.md
@@ -1,10 +1,10 @@
-# Corps de la requête
+# Corps de la requête { #request-body }
Quand vous avez besoin d'envoyer de la donnée depuis un client (comme un navigateur) vers votre API, vous l'envoyez en tant que **corps de requête**.
Le corps d'une **requête** est de la donnée envoyée par le client à votre API. Le corps d'une **réponse** est la donnée envoyée par votre API au client.
-Votre API aura presque toujours à envoyer un corps de **réponse**. Mais un client n'a pas toujours à envoyer un corps de **requête**.
+Votre API aura presque toujours à envoyer un corps de **réponse**. Mais un client n'a pas toujours à envoyer un **corps de requête** : parfois il demande seulement un chemin, peut-être avec quelques paramètres de requête, mais n'envoie pas de corps.
Pour déclarer un corps de **requête**, on utilise les modèles de Pydantic en profitant de tous leurs avantages et fonctionnalités.
@@ -18,23 +18,23 @@ Ceci étant découragé, la documentation interactive générée par Swagger UI
///
-## Importez le `BaseModel` de Pydantic
+## Importer le `BaseModel` de Pydantic { #import-pydantics-basemodel }
Commencez par importer la classe `BaseModel` du module `pydantic` :
-{* ../../docs_src/body/tutorial001.py hl[4] *}
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
-## Créez votre modèle de données
+## Créer votre modèle de données { #create-your-data-model }
Déclarez ensuite votre modèle de données en tant que classe qui hérite de `BaseModel`.
Utilisez les types Python standard pour tous les attributs :
-{* ../../docs_src/body/tutorial001.py hl[7:11] *}
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
-Tout comme pour la déclaration de paramètres de requête, quand un attribut de modèle a une valeur par défaut, il n'est pas nécessaire. Sinon, cet attribut doit être renseigné dans le corps de la requête. Pour rendre ce champ optionnel simplement, utilisez `None` comme valeur par défaut.
+Tout comme pour la déclaration de paramètres de requête, quand un attribut de modèle a une valeur par défaut, il n'est pas nécessaire. Sinon, cet attribut doit être renseigné dans le corps de la requête. Utilisez `None` pour le rendre simplement optionnel.
-Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) tel que :
+Par exemple, le modèle ci-dessus déclare un JSON « `object` » (ou `dict` Python) tel que :
```JSON
{
@@ -45,7 +45,7 @@ Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) te
}
```
-...`description` et `tax` étant des attributs optionnels (avec `None` comme valeur par défaut), cet "objet" JSON serait aussi valide :
+... `description` et `tax` étant des attributs optionnels (avec `None` comme valeur par défaut), ce JSON « `object` » serait aussi valide :
```JSON
{
@@ -54,28 +54,28 @@ Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) te
}
```
-## Déclarez-le comme paramètre
+## Le déclarer comme paramètre { #declare-it-as-a-parameter }
Pour l'ajouter à votre *opération de chemin*, déclarez-le comme vous déclareriez des paramètres de chemin ou de requête :
-{* ../../docs_src/body/tutorial001.py hl[18] *}
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
-...et déclarez que son type est le modèle que vous avez créé : `Item`.
+... et déclarez que son type est le modèle que vous avez créé : `Item`.
-## Résultats
+## Résultats { #results }
En utilisant uniquement les déclarations de type Python, **FastAPI** réussit à :
* Lire le contenu de la requête en tant que JSON.
* Convertir les types correspondants (si nécessaire).
* Valider la donnée.
- * Si la donnée est invalide, une erreur propre et claire sera renvoyée, indiquant exactement où était la donnée incorrecte.
+ * Si la donnée est invalide, une erreur propre et claire sera renvoyée, indiquant exactement où et quelle était la donnée incorrecte.
* Passer la donnée reçue dans le paramètre `item`.
- * Ce paramètre ayant été déclaré dans la fonction comme étant de type `Item`, vous aurez aussi tout le support offert par l'éditeur (auto-complétion, etc.) pour tous les attributs de ce paramètre et les types de ces attributs.
-* Générer des définitions JSON Schema pour votre modèle, qui peuvent être utilisées où vous en avez besoin dans votre projet ensuite.
-* Ces schémas participeront à la constitution du schéma généré OpenAPI, et seront donc utilisés par les documentations automatiquement générées.
+ * Ce paramètre ayant été déclaré dans la fonction comme étant de type `Item`, vous aurez aussi tout le support offert par l'éditeur (autocomplétion, etc.) pour tous les attributs de ce paramètre et les types de ces attributs.
+* Générer des définitions JSON Schema pour votre modèle ; vous pouvez également les utiliser partout ailleurs si cela a du sens pour votre projet.
+* Ces schémas participeront à la constitution du schéma généré OpenAPI, et seront utilisés par les documentations automatiques UIs.
-## Documentation automatique
+## Documentation automatique { #automatic-docs }
Les schémas JSON de vos modèles seront intégrés au schéma OpenAPI global de votre application, et seront donc affichés dans la documentation interactive de l'API :
@@ -85,63 +85,63 @@ Et seront aussi utilisés dans chaque *opération de chemin* de la documentation
-## Support de l'éditeur
+## Support de l'éditeur { #editor-support }
-Dans votre éditeur, vous aurez des annotations de types et de l'auto-complétion partout dans votre fonction (ce qui n'aurait pas été le cas si vous aviez utilisé un classique `dict` plutôt qu'un modèle Pydantic) :
+Dans votre éditeur, vous aurez des annotations de type et de l'autocomplétion partout dans votre fonction (ce qui n'aurait pas été le cas si vous aviez reçu un `dict` plutôt qu'un modèle Pydantic) :
-Et vous obtenez aussi de la vérification d'erreur pour les opérations incorrectes de types :
+Et vous obtenez aussi des vérifications d'erreurs pour les opérations de types incorrectes :
Ce n'est pas un hasard, ce framework entier a été bâti avec ce design comme objectif.
-Et cela a été rigoureusement testé durant la phase de design, avant toute implémentation, pour s'assurer que cela fonctionnerait avec tous les éditeurs.
+Et cela a été rigoureusement testé durant la phase de design, avant toute implémentation, pour vous assurer que cela fonctionnerait avec tous les éditeurs.
Des changements sur Pydantic ont même été faits pour supporter cela.
-Les captures d'écrans précédentes ont été prises sur Visual Studio Code.
+Les captures d'écran précédentes ont été prises sur Visual Studio Code.
-Mais vous auriez le même support de l'éditeur avec PyCharm et la majorité des autres éditeurs de code Python.
+Mais vous auriez le même support de l'éditeur avec PyCharm et la majorité des autres éditeurs de code Python :
/// tip | Astuce
-Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin.
+Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le plug-in Pydantic PyCharm Plugin.
Ce qui améliore le support pour les modèles Pydantic avec :
-* de l'auto-complétion
+* de l'autocomplétion
* des vérifications de type
-* du "refactoring" (ou remaniement de code)
+* du « refactoring » (ou remaniement de code)
* de la recherche
-* de l'inspection
+* des inspections
///
-## Utilisez le modèle
+## Utiliser le modèle { #use-the-model }
Dans la fonction, vous pouvez accéder à tous les attributs de l'objet du modèle directement :
-{* ../../docs_src/body/tutorial002.py hl[21] *}
+{* ../../docs_src/body/tutorial002_py310.py *}
-## Corps de la requête + paramètres de chemin
+## Corps de la requête + paramètres de chemin { #request-body-path-parameters }
Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la même *opération de chemin*.
**FastAPI** est capable de reconnaître que les paramètres de la fonction qui correspondent aux paramètres de chemin doivent être **récupérés depuis le chemin**, et que les paramètres de fonctions déclarés comme modèles Pydantic devraient être **récupérés depuis le corps de la requête**.
-{* ../../docs_src/body/tutorial003.py hl[17:18] *}
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
-## Corps de la requête + paramètres de chemin et de requête
+## Corps de la requête + paramètres de chemin et de requête { #request-body-path-query-parameters }
Vous pouvez aussi déclarer un **corps**, et des paramètres de **chemin** et de **requête** dans la même *opération de chemin*.
**FastAPI** saura reconnaître chacun d'entre eux et récupérer la bonne donnée au bon endroit.
-{* ../../docs_src/body/tutorial004.py hl[18] *}
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
Les paramètres de la fonction seront reconnus comme tel :
@@ -149,14 +149,16 @@ Les paramètres de la fonction seront reconnus comme tel :
* Si le paramètre est d'un **type singulier** (comme `int`, `float`, `str`, `bool`, etc.), il sera interprété comme un paramètre de **requête**.
* Si le paramètre est déclaré comme ayant pour type un **modèle Pydantic**, il sera interprété comme faisant partie du **corps** de la requête.
-/// note
+/// note | Remarque
-**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`.
+**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`.
-Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type.
+L'annotation de type `str | None` (Python 3.10+) ou `Union` dans `Union[str, None]` (Python 3.9+) n'est pas utilisée par **FastAPI** pour déterminer que la valeur n'est pas requise, il le saura parce qu'elle a une valeur par défaut `= None`.
+
+Mais ajouter ces annotations de type permettra à votre éditeur de vous offrir un meilleur support et de détecter des erreurs.
///
-## Sans Pydantic
+## Sans Pydantic { #without-pydantic }
-Si vous ne voulez pas utiliser des modèles Pydantic, vous pouvez aussi utiliser des paramètres de **Corps**. Pour cela, allez voir la partie de la documentation sur [Corps de la requête - Paramètres multiples](body-multiple-params.md){.internal-link target=_blank}.
+Si vous ne voulez pas utiliser des modèles Pydantic, vous pouvez aussi utiliser des paramètres de **Body**. Pour cela, allez voir la documentation sur [Corps de la requête - Paramètres multiples : Valeurs singulières dans le corps](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
diff --git a/docs/fr/docs/tutorial/debugging.md b/docs/fr/docs/tutorial/debugging.md
index ab00fbdeb..a88fa2b23 100644
--- a/docs/fr/docs/tutorial/debugging.md
+++ b/docs/fr/docs/tutorial/debugging.md
@@ -1,14 +1,14 @@
-# Débogage
+# Débogage { #debugging }
Vous pouvez connecter le débogueur dans votre éditeur, par exemple avec Visual Studio Code ou PyCharm.
-## Faites appel à `uvicorn`
+## Appeler `uvicorn` { #call-uvicorn }
Dans votre application FastAPI, importez et exécutez directement `uvicorn` :
-{* ../../docs_src/debugging/tutorial001.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
-### À propos de `__name__ == "__main__"`
+### À propos de `__name__ == "__main__"` { #about-name-main }
Le but principal de `__name__ == "__main__"` est d'avoir du code qui est exécuté lorsque votre fichier est appelé avec :
@@ -26,7 +26,7 @@ mais qui n'est pas appelé lorsqu'un autre fichier l'importe, comme dans :
from myapp import app
```
-#### Pour davantage de détails
+#### Pour davantage de détails { #more-details }
Imaginons que votre fichier s'appelle `myapp.py`.
@@ -78,7 +78,7 @@ Pour plus d'informations, consultez débogueur
+## Exécuter votre code avec votre débogueur { #run-your-code-with-your-debugger }
Parce que vous exécutez le serveur Uvicorn directement depuis votre code, vous pouvez appeler votre programme Python (votre application FastAPI) directement depuis le débogueur.
@@ -86,10 +86,10 @@ Parce que vous exécutez le serveur Uvicorn directement depuis votre code, vous
Par exemple, dans Visual Studio Code, vous pouvez :
-- Cliquer sur l'onglet "Debug" de la barre d'activités de Visual Studio Code.
-- "Add configuration...".
-- Sélectionnez "Python".
-- Lancez le débogueur avec l'option "`Python: Current File (Integrated Terminal)`".
+- Allez dans le panneau « Debug ».
+- « Add configuration... ».
+- Sélectionnez « Python ».
+- Lancez le débogueur avec l'option « Python: Current File (Integrated Terminal) ».
Il démarrera alors le serveur avec votre code **FastAPI**, s'arrêtera à vos points d'arrêt, etc.
@@ -101,8 +101,8 @@ Voici à quoi cela pourrait ressembler :
Si vous utilisez Pycharm, vous pouvez :
-- Ouvrir le menu "Run".
-- Sélectionnez l'option "Debug...".
+- Ouvrez le menu « Run ».
+- Sélectionnez l'option « Debug... ».
- Un menu contextuel s'affiche alors.
- Sélectionnez le fichier à déboguer (dans ce cas, `main.py`).
diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md
index 96ea56e62..b2693b3e5 100644
--- a/docs/fr/docs/tutorial/first-steps.md
+++ b/docs/fr/docs/tutorial/first-steps.md
@@ -1,107 +1,122 @@
-# Démarrage
+# Démarrage { #first-steps }
-Le fichier **FastAPI** le plus simple possible pourrait ressembler à cela :
+Le fichier **FastAPI** le plus simple possible pourrait ressembler à ceci :
-{* ../../docs_src/first_steps/tutorial001.py *}
+{* ../../docs_src/first_steps/tutorial001_py39.py *}
-Copiez ce code dans un fichier nommé `main.py`.
+Copiez cela dans un fichier `main.py`.
-Démarrez le serveur :
+Démarrez le serveur en direct :
get
+* en utilisant une get opération
/// info | `@décorateur` Info
-Cette syntaxe `@something` en Python est appelée un "décorateur".
+Cette syntaxe `@something` en Python est appelée un « décorateur ».
-Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂).
+Vous la mettez au-dessus d’une fonction. Comme un joli chapeau décoratif (j’imagine que c’est de là que vient le terme 🤷🏻♂).
-Un "décorateur" prend la fonction en dessous et en fait quelque chose.
+Un « décorateur » prend la fonction en dessous et fait quelque chose avec.
-Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`.
+Dans notre cas, ce décorateur indique à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec une **opération** `get`.
-C'est le "**décorateur d'opération de chemin**".
+C’est le « décorateur de chemin d’accès ».
///
@@ -269,7 +293,7 @@ Vous pouvez aussi utiliser les autres opérations :
* `@app.put()`
* `@app.delete()`
-Tout comme celles les plus exotiques :
+Ainsi que les plus exotiques :
* `@app.options()`
* `@app.head()`
@@ -278,58 +302,79 @@ Tout comme celles les plus exotiques :
/// tip | Astuce
-Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez.
+Vous êtes libre d’utiliser chaque opération (méthode HTTP) comme vous le souhaitez.
-**FastAPI** n'impose pas de sens spécifique à chacune d'elle.
+**FastAPI** n’impose aucune signification spécifique.
-Les informations qui sont présentées ici forment une directive générale, pas des obligations.
+Les informations ici sont présentées comme des lignes directrices, pas comme une obligation.
-Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`.
+Par exemple, lorsque vous utilisez GraphQL, vous effectuez normalement toutes les actions en utilisant uniquement des opérations `POST`.
///
-### Étape 4 : définir la **fonction de chemin**.
+### Étape 4 : définir la **fonction de chemin d’accès** { #step-4-define-the-path-operation-function }
-Voici notre "**fonction de chemin**" (ou fonction d'opération de chemin) :
+Voici notre « fonction de chemin d’accès » :
* **chemin** : `/`.
* **opération** : `get`.
-* **fonction** : la fonction sous le "décorateur" (sous `@app.get("/")`).
+* **fonction** : la fonction sous le « décorateur » (sous `@app.get("/")`).
-{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
-C'est une fonction Python.
+C’est une fonction Python.
-Elle sera appelée par **FastAPI** quand une requête sur l'URL `/` sera reçue via une opération `GET`.
+Elle sera appelée par **FastAPI** chaque fois qu’il recevra une requête vers l’URL « / » en utilisant une opération `GET`.
-Ici, c'est une fonction asynchrone (définie avec `async def`).
+Dans ce cas, c’est une fonction `async`.
---
-Vous pourriez aussi la définir comme une fonction classique plutôt qu'avec `async def` :
+Vous pouvez aussi la définir comme une fonction normale au lieu de `async def` :
-{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
/// note
-Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}.
+Si vous ne connaissez pas la différence, consultez [Asynchrone : « Pressé ? »](../async.md#in-a-hurry){.internal-link target=_blank}.
///
-### Étape 5 : retourner le contenu
+### Étape 5 : retourner le contenu { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
+{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
-Vous pouvez retourner un dictionnaire (`dict`), une liste (`list`), des valeurs seules comme des chaines de caractères (`str`) et des entiers (`int`), etc.
+Vous pouvez retourner un `dict`, une `list`, des valeurs uniques comme `str`, `int`, etc.
-Vous pouvez aussi retourner des models **Pydantic** (qui seront détaillés plus tard).
+Vous pouvez également retourner des modèles Pydantic (vous en verrez plus à ce sujet plus tard).
-Il y a de nombreux autres objets et modèles qui seront automatiquement convertis en JSON. Essayez d'utiliser vos favoris, il est fort probable qu'ils soient déjà supportés.
+Il existe de nombreux autres objets et modèles qui seront automatiquement convertis en JSON (y compris des ORM, etc.). Essayez d’utiliser vos favoris, il est fort probable qu’ils soient déjà pris en charge.
-## Récapitulatif
+### Étape 6 : le déployer { #step-6-deploy-it }
+
+Déployez votre application sur **FastAPI Cloud** avec une seule commande : `fastapi deploy`. 🎉
+
+#### À propos de FastAPI Cloud { #about-fastapi-cloud }
+
+**FastAPI Cloud** est construit par le même auteur et l’équipe derrière **FastAPI**.
+
+Il simplifie le processus de **construction**, de **déploiement** et d’**accès** à une API avec un minimum d’effort.
+
+Il apporte la même **expérience développeur** de création d’applications avec FastAPI au **déploiement** dans le cloud. 🎉
+
+FastAPI Cloud est le sponsor principal et le financeur des projets open source *FastAPI and friends*. ✨
+
+#### Déployer sur d’autres fournisseurs cloud { #deploy-to-other-cloud-providers }
+
+FastAPI est open source et basé sur des standards. Vous pouvez déployer des applications FastAPI chez n’importe quel fournisseur cloud de votre choix.
+
+Suivez les guides de votre fournisseur cloud pour y déployer des applications FastAPI. 🤓
+
+## Récapitulatif { #recap }
* Importez `FastAPI`.
-* Créez une instance d'`app`.
-* Ajoutez une **décorateur d'opération de chemin** (tel que `@app.get("/")`).
-* Ajoutez une **fonction de chemin** (telle que `def root(): ...` comme ci-dessus).
-* Lancez le serveur de développement (avec `uvicorn main:app --reload`).
+* Créez une instance `app`.
+* Écrivez un **décorateur de chemin d’accès** avec des décorateurs comme `@app.get("/")`.
+* Définissez une **fonction de chemin d’accès** ; par exemple, `def root(): ...`.
+* Exécutez le serveur de développement avec la commande `fastapi dev`.
+* Déployez éventuellement votre application avec `fastapi deploy`.
diff --git a/docs/fr/docs/tutorial/index.md b/docs/fr/docs/tutorial/index.md
index 83cc5f9e8..0251b9b4b 100644
--- a/docs/fr/docs/tutorial/index.md
+++ b/docs/fr/docs/tutorial/index.md
@@ -1,29 +1,53 @@
-# Tutoriel - Guide utilisateur - Introduction
+# Tutoriel - Guide utilisateur { #tutorial-user-guide }
Ce tutoriel vous montre comment utiliser **FastAPI** avec la plupart de ses fonctionnalités, étape par étape.
-Chaque section s'appuie progressivement sur les précédentes, mais elle est structurée de manière à séparer les sujets, afin que vous puissiez aller directement à l'un d'entre eux pour résoudre vos besoins spécifiques en matière d'API.
+Chaque section s'appuie progressivement sur les précédentes, mais elle est structurée de manière à séparer les sujets, afin que vous puissiez aller directement à l'un d'entre eux pour répondre à vos besoins spécifiques d'API.
-Il est également conçu pour fonctionner comme une référence future.
+Il est également conçu pour servir de référence ultérieure, afin que vous puissiez revenir voir exactement ce dont vous avez besoin.
-Vous pouvez donc revenir et voir exactement ce dont vous avez besoin.
-
-## Exécuter le code
+## Exécuter le code { #run-the-code }
Tous les blocs de code peuvent être copiés et utilisés directement (il s'agit en fait de fichiers Python testés).
-Pour exécuter l'un de ces exemples, copiez le code dans un fichier `main.py`, et commencez `uvicorn` avec :
+Pour exécuter l'un de ces exemples, copiez le code dans un fichier `main.py`, et démarrez `fastapi dev` avec :
kwargs. Même s'ils n'ont pas de valeur par défaut.
-{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
-# Avec `Annotated`
+### Mieux avec `Annotated` { #better-with-annotated }
Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`.
{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
-## Validations numériques : supérieur ou égal
+## Validations numériques : supérieur ou égal { #number-validations-greater-than-or-equal }
Avec `Query` et `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des contraintes numériques.
-Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`qual" à `1`.
+Ici, avec `ge=1`, `item_id` devra être un nombre entier « `g`reater than or `e`qual » à `1`.
{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
-## Validations numériques : supérieur ou égal et inférieur ou égal
-
-La même chose s'applique pour :
-
-* `gt` : `g`reater `t`han
-* `le` : `l`ess than or `e`qual
-
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
-
-## Validations numériques : supérieur et inférieur ou égal
+## Validations numériques : supérieur et inférieur ou égal { #number-validations-greater-than-and-less-than-or-equal }
La même chose s'applique pour :
@@ -117,7 +108,7 @@ La même chose s'applique pour :
{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
-## Validations numériques : flottants, supérieur et inférieur
+## Validations numériques : flottants, supérieur et inférieur { #number-validations-floats-greater-than-and-less-than }
Les validations numériques fonctionnent également pour les valeurs `float`.
@@ -129,7 +120,7 @@ Et la même chose pour lt.
{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
-## Pour résumer
+## Pour résumer { #recap }
Avec `Query`, `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des métadonnées et des validations de chaînes de la même manière qu'avec les [Paramètres de requête et validations de chaînes](query-params-str-validations.md){.internal-link target=_blank}.
diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md
index 71c96b18e..3b2955a95 100644
--- a/docs/fr/docs/tutorial/path-params.md
+++ b/docs/fr/docs/tutorial/path-params.md
@@ -1,205 +1,196 @@
-# Paramètres de chemin
+# Paramètres de chemin { #path-parameters }
-Vous pouvez déclarer des "paramètres" ou "variables" de chemin avec la même syntaxe que celle utilisée par le
-formatage de chaîne Python :
+Vous pouvez déclarer des « paramètres » ou « variables » de chemin avec la même syntaxe utilisée par les chaînes de format Python :
+{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
-{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+La valeur du paramètre de chemin `item_id` sera transmise à votre fonction dans l'argument `item_id`.
-La valeur du paramètre `item_id` sera transmise à la fonction dans l'argument `item_id`.
-
-Donc, si vous exécutez cet exemple et allez sur http://127.0.0.1:8000/items/foo,
-vous verrez comme réponse :
+Donc, si vous exécutez cet exemple et allez sur http://127.0.0.1:8000/items/foo, vous verrez comme réponse :
```JSON
{"item_id":"foo"}
```
-## Paramètres de chemin typés
+## Paramètres de chemin typés { #path-parameters-with-types }
-Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en utilisant les annotations de type Python :
+Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en utilisant les annotations de type Python standard :
-
-{* ../../docs_src/path_params/tutorial002.py hl[7] *}
+{* ../../docs_src/path_params/tutorial002_py39.py hl[7] *}
Ici, `item_id` est déclaré comme `int`.
-/// check | vérifier
+/// check | Vérifications
-Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles
-que des vérifications d'erreur, de l'auto-complétion, etc.
+Cela vous apporte la prise en charge par l'éditeur dans votre fonction, avec vérifications d'erreurs, autocomplétion, etc.
///
-## Conversion de données
+## Conversion de données { #data-conversion }
-Si vous exécutez cet exemple et allez sur http://127.0.0.1:8000/items/3, vous aurez comme réponse :
+Si vous exécutez cet exemple et ouvrez votre navigateur sur http://127.0.0.1:8000/items/3, vous verrez comme réponse :
```JSON
{"item_id":3}
```
-/// check | vérifier
+/// check | Vérifications
-Comme vous l'avez remarqué, la valeur reçue par la fonction (et renvoyée ensuite) est `3`,
-en tant qu'entier (`int`) Python, pas la chaîne de caractères (`string`) `"3"`.
+Remarquez que la valeur reçue par votre fonction (et renvoyée) est `3`, en tant qu'entier (`int`) Python, pas la chaîne de caractères « 3 ».
-Grâce aux déclarations de types, **FastAPI** fournit du
-"parsing" automatique.
+Ainsi, avec cette déclaration de type, **FastAPI** vous fournit automatiquement le « parsing » de la requête.
///
-## Validation de données
+## Validation de données { #data-validation }
-Si vous allez sur http://127.0.0.1:8000/items/foo, vous aurez une belle erreur HTTP :
+Mais si vous allez dans le navigateur sur http://127.0.0.1:8000/items/foo, vous verrez une belle erreur HTTP :
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
}
```
-car le paramètre de chemin `item_id` possède comme valeur `"foo"`, qui ne peut pas être convertie en entier (`int`).
+car le paramètre de chemin `item_id` a pour valeur « foo », qui n'est pas un `int`.
-La même erreur se produira si vous passez un nombre flottant (`float`) et non un entier, comme ici
-http://127.0.0.1:8000/items/4.2.
+La même erreur apparaîtrait si vous fournissiez un `float` au lieu d'un `int`, comme ici : http://127.0.0.1:8000/items/4.2
+/// check | Vérifications
-/// check | vérifier
+Ainsi, avec la même déclaration de type Python, **FastAPI** vous fournit la validation de données.
-Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données.
+Remarquez que l'erreur indique clairement l'endroit exact où la validation n'a pas réussi.
-Notez que l'erreur mentionne le point exact où la validation n'a pas réussi.
-
-Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API.
+C'est incroyablement utile lors du développement et du débogage du code qui interagit avec votre API.
///
-## Documentation
+## Documentation { #documentation }
-Et quand vous vous rendez sur http://127.0.0.1:8000/docs, vous verrez la
-documentation générée automatiquement et interactive :
+Et lorsque vous ouvrez votre navigateur sur http://127.0.0.1:8000/docs, vous verrez une documentation d'API automatique et interactive comme :
-/// info
+/// check | Vérifications
-À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI).
+À nouveau, simplement avec cette même déclaration de type Python, **FastAPI** vous fournit une documentation interactive automatique (intégrant Swagger UI).
-On voit bien dans la documentation que `item_id` est déclaré comme entier.
+Remarquez que le paramètre de chemin est déclaré comme entier.
///
-## Les avantages d'avoir une documentation basée sur une norme, et la documentation alternative.
+## Les avantages d'une norme, documentation alternative { #standards-based-benefits-alternative-documentation }
-Le schéma généré suivant la norme OpenAPI,
-il existe de nombreux outils compatibles.
+Et comme le schéma généré suit la norme OpenAPI, il existe de nombreux outils compatibles.
-Grâce à cela, **FastAPI** lui-même fournit une documentation alternative (utilisant ReDoc), qui peut être lue
-sur http://127.0.0.1:8000/redoc :
+Grâce à cela, **FastAPI** fournit lui-même une documentation d'API alternative (utilisant ReDoc), accessible sur http://127.0.0.1:8000/redoc :
-De la même façon, il existe bien d'autres outils compatibles, y compris des outils de génération de code
-pour de nombreux langages.
+De la même façon, il existe de nombreux outils compatibles, y compris des outils de génération de code pour de nombreux langages.
-## Pydantic
+## Pydantic { #pydantic }
-Toute la validation de données est effectué en arrière-plan avec Pydantic,
-dont vous bénéficierez de tous les avantages. Vous savez donc que vous êtes entre de bonnes mains.
+Toute la validation de données est effectuée sous le capot par Pydantic, vous en bénéficiez donc pleinement. Vous savez ainsi que vous êtes entre de bonnes mains.
-## L'ordre importe
+Vous pouvez utiliser les mêmes déclarations de type avec `str`, `float`, `bool` et de nombreux autres types de données complexes.
-Quand vous créez des *fonctions de chemins*, vous pouvez vous retrouver dans une situation où vous avez un chemin fixe.
+Plusieurs d'entre eux sont explorés dans les prochains chapitres du tutoriel.
-Tel que `/users/me`, disons pour récupérer les données sur l'utilisateur actuel.
+## L'ordre importe { #order-matters }
-Et vous avez un second chemin : `/users/{user_id}` pour récupérer de la donnée sur un utilisateur spécifique grâce à son identifiant d'utilisateur
+Quand vous créez des *chemins d'accès*, vous pouvez vous retrouver dans une situation avec un chemin fixe.
-Les *fonctions de chemin* étant évaluées dans l'ordre, il faut s'assurer que la fonction correspondant à `/users/me` est déclarée avant celle de `/users/{user_id}` :
+Par exemple `/users/me`, disons pour récupérer les données de l'utilisateur actuel.
-{* ../../docs_src/path_params/tutorial003.py hl[6,11] *}
+Et vous pouvez aussi avoir un chemin `/users/{user_id}` pour récupérer des données sur un utilisateur spécifique grâce à un identifiant d'utilisateur.
-Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, la fonction "croyant" qu'elle a reçu un paramètre `user_id` avec pour valeur `"me"`.
+Comme les *chemins d'accès* sont évalués dans l'ordre, vous devez vous assurer que le chemin `/users/me` est déclaré avant celui de `/users/{user_id}` :
-## Valeurs prédéfinies
+{* ../../docs_src/path_params/tutorial003_py39.py hl[6,11] *}
-Si vous avez une *fonction de chemin* qui reçoit un *paramètre de chemin*, mais que vous voulez que les valeurs possibles des paramètres soient prédéfinies, vous pouvez utiliser les `Enum` de Python.
+Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, « pensant » qu'il reçoit un paramètre `user_id` avec la valeur « me ».
-### Création d'un `Enum`
+De même, vous ne pouvez pas redéfinir un chemin d'accès :
-Importez `Enum` et créez une sous-classe qui hérite de `str` et `Enum`.
+{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
-En héritant de `str` la documentation sera capable de savoir que les valeurs doivent être de type `string` et pourra donc afficher cette `Enum` correctement.
+Le premier sera toujours utilisé puisque le chemin correspond en premier.
-Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs autorisées pour cette énumération.
+## Valeurs prédéfinies { #predefined-values }
-{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *}
+Si vous avez un *chemin d'accès* qui reçoit un *paramètre de chemin*, mais que vous voulez que les valeurs possibles de ce *paramètre de chemin* soient prédéfinies, vous pouvez utiliser une `Enum` Python standard.
-/// info
+### Créer une classe `Enum` { #create-an-enum-class }
-Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4.
+Importez `Enum` et créez une sous-classe qui hérite de `str` et de `Enum`.
-///
+En héritant de `str`, la documentation de l'API saura que les valeurs doivent être de type `string` et pourra donc s'afficher correctement.
+
+Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs valides disponibles :
+
+{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
/// tip | Astuce
-Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning.
+Si vous vous demandez, « AlexNet », « ResNet » et « LeNet » sont juste des noms de modèles de Machine Learning.
///
-### Déclarer un paramètre de chemin
+### Déclarer un paramètre de chemin { #declare-a-path-parameter }
-Créez ensuite un *paramètre de chemin* avec une annotation de type désignant l'énumération créée précédemment (`ModelName`) :
+Créez ensuite un *paramètre de chemin* avec une annotation de type utilisant la classe d'énumération que vous avez créée (`ModelName`) :
-{* ../../docs_src/path_params/tutorial005.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
-### Documentation
+### Consulter la documentation { #check-the-docs }
-Les valeurs disponibles pour le *paramètre de chemin* sont bien prédéfinies, la documentation les affiche correctement :
+Comme les valeurs disponibles pour le *paramètre de chemin* sont prédéfinies, la documentation interactive peut les afficher clairement :
-### Manipuler les *énumérations* Python
+### Travailler avec les *énumérations* Python { #working-with-python-enumerations }
-La valeur du *paramètre de chemin* sera un des "membres" de l'énumération.
+La valeur du *paramètre de chemin* sera un *membre d'énumération*.
-#### Comparer les *membres d'énumération*
+#### Comparer des *membres d'énumération* { #compare-enumeration-members }
-Vous pouvez comparer ce paramètre avec les membres de votre énumération `ModelName` :
+Vous pouvez le comparer avec le *membre d'énumération* dans votre enum `ModelName` :
-{* ../../docs_src/path_params/tutorial005.py hl[17] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[17] *}
-#### Récupérer la *valeur de l'énumération*
+#### Obtenir la *valeur de l'énumération* { #get-the-enumeration-value }
-Vous pouvez obtenir la valeur réel d'un membre (une chaîne de caractères ici), avec `model_name.value`, ou en général, `votre_membre_d'enum.value` :
+Vous pouvez obtenir la valeur réelle (une `str` dans ce cas) avec `model_name.value`, ou en général, `votre_membre_d_enum.value` :
-{* ../../docs_src/path_params/tutorial005.py hl[20] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[20] *}
/// tip | Astuce
-Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`.
+Vous pouvez aussi accéder à la valeur « lenet » avec `ModelName.lenet.value`.
///
-#### Retourner des *membres d'énumération*
+#### Retourner des *membres d'énumération* { #return-enumeration-members }
-Vous pouvez retourner des *membres d'énumération* dans vos *fonctions de chemin*, même imbriquée dans un JSON (e.g. un `dict`).
+Vous pouvez retourner des *membres d'énumération* depuis votre *chemin d'accès*, même imbriqués dans un corps JSON (par ex. un `dict`).
-Ils seront convertis vers leurs valeurs correspondantes (chaînes de caractères ici) avant d'être transmis au client :
+Ils seront convertis vers leurs valeurs correspondantes (des chaînes de caractères ici) avant d'être renvoyés au client :
-{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[18,21,23] *}
-Le client recevra une réponse JSON comme celle-ci :
+Dans votre client, vous recevrez une réponse JSON comme :
```JSON
{
@@ -208,53 +199,53 @@ Le client recevra une réponse JSON comme celle-ci :
}
```
-## Paramètres de chemin contenant des chemins
+## Paramètres de chemin contenant des chemins { #path-parameters-containing-paths }
-Disons que vous avez une *fonction de chemin* liée au chemin `/files/{file_path}`.
+Disons que vous avez un *chemin d'accès* avec un chemin `/files/{file_path}`.
-Mais que `file_path` lui-même doit contenir un *chemin*, comme `home/johndoe/myfile.txt` par exemple.
+Mais vous avez besoin que `file_path` lui-même contienne un *chemin*, comme `home/johndoe/myfile.txt`.
-Donc, l'URL pour ce fichier pourrait être : `/files/home/johndoe/myfile.txt`.
+Ainsi, l'URL pour ce fichier serait : `/files/home/johndoe/myfile.txt`.
-### Support d'OpenAPI
+### Support d'OpenAPI { #openapi-support }
-OpenAPI ne supporte pas de manière de déclarer un paramètre de chemin contenant un *chemin*, cela pouvant causer des scénarios difficiles à tester et définir.
+OpenAPI ne prend pas en charge une manière de déclarer un *paramètre de chemin* contenant un *chemin* à l'intérieur, car cela peut conduire à des scénarios difficiles à tester et à définir.
-Néanmoins, cela reste faisable dans **FastAPI**, via les outils internes de Starlette.
+Néanmoins, vous pouvez toujours le faire dans **FastAPI**, en utilisant l'un des outils internes de Starlette.
-Et la documentation fonctionne quand même, bien qu'aucune section ne soit ajoutée pour dire que la paramètre devrait contenir un *chemin*.
+Et la documentation fonctionnera quand même, même si aucune indication supplémentaire ne sera ajoutée pour dire que le paramètre doit contenir un chemin.
-### Convertisseur de *chemin*
+### Convertisseur de chemin { #path-convertor }
-En utilisant une option de Starlette directement, vous pouvez déclarer un *paramètre de chemin* contenant un *chemin* avec une URL comme :
+En utilisant une option directement depuis Starlette, vous pouvez déclarer un *paramètre de chemin* contenant un *chemin* avec une URL comme :
```
/files/{file_path:path}
```
-Dans ce cas, le nom du paramètre est `file_path`, et la dernière partie, `:path`, indique à Starlette que le paramètre devrait correspondre à un *chemin*.
+Dans ce cas, le nom du paramètre est `file_path`, et la dernière partie, `:path`, indique que le paramètre doit correspondre à n'importe quel *chemin*.
-Vous pouvez donc l'utilisez comme tel :
+Vous pouvez donc l'utiliser ainsi :
-{* ../../docs_src/path_params/tutorial004.py hl[6] *}
+{* ../../docs_src/path_params/tutorial004_py39.py hl[6] *}
/// tip | Astuce
-Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`).
+Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash initial (`/`).
Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`.
///
-## Récapitulatif
+## Récapitulatif { #recap }
-Avec **FastAPI**, en utilisant les déclarations de type rapides, intuitives et standards de Python, vous bénéficiez de :
+Avec **FastAPI**, en utilisant des déclarations de type Python courtes, intuitives et standard, vous obtenez :
-* Support de l'éditeur : vérification d'erreurs, auto-complétion, etc.
-* "Parsing" de données.
-* Validation de données.
-* Annotations d'API et documentation automatique.
+* Support de l'éditeur : vérifications d'erreurs, autocomplétion, etc.
+* Données « parsing »
+* Validation de données
+* Annotations d'API et documentation automatique
-Et vous n'avez besoin de le déclarer qu'une fois.
+Et vous n'avez besoin de les déclarer qu'une seule fois.
-C'est probablement l'avantage visible principal de **FastAPI** comparé aux autres *frameworks* (outre les performances pures).
+C'est probablement l'avantage visible principal de **FastAPI** comparé aux autres frameworks (outre les performances pures).
diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md
index c54c0c717..544d10328 100644
--- a/docs/fr/docs/tutorial/query-params-str-validations.md
+++ b/docs/fr/docs/tutorial/query-params-str-validations.md
@@ -1,166 +1,273 @@
-# Paramètres de requête et validations de chaînes de caractères
+# Paramètres de requête et validations de chaînes de caractères { #query-parameters-and-string-validations }
-**FastAPI** vous permet de déclarer des informations et des validateurs additionnels pour vos paramètres de requêtes.
+**FastAPI** vous permet de déclarer des informations et des validations supplémentaires pour vos paramètres.
-Commençons avec cette application pour exemple :
+Prenons cette application comme exemple :
-{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *}
-Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis.
+Le paramètre de requête `q` est de type `str | None`, cela signifie qu’il est de type `str` mais peut aussi être `None`, et en effet, la valeur par défaut est `None`, donc FastAPI saura qu’il n’est pas requis.
-/// note
+/// note | Remarque
-**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`.
+FastAPI saura que la valeur de `q` n’est pas requise grâce à la valeur par défaut `= None`.
-Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs.
+Avoir `str | None` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs.
///
-## Validation additionnelle
+## Validation additionnelle { #additional-validation }
-Nous allons imposer que bien que `q` soit un paramètre optionnel, dès qu'il est fourni, **sa longueur n'excède pas 50 caractères**.
+Nous allons imposer que, même si `q` est optionnel, dès qu’il est fourni, **sa longueur n’excède pas 50 caractères**.
-## Importer `Query`
+### Importer `Query` et `Annotated` { #import-query-and-annotated }
-Pour cela, importez d'abord `Query` depuis `fastapi` :
+Pour ce faire, importez d’abord :
-{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *}
+- `Query` depuis `fastapi`
+- `Annotated` depuis `typing`
-## Utiliser `Query` comme valeur par défaut
+{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[1,3] *}
-Construisez ensuite la valeur par défaut de votre paramètre avec `Query`, en choisissant 50 comme `max_length` :
+/// info
-{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *}
+FastAPI a ajouté la prise en charge de `Annotated` (et a commencé à le recommander) dans la version 0.95.0.
-Comme nous devons remplacer la valeur par défaut `None` dans la fonction par `Query()`, nous pouvons maintenant définir la valeur par défaut avec le paramètre `Query(default=None)`, il sert le même objectif qui est de définir cette valeur par défaut.
+Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d’utiliser `Annotated`.
-Donc :
+Assurez-vous de [mettre à niveau la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} vers au moins 0.95.1 avant d’utiliser `Annotated`.
+
+///
+
+## Utiliser `Annotated` dans le type pour le paramètre `q` { #use-annotated-in-the-type-for-the-q-parameter }
+
+Vous vous souvenez que je vous ai dit plus tôt que `Annotated` peut être utilisé pour ajouter des métadonnées à vos paramètres dans l’[Introduction aux types Python](../python-types.md#type-hints-with-metadata-annotations){.internal-link target=_blank} ?
+
+C’est le moment de l’utiliser avec FastAPI. 🚀
+
+Nous avions cette annotation de type :
+
+//// tab | Python 3.10+
```Python
-q: Union[str, None] = Query(default=None)
+q: str | None = None
```
-... rend le paramètre optionnel, et est donc équivalent à :
+////
+
+//// tab | Python 3.9+
```Python
q: Union[str, None] = None
```
-Mais déclare explicitement `q` comme étant un paramètre de requête.
+////
-/// info
+Ce que nous allons faire, c’est l’englober avec `Annotated`, de sorte que cela devienne :
-Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est :
+//// tab | Python 3.10+
```Python
-= None
+q: Annotated[str | None] = None
```
-ou :
+////
+
+//// tab | Python 3.9+
```Python
-= Query(None)
+q: Annotated[Union[str, None]] = None
```
-et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**.
+////
-Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support.
+Les deux versions signifient la même chose, `q` est un paramètre qui peut être une `str` ou `None`, et par défaut, c’est `None`.
+
+Passons maintenant aux choses amusantes. 🎉
+
+## Ajouter `Query` à `Annotated` dans le paramètre `q` { #add-query-to-annotated-in-the-q-parameter }
+
+Maintenant que nous avons cet `Annotated` dans lequel nous pouvons mettre plus d’informations (dans ce cas une validation supplémentaire), ajoutez `Query` à l’intérieur de `Annotated`, et définissez le paramètre `max_length` à `50` :
+
+{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *}
+
+Remarquez que la valeur par défaut est toujours `None`, donc le paramètre est toujours optionnel.
+
+Mais maintenant, avec `Query(max_length=50)` à l’intérieur de `Annotated`, nous indiquons à FastAPI que nous voulons **une validation supplémentaire** pour cette valeur, nous voulons qu’elle ait au maximum 50 caractères. 😎
+
+/// tip | Astuce
+
+Ici nous utilisons `Query()` parce qu’il s’agit d’un **paramètre de requête**. Plus tard nous verrons d’autres comme `Path()`, `Body()`, `Header()` et `Cookie()`, qui acceptent également les mêmes arguments que `Query()`.
///
-Ensuite, nous pouvons passer d'autres paramètres à `Query`. Dans cet exemple, le paramètre `max_length` qui s'applique aux chaînes de caractères :
+FastAPI va maintenant :
-```Python
-q: Union[str, None] = Query(default=None, max_length=50)
-```
+- **Valider** les données en s’assurant que la longueur maximale est de 50 caractères
+- Afficher une **erreur claire** au client quand les données ne sont pas valides
+- **Documenter** le paramètre dans la *chemin d'accès* du schéma OpenAPI (il apparaîtra donc dans l’**interface de documentation automatique**)
-Cela va valider les données, montrer une erreur claire si ces dernières ne sont pas valides, et documenter le paramètre dans le schéma `OpenAPI` de cette *path operation*.
+## Alternative (ancienne) : `Query` comme valeur par défaut { #alternative-old-query-as-the-default-value }
-## Rajouter plus de validation
+Les versions précédentes de FastAPI (avant 0.95.0) exigeaient d’utiliser `Query` comme valeur par défaut de votre paramètre, au lieu de le mettre dans `Annotated`. Il y a de fortes chances que vous voyiez du code qui l’utilise encore, je vais donc vous l’expliquer.
-Vous pouvez aussi rajouter un second paramètre `min_length` :
+/// tip | Astuce
-{* ../../docs_src/query_params_str_validations/tutorial003.py hl[9] *}
-
-## Ajouter des validations par expressions régulières
-
-On peut définir une expression régulière à laquelle le paramètre doit correspondre :
-
-{* ../../docs_src/query_params_str_validations/tutorial004.py hl[10] *}
-
-Cette expression régulière vérifie que la valeur passée comme paramètre :
-
-* `^` : commence avec les caractères qui suivent, avec aucun caractère avant ceux-là.
-* `fixedquery` : a pour valeur exacte `fixedquery`.
-* `$` : se termine directement ensuite, n'a pas d'autres caractères après `fixedquery`.
-
-Si vous vous sentez perdu avec le concept d'**expression régulière**, pas d'inquiétudes. Il s'agit d'une notion difficile pour beaucoup, et l'on peut déjà réussir à faire beaucoup sans jamais avoir à les manipuler.
-
-Mais si vous décidez d'apprendre à les utiliser, sachez qu'ensuite vous pouvez les utiliser directement dans **FastAPI**.
-
-## Valeurs par défaut
-
-De la même façon que vous pouvez passer `None` comme premier argument pour l'utiliser comme valeur par défaut, vous pouvez passer d'autres valeurs.
-
-Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de `3`, et une valeur par défaut étant `"fixedquery"` :
-
-{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *}
-
-/// note | Rappel
-
-Avoir une valeur par défaut rend le paramètre optionnel.
+Pour du nouveau code et dès que possible, utilisez `Annotated` comme expliqué ci-dessus. Il y a de multiples avantages (expliqués ci-dessous) et aucun inconvénient. 🍰
///
-## Rendre ce paramètre requis
+Voici comment vous utiliseriez `Query()` comme valeur par défaut du paramètre de votre fonction, en définissant le paramètre `max_length` à 50 :
-Quand on ne déclare ni validation, ni métadonnée, on peut rendre le paramètre `q` requis en ne lui déclarant juste aucune valeur par défaut :
+{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *}
+
+Comme, dans ce cas (sans utiliser `Annotated`), nous devons remplacer la valeur par défaut `None` dans la fonction par `Query()`, nous devons maintenant définir la valeur par défaut avec le paramètre `Query(default=None)`, cela sert le même objectif de définir cette valeur par défaut (au moins pour FastAPI).
+
+Donc :
+
+```Python
+q: str | None = Query(default=None)
+```
+
+... rend le paramètre optionnel, avec une valeur par défaut de `None`, comme :
+
+```Python
+q: str | None = None
+```
+
+Mais la version avec `Query` le déclare explicitement comme étant un paramètre de requête.
+
+Ensuite, nous pouvons passer plus de paramètres à `Query`. Dans ce cas, le paramètre `max_length` qui s’applique aux chaînes de caractères :
+
+```Python
+q: str | None = Query(default=None, max_length=50)
+```
+
+Cela validera les données, affichera une erreur claire lorsque les données ne sont pas valides et documentera le paramètre dans la *chemin d'accès* du schéma OpenAPI.
+
+### `Query` comme valeur par défaut ou dans `Annotated` { #query-as-the-default-value-or-in-annotated }
+
+Gardez à l’esprit qu’en utilisant `Query` à l’intérieur de `Annotated`, vous ne pouvez pas utiliser le paramètre `default` de `Query`.
+
+Utilisez à la place la valeur par défaut réelle du paramètre de fonction. Sinon, ce serait incohérent.
+
+Par exemple, ceci n’est pas autorisé :
+
+```Python
+q: Annotated[str, Query(default="rick")] = "morty"
+```
+
+... parce qu’il n’est pas clair si la valeur par défaut doit être « rick » ou « morty ».
+
+Donc, vous utiliseriez (de préférence) :
+
+```Python
+q: Annotated[str, Query()] = "rick"
+```
+
+... ou dans des bases de code plus anciennes, vous trouverez :
+
+```Python
+q: str = Query(default="rick")
+```
+
+### Avantages de `Annotated` { #advantages-of-annotated }
+
+**L’utilisation de `Annotated` est recommandée** plutôt que la valeur par défaut dans les paramètres de fonction, c’est **mieux** pour plusieurs raisons. 🤓
+
+La valeur **par défaut** du **paramètre de fonction** est la **vraie valeur par défaut**, c’est plus intuitif en Python en général. 😌
+
+Vous pouvez **appeler** cette même fonction dans **d’autres endroits** sans FastAPI, et elle **fonctionnera comme prévu**. S’il y a un paramètre **requis** (sans valeur par défaut), votre **éditeur** vous le signalera avec une erreur, **Python** se plaindra aussi si vous l’exécutez sans passer le paramètre requis.
+
+Quand vous n’utilisez pas `Annotated` et utilisez à la place l’**ancienne** méthode avec la **valeur par défaut**, si vous appelez cette fonction sans FastAPI dans **d’autres endroits**, vous devez **penser** à passer les arguments à la fonction pour qu’elle fonctionne correctement, sinon les valeurs seront différentes de ce que vous attendez (par ex. `QueryInfo` ou quelque chose de similaire au lieu d’une `str`). Et votre éditeur ne se plaindra pas, et Python ne se plaindra pas en exécutant cette fonction, seulement quand les opérations internes échoueront.
+
+Comme `Annotated` peut avoir plus d’une annotation de métadonnées, vous pouvez maintenant même utiliser la même fonction avec d’autres outils, comme Typer. 🚀
+
+## Ajouter plus de validations { #add-more-validations }
+
+Vous pouvez également ajouter un paramètre `min_length` :
+
+{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *}
+
+## Ajouter des expressions régulières { #add-regular-expressions }
+
+Vous pouvez définir un `pattern` d’expression régulière auquel le paramètre doit correspondre :
+
+{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
+
+Ce pattern d’expression régulière spécifique vérifie que la valeur reçue pour le paramètre :
+
+- `^` : commence avec les caractères qui suivent, n’a pas de caractères avant.
+- `fixedquery` : a exactement la valeur `fixedquery`.
+- `$` : se termine là, n’a pas d’autres caractères après `fixedquery`.
+
+Si vous vous sentez perdu avec toutes ces idées d’**« expression régulière »**, pas d’inquiétude. C’est un sujet difficile pour beaucoup. Vous pouvez déjà faire beaucoup de choses sans avoir besoin d’expressions régulières.
+
+Désormais, vous savez que, lorsque vous en aurez besoin, vous pourrez les utiliser dans **FastAPI**.
+
+## Valeurs par défaut { #default-values }
+
+Vous pouvez, bien sûr, utiliser des valeurs par défaut autres que `None`.
+
+Disons que vous voulez déclarer le paramètre de requête `q` avec un `min_length` de `3`, et avec une valeur par défaut de « fixedquery » :
+
+{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *}
+
+/// note | Remarque
+
+Avoir une valeur par défaut de n’importe quel type, y compris `None`, rend le paramètre optionnel (non requis).
+
+///
+
+## Paramètres requis { #required-parameters }
+
+Quand nous n’avons pas besoin de déclarer plus de validations ou de métadonnées, nous pouvons rendre le paramètre de requête `q` requis en n’indiquant simplement pas de valeur par défaut, comme :
```Python
q: str
```
-à la place de :
+au lieu de :
```Python
-q: Union[str, None] = None
+q: str | None = None
```
-Mais maintenant, on déclare `q` avec `Query`, comme ceci :
+Mais maintenant nous le déclarons avec `Query`, par exemple ainsi :
```Python
-q: Union[str, None] = Query(default=None, min_length=3)
+q: Annotated[str | None, Query(min_length=3)] = None
```
-Donc pour déclarer une valeur comme requise tout en utilisant `Query`, il faut utiliser `...` comme premier argument :
+Donc, lorsque vous avez besoin de déclarer une valeur comme requise tout en utilisant `Query`, vous pouvez simplement ne pas déclarer de valeur par défaut :
-{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *}
+{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *}
-/// info
+### Requis, peut valoir `None` { #required-can-be-none }
-Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis".
+Vous pouvez déclarer qu’un paramètre accepte `None`, mais qu’il est tout de même requis. Cela obligerait les clients à envoyer une valeur, même si la valeur est `None`.
-///
+Pour ce faire, vous pouvez déclarer que `None` est un type valide tout en ne déclarant pas de valeur par défaut :
-Cela indiquera à **FastAPI** que la présence de ce paramètre est obligatoire.
+{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *}
-## Liste de paramètres / valeurs multiples via Query
+## Liste de paramètres de requête / valeurs multiples { #query-parameter-list-multiple-values }
-Quand on définit un paramètre de requête explicitement avec `Query` on peut aussi déclarer qu'il reçoit une liste de valeur, ou des "valeurs multiples".
+Quand vous définissez un paramètre de requête explicitement avec `Query`, vous pouvez aussi déclarer qu’il reçoit une liste de valeurs, autrement dit, qu’il reçoit des valeurs multiples.
-Par exemple, pour déclarer un paramètre de requête `q` qui peut apparaître plusieurs fois dans une URL, on écrit :
+Par exemple, pour déclarer un paramètre de requête `q` qui peut apparaître plusieurs fois dans l’URL, vous pouvez écrire :
-{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *}
-Ce qui fait qu'avec une URL comme :
+Ensuite, avec une URL comme :
```
http://localhost:8000/items/?q=foo&q=bar
```
-vous recevriez les valeurs des multiples paramètres de requête `q` (`foo` et `bar`) dans une `list` Python au sein de votre fonction de **path operation**, dans le paramètre de fonction `q`.
+vous recevriez les valeurs des multiples paramètres de requête `q` (`foo` et `bar`) dans une `list` Python à l’intérieur de votre fonction de *chemin d'accès*, dans le *paramètre de fonction* `q`.
-Donc la réponse de cette URL serait :
+Donc, la réponse pour cette URL serait :
```JSON
{
@@ -173,19 +280,19 @@ Donc la réponse de cette URL serait :
/// tip | Astuce
-Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête.
+Pour déclarer un paramètre de requête avec un type `list`, comme dans l’exemple ci-dessus, vous devez explicitement utiliser `Query`, sinon il serait interprété comme faisant partie du corps de la requête.
///
-La documentation sera donc mise à jour automatiquement pour autoriser plusieurs valeurs :
+L’interface de documentation interactive de l’API sera mise à jour en conséquence, pour autoriser plusieurs valeurs :
-### Combiner liste de paramètres et valeurs par défaut
+### Liste de paramètres de requête / valeurs multiples avec valeurs par défaut { #query-parameter-list-multiple-values-with-defaults }
-Et l'on peut aussi définir une liste de valeurs par défaut si aucune n'est fournie :
+Vous pouvez également définir une `list` de valeurs par défaut si aucune n’est fournie :
-{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *}
Si vous allez à :
@@ -193,9 +300,7 @@ Si vous allez à :
http://localhost:8000/items/
```
-la valeur par défaut de `q` sera : `["foo", "bar"]`
-
-et la réponse sera :
+la valeur par défaut de `q` sera : `["foo", "bar"]` et votre réponse sera :
```JSON
{
@@ -206,93 +311,163 @@ et la réponse sera :
}
```
-#### Utiliser `list`
+#### Utiliser simplement `list` { #using-just-list }
-Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` :
+Vous pouvez aussi utiliser `list` directement au lieu de `list[str]` :
-{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *}
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}
-/// note
+/// note | Remarque
-Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste.
+Gardez à l’esprit que dans ce cas, FastAPI ne vérifiera pas le contenu de la liste.
-Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification.
+Par exemple, `list[int]` vérifierait (et documenterait) que le contenu de la liste est composé d’entiers. Mais un simple `list` ne le ferait pas.
///
-## Déclarer des métadonnées supplémentaires
+## Déclarer plus de métadonnées { #declare-more-metadata }
-On peut aussi ajouter plus d'informations sur le paramètre.
+Vous pouvez ajouter plus d’informations à propos du paramètre.
-Ces informations seront incluses dans le schéma `OpenAPI` généré et utilisées par la documentation interactive ou les outils externes utilisés.
+Ces informations seront incluses dans l’OpenAPI généré et utilisées par les interfaces de documentation et les outils externes.
-/// note
+/// note | Remarque
-Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI.
+Gardez à l’esprit que différents outils peuvent avoir des niveaux de prise en charge d’OpenAPI différents.
-Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées.
+Certains d’entre eux pourraient ne pas encore afficher toutes les informations supplémentaires déclarées, bien que, dans la plupart des cas, la fonctionnalité manquante soit déjà prévue au développement.
///
Vous pouvez ajouter un `title` :
-{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *}
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
Et une `description` :
-{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *}
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
-## Alias de paramètres
+## Paramètres avec alias { #alias-parameters }
-Imaginez que vous vouliez que votre paramètre se nomme `item-query`.
+Imaginez que vous vouliez que le paramètre soit `item-query`.
-Comme dans la requête :
+Comme dans :
```
http://127.0.0.1:8000/items/?item-query=foobaritems
```
-Mais `item-query` n'est pas un nom de variable valide en Python.
+Mais `item-query` n’est pas un nom de variable Python valide.
-Le nom le plus proche serait `item_query`.
+Le plus proche serait `item_query`.
-Mais vous avez vraiment envie que ce soit exactement `item-query`...
+Mais vous avez quand même besoin que ce soit exactement `item-query` ...
-Pour cela vous pouvez déclarer un `alias`, et cet alias est ce qui sera utilisé pour trouver la valeur du paramètre :
+Vous pouvez alors déclarer un `alias`, et cet alias sera utilisé pour trouver la valeur du paramètre :
-{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
-## Déprécier des paramètres
+## Déprécier des paramètres { #deprecating-parameters }
-Disons que vous ne vouliez plus utiliser ce paramètre désormais.
+Disons que vous n’aimez plus ce paramètre.
-Il faut qu'il continue à exister pendant un certain temps car vos clients l'utilisent, mais vous voulez que la documentation mentionne clairement que ce paramètre est déprécié.
+Vous devez le laisser là quelque temps car des clients l’utilisent, mais vous voulez que les documents l’affichent clairement comme déprécié.
-On utilise alors l'argument `deprecated=True` de `Query` :
+Passez alors le paramètre `deprecated=True` à `Query` :
-{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *}
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
-La documentation le présentera comme il suit :
+Les documents l’afficheront ainsi :
-## Pour résumer
+## Exclure des paramètres d’OpenAPI { #exclude-parameters-from-openapi }
-Il est possible d'ajouter des validateurs et métadonnées pour vos paramètres.
+Pour exclure un paramètre de requête du schéma OpenAPI généré (et donc, des systèmes de documentation automatiques), définissez le paramètre `include_in_schema` de `Query` à `False` :
-Validateurs et métadonnées génériques:
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
-* `alias`
-* `title`
-* `description`
-* `deprecated`
+## Validation personnalisée { #custom-validation }
-Validateurs spécifiques aux chaînes de caractères :
+Il peut y avoir des cas où vous devez faire une **validation personnalisée** qui ne peut pas être réalisée avec les paramètres montrés ci-dessus.
-* `min_length`
-* `max_length`
-* `regex`
+Dans ces cas, vous pouvez utiliser une **fonction de validation personnalisée** qui est appliquée après la validation normale (par ex. après avoir validé que la valeur est une `str`).
-Parmi ces exemples, vous avez pu voir comment déclarer des validateurs pour les chaînes de caractères.
+Vous pouvez y parvenir en utilisant `AfterValidator` de Pydantic à l’intérieur de `Annotated`.
-Dans les prochains chapitres, vous verrez comment déclarer des validateurs pour d'autres types, comme les nombres.
+/// tip | Astuce
+
+Pydantic a aussi `BeforeValidator` et d’autres. 🤓
+
+///
+
+Par exemple, ce validateur personnalisé vérifie que l’ID d’item commence par `isbn-` pour un numéro de livre ISBN ou par `imdb-` pour un ID d’URL de film IMDB :
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info
+
+C’est disponible avec Pydantic version 2 ou supérieure. 😎
+
+///
+
+/// tip | Astuce
+
+Si vous devez faire un type de validation qui nécessite de communiquer avec un **composant externe**, comme une base de données ou une autre API, vous devez plutôt utiliser les **Dépendances de FastAPI**, vous en apprendrez davantage plus tard.
+
+Ces validateurs personnalisés sont destinés aux éléments qui peuvent être vérifiés **uniquement** avec les **mêmes données** fournies dans la requête.
+
+///
+
+### Comprendre ce code { #understand-that-code }
+
+Le point important est simplement d’utiliser **`AfterValidator` avec une fonction à l’intérieur de `Annotated`**. N’hésitez pas à passer cette partie. 🤸
+
+---
+
+Mais si vous êtes curieux de cet exemple de code spécifique et que vous êtes toujours partant, voici quelques détails supplémentaires.
+
+#### Chaîne avec `value.startswith()` { #string-with-value-startswith }
+
+Avez-vous remarqué ? Une chaîne utilisant `value.startswith()` peut prendre un tuple, et elle vérifiera chaque valeur du tuple :
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### Un élément aléatoire { #a-random-item }
+
+Avec `data.items()` nous obtenons un objet itérable avec des tuples contenant la clé et la valeur pour chaque élément du dictionnaire.
+
+Nous convertissons cet objet itérable en une `list` propre avec `list(data.items())`.
+
+Ensuite, avec `random.choice()` nous pouvons obtenir une **valeur aléatoire** depuis la liste, nous obtenons donc un tuple `(id, name)`. Ce sera quelque chose comme `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
+
+Puis nous **affectons ces deux valeurs** du tuple aux variables `id` et `name`.
+
+Ainsi, si l’utilisateur n’a pas fourni d’ID d’item, il recevra quand même une suggestion aléatoire.
+
+... nous faisons tout cela en **une seule ligne simple**. 🤯 Vous n’adorez pas Python ? 🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## Récapitulatif { #recap }
+
+Vous pouvez déclarer des validations et des métadonnées supplémentaires pour vos paramètres.
+
+Validations et métadonnées génériques :
+
+- `alias`
+- `title`
+- `description`
+- `deprecated`
+
+Validations spécifiques aux chaînes :
+
+- `min_length`
+- `max_length`
+- `pattern`
+
+Validations personnalisées avec `AfterValidator`.
+
+Dans ces exemples, vous avez vu comment déclarer des validations pour des valeurs `str`.
+
+Voyez les prochains chapitres pour apprendre à déclarer des validations pour d’autres types, comme les nombres.
diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md
index b87c26c78..1a4880ced 100644
--- a/docs/fr/docs/tutorial/query-params.md
+++ b/docs/fr/docs/tutorial/query-params.md
@@ -1,10 +1,10 @@
-# Paramètres de requête
+# Paramètres de requête { #query-parameters }
-Quand vous déclarez des paramètres dans votre fonction de chemin qui ne font pas partie des paramètres indiqués dans le chemin associé, ces paramètres sont automatiquement considérés comme des paramètres de "requête".
+Quand vous déclarez d'autres paramètres de fonction qui ne font pas partie des paramètres de chemin, ils sont automatiquement interprétés comme des paramètres de « query ».
-{* ../../docs_src/query_params/tutorial001.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
-La partie appelée requête (ou **query**) dans une URL est l'ensemble des paires clés-valeurs placées après le `?` , séparées par des `&`.
+La query est l'ensemble des paires clé-valeur placées après le `?` dans une URL, séparées par des caractères `&`.
Par exemple, dans l'URL :
@@ -12,27 +12,27 @@ Par exemple, dans l'URL :
http://127.0.0.1:8000/items/?skip=0&limit=10
```
-...les paramètres de requête sont :
+... les paramètres de requête sont :
-* `skip` : avec une valeur de`0`
+* `skip` : avec une valeur de `0`
* `limit` : avec une valeur de `10`
-Faisant partie de l'URL, ces valeurs sont des chaînes de caractères (`str`).
+Comme ils font partie de l'URL, ce sont « naturellement » des chaînes de caractères.
-Mais quand on les déclare avec des types Python (dans l'exemple précédent, en tant qu'`int`), elles sont converties dans les types renseignés.
+Mais lorsque vous les déclarez avec des types Python (dans l'exemple ci-dessus, en tant que `int`), ils sont convertis vers ce type et validés par rapport à celui-ci.
-Toutes les fonctionnalités qui s'appliquent aux paramètres de chemin s'appliquent aussi aux paramètres de requête :
+Tous les mêmes processus qui s'appliquaient aux paramètres de chemin s'appliquent aussi aux paramètres de requête :
-* Support de l'éditeur : vérification d'erreurs, auto-complétion, etc.
-* "Parsing" de données.
-* Validation de données.
-* Annotations d'API et documentation automatique.
+* Prise en charge de l'éditeur (évidemment)
+* « parsing » des données
+* Validation des données
+* Documentation automatique
-## Valeurs par défaut
+## Valeurs par défaut { #defaults }
-Les paramètres de requête ne sont pas une partie fixe d'un chemin, ils peuvent être optionnels et avoir des valeurs par défaut.
+Comme les paramètres de requête ne sont pas une partie fixe d'un chemin, ils peuvent être optionnels et avoir des valeurs par défaut.
-Dans l'exemple ci-dessus, ils ont des valeurs par défaut qui sont `skip=0` et `limit=10`.
+Dans l'exemple ci-dessus, ils ont des valeurs par défaut `skip=0` et `limit=10`.
Donc, accéder à l'URL :
@@ -40,52 +40,44 @@ Donc, accéder à l'URL :
http://127.0.0.1:8000/items/
```
-serait équivalent à accéder à l'URL :
+serait équivalent à accéder à :
```
http://127.0.0.1:8000/items/?skip=0&limit=10
```
-Mais si vous accédez à, par exemple :
+Mais si vous accédez, par exemple, à :
```
http://127.0.0.1:8000/items/?skip=20
```
-Les valeurs des paramètres de votre fonction seront :
+Les valeurs des paramètres dans votre fonction seront :
-* `skip=20` : car c'est la valeur déclarée dans l'URL.
-* `limit=10` : car `limit` n'a pas été déclaré dans l'URL, et que la valeur par défaut était `10`.
+* `skip=20` : car vous l'avez défini dans l'URL
+* `limit=10` : car c'était la valeur par défaut
-## Paramètres optionnels
+## Paramètres optionnels { #optional-parameters }
-De la même façon, vous pouvez définir des paramètres de requête comme optionnels, en leur donnant comme valeur par défaut `None` :
+De la même façon, vous pouvez déclarer des paramètres de requête optionnels, en définissant leur valeur par défaut à `None` :
-{* ../../docs_src/query_params/tutorial002.py hl[9] *}
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
-Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut.
+Dans ce cas, le paramètre de fonction `q` sera optionnel et vaudra `None` par défaut.
-/// check | Remarque
+/// check | Vérifications
-On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête.
+Notez également que FastAPI est suffisamment intelligent pour remarquer que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` ne l'est pas, c'est donc un paramètre de requête.
///
-/// note
+## Conversion des types des paramètres de requête { #query-parameter-type-conversion }
-**FastAPI** saura que `q` est optionnel grâce au `=None`.
+Vous pouvez aussi déclarer des types `bool`, ils seront convertis :
-Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code.
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
-///
-
-## Conversion des types des paramètres de requête
-
-Vous pouvez aussi déclarer des paramètres de requête comme booléens (`bool`), **FastAPI** les convertira :
-
-{* ../../docs_src/query_params/tutorial003.py hl[9] *}
-
-Avec ce code, en allant sur :
+Dans ce cas, si vous allez sur :
```
http://127.0.0.1:8000/items/foo?short=1
@@ -115,60 +107,61 @@ ou
http://127.0.0.1:8000/items/foo?short=yes
```
-ou n'importe quelle autre variation de casse (tout en majuscules, uniquement la première lettre en majuscule, etc.), votre fonction considérera le paramètre `short` comme ayant une valeur booléenne à `True`. Sinon la valeur sera à `False`.
+ou n'importe quelle autre variation de casse (tout en majuscules, uniquement la première lettre en majuscule, etc.), votre fonction verra le paramètre `short` avec une valeur `bool` à `True`. Sinon la valeur sera à `False`.
-## Multiples paramètres de chemin et de requête
+## Multiples paramètres de chemin et de requête { #multiple-path-and-query-parameters }
-Vous pouvez déclarer plusieurs paramètres de chemin et paramètres de requête dans la même fonction, **FastAPI** saura comment les gérer.
+Vous pouvez déclarer plusieurs paramètres de chemin et paramètres de requête en même temps, FastAPI sait lequel est lequel.
Et vous n'avez pas besoin de les déclarer dans un ordre spécifique.
-Ils seront détectés par leurs noms :
+Ils seront détectés par leur nom :
-{* ../../docs_src/query_params/tutorial004.py hl[8,10] *}
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
-## Paramètres de requête requis
+## Paramètres de requête requis { #required-query-parameters }
-Quand vous déclarez une valeur par défaut pour un paramètre qui n'est pas un paramètre de chemin (actuellement, nous n'avons vu que les paramètres de requête), alors ce paramètre n'est pas requis.
+Quand vous déclarez une valeur par défaut pour des paramètres qui ne sont pas des paramètres de chemin (pour l'instant, nous n'avons vu que les paramètres de requête), alors ils ne sont pas requis.
-Si vous ne voulez pas leur donner de valeur par défaut mais juste les rendre optionnels, utilisez `None` comme valeur par défaut.
+Si vous ne voulez pas leur donner de valeur spécifique mais simplement les rendre optionnels, définissez la valeur par défaut à `None`.
-Mais si vous voulez rendre un paramètre de requête obligatoire, vous pouvez juste ne pas y affecter de valeur par défaut :
+Mais si vous voulez rendre un paramètre de requête obligatoire, vous pouvez simplement ne déclarer aucune valeur par défaut :
-{* ../../docs_src/query_params/tutorial005.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
-Ici le paramètre `needy` est un paramètre requis (ou obligatoire) de type `str`.
+Ici, le paramètre de requête `needy` est un paramètre de requête requis de type `str`.
-Si vous ouvrez une URL comme :
+Si vous ouvrez dans votre navigateur une URL comme :
```
http://127.0.0.1:8000/items/foo-item
```
-...sans ajouter le paramètre requis `needy`, vous aurez une erreur :
+... sans ajouter le paramètre requis `needy`, vous verrez une erreur comme :
```JSON
{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
}
```
-La présence de `needy` étant nécessaire, vous auriez besoin de l'insérer dans l'URL :
+Comme `needy` est un paramètre requis, vous devez le définir dans l'URL :
```
http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
```
-...ce qui fonctionnerait :
+... cela fonctionnerait :
```JSON
{
@@ -177,18 +170,18 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
}
```
-Et bien sur, vous pouvez définir certains paramètres comme requis, certains avec des valeurs par défaut et certains entièrement optionnels :
+Et bien sûr, vous pouvez définir certains paramètres comme requis, certains avec une valeur par défaut et certains entièrement optionnels :
-{* ../../docs_src/query_params/tutorial006.py hl[10] *}
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
-Ici, on a donc 3 paramètres de requête :
+Dans ce cas, il y a 3 paramètres de requête :
-* `needy`, requis et de type `str`.
-* `skip`, un `int` avec comme valeur par défaut `0`.
+* `needy`, un `str` requis.
+* `skip`, un `int` avec une valeur par défaut de `0`.
* `limit`, un `int` optionnel.
/// tip | Astuce
-Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}.
+Vous pourriez aussi utiliser des `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#predefined-values){.internal-link target=_blank}.
///
From 2c5a844c44c053251d557ce888811ea40dea0b01 Mon Sep 17 00:00:00 2001
From: "github-actions[bot]" lt
+* XWT
+* PSGI
+
+### abbr bir açıklama verir { #the-abbr-gives-an-explanation }
+
+* cluster
+* Deep Learning
+
+### abbr tam bir ifade ve bir açıklama verir { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | Bilgi
+
+"abbr" öğelerinin "title" attribute'ları belirli talimatlara göre çevrilir.
+
+Çeviriler, LLM'nin kaldırmaması gereken kendi "abbr" öğelerini ekleyebilir. Örneğin İngilizce kelimeleri açıklamak için.
+
+`script/translate.py` içindeki genel prompt'ta `### HTML abbr elements` bölümüne bakın.
+
+////
+
+## Başlıklar { #headings }
+
+//// tab | Test
+
+### Bir web uygulaması geliştirin - bir öğretici { #develop-a-webapp-a-tutorial }
+
+Merhaba.
+
+### Type hint'ler ve -annotation'lar { #type-hints-and-annotations }
+
+Tekrar merhaba.
+
+### Super- ve subclass'lar { #super-and-subclasses }
+
+Tekrar merhaba.
+
+////
+
+//// tab | Bilgi
+
+Başlıklarla ilgili tek katı kural, LLM'nin süslü parantezler içindeki hash kısmını değiştirmemesidir; böylece link'ler bozulmaz.
+
+`script/translate.py` içindeki genel prompt'ta `### Headings` bölümüne bakın.
+
+Dile özel bazı talimatlar için örneğin `docs/de/llm-prompt.md` içindeki `### Headings` bölümüne bakın.
+
+////
+
+## Dokümanlarda kullanılan terimler { #terms-used-in-the-docs }
+
+//// tab | Test
+
+* siz
+* sizin
+
+* örn.
+* vb.
+
+* `foo` bir `int` olarak
+* `bar` bir `str` olarak
+* `baz` bir `list` olarak
+
+* Tutorial - Kullanıcı kılavuzu
+* İleri Düzey Kullanıcı Kılavuzu
+* SQLModel dokümanları
+* API dokümanları
+* otomatik dokümanlar
+
+* Veri Bilimi
+* Deep Learning
+* Machine Learning
+* Dependency Injection
+* HTTP Basic authentication
+* HTTP Digest
+* ISO formatı
+* JSON Schema standardı
+* JSON schema
+* schema tanımı
+* Password Flow
+* Mobil
+
+* deprecated
+* designed
+* invalid
+* on the fly
+* standard
+* default
+* case-sensitive
+* case-insensitive
+
+* uygulamayı serve etmek
+* sayfayı serve etmek
+
+* app
+* application
+
+* request
+* response
+* error response
+
+* path operation
+* path operation decorator
+* path operation function
+
+* body
+* request body
+* response body
+* JSON body
+* form body
+* file body
+* function body
+
+* parameter
+* body parameter
+* path parameter
+* query parameter
+* cookie parameter
+* header parameter
+* form parameter
+* function parameter
+
+* event
+* startup event
+* server'ın startup'ı
+* shutdown event
+* lifespan event
+
+* handler
+* event handler
+* exception handler
+* handle etmek
+
+* model
+* Pydantic model
+* data model
+* database model
+* form model
+* model object
+
+* class
+* base class
+* parent class
+* subclass
+* child class
+* sibling class
+* class method
+
+* header
+* headers
+* authorization header
+* `Authorization` header
+* forwarded header
+
+* dependency injection system
+* dependency
+* dependable
+* dependant
+
+* I/O bound
+* CPU bound
+* concurrency
+* parallelism
+* multiprocessing
+
+* env var
+* environment variable
+* `PATH`
+* `PATH` variable
+
+* authentication
+* authentication provider
+* authorization
+* authorization form
+* authorization provider
+* kullanıcı authenticate olur
+* sistem kullanıcıyı authenticate eder
+
+* CLI
+* command line interface
+
+* server
+* client
+
+* cloud provider
+* cloud service
+
+* geliştirme
+* geliştirme aşamaları
+
+* dict
+* dictionary
+* enumeration
+* enum
+* enum member
+
+* encoder
+* decoder
+* encode etmek
+* decode etmek
+
+* exception
+* raise etmek
+
+* expression
+* statement
+
+* frontend
+* backend
+
+* GitHub discussion
+* GitHub issue
+
+* performance
+* performance optimization
+
+* return type
+* return value
+
+* security
+* security scheme
+
+* task
+* background task
+* task function
+
+* template
+* template engine
+
+* type annotation
+* type hint
+
+* server worker
+* Uvicorn worker
+* Gunicorn Worker
+* worker process
+* worker class
+* workload
+
+* deployment
+* deploy etmek
+
+* SDK
+* software development kit
+
+* `APIRouter`
+* `requirements.txt`
+* Bearer Token
+* breaking change
+* bug
+* button
+* callable
+* code
+* commit
+* context manager
+* coroutine
+* database session
+* disk
+* domain
+* engine
+* fake X
+* HTTP GET method
+* item
+* library
+* lifespan
+* lock
+* middleware
+* mobile application
+* module
+* mounting
+* network
+* origin
+* override
+* payload
+* processor
+* property
+* proxy
+* pull request
+* query
+* RAM
+* remote machine
+* status code
+* string
+* tag
+* web framework
+* wildcard
+* return etmek
+* validate etmek
+
+////
+
+//// tab | Bilgi
+
+Bu, dokümanlarda görülen (çoğunlukla) teknik terimlerin eksiksiz ve normatif olmayan bir listesidir. Prompt tasarlayan kişi için, LLM'nin hangi terimlerde desteğe ihtiyaç duyduğunu anlamada yardımcı olabilir. Örneğin iyi bir çeviriyi sürekli daha zayıf bir çeviriye geri alıyorsa. Ya da sizin dilinizde bir terimi çekimlemekte (conjugating/declinating) zorlanıyorsa.
+
+Örneğin `docs/de/llm-prompt.md` içindeki `### List of English terms and their preferred German translations` bölümüne bakın.
+
+////
diff --git a/docs/tr/docs/advanced/additional-responses.md b/docs/tr/docs/advanced/additional-responses.md
new file mode 100644
index 000000000..c8e372775
--- /dev/null
+++ b/docs/tr/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# OpenAPI'de Ek Response'lar { #additional-responses-in-openapi }
+
+/// warning | Uyarı
+
+Bu konu oldukça ileri seviye bir konudur.
+
+**FastAPI**'ye yeni başlıyorsanız buna ihtiyaç duymayabilirsiniz.
+
+///
+
+Ek status code'lar, media type'lar, açıklamalar vb. ile ek response'lar tanımlayabilirsiniz.
+
+Bu ek response'lar OpenAPI şemasına dahil edilir; dolayısıyla API dokümanlarında da görünürler.
+
+Ancak bu ek response'lar için, status code'unuzu ve içeriğinizi vererek `JSONResponse` gibi bir `Response`'u doğrudan döndürdüğünüzden emin olmanız gerekir.
+
+## `model` ile Ek Response { #additional-response-with-model }
+
+*Path operation decorator*'larınıza `responses` adlı bir parametre geçebilirsiniz.
+
+Bu parametre bir `dict` alır: anahtarlar her response için status code'lardır (`200` gibi), değerler ise her birine ait bilgileri içeren başka `dict`'lerdir.
+
+Bu response `dict`'lerinin her birinde, `response_model`'e benzer şekilde bir Pydantic model içeren `model` anahtarı olabilir.
+
+**FastAPI** bu modeli alır, JSON Schema'sını üretir ve OpenAPI'de doğru yere ekler.
+
+Örneğin, `404` status code'u ve `Message` Pydantic model'i ile başka bir response tanımlamak için şunu yazabilirsiniz:
+
+{* ../../docs_src/additional_responses/tutorial001_py39.py hl[18,22] *}
+
+/// note | Not
+
+`JSONResponse`'u doğrudan döndürmeniz gerektiğini unutmayın.
+
+///
+
+/// info | Bilgi
+
+`model` anahtarı OpenAPI'nin bir parçası değildir.
+
+**FastAPI** buradaki Pydantic model'i alır, JSON Schema'yı üretir ve doğru yere yerleştirir.
+
+Doğru yer şurasıdır:
+
+* Değeri başka bir JSON nesnesi (`dict`) olan `content` anahtarının içinde:
+ * Media type anahtarı (örn. `application/json`) bulunur; bunun değeri başka bir JSON nesnesidir ve onun içinde:
+ * Değeri model'den gelen JSON Schema olan `schema` anahtarı vardır; doğru yer burasıdır.
+ * **FastAPI** bunu doğrudan gömmek yerine OpenAPI'deki başka bir yerde bulunan global JSON Schema'lara bir referans ekler. Böylece diğer uygulamalar ve client'lar bu JSON Schema'ları doğrudan kullanabilir, daha iyi code generation araçları sağlayabilir, vb.
+
+///
+
+Bu *path operation* için OpenAPI'de üretilen response'lar şöyle olur:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+Schema'lar OpenAPI şemasının içinde başka bir yere referanslanır:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## Ana Response İçin Ek Media Type'lar { #additional-media-types-for-the-main-response }
+
+Aynı `responses` parametresini, aynı ana response için farklı media type'lar eklemek amacıyla da kullanabilirsiniz.
+
+Örneğin, `image/png` için ek bir media type ekleyerek, *path operation*'ınızın bir JSON nesnesi (media type `application/json`) ya da bir PNG görseli döndürebildiğini belirtebilirsiniz:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | Not
+
+Görseli `FileResponse` kullanarak doğrudan döndürmeniz gerektiğine dikkat edin.
+
+///
+
+/// info | Bilgi
+
+`responses` parametrenizde açıkça farklı bir media type belirtmediğiniz sürece FastAPI, response'un ana response class'ı ile aynı media type'a sahip olduğunu varsayar (varsayılan `application/json`).
+
+Ancak media type'ı `None` olan özel bir response class belirttiyseniz, FastAPI ilişkili bir model'i olan tüm ek response'lar için `application/json` kullanır.
+
+///
+
+## Bilgileri Birleştirme { #combining-information }
+
+`response_model`, `status_code` ve `responses` parametreleri dahil olmak üzere, response bilgilerini birden fazla yerden birleştirebilirsiniz.
+
+Varsayılan `200` status code'unu (ya da gerekiyorsa özel bir tane) kullanarak bir `response_model` tanımlayabilir, ardından aynı response için ek bilgileri `responses` içinde, doğrudan OpenAPI şemasına ekleyebilirsiniz.
+
+**FastAPI**, `responses` içindeki ek bilgileri korur ve model'inizin JSON Schema'sı ile birleştirir.
+
+Örneğin, Pydantic model kullanan ve özel bir `description` içeren `404` status code'lu bir response tanımlayabilirsiniz.
+
+Ayrıca `response_model`'inizi kullanan, ancak özel bir `example` içeren `200` status code'lu bir response da tanımlayabilirsiniz:
+
+{* ../../docs_src/additional_responses/tutorial003_py39.py hl[20:31] *}
+
+Bunların hepsi OpenAPI'nize birleştirilerek dahil edilir ve API dokümanlarında gösterilir:
+
+
+
+## Ön Tanımlı Response'ları Özel Olanlarla Birleştirme { #combine-predefined-responses-and-custom-ones }
+
+Birçok *path operation* için geçerli olacak bazı ön tanımlı response'larınız olabilir; ancak bunları her *path operation*'ın ihtiyaç duyduğu özel response'larla birleştirmek isteyebilirsiniz.
+
+Bu durumlarda, Python'daki bir `dict`'i `**dict_to_unpack` ile "unpacking" tekniğini kullanabilirsiniz:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+Burada `new_dict`, `old_dict` içindeki tüm key-value çiftlerini ve buna ek olarak yeni key-value çiftini içerir:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+Bu tekniği, *path operation*'larınızda bazı ön tanımlı response'ları yeniden kullanmak ve bunları ek özel response'larla birleştirmek için kullanabilirsiniz.
+
+Örneğin:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## OpenAPI Response'ları Hakkında Daha Fazla Bilgi { #more-information-about-openapi-responses }
+
+Response'ların içine tam olarak neleri dahil edebileceğinizi görmek için OpenAPI spesifikasyonundaki şu bölümlere bakabilirsiniz:
+
+* OpenAPI Responses Object, `Response Object`'i içerir.
+* OpenAPI Response Object, buradaki her şeyi `responses` parametreniz içinde, her bir response'un içine doğrudan ekleyebilirsiniz. Buna `description`, `headers`, `content` (bunun içinde farklı media type'lar ve JSON Schema'lar tanımlarsınız) ve `links` dahildir.
diff --git a/docs/tr/docs/advanced/additional-status-codes.md b/docs/tr/docs/advanced/additional-status-codes.md
new file mode 100644
index 000000000..710a6459f
--- /dev/null
+++ b/docs/tr/docs/advanced/additional-status-codes.md
@@ -0,0 +1,41 @@
+# Ek Status Code'ları { #additional-status-codes }
+
+Varsayılan olarak **FastAPI**, response'ları bir `JSONResponse` kullanarak döndürür; *path operation*'ınızdan döndürdüğünüz içeriği bu `JSONResponse`'un içine yerleştirir.
+
+Varsayılan status code'u veya *path operation* içinde sizin belirlediğiniz status code'u kullanır.
+
+## Ek status code'ları { #additional-status-codes_1 }
+
+Ana status code'a ek olarak başka status code'lar da döndürmek istiyorsanız, `JSONResponse` gibi bir `Response`'u doğrudan döndürerek bunu yapabilirsiniz ve ek status code'u doğrudan orada ayarlarsınız.
+
+Örneğin, item'ları güncellemeye izin veren bir *path operation*'ınız olduğunu düşünelim; başarılı olduğunda 200 "OK" HTTP status code'unu döndürüyor olsun.
+
+Ancak yeni item'ları da kabul etmesini istiyorsunuz. Ve item daha önce yoksa, onu oluşturup 201 "Created" HTTP status code'unu döndürsün.
+
+Bunu yapmak için `JSONResponse` import edin ve içeriğinizi doğrudan onunla döndürün; istediğiniz `status_code`'u da ayarlayın:
+
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
+
+/// warning | Uyarı
+
+Yukarıdaki örnekte olduğu gibi bir `Response`'u doğrudan döndürdüğünüzde, response aynen olduğu gibi döndürülür.
+
+Bir model ile serialize edilmez, vb.
+
+İçinde olmasını istediğiniz veriyi taşıdığından emin olun ve değerlerin geçerli JSON olduğundan emin olun (eğer `JSONResponse` kullanıyorsanız).
+
+///
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import JSONResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olsun diye `starlette.responses` içindekileri `fastapi.responses` altında da sunar. Ancak mevcut response'ların çoğu doğrudan Starlette'ten gelir. `status` için de aynı durum geçerlidir.
+
+///
+
+## OpenAPI ve API docs { #openapi-and-api-docs }
+
+Ek status code'ları ve response'ları doğrudan döndürürseniz, FastAPI sizin ne döndüreceğinizi önceden bilemeyeceği için bunlar OpenAPI şemasına (API docs) dahil edilmez.
+
+Ancak bunu kodunuzda şu şekilde dokümante edebilirsiniz: [Ek Response'lar](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/tr/docs/advanced/advanced-dependencies.md b/docs/tr/docs/advanced/advanced-dependencies.md
new file mode 100644
index 000000000..48c0b6211
--- /dev/null
+++ b/docs/tr/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# Gelişmiş Dependency'ler { #advanced-dependencies }
+
+## Parametreli dependency'ler { #parameterized-dependencies }
+
+Şimdiye kadar gördüğümüz tüm dependency'ler sabit bir function ya da class idi.
+
+Ancak, birçok farklı function veya class tanımlamak zorunda kalmadan, dependency üzerinde bazı parametreler ayarlamak isteyebileceğiniz durumlar olabilir.
+
+Örneğin, query parametresi `q`'nun belirli bir sabit içeriği barındırıp barındırmadığını kontrol eden bir dependency istediğimizi düşünelim.
+
+Ama bu sabit içeriği parametreleştirebilmek istiyoruz.
+
+## "Callable" bir instance { #a-callable-instance }
+
+Python'da bir class'ın instance'ını "callable" yapmanın bir yolu vardır.
+
+Class'ın kendisini değil (zaten callable'dır), o class'ın bir instance'ını.
+
+Bunu yapmak için `__call__` adında bir method tanımlarız:
+
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *}
+
+Bu durumda, ek parametreleri ve alt-dependency'leri kontrol etmek için **FastAPI**'nin kullanacağı şey bu `__call__` olacaktır; ayrıca daha sonra *path operation function* içindeki parametreye bir değer geçmek için çağrılacak olan da budur.
+
+## Instance'ı parametreleştirme { #parameterize-the-instance }
+
+Ve şimdi, dependency'yi "parametreleştirmek" için kullanacağımız instance parametrelerini tanımlamak üzere `__init__` kullanabiliriz:
+
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *}
+
+Bu durumda **FastAPI**, `__init__` ile asla uğraşmaz veya onu önemsemez; onu doğrudan kendi kodumuzda kullanırız.
+
+## Bir instance oluşturma { #create-an-instance }
+
+Bu class'tan bir instance'ı şöyle oluşturabiliriz:
+
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *}
+
+Böylece dependency'mizi "parametreleştirmiş" oluruz; artık içinde `"bar"` vardır ve bu değer `checker.fixed_content` attribute'u olarak durur.
+
+## Instance'ı dependency olarak kullanma { #use-the-instance-as-a-dependency }
+
+Sonra `Depends(FixedContentQueryChecker)` yerine `Depends(checker)` içinde bu `checker`'ı kullanabiliriz. Çünkü dependency, class'ın kendisi değil, `checker` instance'ıdır.
+
+Ve dependency çözülürken **FastAPI** bu `checker`'ı şöyle çağırır:
+
+```Python
+checker(q="somequery")
+```
+
+...ve bunun döndürdüğü her şeyi, *path operation function* içinde `fixed_content_included` parametresine dependency değeri olarak geçirir:
+
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *}
+
+/// tip | İpucu
+
+Bunların tamamı biraz yapay görünebilir. Ayrıca bunun nasıl faydalı olduğu da henüz çok net olmayabilir.
+
+Bu örnekler bilerek basit tutuldu; ama mekanizmanın nasıl çalıştığını gösteriyor.
+
+Security bölümlerinde, aynı şekilde implement edilmiş yardımcı function'lar bulunuyor.
+
+Buradaki her şeyi anladıysanız, security için kullanılan bu yardımcı araçların arka planda nasıl çalıştığını da zaten biliyorsunuz demektir.
+
+///
+
+## `yield`, `HTTPException`, `except` ve Background Tasks ile Dependency'ler { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | Uyarı
+
+Büyük ihtimalle bu teknik detaylara ihtiyacınız yok.
+
+Bu detaylar, özellikle 0.121.0'dan eski bir FastAPI uygulamanız varsa ve `yield` kullanan dependency'lerle ilgili sorunlar yaşıyorsanız faydalıdır.
+
+///
+
+`yield` kullanan dependency'ler; farklı kullanım senaryolarını kapsamak ve bazı sorunları düzeltmek için zaman içinde evrildi. Aşağıda nelerin değiştiğinin bir özeti var.
+
+### `yield` ve `scope` ile dependency'ler { #dependencies-with-yield-and-scope }
+
+0.121.0 sürümünde FastAPI, `yield` kullanan dependency'ler için `Depends(scope="function")` desteğini ekledi.
+
+`Depends(scope="function")` kullanıldığında, `yield` sonrasındaki çıkış kodu, *path operation function* biter bitmez, response client'a geri gönderilmeden önce çalıştırılır.
+
+`Depends(scope="request")` (varsayılan) kullanıldığında ise `yield` sonrasındaki çıkış kodu, response gönderildikten sonra çalıştırılır.
+
+Daha fazlasını [Dependencies with `yield` - Early exit and `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope) dokümantasyonunda okuyabilirsiniz.
+
+### `yield` ve `StreamingResponse` ile dependency'ler, Teknik Detaylar { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+FastAPI 0.118.0 öncesinde, `yield` kullanan bir dependency kullanırsanız, *path operation function* döndükten sonra ama response gönderilmeden hemen önce `yield` sonrasındaki çıkış kodu çalıştırılırdı.
+
+Amaç, response'un ağ üzerinden taşınmasını beklerken gereğinden uzun süre resource tutmaktan kaçınmaktı.
+
+Bu değişiklik aynı zamanda şunu da ifade ediyordu: `StreamingResponse` döndürürseniz, `yield` kullanan dependency'nin çıkış kodu zaten çalışmış olurdu.
+
+Örneğin, `yield` kullanan bir dependency içinde bir veritabanı session'ınız varsa, `StreamingResponse` veri stream ederken bu session'ı kullanamazdı; çünkü `yield` sonrasındaki çıkış kodunda session zaten kapatılmış olurdu.
+
+Bu davranış 0.118.0'da geri alındı ve `yield` sonrasındaki çıkış kodunun, response gönderildikten sonra çalıştırılması sağlandı.
+
+/// info | Bilgi
+
+Aşağıda göreceğiniz gibi, bu davranış 0.106.0 sürümünden önceki davranışa oldukça benzer; ancak köşe durumlar için çeşitli iyileştirmeler ve bug fix'ler içerir.
+
+///
+
+#### Erken Çıkış Kodu için Kullanım Senaryoları { #use-cases-with-early-exit-code }
+
+Bazı özel koşullardaki kullanım senaryoları, response gönderilmeden önce `yield` kullanan dependency'lerin çıkış kodunun çalıştırıldığı eski davranıştan fayda görebilir.
+
+Örneğin, `yield` kullanan bir dependency içinde yalnızca bir kullanıcıyı doğrulamak için veritabanı session'ı kullanan bir kodunuz olduğunu düşünün; ama bu session *path operation function* içinde bir daha hiç kullanılmıyor, yalnızca dependency içinde kullanılıyor **ve** response'un gönderilmesi uzun sürüyor. Mesela veriyi yavaş gönderen bir `StreamingResponse` var, ama herhangi bir nedenle veritabanını kullanmıyor.
+
+Bu durumda veritabanı session'ı, response tamamen gönderilene kadar elde tutulur. Ancak session kullanılmıyorsa, bunu elde tutmak gerekli değildir.
+
+Şöyle görünebilir:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+`Session`'ın otomatik kapatılması olan çıkış kodu şurada:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...yavaş veri gönderen response'un gönderimi bittikten sonra çalıştırılır:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+Ama `generate_stream()` veritabanı session'ını kullanmadığı için, response gönderilirken session'ı açık tutmak aslında gerekli değildir.
+
+SQLModel (veya SQLAlchemy) kullanarak bu spesifik senaryoya sahipseniz, session'a artık ihtiyacınız kalmadıktan sonra session'ı açıkça kapatabilirsiniz:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+Böylece session veritabanı bağlantısını serbest bırakır ve diğer request'ler bunu kullanabilir.
+
+`yield` kullanan bir dependency'den erken çıkış gerektiren farklı bir kullanım senaryonuz varsa, lütfen kullanım senaryonuzla birlikte ve `yield` kullanan dependency'ler için erken kapatmadan neden fayda göreceğinizi açıklayarak bir GitHub Discussion Question oluşturun.
+
+`yield` kullanan dependency'lerde erken kapatma için ikna edici kullanım senaryoları varsa, erken kapatmayı seçmeli (opt-in) hale getiren yeni bir yöntem eklemeyi düşünebilirim.
+
+### `yield` ve `except` ile dependency'ler, Teknik Detaylar { #dependencies-with-yield-and-except-technical-details }
+
+FastAPI 0.110.0 öncesinde, `yield` kullanan bir dependency kullanır, sonra o dependency içinde `except` ile bir exception yakalar ve exception'ı tekrar raise etmezseniz; exception otomatik olarak herhangi bir exception handler'a veya internal server error handler'a raise/forward edilirdi.
+
+Bu davranış 0.110.0 sürümünde değiştirildi. Amaç, handler olmayan (internal server errors) forward edilmiş exception'ların yönetilmemesinden kaynaklanan bellek tüketimini düzeltmek ve bunu normal Python kodunun davranışıyla tutarlı hale getirmekti.
+
+### Background Tasks ve `yield` ile dependency'ler, Teknik Detaylar { #background-tasks-and-dependencies-with-yield-technical-details }
+
+FastAPI 0.106.0 öncesinde, `yield` sonrasında exception raise etmek mümkün değildi; çünkü `yield` kullanan dependency'lerdeki çıkış kodu response gönderildikten *sonra* çalıştırılıyordu. Bu nedenle [Exception Handlers](../tutorial/handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} zaten çalışmış olurdu.
+
+Bu tasarımın ana sebeplerinden biri, background task'lerin içinde dependency'lerin "yield ettiği" aynı objeleri kullanmaya izin vermekti; çünkü çıkış kodu, background task'ler bittikten sonra çalıştırılıyordu.
+
+Bu davranış FastAPI 0.106.0'da, response'un ağ üzerinde taşınmasını beklerken resource tutmamak amacıyla değiştirildi.
+
+/// tip | İpucu
+
+Ek olarak, bir background task normalde ayrı ele alınması gereken bağımsız bir mantık setidir ve kendi resource'larına sahip olmalıdır (ör. kendi veritabanı bağlantısı).
+
+Bu şekilde muhtemelen daha temiz bir kod elde edersiniz.
+
+///
+
+Bu davranışa güvenerek kod yazdıysanız, artık background task'ler için resource'ları background task'in içinde oluşturmalı ve içeride yalnızca `yield` kullanan dependency'lerin resource'larına bağlı olmayan verileri kullanmalısınız.
+
+Örneğin, aynı veritabanı session'ını kullanmak yerine background task içinde yeni bir veritabanı session'ı oluşturur ve veritabanındaki objeleri bu yeni session ile alırsınız. Ardından, background task function'ına veritabanından gelen objeyi parametre olarak geçirmek yerine, o objenin ID'sini geçirir ve objeyi background task function'ı içinde yeniden elde edersiniz.
diff --git a/docs/tr/docs/advanced/async-tests.md b/docs/tr/docs/advanced/async-tests.md
new file mode 100644
index 000000000..82349bbec
--- /dev/null
+++ b/docs/tr/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# Async Testler { #async-tests }
+
+Sağlanan `TestClient` ile **FastAPI** uygulamalarınızı nasıl test edeceğinizi zaten gördünüz. Şimdiye kadar yalnızca senkron testler yazdık, yani `async` fonksiyonlar kullanmadan.
+
+Testlerinizde asenkron fonksiyonlar kullanabilmek faydalı olabilir; örneğin veritabanınızı asenkron olarak sorguluyorsanız. Diyelim ki FastAPI uygulamanıza request gönderilmesini test etmek ve ardından async bir veritabanı kütüphanesi kullanırken backend'in doğru veriyi veritabanına başarıyla yazdığını doğrulamak istiyorsunuz.
+
+Bunu nasıl çalıştırabileceğimize bir bakalım.
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+Testlerimizde asenkron fonksiyonlar çağırmak istiyorsak, test fonksiyonlarımızın da asenkron olması gerekir. AnyIO bunun için güzel bir plugin sağlar; böylece bazı test fonksiyonlarının asenkron olarak çağrılacağını belirtebiliriz.
+
+## HTTPX { #httpx }
+
+**FastAPI** uygulamanız `async def` yerine normal `def` fonksiyonları kullanıyor olsa bile, altta yatan yapı hâlâ bir `async` uygulamadır.
+
+`TestClient`, standart pytest kullanarak normal `def` test fonksiyonlarınızın içinden asenkron FastAPI uygulamasını çağırmak için içeride bazı “sihirli” işlemler yapar. Ancak bu sihir, onu asenkron fonksiyonların içinde kullandığımızda artık çalışmaz. Testlerimizi asenkron çalıştırdığımızda, test fonksiyonlarımızın içinde `TestClient` kullanamayız.
+
+`TestClient`, HTTPX tabanlıdır ve neyse ki API'yi test etmek için HTTPX'i doğrudan kullanabiliriz.
+
+## Örnek { #example }
+
+Basit bir örnek için, [Bigger Applications](../tutorial/bigger-applications.md){.internal-link target=_blank} ve [Testing](../tutorial/testing.md){.internal-link target=_blank} bölümlerinde anlatılana benzer bir dosya yapısı düşünelim:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+`main.py` dosyası şöyle olur:
+
+{* ../../docs_src/async_tests/app_a_py39/main.py *}
+
+`test_main.py` dosyasında `main.py` için testler yer alır, artık şöyle görünebilir:
+
+{* ../../docs_src/async_tests/app_a_py39/test_main.py *}
+
+## Çalıştırma { #run-it }
+
+Testlerinizi her zamanki gibi şu şekilde çalıştırabilirsiniz:
+
+
Host: mysuperapp.com
Path: /items
+
+ Note over Proxy: Proxy adds forwarded headers
+
+ Proxy->>Server: HTTP Request
X-Forwarded-For: [client IP]
X-Forwarded-Proto: https
X-Forwarded-Host: mysuperapp.com
Path: /items
+
+ Note over Server: Server interprets headers
(if --forwarded-allow-ips is set)
+
+ Server->>Proxy: HTTP Response
with correct HTTPS URLs
+
+ Proxy->>Client: HTTPS Response
+```
+
+**Proxy**, orijinal client request'ini araya girerek (intercept) alır ve request'i **application server**'a iletmeden önce özel *forwarded* header'ları (`X-Forwarded-*`) ekler.
+
+Bu header'lar, aksi halde kaybolacak olan orijinal request bilgilerini korur:
+
+* **X-Forwarded-For**: Orijinal client'ın IP adresi
+* **X-Forwarded-Proto**: Orijinal protokol (`https`)
+* **X-Forwarded-Host**: Orijinal host (`mysuperapp.com`)
+
+**FastAPI CLI** `--forwarded-allow-ips` ile yapılandırıldığında bu header'lara güvenir ve örneğin redirect'lerde doğru URL'leri üretmek için bunları kullanır.
+
+## Path Prefix'i Kırpılan (Stripped) Bir Proxy { #proxy-with-a-stripped-path-prefix }
+
+Uygulamanıza bir path prefix ekleyen bir proxy'niz olabilir.
+
+Bu durumlarda uygulamanızı yapılandırmak için `root_path` kullanabilirsiniz.
+
+`root_path`, FastAPI'nin (Starlette üzerinden) üzerine kurulduğu ASGI spesifikasyonunun sağladığı bir mekanizmadır.
+
+`root_path` bu özel senaryoları yönetmek için kullanılır.
+
+Ayrıca sub-application mount ederken de içeride kullanılır.
+
+Path prefix'i kırpılan bir proxy kullanmak, şu anlama gelir: Kodunuzda `/app` altında bir path tanımlarsınız; ancak üstte bir katman (proxy) ekleyip **FastAPI** uygulamanızı `/api/v1` gibi bir path'in altına koyarsınız.
+
+Bu durumda, orijinal `/app` path'i aslında `/api/v1/app` altında servis edilir.
+
+Kodunuzun tamamı sadece `/app` varmış gibi yazılmış olsa bile.
+
+{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[6] *}
+
+Proxy, request'i app server'a (muhtemelen FastAPI CLI üzerinden Uvicorn) iletmeden önce **path prefix**'i anlık olarak **"kırpar"** (strip). Böylece uygulamanız hâlâ `/app` altında servis ediliyormuş gibi davranır ve tüm kodunuzu `/api/v1` prefix'ini içerecek şekilde güncellemeniz gerekmez.
+
+Buraya kadar her şey normal çalışır.
+
+Ancak entegre doküman arayüzünü (frontend) açtığınızda, OpenAPI şemasını `/api/v1/openapi.json` yerine `/openapi.json` üzerinden almayı bekler.
+
+Dolayısıyla tarayıcıda çalışan frontend `/openapi.json`'a erişmeye çalışır ve OpenAPI şemasını alamaz.
+
+Çünkü uygulamamız proxy arkasında `/api/v1` path prefix'i ile çalışmaktadır; frontend'in OpenAPI şemasını `/api/v1/openapi.json` üzerinden çekmesi gerekir.
+
+```mermaid
+graph LR
+
+browser("Browser")
+proxy["Proxy on http://0.0.0.0:9999/api/v1/app"]
+server["Server on http://127.0.0.1:8000/app"]
+
+browser --> proxy
+proxy --> server
+```
+
+/// tip | İpucu
+
+`0.0.0.0` IP'si, genelde programın ilgili makine/server üzerindeki tüm kullanılabilir IP'lerde dinlediği anlamına gelir.
+
+///
+
+Docs UI'nin, bu API `server`'ının (proxy arkasında) `/api/v1` altında bulunduğunu belirtmek için OpenAPI şemasına da ihtiyacı olur. Örneğin:
+
+```JSON hl_lines="4-8"
+{
+ "openapi": "3.1.0",
+ // More stuff here
+ "servers": [
+ {
+ "url": "/api/v1"
+ }
+ ],
+ "paths": {
+ // More stuff here
+ }
+}
+```
+
+Bu örnekte "Proxy", **Traefik** gibi bir şey olabilir. Server da FastAPI uygulamanızı çalıştıran (Uvicorn'lu) FastAPI CLI olabilir.
+
+### `root_path` Sağlama { #providing-the-root-path }
+
+Bunu yapmak için `--root-path` komut satırı seçeneğini şöyle kullanabilirsiniz:
+
+
+
+Ancak docs UI'yi proxy üzerinden, `9999` portuyla, `/api/v1/docs` altında "resmi" URL'den açarsak doğru çalışır! 🎉
+
+Şuradan kontrol edebilirsiniz: http://127.0.0.1:9999/api/v1/docs:
+
+
+
+Tam istediğimiz gibi. ✔️
+
+Bunun nedeni, FastAPI'nin OpenAPI içinde varsayılan `server`'ı, `root_path` tarafından verilen URL ile oluşturmak için bu `root_path`'i kullanmasıdır.
+
+## Ek `server`'lar { #additional-servers }
+
+/// warning | Uyarı
+
+Bu daha ileri seviye bir kullanım senaryosudur. İsterseniz atlayabilirsiniz.
+
+///
+
+Varsayılan olarak **FastAPI**, OpenAPI şemasında `root_path` için bir `server` oluşturur.
+
+Ancak başka alternatif `servers` da sağlayabilirsiniz; örneğin *aynı* docs UI'nin hem staging hem de production ortamıyla etkileşime girmesini istiyorsanız.
+
+Özel bir `servers` listesi verirseniz ve bir `root_path` varsa (çünkü API'niz proxy arkasındadır), **FastAPI** bu `root_path` ile bir "server"ı listenin başına ekler.
+
+Örneğin:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py39.py hl[4:7] *}
+
+Şöyle bir OpenAPI şeması üretir:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // More stuff here
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // More stuff here
+ }
+}
+```
+
+/// tip | İpucu
+
+`url` değeri `/api/v1` olan, `root_path`'ten alınmış otomatik üretilen server'a dikkat edin.
+
+///
+
+Docs UI'de, http://127.0.0.1:9999/api/v1/docs adresinde şöyle görünür:
+
+
+
+/// tip | İpucu
+
+Docs UI, seçtiğiniz server ile etkileşime girer.
+
+///
+
+/// note | Teknik Detaylar
+
+OpenAPI spesifikasyonunda `servers` özelliği opsiyoneldir.
+
+`servers` parametresini belirtmezseniz ve `root_path` `/` ile aynıysa, üretilen OpenAPI şemasında `servers` özelliği varsayılan olarak tamamen çıkarılır; bu da `url` değeri `/` olan tek bir server ile eşdeğerdir.
+
+///
+
+### `root_path`'ten Otomatik `server` Eklenmesini Kapatma { #disable-automatic-server-from-root-path }
+
+**FastAPI**'nin `root_path` kullanarak otomatik bir server eklemesini istemiyorsanız, `root_path_in_servers=False` parametresini kullanabilirsiniz:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py39.py hl[9] *}
+
+Böylece OpenAPI şemasına dahil etmez.
+
+## Bir Sub-Application Mount Etme { #mounting-a-sub-application }
+
+Bir sub-application'ı ( [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank} bölümünde anlatıldığı gibi) mount etmeniz gerekiyorsa ve aynı zamanda `root_path` ile bir proxy kullanıyorsanız, bunu beklendiği gibi normal şekilde yapabilirsiniz.
+
+FastAPI içeride `root_path`'i akıllıca kullanır; dolayısıyla doğrudan çalışır. ✨
diff --git a/docs/tr/docs/advanced/custom-response.md b/docs/tr/docs/advanced/custom-response.md
new file mode 100644
index 000000000..c5148f428
--- /dev/null
+++ b/docs/tr/docs/advanced/custom-response.md
@@ -0,0 +1,312 @@
+# Özel Response - HTML, Stream, File ve Diğerleri { #custom-response-html-stream-file-others }
+
+Varsayılan olarak **FastAPI**, response'ları `JSONResponse` kullanarak döndürür.
+
+Bunu, [Doğrudan bir Response döndür](response-directly.md){.internal-link target=_blank} bölümünde gördüğünüz gibi doğrudan bir `Response` döndürerek geçersiz kılabilirsiniz.
+
+Ancak doğrudan bir `Response` döndürürseniz (veya `JSONResponse` gibi herhangi bir alt sınıfını), veri otomatik olarak dönüştürülmez (bir `response_model` tanımlamış olsanız bile) ve dokümantasyon da otomatik üretilmez (örneğin, üretilen OpenAPI’nin parçası olarak HTTP header `Content-Type` içindeki ilgili "media type" dahil edilmez).
+
+Bununla birlikte, *path operation decorator* içinde `response_class` parametresini kullanarak hangi `Response`’un (örn. herhangi bir `Response` alt sınıfı) kullanılacağını da ilan edebilirsiniz.
+
+*path operation function*’ınızdan döndürdüğünüz içerik, o `Response`’un içine yerleştirilir.
+
+Ve eğer bu `Response` ( `JSONResponse` ve `UJSONResponse`’ta olduğu gibi) bir JSON media type’a (`application/json`) sahipse, döndürdüğünüz veri; *path operation decorator* içinde tanımladığınız herhangi bir Pydantic `response_model` ile otomatik olarak dönüştürülür (ve filtrelenir).
+
+/// note | Not
+
+Media type’ı olmayan bir response class kullanırsanız, FastAPI response’unuzun content içermediğini varsayar; bu yüzden ürettiği OpenAPI dokümanında response formatını dokümante etmez.
+
+///
+
+## `ORJSONResponse` Kullan { #use-orjsonresponse }
+
+Örneğin performansı sıkıştırmaya çalışıyorsanız, `orjson` kurup kullanabilir ve response’u `ORJSONResponse` olarak ayarlayabilirsiniz.
+
+Kullanmak istediğiniz `Response` class’ını (alt sınıfını) import edin ve *path operation decorator* içinde tanımlayın.
+
+Büyük response'larda, doğrudan bir `Response` döndürmek bir dictionary döndürmekten çok daha hızlıdır.
+
+Çünkü varsayılan olarak FastAPI, içindeki her item’ı inceleyip JSON olarak serialize edilebilir olduğundan emin olur; tutorial’da anlatılan aynı [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} mekanizmasını kullanır. Bu da örneğin veritabanı modelleri gibi **keyfi objeleri** döndürebilmenizi sağlar.
+
+Ancak döndürdüğünüz içeriğin **JSON ile serialize edilebilir** olduğundan eminseniz, onu doğrudan response class’ına verebilir ve FastAPI’nin response class’ına vermeden önce dönüş içeriğinizi `jsonable_encoder` içinden geçirirken oluşturacağı ek yükten kaçınabilirsiniz.
+
+{* ../../docs_src/custom_response/tutorial001b_py39.py hl[2,7] *}
+
+/// info | Bilgi
+
+`response_class` parametresi, response’un "media type"’ını tanımlamak için de kullanılır.
+
+Bu durumda HTTP header `Content-Type`, `application/json` olarak ayarlanır.
+
+Ve OpenAPI’de de bu şekilde dokümante edilir.
+
+///
+
+/// tip | İpucu
+
+`ORJSONResponse` yalnızca FastAPI’de vardır, Starlette’te yoktur.
+
+///
+
+## HTML Response { #html-response }
+
+**FastAPI**’den doğrudan HTML içeren bir response döndürmek için `HTMLResponse` kullanın.
+
+* `HTMLResponse` import edin.
+* *path operation decorator*’ınızın `response_class` parametresi olarak `HTMLResponse` verin.
+
+{* ../../docs_src/custom_response/tutorial002_py39.py hl[2,7] *}
+
+/// info | Bilgi
+
+`response_class` parametresi, response’un "media type"’ını tanımlamak için de kullanılır.
+
+Bu durumda HTTP header `Content-Type`, `text/html` olarak ayarlanır.
+
+Ve OpenAPI’de de bu şekilde dokümante edilir.
+
+///
+
+### Bir `Response` Döndür { #return-a-response }
+
+[Doğrudan bir Response döndür](response-directly.md){.internal-link target=_blank} bölümünde görüldüğü gibi, *path operation* içinde doğrudan bir response döndürerek response’u override edebilirsiniz.
+
+Yukarıdaki örneğin aynısı, bu sefer bir `HTMLResponse` döndürerek, şöyle görünebilir:
+
+{* ../../docs_src/custom_response/tutorial003_py39.py hl[2,7,19] *}
+
+/// warning | Uyarı
+
+*path operation function*’ınızın doğrudan döndürdüğü bir `Response`, OpenAPI’de dokümante edilmez (örneğin `Content-Type` dokümante edilmez) ve otomatik interaktif dokümanlarda görünmez.
+
+///
+
+/// info | Bilgi
+
+Elbette gerçek `Content-Type` header’ı, status code vb. değerler, döndürdüğünüz `Response` objesinden gelir.
+
+///
+
+### OpenAPI’de Dokümante Et ve `Response`’u Override Et { #document-in-openapi-and-override-response }
+
+Response’u fonksiyonun içinden override etmek ama aynı zamanda OpenAPI’de "media type"’ı dokümante etmek istiyorsanız, `response_class` parametresini kullanıp ayrıca bir `Response` objesi döndürebilirsiniz.
+
+Bu durumda `response_class` sadece OpenAPI *path operation*’ını dokümante etmek için kullanılır; sizin `Response`’unuz ise olduğu gibi kullanılır.
+
+#### Doğrudan bir `HTMLResponse` Döndür { #return-an-htmlresponse-directly }
+
+Örneğin şöyle bir şey olabilir:
+
+{* ../../docs_src/custom_response/tutorial004_py39.py hl[7,21,23] *}
+
+Bu örnekte `generate_html_response()` fonksiyonu, HTML’i bir `str` olarak döndürmek yerine zaten bir `Response` üretip döndürmektedir.
+
+`generate_html_response()` çağrısının sonucunu döndürerek, varsayılan **FastAPI** davranışını override edecek bir `Response` döndürmüş olursunuz.
+
+Ama `response_class` içinde `HTMLResponse` da verdiğiniz için **FastAPI**, bunu OpenAPI’de ve interaktif dokümanlarda `text/html` ile HTML olarak nasıl dokümante edeceğini bilir:
+
+
+
+## Mevcut Response'lar { #available-responses }
+
+Mevcut response'lardan bazıları aşağıdadır.
+
+Unutmayın: `Response` ile başka herhangi bir şeyi döndürebilir, hatta özel bir alt sınıf da oluşturabilirsiniz.
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import HTMLResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici için kolaylık olsun diye `starlette.responses` içindekileri `fastapi.responses` olarak da sağlar. Ancak mevcut response'ların çoğu doğrudan Starlette’ten gelir.
+
+///
+
+### `Response` { #response }
+
+Ana `Response` class’ıdır; diğer tüm response'lar bundan türetilir.
+
+Bunu doğrudan döndürebilirsiniz.
+
+Şu parametreleri kabul eder:
+
+* `content` - Bir `str` veya `bytes`.
+* `status_code` - Bir `int` HTTP status code.
+* `headers` - String’lerden oluşan bir `dict`.
+* `media_type` - Media type’ı veren bir `str`. Örn. `"text/html"`.
+
+FastAPI (aslında Starlette) otomatik olarak bir Content-Length header’ı ekler. Ayrıca `media_type`’a göre bir Content-Type header’ı ekler ve text türleri için sona bir charset ekler.
+
+{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+Yukarıda okuduğunuz gibi, bir miktar text veya bytes alır ve HTML response döndürür.
+
+### `PlainTextResponse` { #plaintextresponse }
+
+Bir miktar text veya bytes alır ve düz metin response döndürür.
+
+{* ../../docs_src/custom_response/tutorial005_py39.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+Bir miktar veri alır ve `application/json` olarak encode edilmiş bir response döndürür.
+
+Yukarıda okuduğunuz gibi, **FastAPI**’de varsayılan response budur.
+
+### `ORJSONResponse` { #orjsonresponse }
+
+Yukarıda okuduğunuz gibi `orjson` kullanan hızlı bir alternatif JSON response.
+
+/// info | Bilgi
+
+Bunun için `orjson` kurulmalıdır; örneğin `pip install orjson`.
+
+///
+
+### `UJSONResponse` { #ujsonresponse }
+
+`ujson` kullanan alternatif bir JSON response.
+
+/// info | Bilgi
+
+Bunun için `ujson` kurulmalıdır; örneğin `pip install ujson`.
+
+///
+
+/// warning | Uyarı
+
+`ujson`, bazı edge-case’leri ele alma konusunda Python’un built-in implementasyonu kadar dikkatli değildir.
+
+///
+
+{* ../../docs_src/custom_response/tutorial001_py39.py hl[2,7] *}
+
+/// tip | İpucu
+
+`ORJSONResponse` daha hızlı bir alternatif olabilir.
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+HTTP redirect döndürür. Varsayılan olarak 307 status code (Temporary Redirect) kullanır.
+
+`RedirectResponse`’u doğrudan döndürebilirsiniz:
+
+{* ../../docs_src/custom_response/tutorial006_py39.py hl[2,9] *}
+
+---
+
+Veya `response_class` parametresi içinde kullanabilirsiniz:
+
+{* ../../docs_src/custom_response/tutorial006b_py39.py hl[2,7,9] *}
+
+Bunu yaparsanız, *path operation* function’ınızdan doğrudan URL döndürebilirsiniz.
+
+Bu durumda kullanılan `status_code`, `RedirectResponse` için varsayılan olan `307` olur.
+
+---
+
+Ayrıca `status_code` parametresini `response_class` parametresiyle birlikte kullanabilirsiniz:
+
+{* ../../docs_src/custom_response/tutorial006c_py39.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+Bir async generator veya normal generator/iterator alır ve response body’yi stream eder.
+
+{* ../../docs_src/custom_response/tutorial007_py39.py hl[2,14] *}
+
+#### `StreamingResponse`’u file-like objelerle kullanma { #using-streamingresponse-with-file-like-objects }
+
+Bir file-like objeniz varsa (örn. `open()`’ın döndürdüğü obje), o file-like obje üzerinde iterate eden bir generator function oluşturabilirsiniz.
+
+Böylece önce hepsini memory’ye okumak zorunda kalmazsınız; bu generator function’ı `StreamingResponse`’a verip döndürebilirsiniz.
+
+Buna cloud storage ile etkileşime giren, video işleyen ve benzeri birçok kütüphane dahildir.
+
+{* ../../docs_src/custom_response/tutorial008_py39.py hl[2,10:12,14] *}
+
+1. Bu generator function’dır. İçinde `yield` ifadeleri olduğu için "generator function" denir.
+2. Bir `with` bloğu kullanarak, generator function bittiğinde file-like objenin kapandığından emin oluruz. Yani response göndermeyi bitirdikten sonra kapanır.
+3. Bu `yield from`, fonksiyona `file_like` isimli şeyi iterate etmesini söyler. Ardından iterate edilen her parça için, o parçayı bu generator function’dan (`iterfile`) geliyormuş gibi yield eder.
+
+ Yani, içerdeki "üretme" (generating) işini başka bir şeye devreden bir generator function’dır.
+
+ Bunu bu şekilde yaptığımızda `with` bloğu içinde tutabilir ve böylece iş bitince file-like objenin kapanmasını garanti edebiliriz.
+
+/// tip | İpucu
+
+Burada `async` ve `await` desteklemeyen standart `open()` kullandığımız için path operation’ı normal `def` ile tanımlarız.
+
+///
+
+### `FileResponse` { #fileresponse }
+
+Asenkron olarak bir dosyayı response olarak stream eder.
+
+Diğer response türlerine göre instantiate ederken farklı argümanlar alır:
+
+* `path` - Stream edilecek dosyanın dosya path'i.
+* `headers` - Eklenecek özel header’lar; dictionary olarak.
+* `media_type` - Media type’ı veren string. Ayarlanmazsa, dosya adı veya path kullanılarak media type tahmin edilir.
+* `filename` - Ayarlanırsa response içindeki `Content-Disposition`’a dahil edilir.
+
+File response'ları uygun `Content-Length`, `Last-Modified` ve `ETag` header’larını içerir.
+
+{* ../../docs_src/custom_response/tutorial009_py39.py hl[2,10] *}
+
+`response_class` parametresini de kullanabilirsiniz:
+
+{* ../../docs_src/custom_response/tutorial009b_py39.py hl[2,8,10] *}
+
+Bu durumda *path operation* function’ınızdan doğrudan dosya path'ini döndürebilirsiniz.
+
+## Özel response class { #custom-response-class }
+
+`Response`’dan türeterek kendi özel response class’ınızı oluşturabilir ve kullanabilirsiniz.
+
+Örneğin, dahil gelen `ORJSONResponse` class’ında kullanılmayan bazı özel ayarlarla `orjson` kullanmak istediğinizi varsayalım.
+
+Diyelim ki girintili ve biçimlendirilmiş JSON döndürmek istiyorsunuz; bunun için `orjson.OPT_INDENT_2` seçeneğini kullanmak istiyorsunuz.
+
+Bir `CustomORJSONResponse` oluşturabilirsiniz. Burada yapmanız gereken temel şey, content’i `bytes` olarak döndüren bir `Response.render(content)` metodu yazmaktır:
+
+{* ../../docs_src/custom_response/tutorial009c_py39.py hl[9:14,17] *}
+
+Artık şunu döndürmek yerine:
+
+```json
+{"message": "Hello World"}
+```
+
+...bu response şunu döndürür:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+Elbette JSON’u formatlamaktan çok daha iyi şekillerde bundan faydalanabilirsiniz. 😉
+
+## Varsayılan response class { #default-response-class }
+
+Bir **FastAPI** class instance’ı veya bir `APIRouter` oluştururken, varsayılan olarak hangi response class’ının kullanılacağını belirtebilirsiniz.
+
+Bunu tanımlayan parametre `default_response_class`’tır.
+
+Aşağıdaki örnekte **FastAPI**, tüm *path operations* için varsayılan olarak `JSONResponse` yerine `ORJSONResponse` kullanır.
+
+{* ../../docs_src/custom_response/tutorial010_py39.py hl[2,4] *}
+
+/// tip | İpucu
+
+Daha önce olduğu gibi, *path operations* içinde `response_class`’ı yine override edebilirsiniz.
+
+///
+
+## Ek dokümantasyon { #additional-documentation }
+
+OpenAPI’de media type’ı ve daha birçok detayı `responses` kullanarak da tanımlayabilirsiniz: [OpenAPI’de Ek Response'lar](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/tr/docs/advanced/dataclasses.md b/docs/tr/docs/advanced/dataclasses.md
new file mode 100644
index 000000000..263976007
--- /dev/null
+++ b/docs/tr/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Dataclass Kullanımı { #using-dataclasses }
+
+FastAPI, **Pydantic** üzerine inşa edilmiştir ve request/response tanımlamak için Pydantic model'lerini nasıl kullanacağınızı gösteriyordum.
+
+Ancak FastAPI, `dataclasses` kullanmayı da aynı şekilde destekler:
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+Bu destek hâlâ **Pydantic** sayesinde vardır; çünkü Pydantic, `dataclasses` için dahili destek sunar.
+
+Yani yukarıdaki kod Pydantic'i doğrudan kullanmasa bile, FastAPI bu standart dataclass'ları Pydantic'in kendi dataclass biçimine dönüştürmek için Pydantic'i kullanmaktadır.
+
+Ve elbette aynı özellikleri destekler:
+
+* veri doğrulama (data validation)
+* veri serileştirme (data serialization)
+* veri dokümantasyonu (data documentation), vb.
+
+Bu, Pydantic model'lerinde olduğu gibi çalışır. Aslında arka planda da aynı şekilde, Pydantic kullanılarak yapılır.
+
+/// info | Bilgi
+
+Dataclass'ların, Pydantic model'lerinin yapabildiği her şeyi yapamadığını unutmayın.
+
+Bu yüzden yine de Pydantic model'lerini kullanmanız gerekebilir.
+
+Ancak elinizde zaten bir sürü dataclass varsa, bunları FastAPI ile bir web API'yi beslemek için kullanmak güzel bir numaradır. 🤓
+
+///
+
+## `response_model` İçinde Dataclass'lar { #dataclasses-in-response-model }
+
+`response_model` parametresinde `dataclasses` da kullanabilirsiniz:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+Dataclass otomatik olarak bir Pydantic dataclass'ına dönüştürülür.
+
+Bu sayede şeması API docs kullanıcı arayüzünde görünür:
+
+
+
+## İç İçe Veri Yapılarında Dataclass'lar { #dataclasses-in-nested-data-structures }
+
+İç içe veri yapıları oluşturmak için `dataclasses` ile diğer type annotation'ları da birleştirebilirsiniz.
+
+Bazı durumlarda yine de Pydantic'in `dataclasses` sürümünü kullanmanız gerekebilir. Örneğin, otomatik oluşturulan API dokümantasyonunda hata alıyorsanız.
+
+Bu durumda standart `dataclasses` yerine, drop-in replacement olan `pydantic.dataclasses` kullanabilirsiniz:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. `field` hâlâ standart `dataclasses` içinden import edilir.
+
+2. `pydantic.dataclasses`, `dataclasses` için bir drop-in replacement'tır.
+
+3. `Author` dataclass'ı, `Item` dataclass'larından oluşan bir liste içerir.
+
+4. `Author` dataclass'ı, `response_model` parametresi olarak kullanılır.
+
+5. Request body olarak dataclass'larla birlikte diğer standart type annotation'ları da kullanabilirsiniz.
+
+ Bu örnekte, `Item` dataclass'larından oluşan bir listedir.
+
+6. Burada `items` içeren bir dictionary döndürüyoruz; `items` bir dataclass listesi.
+
+ FastAPI, veriyi JSON'a serializing etmeyi yine başarır.
+
+7. Burada `response_model`, `Author` dataclass'larından oluşan bir listenin type annotation'ını kullanıyor.
+
+ Yine `dataclasses` ile standart type annotation'ları birleştirebilirsiniz.
+
+8. Bu *path operation function*, `async def` yerine normal `def` kullanıyor.
+
+ Her zaman olduğu gibi, FastAPI'de ihtiyaca göre `def` ve `async def`’i birlikte kullanabilirsiniz.
+
+ Hangisini ne zaman kullanmanız gerektiğine dair hızlı bir hatırlatma isterseniz, [`async` ve `await`](../async.md#in-a-hurry){.internal-link target=_blank} dokümanındaki _"In a hurry?"_ bölümüne bakın.
+
+9. Bu *path operation function* dataclass döndürmüyor (isterse döndürebilir), onun yerine dahili verilerle bir dictionary listesi döndürüyor.
+
+ FastAPI, response'u dönüştürmek için (dataclass'ları içeren) `response_model` parametresini kullanacaktır.
+
+Karmaşık veri yapıları oluşturmak için `dataclasses` ile diğer type annotation'ları pek çok farklı kombinasyonda birleştirebilirsiniz.
+
+Daha spesifik ayrıntılar için yukarıdaki kod içi annotation ipuçlarına bakın.
+
+## Daha Fazla Öğrenin { #learn-more }
+
+`dataclasses`'ı diğer Pydantic model'leriyle de birleştirebilir, onlardan kalıtım alabilir, kendi model'lerinize dahil edebilirsiniz, vb.
+
+Daha fazlası için Pydantic'in dataclasses dokümantasyonuna bakın.
+
+## Sürüm { #version }
+
+Bu özellik FastAPI `0.67.0` sürümünden beri mevcuttur. 🔖
diff --git a/docs/tr/docs/advanced/events.md b/docs/tr/docs/advanced/events.md
new file mode 100644
index 000000000..257b952f9
--- /dev/null
+++ b/docs/tr/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# Lifespan Olayları { #lifespan-events }
+
+Uygulama **başlamadan** önce çalıştırılması gereken mantığı (kodu) tanımlayabilirsiniz. Bu, bu kodun **bir kez**, uygulama **request almaya başlamadan önce** çalıştırılacağı anlamına gelir.
+
+Benzer şekilde, uygulama **kapanırken** çalıştırılması gereken mantığı (kodu) da tanımlayabilirsiniz. Bu durumda bu kod, muhtemelen **çok sayıda request** işlendi **sonra**, **bir kez** çalıştırılır.
+
+Bu kod, uygulama request almaya **başlamadan** önce ve request’leri işlemeyi **bitirdikten** hemen sonra çalıştığı için, uygulamanın tüm **lifespan**’ını (birazdan "lifespan" kelimesi önemli olacak 😉) kapsar.
+
+Bu yaklaşım, tüm uygulama boyunca kullanacağınız ve request’ler arasında **paylaşılan** **resource**’ları kurmak ve/veya sonrasında bunları **temizlemek** için çok faydalıdır. Örneğin bir veritabanı connection pool’u ya da paylaşılan bir machine learning modelini yüklemek gibi.
+
+## Kullanım Senaryosu { #use-case }
+
+Önce bir **kullanım senaryosu** örneğiyle başlayalım, sonra bunu bununla nasıl çözeceğimize bakalım.
+
+Request’leri işlemek için kullanmak istediğiniz bazı **machine learning modelleriniz** olduğunu hayal edelim. 🤖
+
+Aynı modeller request’ler arasında paylaşılır; yani request başına bir model, kullanıcı başına bir model vb. gibi değil.
+
+Modeli yüklemenin, diskten çok fazla **data** okunması gerektiği için **oldukça uzun sürebildiğini** düşünelim. Dolayısıyla bunu her request için yapmak istemezsiniz.
+
+Modeli modülün/dosyanın en üst seviyesinde yükleyebilirdiniz; ancak bu, basit bir otomatik test çalıştırdığınızda bile **modelin yükleneceği** anlamına gelir. Böyle olunca test, kodun bağımsız bir kısmını çalıştırabilmek için önce modelin yüklenmesini beklemek zorunda kalır ve **yavaş** olur.
+
+Burada çözeceğimiz şey bu: modeli request’ler işlenmeden önce yükleyelim, ama kod yüklenirken değil; yalnızca uygulama request almaya başlamadan hemen önce.
+
+## Lifespan { #lifespan }
+
+Bu *startup* ve *shutdown* mantığını, `FastAPI` uygulamasının `lifespan` parametresi ve bir "context manager" kullanarak tanımlayabilirsiniz (bunun ne olduğunu birazdan göstereceğim).
+
+Önce bir örnekle başlayıp sonra ayrıntılarına bakalım.
+
+Aşağıdaki gibi `yield` kullanan async bir `lifespan()` fonksiyonu oluşturuyoruz:
+
+{* ../../docs_src/events/tutorial003_py39.py hl[16,19] *}
+
+Burada, `yield` öncesinde (sahte) model fonksiyonunu machine learning modellerini içeren dictionary’e koyarak, modeli yükleme gibi maliyetli bir *startup* işlemini simüle ediyoruz. Bu kod, *startup* sırasında, uygulama **request almaya başlamadan önce** çalıştırılır.
+
+Ardından `yield`’den hemen sonra modeli bellekten kaldırıyoruz (unload). Bu kod, uygulama **request’leri işlemeyi bitirdikten sonra**, *shutdown*’dan hemen önce çalıştırılır. Örneğin memory veya GPU gibi resource’ları serbest bırakabilir.
+
+/// tip | İpucu
+
+`shutdown`, uygulamayı **durdurduğunuzda** gerçekleşir.
+
+Belki yeni bir sürüm başlatmanız gerekiyordur, ya da çalıştırmaktan sıkılmışsınızdır. 🤷
+
+///
+
+### Lifespan fonksiyonu { #lifespan-function }
+
+Dikkat edilmesi gereken ilk şey, `yield` içeren async bir fonksiyon tanımlıyor olmamız. Bu, `yield` kullanan Dependencies’e oldukça benzer.
+
+{* ../../docs_src/events/tutorial003_py39.py hl[14:19] *}
+
+Fonksiyonun `yield`’den önceki kısmı, uygulama başlamadan **önce** çalışır.
+
+`yield`’den sonraki kısım ise, uygulama işini bitirdikten **sonra** çalışır.
+
+### Async Context Manager { #async-context-manager }
+
+Bakarsanız, fonksiyon `@asynccontextmanager` ile dekore edilmiş.
+
+Bu da fonksiyonu "**async context manager**" denen şeye dönüştürür.
+
+{* ../../docs_src/events/tutorial003_py39.py hl[1,13] *}
+
+Python’da **context manager**, `with` ifadesi içinde kullanabildiğiniz bir yapıdır. Örneğin `open()` bir context manager olarak kullanılabilir:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+Python’ın güncel sürümlerinde bir de **async context manager** vardır. Bunu `async with` ile kullanırsınız:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+Yukarıdaki gibi bir context manager veya async context manager oluşturduğunuzda, yaptığı şey şudur: `with` bloğuna girmeden önce `yield`’den önceki kodu çalıştırır, `with` bloğundan çıktıktan sonra da `yield`’den sonraki kodu çalıştırır.
+
+Yukarıdaki kod örneğimizde bunu doğrudan kullanmıyoruz; bunun yerine FastAPI’ye veriyoruz ki o kullansın.
+
+`FastAPI` uygulamasının `lifespan` parametresi bir **async context manager** alır; dolayısıyla oluşturduğumuz yeni `lifespan` async context manager’ını buraya geçebiliriz.
+
+{* ../../docs_src/events/tutorial003_py39.py hl[22] *}
+
+## Alternatif Events (kullanımdan kaldırıldı) { #alternative-events-deprecated }
+
+/// warning | Uyarı
+
+*startup* ve *shutdown* işlemlerini yönetmenin önerilen yolu, yukarıda anlatıldığı gibi `FastAPI` uygulamasının `lifespan` parametresini kullanmaktır. Bir `lifespan` parametresi sağlarsanız, `startup` ve `shutdown` event handler’ları artık çağrılmaz. Ya tamamen `lifespan` ya da tamamen events; ikisi birden değil.
+
+Muhtemelen bu bölümü atlayabilirsiniz.
+
+///
+
+*startup* ve *shutdown* sırasında çalıştırılacak bu mantığı tanımlamanın alternatif bir yolu daha vardır.
+
+Uygulama başlamadan önce veya uygulama kapanırken çalıştırılması gereken event handler’ları (fonksiyonları) tanımlayabilirsiniz.
+
+Bu fonksiyonlar `async def` ile veya normal `def` ile tanımlanabilir.
+
+### `startup` eventi { #startup-event }
+
+Uygulama başlamadan önce çalıştırılacak bir fonksiyon eklemek için, `"startup"` event’i ile tanımlayın:
+
+{* ../../docs_src/events/tutorial001_py39.py hl[8] *}
+
+Bu durumda `startup` event handler fonksiyonu, "database" öğesini (sadece bir `dict`) bazı değerlerle başlatır.
+
+Birden fazla event handler fonksiyonu ekleyebilirsiniz.
+
+Ve tüm `startup` event handler’ları tamamlanmadan uygulamanız request almaya başlamaz.
+
+### `shutdown` eventi { #shutdown-event }
+
+Uygulama kapanırken çalıştırılacak bir fonksiyon eklemek için, `"shutdown"` event’i ile tanımlayın:
+
+{* ../../docs_src/events/tutorial002_py39.py hl[6] *}
+
+Burada `shutdown` event handler fonksiyonu, `log.txt` dosyasına `"Application shutdown"` satırını yazar.
+
+/// info | Bilgi
+
+`open()` fonksiyonunda `mode="a"` "append" anlamına gelir; yani satır, önceki içeriği silmeden dosyada ne varsa onun sonuna eklenir.
+
+///
+
+/// tip | İpucu
+
+Dikkat edin, bu örnekte bir dosyayla etkileşen standart Python `open()` fonksiyonunu kullanıyoruz.
+
+Dolayısıyla disk’e yazılmasını beklemeyi gerektiren I/O (input/output) söz konusu.
+
+Ancak `open()` `async` ve `await` kullanmaz.
+
+Bu yüzden event handler fonksiyonunu `async def` yerine standart `def` ile tanımlarız.
+
+///
+
+### `startup` ve `shutdown` birlikte { #startup-and-shutdown-together }
+
+*startup* ve *shutdown* mantığınızın birbiriyle bağlantılı olma ihtimali yüksektir; bir şeyi başlatıp sonra bitirmek, bir resource edinip sonra serbest bırakmak vb. isteyebilirsiniz.
+
+Bunu, ortak mantık veya değişken paylaşmayan ayrı fonksiyonlarda yapmak daha zordur; çünkü değerleri global değişkenlerde tutmanız veya benzer numaralar yapmanız gerekir.
+
+Bu nedenle artık bunun yerine, yukarıda açıklandığı gibi `lifespan` kullanmanız önerilmektedir.
+
+## Teknik Detaylar { #technical-details }
+
+Meraklı nerd’ler için küçük bir teknik detay. 🤓
+
+Altta, ASGI teknik spesifikasyonunda bu, Lifespan Protocol’ün bir parçasıdır ve `startup` ile `shutdown` adında event’ler tanımlar.
+
+/// info | Bilgi
+
+Starlette `lifespan` handler’ları hakkında daha fazlasını Starlette's Lifespan docs içinde okuyabilirsiniz.
+
+Ayrıca kodunuzun başka bölgelerinde de kullanılabilecek lifespan state’i nasıl yöneteceğinizi de kapsar.
+
+///
+
+## Alt Uygulamalar { #sub-applications }
+
+🚨 Unutmayın: Bu lifespan event’leri (`startup` ve `shutdown`) yalnızca ana uygulama için çalıştırılır; [Alt Uygulamalar - Mounts](sub-applications.md){.internal-link target=_blank} için çalıştırılmaz.
diff --git a/docs/tr/docs/advanced/generate-clients.md b/docs/tr/docs/advanced/generate-clients.md
new file mode 100644
index 000000000..af278f2fe
--- /dev/null
+++ b/docs/tr/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# SDK Üretme { #generating-sdks }
+
+**FastAPI**, **OpenAPI** spesifikasyonunu temel aldığı için API'leri birçok aracın anlayabildiği standart bir formatta tanımlanabilir.
+
+Bu sayede güncel **dokümantasyon**, birden fazla dilde istemci kütüphaneleri (**SDKs**) ve kodunuzla senkron kalan **test** veya **otomasyon iş akışları** üretmek kolaylaşır.
+
+Bu rehberde, FastAPI backend'iniz için bir **TypeScript SDK** üretmeyi öğreneceksiniz.
+
+## Açık Kaynak SDK Üreteçleri { #open-source-sdk-generators }
+
+Esnek bir seçenek olan OpenAPI Generator, **birçok programlama dilini** destekler ve OpenAPI spesifikasyonunuzdan SDK üretebilir.
+
+**TypeScript client**'lar için Hey API, TypeScript ekosistemi için özel olarak tasarlanmış, optimize bir deneyim sunan bir çözümdür.
+
+Daha fazla SDK üretecini OpenAPI.Tools üzerinde keşfedebilirsiniz.
+
+/// tip | İpucu
+
+FastAPI otomatik olarak **OpenAPI 3.1** spesifikasyonları üretir; bu yüzden kullanacağınız aracın bu sürümü desteklemesi gerekir.
+
+///
+
+## FastAPI Sponsorlarından SDK Üreteçleri { #sdk-generators-from-fastapi-sponsors }
+
+Bu bölüm, FastAPI'yi sponsorlayan şirketlerin sunduğu **yatırım destekli** ve **şirket destekli** çözümleri öne çıkarır. Bu ürünler, yüksek kaliteli üretilen SDK'ların üzerine **ek özellikler** ve **entegrasyonlar** sağlar.
+
+✨ [**FastAPI'ye sponsor olarak**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨ bu şirketler, framework'ün ve **ekosisteminin** sağlıklı ve **sürdürülebilir** kalmasına yardımcı olur.
+
+Sponsor olmaları aynı zamanda FastAPI **topluluğuna** (size) güçlü bir bağlılığı da gösterir; yalnızca **iyi bir hizmet** sunmayı değil, aynı zamanda **güçlü ve gelişen bir framework** olan FastAPI'yi desteklemeyi de önemsediklerini gösterir. 🙇
+
+Örneğin şunları deneyebilirsiniz:
+
+* Speakeasy
+* Stainless
+* liblab
+
+Bu çözümlerin bazıları açık kaynak olabilir veya ücretsiz katman sunabilir; yani finansal bir taahhüt olmadan deneyebilirsiniz. Başka ticari SDK üreteçleri de vardır ve internette bulunabilir. 🤓
+
+## TypeScript SDK Oluşturma { #create-a-typescript-sdk }
+
+Basit bir FastAPI uygulamasıyla başlayalım:
+
+{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *}
+
+*Path operation*'ların, request payload ve response payload için kullandıkları modelleri `Item` ve `ResponseMessage` modelleriyle tanımladıklarına dikkat edin.
+
+### API Dokümanları { #api-docs }
+
+`/docs` adresine giderseniz, request'lerde gönderilecek ve response'larda alınacak veriler için **schema**'ları içerdiğini görürsünüz:
+
+
+
+Bu schema'ları görebilirsiniz, çünkü uygulamada modellerle birlikte tanımlandılar.
+
+Bu bilgi uygulamanın **OpenAPI schema**'sında bulunur ve sonrasında API dokümanlarında gösterilir.
+
+OpenAPI'ye dahil edilen, modellerden gelen bu bilginin aynısı **client code üretmek** için kullanılabilir.
+
+### Hey API { #hey-api }
+
+Modelleri olan bir FastAPI uygulamamız olduğunda, Hey API ile bir TypeScript client üretebiliriz. Bunu yapmanın en hızlı yolu npx kullanmaktır.
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+Bu komut `./src/client` içine bir TypeScript SDK üretecektir.
+
+Web sitelerinde `@hey-api/openapi-ts` kurulumunu öğrenebilir ve üretilen çıktıyı inceleyebilirsiniz.
+
+### SDK'yı Kullanma { #using-the-sdk }
+
+Artık client code'u import edip kullanabilirsiniz. Şuna benzer görünebilir; method'lar için otomatik tamamlama aldığınıza dikkat edin:
+
+
+
+Ayrıca gönderilecek payload için de otomatik tamamlama alırsınız:
+
+
+
+/// tip | İpucu
+
+`name` ve `price` için otomatik tamamlamaya dikkat edin; bunlar FastAPI uygulamasında, `Item` modelinde tanımlanmıştı.
+
+///
+
+Gönderdiğiniz veriler için satır içi hatalar (inline errors) da alırsınız:
+
+
+
+Response objesi de otomatik tamamlama sunacaktır:
+
+
+
+## Tag'lerle FastAPI Uygulaması { #fastapi-app-with-tags }
+
+Birçok durumda FastAPI uygulamanız daha büyük olacaktır ve farklı *path operation* gruplarını ayırmak için muhtemelen tag'leri kullanacaksınız.
+
+Örneğin **items** için bir bölüm, **users** için başka bir bölüm olabilir ve bunları tag'lerle ayırabilirsiniz:
+
+{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *}
+
+### Tag'lerle TypeScript Client Üretme { #generate-a-typescript-client-with-tags }
+
+Tag'leri kullanan bir FastAPI uygulaması için client ürettiğinizde, genelde client code da tag'lere göre ayrılır.
+
+Bu sayede client code tarafında her şey doğru şekilde sıralanır ve gruplandırılır:
+
+
+
+Bu örnekte şunlar var:
+
+* `ItemsService`
+* `UsersService`
+
+### Client Method İsimleri { #client-method-names }
+
+Şu an üretilen `createItemItemsPost` gibi method isimleri çok temiz görünmüyor:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+...çünkü client üreteci, her *path operation* için OpenAPI'nin dahili **operation ID** değerini kullanır.
+
+OpenAPI, her operation ID'nin tüm *path operation*'lar arasında benzersiz olmasını ister. Bu yüzden FastAPI; operation ID'yi benzersiz tutabilmek için **function adı**, **path** ve **HTTP method/operation** bilgilerini birleştirerek üretir.
+
+Ancak bunu bir sonraki adımda nasıl iyileştirebileceğinizi göstereceğim. 🤓
+
+## Özel Operation ID'ler ve Daha İyi Method İsimleri { #custom-operation-ids-and-better-method-names }
+
+Bu operation ID'lerin **üretilme** şeklini **değiştirerek**, client'larda daha basit **method isimleri** elde edebilirsiniz.
+
+Bu durumda, her operation ID'nin **benzersiz** olduğundan başka bir şekilde emin olmanız gerekir.
+
+Örneğin, her *path operation*'ın bir tag'i olmasını sağlayabilir ve operation ID'yi **tag** ve *path operation* **adı**na (function adı) göre üretebilirsiniz.
+
+### Benzersiz ID Üreten Özel Fonksiyon { #custom-generate-unique-id-function }
+
+FastAPI, her *path operation* için bir **unique ID** kullanır. Bu ID, **operation ID** için ve ayrıca request/response'lar için gerekebilecek özel model isimleri için de kullanılır.
+
+Bu fonksiyonu özelleştirebilirsiniz. Bir `APIRoute` alır ve string döndürür.
+
+Örneğin burada ilk tag'i (muhtemelen tek tag'iniz olur) ve *path operation* adını (function adı) kullanıyor.
+
+Sonrasında bu özel fonksiyonu `generate_unique_id_function` parametresiyle **FastAPI**'ye geçebilirsiniz:
+
+{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *}
+
+### Özel Operation ID'lerle TypeScript Client Üretme { #generate-a-typescript-client-with-custom-operation-ids }
+
+Artık client'ı tekrar üretirseniz, geliştirilmiş method isimlerini göreceksiniz:
+
+
+
+Gördüğünüz gibi method isimleri artık önce tag'i, sonra function adını içeriyor; URL path'i ve HTTP operation bilgisini artık taşımıyor.
+
+### Client Üretecine Vermeden Önce OpenAPI Spesifikasyonunu Ön İşlemek { #preprocess-the-openapi-specification-for-the-client-generator }
+
+Üretilen kodda hâlâ bazı **tekrarlanan bilgiler** var.
+
+Bu method'un **items** ile ilişkili olduğunu zaten biliyoruz; çünkü bu kelime `ItemsService` içinde var (tag'den geliyor). Ama method adında da tag adı önek olarak duruyor. 😕
+
+OpenAPI genelinde muhtemelen bunu korumak isteriz; çünkü operation ID'lerin **benzersiz** olmasını sağlar.
+
+Ancak üretilen client için, client'ları üretmeden hemen önce OpenAPI operation ID'lerini **değiştirip**, method isimlerini daha hoş ve **temiz** hale getirebiliriz.
+
+OpenAPI JSON'u `openapi.json` diye bir dosyaya indirip, şu tarz bir script ile **öndeki tag'i kaldırabiliriz**:
+
+{* ../../docs_src/generate_clients/tutorial004_py39.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+Bununla operation ID'ler `items-get_items` gibi değerlerden sadece `get_items` olacak şekilde yeniden adlandırılır; böylece client üreteci daha basit method isimleri üretebilir.
+
+### Ön İşlenmiş OpenAPI ile TypeScript Client Üretme { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Sonuç artık bir `openapi.json` dosyasında olduğuna göre, input konumunu güncellemeniz gerekir:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+Yeni client'ı ürettikten sonra, tüm **otomatik tamamlama**, **satır içi hatalar**, vb. ile birlikte **temiz method isimleri** elde edersiniz:
+
+
+
+## Faydalar { #benefits }
+
+Otomatik üretilen client'ları kullanınca şu alanlarda **otomatik tamamlama** elde edersiniz:
+
+* Method'lar.
+* Body'deki request payload'ları, query parametreleri, vb.
+* Response payload'ları.
+
+Ayrıca her şey için **satır içi hatalar** (inline errors) da olur.
+
+Backend kodunu her güncellediğinizde ve frontend'i **yeniden ürettiğinizde**, yeni *path operation*'lar method olarak eklenir, eskileri kaldırılır ve diğer değişiklikler de üretilen koda yansır. 🤓
+
+Bu, bir şey değiştiğinde client code'a otomatik olarak **yansıyacağı** anlamına gelir. Ayrıca client'ı **build** ettiğinizde, kullanılan verilerde bir **uyuşmazlık** (mismatch) varsa hata alırsınız.
+
+Böylece üretimde son kullanıcılara hata yansımasını beklemek ve sonra sorunun nerede olduğunu debug etmeye çalışmak yerine, geliştirme sürecinin çok erken aşamalarında **birçok hatayı tespit edersiniz**. ✨
diff --git a/docs/tr/docs/advanced/middleware.md b/docs/tr/docs/advanced/middleware.md
new file mode 100644
index 000000000..a22644a09
--- /dev/null
+++ b/docs/tr/docs/advanced/middleware.md
@@ -0,0 +1,97 @@
+# İleri Seviye Middleware { #advanced-middleware }
+
+Ana tutorial'da uygulamanıza [Özel Middleware](../tutorial/middleware.md){.internal-link target=_blank} eklemeyi gördünüz.
+
+Ardından [`CORSMiddleware` ile CORS'u yönetmeyi](../tutorial/cors.md){.internal-link target=_blank} de okudunuz.
+
+Bu bölümde diğer middleware'leri nasıl kullanacağımıza bakacağız.
+
+## ASGI middleware'leri ekleme { #adding-asgi-middlewares }
+
+**FastAPI**, Starlette üzerine kurulu olduğu ve ASGI spesifikasyonunu uyguladığı için, herhangi bir ASGI middleware'ini kullanabilirsiniz.
+
+Bir middleware'in çalışması için özellikle FastAPI ya da Starlette için yazılmış olması gerekmez; ASGI spec'ine uyduğu sürece yeterlidir.
+
+Genel olarak ASGI middleware'leri, ilk argüman olarak bir ASGI app almayı bekleyen class'lar olur.
+
+Dolayısıyla üçüncü taraf ASGI middleware'lerinin dokümantasyonunda muhtemelen şöyle bir şey yapmanızı söylerler:
+
+```Python
+from unicorn import UnicornMiddleware
+
+app = SomeASGIApp()
+
+new_app = UnicornMiddleware(app, some_config="rainbow")
+```
+
+Ancak FastAPI (aslında Starlette) bunu yapmanın daha basit bir yolunu sunar; böylece dahili middleware'ler server hatalarını doğru şekilde ele alır ve özel exception handler'lar düzgün çalışır.
+
+Bunun için `app.add_middleware()` kullanırsınız (CORS örneğindeki gibi).
+
+```Python
+from fastapi import FastAPI
+from unicorn import UnicornMiddleware
+
+app = FastAPI()
+
+app.add_middleware(UnicornMiddleware, some_config="rainbow")
+```
+
+`app.add_middleware()` ilk argüman olarak bir middleware class'ı alır ve middleware'e aktarılacak ek argümanları da kabul eder.
+
+## Entegre middleware'ler { #integrated-middlewares }
+
+**FastAPI**, yaygın kullanım senaryoları için birkaç middleware içerir; şimdi bunları nasıl kullanacağımıza bakacağız.
+
+/// note | Teknik Detaylar
+
+Bir sonraki örneklerde `from starlette.middleware.something import SomethingMiddleware` kullanmanız da mümkündür.
+
+**FastAPI**, size (geliştirici olarak) kolaylık olsun diye `fastapi.middleware` içinde bazı middleware'leri sağlar. Ancak mevcut middleware'lerin çoğu doğrudan Starlette'ten gelir.
+
+///
+
+## `HTTPSRedirectMiddleware` { #httpsredirectmiddleware }
+
+Gelen tüm request'lerin `https` veya `wss` olmasını zorunlu kılar.
+
+`http` veya `ws` olarak gelen herhangi bir request, bunun yerine güvenli şemaya redirect edilir.
+
+{* ../../docs_src/advanced_middleware/tutorial001_py39.py hl[2,6] *}
+
+## `TrustedHostMiddleware` { #trustedhostmiddleware }
+
+HTTP Host Header saldırılarına karşı korunmak için, gelen tüm request'lerde `Host` header'ının doğru ayarlanmış olmasını zorunlu kılar.
+
+{* ../../docs_src/advanced_middleware/tutorial002_py39.py hl[2,6:8] *}
+
+Aşağıdaki argümanlar desteklenir:
+
+* `allowed_hosts` - Hostname olarak izin verilmesi gereken domain adlarının listesi. `*.example.com` gibi wildcard domain'ler subdomain eşleştirmesi için desteklenir. Herhangi bir hostname'e izin vermek için `allowed_hosts=["*"]` kullanın veya middleware'i hiç eklemeyin.
+* `www_redirect` - True olarak ayarlanırsa, izin verilen host'ların www olmayan sürümlerine gelen request'ler www sürümlerine redirect edilir. Varsayılanı `True`'dur.
+
+Gelen bir request doğru şekilde doğrulanmazsa `400` response gönderilir.
+
+## `GZipMiddleware` { #gzipmiddleware }
+
+`Accept-Encoding` header'ında `"gzip"` içeren herhangi bir request için GZip response'larını yönetir.
+
+Middleware hem standart hem de streaming response'ları ele alır.
+
+{* ../../docs_src/advanced_middleware/tutorial003_py39.py hl[2,6] *}
+
+Aşağıdaki argümanlar desteklenir:
+
+* `minimum_size` - Bayt cinsinden bu minimum boyuttan küçük response'lara GZip uygulama. Varsayılanı `500`'dür.
+* `compresslevel` - GZip sıkıştırması sırasında kullanılır. 1 ile 9 arasında bir tamsayıdır. Varsayılanı `9`'dur. Daha düşük değer daha hızlı sıkıştırma ama daha büyük dosya boyutları üretir; daha yüksek değer daha yavaş sıkıştırma ama daha küçük dosya boyutları üretir.
+
+## Diğer middleware'ler { #other-middlewares }
+
+Başka birçok ASGI middleware'i vardır.
+
+Örneğin:
+
+* Uvicorn'un `ProxyHeadersMiddleware`'i
+* MessagePack
+
+Diğer mevcut middleware'leri görmek için Starlette'in Middleware dokümanlarına ve ASGI Awesome List listesine bakın.
diff --git a/docs/tr/docs/advanced/openapi-callbacks.md b/docs/tr/docs/advanced/openapi-callbacks.md
new file mode 100644
index 000000000..61135b7e0
--- /dev/null
+++ b/docs/tr/docs/advanced/openapi-callbacks.md
@@ -0,0 +1,186 @@
+# OpenAPI Callback'leri { #openapi-callbacks }
+
+Başka biri tarafından (muhtemelen API'nizi *kullanacak* olan aynı geliştirici tarafından) oluşturulmuş bir *external API*'ye request tetikleyebilen bir *path operation* ile bir API oluşturabilirsiniz.
+
+API uygulamanızın *external API*'yi çağırdığı sırada gerçekleşen sürece "callback" denir. Çünkü dış geliştiricinin yazdığı yazılım API'nize bir request gönderir ve ardından API'niz *geri çağrı* yaparak (*call back*), bir *external API*'ye request gönderir (muhtemelen aynı geliştiricinin oluşturduğu).
+
+Bu durumda, o external API'nin nasıl görünmesi *gerektiğini* dokümante etmek isteyebilirsiniz. Hangi *path operation*'a sahip olmalı, hangi body'yi beklemeli, hangi response'u döndürmeli, vb.
+
+## Callback'leri olan bir uygulama { #an-app-with-callbacks }
+
+Bunların hepsine bir örnekle bakalım.
+
+Fatura oluşturmayı sağlayan bir uygulama geliştirdiğinizi düşünün.
+
+Bu faturaların `id`, `title` (opsiyonel), `customer` ve `total` alanları olacak.
+
+API'nizin kullanıcısı (external bir geliştirici) API'nizde bir POST request ile fatura oluşturacak.
+
+Sonra API'niz (varsayalım ki):
+
+* Faturayı external geliştiricinin bir müşterisine gönderir.
+* Parayı tahsil eder.
+* API kullanıcısına (external geliştiriciye) tekrar bir bildirim gönderir.
+ * Bu, external geliştiricinin sağladığı bir *external API*'ye (*sizin API'nizden*) bir POST request gönderilerek yapılır (işte bu "callback"tir).
+
+## Normal **FastAPI** uygulaması { #the-normal-fastapi-app }
+
+Önce callback eklemeden önce normal API uygulamasının nasıl görüneceğine bakalım.
+
+Bir `Invoice` body alacak bir *path operation*'ı ve callback için URL'yi taşıyacak `callback_url` adlı bir query parametresi olacak.
+
+Bu kısım oldukça standart; kodun çoğu muhtemelen size zaten tanıdık gelecektir:
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[7:11,34:51] *}
+
+/// tip | İpucu
+
+`callback_url` query parametresi, Pydantic'in Url tipini kullanır.
+
+///
+
+Tek yeni şey, *path operation decorator*'ına argüman olarak verilen `callbacks=invoices_callback_router.routes`. Bunun ne olduğuna şimdi bakacağız.
+
+## Callback'i dokümante etmek { #documenting-the-callback }
+
+Callback'in gerçek kodu, büyük ölçüde sizin API uygulamanıza bağlıdır.
+
+Ve bir uygulamadan diğerine oldukça değişebilir.
+
+Sadece bir-iki satır kod bile olabilir, örneğin:
+
+```Python
+callback_url = "https://example.com/api/v1/invoices/events/"
+httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
+```
+
+Ancak callback'in belki de en önemli kısmı, API'nizin kullanıcısının (external geliştiricinin) *external API*'yi doğru şekilde uyguladığından emin olmaktır; çünkü *sizin API'niz* callback'in request body'sinde belirli veriler gönderecektir, vb.
+
+Dolayısıyla sıradaki adım olarak, *sizin API'nizden* callback almak için o *external API*'nin nasıl görünmesi gerektiğini dokümante eden kodu ekleyeceğiz.
+
+Bu dokümantasyon, API'nizde `/docs` altındaki Swagger UI'da görünecek ve external geliştiricilere *external API*'yi nasıl inşa edeceklerini gösterecek.
+
+Bu örnek callback'in kendisini implemente etmiyor (o zaten tek satır kod olabilir), sadece dokümantasyon kısmını ekliyor.
+
+/// tip | İpucu
+
+Gerçek callback, sadece bir HTTP request'tir.
+
+Callback'i kendiniz implemente ederken HTTPX veya Requests gibi bir şey kullanabilirsiniz.
+
+///
+
+## Callback dokümantasyon kodunu yazın { #write-the-callback-documentation-code }
+
+Bu kod uygulamanızda çalıştırılmayacak; sadece o *external API*'nin nasıl görünmesi gerektiğini *dokümante etmek* için gerekiyor.
+
+Ancak **FastAPI** ile bir API için otomatik dokümantasyonu kolayca nasıl üreteceğinizi zaten biliyorsunuz.
+
+O halde aynı bilgiyi kullanarak, *external API*'nin nasıl görünmesi gerektiğini dokümante edeceğiz... external API'nin implemente etmesi gereken *path operation*'ları oluşturarak (API'nizin çağıracağı olanlar).
+
+/// tip | İpucu
+
+Bir callback'i dokümante eden kodu yazarken, kendinizi *external geliştirici* olarak hayal etmek faydalı olabilir. Ve şu anda *sizin API'nizi* değil, *external API*'yi implemente ettiğinizi düşünün.
+
+Bu bakış açısını (external geliştiricinin bakış açısını) geçici olarak benimsemek; parametreleri nereye koyacağınızı, body için Pydantic modelini, response için modelini vb. external API tarafında nasıl tasarlayacağınızı daha net hale getirebilir.
+
+///
+
+### Bir callback `APIRouter` oluşturun { #create-a-callback-apirouter }
+
+Önce bir veya daha fazla callback içerecek yeni bir `APIRouter` oluşturun.
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[1,23] *}
+
+### Callback *path operation*'ını oluşturun { #create-the-callback-path-operation }
+
+Callback *path operation*'ını oluşturmak için, yukarıda oluşturduğunuz aynı `APIRouter`'ı kullanın.
+
+Normal bir FastAPI *path operation*'ı gibi görünmelidir:
+
+* Muhtemelen alması gereken body'nin bir deklarasyonu olmalı, örn. `body: InvoiceEvent`.
+* Ayrıca döndürmesi gereken response'un deklarasyonu da olabilir, örn. `response_model=InvoiceEventReceived`.
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[14:16,19:20,26:30] *}
+
+Normal bir *path operation*'dan 2 temel farkı vardır:
+
+* Gerçek bir koda ihtiyaç duymaz; çünkü uygulamanız bu kodu asla çağırmayacak. Bu yalnızca *external API*'yi dokümante etmek için kullanılır. Yani fonksiyon sadece `pass` içerebilir.
+* *path*, bir OpenAPI 3 expression (aşağıda daha fazlası) içerebilir; böylece parametreler ve *sizin API'nize* gönderilen orijinal request'in bazı parçalarıyla değişkenler kullanılabilir.
+
+### Callback path ifadesi { #the-callback-path-expression }
+
+Callback *path*'i, *sizin API'nize* gönderilen orijinal request'in bazı parçalarını içerebilen bir OpenAPI 3 expression barındırabilir.
+
+Bu örnekte, bu bir `str`:
+
+```Python
+"{$callback_url}/invoices/{$request.body.id}"
+```
+
+Yani API'nizin kullanıcısı (external geliştirici) *sizin API'nize* şu adrese bir request gönderirse:
+
+```
+https://yourapi.com/invoices/?callback_url=https://www.external.org/events
+```
+
+ve JSON body şu şekilde olursa:
+
+```JSON
+{
+ "id": "2expen51ve",
+ "customer": "Mr. Richie Rich",
+ "total": "9999"
+}
+```
+
+o zaman *sizin API'niz* faturayı işleyecek ve daha sonra bir noktada `callback_url`'ye (yani *external API*'ye) bir callback request gönderecek:
+
+```
+https://www.external.org/events/invoices/2expen51ve
+```
+
+ve JSON body yaklaşık şöyle bir şey içerecek:
+
+```JSON
+{
+ "description": "Payment celebration",
+ "paid": true
+}
+```
+
+ve o *external API*'den şu gibi bir JSON body içeren response bekleyecek:
+
+```JSON
+{
+ "ok": true
+}
+```
+
+/// tip | İpucu
+
+Callback URL'sinin, `callback_url` içindeki query parametresi olarak alınan URL'yi (`https://www.external.org/events`) ve ayrıca JSON body'nin içindeki fatura `id`'sini (`2expen51ve`) birlikte kullandığına dikkat edin.
+
+///
+
+### Callback router'ını ekleyin { #add-the-callback-router }
+
+Bu noktada, yukarıda oluşturduğunuz callback router'ında gerekli callback *path operation*'ları (external geliştiricinin *external API*'de implemente etmesi gerekenler) hazır.
+
+Şimdi *sizin API'nizin path operation decorator*'ında `callbacks` parametresini kullanarak, callback router'ının `.routes` attribute'unu (bu aslında route/*path operation*'lardan oluşan bir `list`) geçin:
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *}
+
+/// tip | İpucu
+
+`callback=` içine router'ın kendisini (`invoices_callback_router`) değil, `invoices_callback_router.routes` şeklinde `.routes` attribute'unu verdiğinize dikkat edin.
+
+///
+
+### Dokümanları kontrol edin { #check-the-docs }
+
+Artık uygulamanızı başlatıp http://127.0.0.1:8000/docs adresine gidebilirsiniz.
+
+*Path operation*'ınız için, *external API*'nin nasıl görünmesi gerektiğini gösteren bir "Callbacks" bölümünü içeren dokümanları göreceksiniz:
+
+
diff --git a/docs/tr/docs/advanced/openapi-webhooks.md b/docs/tr/docs/advanced/openapi-webhooks.md
new file mode 100644
index 000000000..dd9e9bbe7
--- /dev/null
+++ b/docs/tr/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# OpenAPI Webhook'lar { #openapi-webhooks }
+
+Bazı durumlarda, API'nizi kullanan **kullanıcılara** uygulamanızın *onların* uygulamasını (request göndererek) bazı verilerle çağırabileceğini; genellikle bir tür **event** hakkında **bildirim** yapmak için kullanacağını söylemek istersiniz.
+
+Bu da şunu ifade eder: Kullanıcılarınızın API'nize request göndermesi şeklindeki normal akış yerine, request'i **sizin API'niz** (veya uygulamanız) **onların sistemine** (onların API'sine, onların uygulamasına) **gönderebilir**.
+
+Buna genellikle **webhook** denir.
+
+## Webhook adımları { #webhooks-steps }
+
+Süreç genellikle şöyledir: Kodunuzda göndereceğiniz mesajın ne olduğunu, yani request'in **body**'sini **siz tanımlarsınız**.
+
+Ayrıca uygulamanızın bu request'leri veya event'leri hangi **anlarda** göndereceğini de bir şekilde tanımlarsınız.
+
+Ve **kullanıcılarınız** da bir şekilde (örneğin bir web dashboard üzerinden) uygulamanızın bu request'leri göndermesi gereken **URL**'yi tanımlar.
+
+Webhook'lar için URL'lerin nasıl kaydedileceğine dair tüm **mantık** ve bu request'leri gerçekten gönderen kod tamamen size bağlıdır. Bunu **kendi kodunuzda** istediğiniz gibi yazarsınız.
+
+## **FastAPI** ve OpenAPI ile webhook'ları dokümante etmek { #documenting-webhooks-with-fastapi-and-openapi }
+
+**FastAPI** ile OpenAPI kullanarak bu webhook'ların adlarını, uygulamanızın gönderebileceği HTTP operation türlerini (örn. `POST`, `PUT`, vb.) ve uygulamanızın göndereceği request **body**'lerini tanımlayabilirsiniz.
+
+Bu, kullanıcılarınızın **webhook** request'lerinizi alacak şekilde **API'lerini implement etmesini** çok daha kolaylaştırabilir; hatta kendi API kodlarının bir kısmını otomatik üretebilirler.
+
+/// info | Bilgi
+
+Webhook'lar OpenAPI 3.1.0 ve üzeri sürümlerde mevcuttur; FastAPI `0.99.0` ve üzeri tarafından desteklenir.
+
+///
+
+## Webhook'ları olan bir uygulama { #an-app-with-webhooks }
+
+Bir **FastAPI** uygulaması oluşturduğunuzda, *webhook*'ları tanımlamak için kullanabileceğiniz bir `webhooks` attribute'u vardır; *path operation* tanımlar gibi, örneğin `@app.webhooks.post()` ile.
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py39.py hl[9:13,36:53] *}
+
+Tanımladığınız webhook'lar **OpenAPI** şemasında ve otomatik **docs UI**'da yer alır.
+
+/// info | Bilgi
+
+`app.webhooks` nesnesi aslında sadece bir `APIRouter`'dır; uygulamanızı birden fazla dosya ile yapılandırırken kullanacağınız türün aynısıdır.
+
+///
+
+Dikkat edin: Webhook'larda aslında bir *path* (ör. `/items/`) deklare etmiyorsunuz; oraya verdiğiniz metin sadece webhook'un bir **identifier**'ıdır (event'in adı). Örneğin `@app.webhooks.post("new-subscription")` içinde webhook adı `new-subscription`'dır.
+
+Bunun nedeni, webhook request'ini almak istedikleri gerçek **URL path**'i **kullanıcılarınızın** başka bir şekilde (örn. bir web dashboard üzerinden) tanımlamasının beklenmesidir.
+
+### Dokümanları kontrol edin { #check-the-docs }
+
+Şimdi uygulamanızı başlatıp http://127.0.0.1:8000/docs adresine gidin.
+
+Dokümanlarınızda normal *path operation*'ları ve artık bazı **webhook**'ları da göreceksiniz:
+
+
diff --git a/docs/tr/docs/advanced/path-operation-advanced-configuration.md b/docs/tr/docs/advanced/path-operation-advanced-configuration.md
new file mode 100644
index 000000000..e326842d6
--- /dev/null
+++ b/docs/tr/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,172 @@
+# Path Operation İleri Düzey Yapılandırma { #path-operation-advanced-configuration }
+
+## OpenAPI operationId { #openapi-operationid }
+
+/// warning | Uyarı
+
+OpenAPI konusunda "uzman" değilseniz, muhtemelen buna ihtiyacınız yok.
+
+///
+
+*path operation*’ınızda kullanılacak OpenAPI `operationId` değerini `operation_id` parametresiyle ayarlayabilirsiniz.
+
+Bunun her operation için benzersiz olduğundan emin olmanız gerekir.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}
+
+### operationId olarak *path operation function* adını kullanma { #using-the-path-operation-function-name-as-the-operationid }
+
+API’lerinizin function adlarını `operationId` olarak kullanmak istiyorsanız, hepsini dolaşıp her *path operation*’ın `operation_id` değerini `APIRoute.name` ile override edebilirsiniz.
+
+Bunu, tüm *path operation*’ları ekledikten sonra yapmalısınız.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py39.py hl[2, 12:21, 24] *}
+
+/// tip | İpucu
+
+`app.openapi()` fonksiyonunu manuel olarak çağırıyorsanız, bunu yapmadan önce `operationId`’leri güncellemelisiniz.
+
+///
+
+/// warning | Uyarı
+
+Bunu yaparsanız, her bir *path operation function*’ın adının benzersiz olduğundan emin olmanız gerekir.
+
+Farklı modüllerde (Python dosyalarında) olsalar bile.
+
+///
+
+## OpenAPI’den Hariç Tutma { #exclude-from-openapi }
+
+Bir *path operation*’ı üretilen OpenAPI şemasından (dolayısıyla otomatik dokümantasyon sistemlerinden) hariç tutmak için `include_in_schema` parametresini kullanın ve `False` yapın:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}
+
+## Docstring’den İleri Düzey Açıklama { #advanced-description-from-docstring }
+
+OpenAPI için, bir *path operation function*’ın docstring’inden kullanılacak satırları sınırlandırabilirsiniz.
+
+Bir `\f` (escape edilmiş "form feed" karakteri) eklerseniz, **FastAPI** OpenAPI için kullanılan çıktıyı bu noktada **keser**.
+
+Dokümantasyonda görünmez, ancak diğer araçlar (Sphinx gibi) geri kalan kısmı kullanabilir.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## Ek Responses { #additional-responses }
+
+Muhtemelen bir *path operation* için `response_model` ve `status_code` tanımlamayı görmüşsünüzdür.
+
+Bu, bir *path operation*’ın ana response’u ile ilgili metadata’yı tanımlar.
+
+Ek response’ları; modelleri, status code’ları vb. ile birlikte ayrıca da tanımlayabilirsiniz.
+
+Dokümantasyonda bununla ilgili ayrı bir bölüm var; [OpenAPI’de Ek Responses](additional-responses.md){.internal-link target=_blank} sayfasından okuyabilirsiniz.
+
+## OpenAPI Extra { #openapi-extra }
+
+Uygulamanızda bir *path operation* tanımladığınızda, **FastAPI** OpenAPI şemasına dahil edilmek üzere o *path operation* ile ilgili metadata’yı otomatik olarak üretir.
+
+/// note | Teknik Detaylar
+
+OpenAPI spesifikasyonunda buna Operation Object denir.
+
+///
+
+Bu, *path operation* hakkında tüm bilgileri içerir ve otomatik dokümantasyonu üretmek için kullanılır.
+
+`tags`, `parameters`, `requestBody`, `responses` vb. alanları içerir.
+
+Bu *path operation*’a özel OpenAPI şeması normalde **FastAPI** tarafından otomatik üretilir; ancak siz bunu genişletebilirsiniz.
+
+/// tip | İpucu
+
+Bu, düşük seviyeli bir genişletme noktasıdır.
+
+Yalnızca ek response’lar tanımlamanız gerekiyorsa, bunu yapmanın daha pratik yolu [OpenAPI’de Ek Responses](additional-responses.md){.internal-link target=_blank} kullanmaktır.
+
+///
+
+Bir *path operation* için OpenAPI şemasını `openapi_extra` parametresiyle genişletebilirsiniz.
+
+### OpenAPI Extensions { #openapi-extensions }
+
+Örneğin bu `openapi_extra`, [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) tanımlamak için faydalı olabilir:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py39.py hl[6] *}
+
+Otomatik API dokümanlarını açtığınızda, extension’ınız ilgili *path operation*’ın en altında görünür.
+
+
+
+Ayrıca ortaya çıkan OpenAPI’yi (API’nizde `/openapi.json`) görüntülerseniz, extension’ınızı ilgili *path operation*’ın bir parçası olarak orada da görürsünüz:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### Özel OpenAPI *path operation* şeması { #custom-openapi-path-operation-schema }
+
+`openapi_extra` içindeki dictionary, *path operation* için otomatik üretilen OpenAPI şemasıyla derinlemesine (deep) birleştirilir.
+
+Böylece otomatik üretilen şemaya ek veri ekleyebilirsiniz.
+
+Örneğin, Pydantic ile FastAPI’nin otomatik özelliklerini kullanmadan request’i kendi kodunuzla okuyup doğrulamaya karar verebilirsiniz; ancak yine de OpenAPI şemasında request’i tanımlamak isteyebilirsiniz.
+
+Bunu `openapi_extra` ile yapabilirsiniz:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py39.py hl[19:36, 39:40] *}
+
+Bu örnekte herhangi bir Pydantic model tanımlamadık. Hatta request body JSON olarak parsed bile edilmiyor; doğrudan `bytes` olarak okunuyor ve `magic_data_reader()` fonksiyonu bunu bir şekilde parse etmekten sorumlu oluyor.
+
+Buna rağmen, request body için beklenen şemayı tanımlayabiliriz.
+
+### Özel OpenAPI content type { #custom-openapi-content-type }
+
+Aynı yöntemi kullanarak, Pydantic model ile JSON Schema’yı tanımlayıp bunu *path operation* için özel OpenAPI şeması bölümüne dahil edebilirsiniz.
+
+Ve bunu, request içindeki veri tipi JSON olmasa bile yapabilirsiniz.
+
+Örneğin bu uygulamada, FastAPI’nin Pydantic modellerinden JSON Schema çıkarmaya yönelik entegre işlevselliğini ve JSON için otomatik doğrulamayı kullanmıyoruz. Hatta request content type’ını JSON değil, YAML olarak tanımlıyoruz:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[15:20, 22] *}
+
+Buna rağmen, varsayılan entegre işlevselliği kullanmasak da, YAML olarak almak istediğimiz veri için JSON Schema’yı manuel üretmek üzere bir Pydantic model kullanmaya devam ediyoruz.
+
+Ardından request’i doğrudan kullanıp body’yi `bytes` olarak çıkarıyoruz. Bu da FastAPI’nin request payload’ını JSON olarak parse etmeye çalışmayacağı anlamına gelir.
+
+Sonrasında kodumuzda bu YAML içeriğini doğrudan parse ediyor, ardından YAML içeriğini doğrulamak için yine aynı Pydantic modeli kullanıyoruz:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[24:31] *}
+
+/// tip | İpucu
+
+Burada aynı Pydantic modeli tekrar kullanıyoruz.
+
+Aynı şekilde, başka bir yöntemle de doğrulama yapabilirdik.
+
+///
diff --git a/docs/tr/docs/advanced/response-change-status-code.md b/docs/tr/docs/advanced/response-change-status-code.md
new file mode 100644
index 000000000..239c0dddd
--- /dev/null
+++ b/docs/tr/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# Response - Status Code Değiştirme { #response-change-status-code }
+
+Muhtemelen daha önce varsayılan bir [Response Status Code](../tutorial/response-status-code.md){.internal-link target=_blank} ayarlayabileceğinizi okumuşsunuzdur.
+
+Ancak bazı durumlarda, varsayılandan farklı bir status code döndürmeniz gerekir.
+
+## Kullanım senaryosu { #use-case }
+
+Örneğin, varsayılan olarak "OK" `200` HTTP status code'u döndürmek istediğinizi düşünün.
+
+Ama veri mevcut değilse onu oluşturmak ve "CREATED" `201` HTTP status code'u döndürmek istiyorsunuz.
+
+Aynı zamanda, döndürdüğünüz veriyi bir `response_model` ile filtreleyip dönüştürebilmeyi de sürdürmek istiyorsunuz.
+
+Bu tür durumlarda bir `Response` parametresi kullanabilirsiniz.
+
+## Bir `Response` parametresi kullanın { #use-a-response-parameter }
+
+*Path operation function* içinde `Response` tipinde bir parametre tanımlayabilirsiniz (cookie ve header'lar için yapabildiğiniz gibi).
+
+Ardından bu *geçici (temporal)* `Response` nesnesi üzerinde `status_code` değerini ayarlayabilirsiniz.
+
+{* ../../docs_src/response_change_status_code/tutorial001_py39.py hl[1,9,12] *}
+
+Sonrasında, normalde yaptığınız gibi ihtiyacınız olan herhangi bir nesneyi döndürebilirsiniz (`dict`, bir veritabanı modeli, vb.).
+
+Ve eğer bir `response_model` tanımladıysanız, döndürdüğünüz nesneyi filtrelemek ve dönüştürmek için yine kullanılacaktır.
+
+**FastAPI**, status code'u (ayrıca cookie ve header'ları) bu *geçici (temporal)* response'tan alır ve `response_model` ile filtrelenmiş, sizin döndürdüğünüz değeri içeren nihai response'a yerleştirir.
+
+Ayrıca `Response` parametresini dependency'lerde de tanımlayıp status code'u orada ayarlayabilirsiniz. Ancak unutmayın, en son ayarlanan değer geçerli olur.
diff --git a/docs/tr/docs/advanced/response-cookies.md b/docs/tr/docs/advanced/response-cookies.md
new file mode 100644
index 000000000..d00bfc4cd
--- /dev/null
+++ b/docs/tr/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# Response Cookie'leri { #response-cookies }
+
+## Bir `Response` parametresi kullanın { #use-a-response-parameter }
+
+*Path operation function* içinde `Response` tipinde bir parametre tanımlayabilirsiniz.
+
+Ardından bu *geçici* response nesnesi üzerinde cookie'leri set edebilirsiniz.
+
+{* ../../docs_src/response_cookies/tutorial002_py39.py hl[1, 8:9] *}
+
+Sonrasında normalde yaptığınız gibi ihtiyaç duyduğunuz herhangi bir nesneyi döndürebilirsiniz (bir `dict`, bir veritabanı modeli vb.).
+
+Ayrıca bir `response_model` tanımladıysanız, döndürdüğünüz nesneyi filtrelemek ve dönüştürmek için yine kullanılacaktır.
+
+**FastAPI**, bu *geçici* response'u cookie'leri (ayrıca header'ları ve status code'u) çıkarmak için kullanır ve bunları, döndürdüğünüz değeri içeren nihai response'a ekler. Döndürdüğünüz değer, varsa `response_model` ile filtrelenmiş olur.
+
+`Response` parametresini dependency'lerde de tanımlayıp, onların içinde cookie (ve header) set edebilirsiniz.
+
+## Doğrudan bir `Response` döndürün { #return-a-response-directly }
+
+Kodunuzda doğrudan bir `Response` döndürürken de cookie oluşturabilirsiniz.
+
+Bunu yapmak için, [Doğrudan Response Döndürme](response-directly.md){.internal-link target=_blank} bölümünde anlatıldığı gibi bir response oluşturabilirsiniz.
+
+Sonra bunun içinde Cookie'leri set edin ve response'u döndürün:
+
+{* ../../docs_src/response_cookies/tutorial001_py39.py hl[10:12] *}
+
+/// tip | İpucu
+
+`Response` parametresini kullanmak yerine doğrudan bir response döndürürseniz, FastAPI onu olduğu gibi (doğrudan) döndürür.
+
+Bu yüzden, verinizin doğru tipte olduğundan emin olmanız gerekir. Örneğin `JSONResponse` döndürüyorsanız, verinin JSON ile uyumlu olması gerekir.
+
+Ayrıca `response_model` tarafından filtrelenmesi gereken bir veriyi göndermediğinizden de emin olun.
+
+///
+
+### Daha fazla bilgi { #more-info }
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import Response` veya `from starlette.responses import JSONResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olması için `fastapi.responses` içinde `starlette.responses` ile aynı response sınıflarını sunar. Ancak mevcut response'ların büyük kısmı doğrudan Starlette'ten gelir.
+
+Ve `Response`, header ve cookie set etmek için sık kullanıldığından, **FastAPI** bunu `fastapi.Response` olarak da sağlar.
+
+///
+
+Mevcut tüm parametreleri ve seçenekleri görmek için Starlette dokümantasyonuna bakın.
diff --git a/docs/tr/docs/advanced/response-directly.md b/docs/tr/docs/advanced/response-directly.md
new file mode 100644
index 000000000..332f1224f
--- /dev/null
+++ b/docs/tr/docs/advanced/response-directly.md
@@ -0,0 +1,65 @@
+# Doğrudan Bir Response Döndürme { #return-a-response-directly }
+
+**FastAPI** ile bir *path operation* oluşturduğunuzda, normalde ondan herhangi bir veri döndürebilirsiniz: bir `dict`, bir `list`, bir Pydantic model, bir veritabanı modeli vb.
+
+Varsayılan olarak **FastAPI**, döndürdüğünüz bu değeri [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} bölümünde anlatılan `jsonable_encoder` ile otomatik olarak JSON'a çevirir.
+
+Ardından perde arkasında, JSON-uyumlu bu veriyi (ör. bir `dict`) client'a response göndermek için kullanılacak bir `JSONResponse` içine yerleştirir.
+
+Ancak *path operation*'larınızdan doğrudan bir `JSONResponse` döndürebilirsiniz.
+
+Bu, örneğin özel header'lar veya cookie'ler döndürmek istediğinizde faydalı olabilir.
+
+## Bir `Response` Döndürme { #return-a-response }
+
+Aslında herhangi bir `Response` veya onun herhangi bir alt sınıfını döndürebilirsiniz.
+
+/// tip | İpucu
+
+`JSONResponse` zaten `Response`'un bir alt sınıfıdır.
+
+///
+
+Bir `Response` döndürdüğünüzde, **FastAPI** bunu olduğu gibi doğrudan iletir.
+
+Pydantic model'leriyle herhangi bir veri dönüşümü yapmaz, içeriği başka bir tipe çevirmez vb.
+
+Bu size ciddi bir esneklik sağlar. Herhangi bir veri türü döndürebilir, herhangi bir veri deklarasyonunu veya validasyonunu override edebilirsiniz.
+
+## Bir `Response` İçinde `jsonable_encoder` Kullanma { #using-the-jsonable-encoder-in-a-response }
+
+**FastAPI**, sizin döndürdüğünüz `Response` üzerinde hiçbir değişiklik yapmadığı için, içeriğinin gönderilmeye hazır olduğundan emin olmanız gerekir.
+
+Örneğin, bir Pydantic model'i, önce JSON-uyumlu tiplere çevrilmeden (`datetime`, `UUID` vb.) doğrudan bir `JSONResponse` içine koyamazsınız. Önce tüm veri tipleri JSON-uyumlu hale gelecek şekilde `dict`'e çevrilmesi gerekir.
+
+Bu gibi durumlarda, response'a vermeden önce verinizi dönüştürmek için `jsonable_encoder` kullanabilirsiniz:
+
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import JSONResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olması için `starlette.responses` içeriğini `fastapi.responses` üzerinden de sunar. Ancak mevcut response'ların çoğu doğrudan Starlette'tan gelir.
+
+///
+
+## Özel Bir `Response` Döndürme { #returning-a-custom-response }
+
+Yukarıdaki örnek ihtiyaç duyduğunuz tüm parçaları gösteriyor, ancak henüz çok kullanışlı değil. Çünkü `item`'ı zaten doğrudan döndürebilirdiniz ve **FastAPI** varsayılan olarak onu sizin için bir `JSONResponse` içine koyup `dict`'e çevirirdi vb.
+
+Şimdi bunu kullanarak nasıl özel bir response döndürebileceğinize bakalım.
+
+Diyelim ki XML response döndürmek istiyorsunuz.
+
+XML içeriğinizi bir string içine koyabilir, onu bir `Response` içine yerleştirip döndürebilirsiniz:
+
+{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
+
+## Notlar { #notes }
+
+Bir `Response`'u doğrudan döndürdüğünüzde, verisi otomatik olarak validate edilmez, dönüştürülmez (serialize edilmez) veya dokümante edilmez.
+
+Ancak yine de [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} bölümünde anlatıldığı şekilde dokümante edebilirsiniz.
+
+İlerleyen bölümlerde, otomatik veri dönüşümü, dokümantasyon vb. özellikleri korurken bu özel `Response`'ları nasıl kullanıp declare edebileceğinizi göreceksiniz.
diff --git a/docs/tr/docs/advanced/response-headers.md b/docs/tr/docs/advanced/response-headers.md
new file mode 100644
index 000000000..85b0799d3
--- /dev/null
+++ b/docs/tr/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# Response Header'ları { #response-headers }
+
+## Bir `Response` parametresi kullanın { #use-a-response-parameter }
+
+*Path operation function* içinde (cookie'lerde yapabildiğiniz gibi) tipi `Response` olan bir parametre tanımlayabilirsiniz.
+
+Sonra da bu *geçici* response nesnesi üzerinde header'ları ayarlayabilirsiniz.
+
+{* ../../docs_src/response_headers/tutorial002_py39.py hl[1, 7:8] *}
+
+Ardından normalde yaptığınız gibi ihtiyacınız olan herhangi bir nesneyi döndürebilirsiniz (bir `dict`, bir veritabanı modeli vb.).
+
+Eğer bir `response_model` tanımladıysanız, döndürdüğünüz nesneyi filtrelemek ve dönüştürmek için yine kullanılacaktır.
+
+**FastAPI**, header'ları (aynı şekilde cookie'leri ve status code'u) bu *geçici* response'dan alır ve döndürdüğünüz değeri (varsa bir `response_model` ile filtrelenmiş hâliyle) içeren nihai response'a ekler.
+
+`Response` parametresini dependency'lerde de tanımlayıp, onların içinde header (ve cookie) ayarlayabilirsiniz.
+
+## Doğrudan bir `Response` döndürün { #return-a-response-directly }
+
+Doğrudan bir `Response` döndürdüğünüzde de header ekleyebilirsiniz.
+
+[Bir Response'u Doğrudan Döndürün](response-directly.md){.internal-link target=_blank} bölümünde anlatıldığı gibi bir response oluşturun ve header'ları ek bir parametre olarak geçin:
+
+{* ../../docs_src/response_headers/tutorial001_py39.py hl[10:12] *}
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import Response` veya `from starlette.responses import JSONResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olsun diye `starlette.responses` içeriğini `fastapi.responses` olarak da sunar. Ancak mevcut response'ların çoğu doğrudan Starlette'ten gelir.
+
+Ayrıca `Response` header ve cookie ayarlamak için sık kullanıldığından, **FastAPI** bunu `fastapi.Response` altında da sağlar.
+
+///
+
+## Özel Header'lar { #custom-headers }
+
+Özel/proprietary header'ların `X-` prefix'i kullanılarak eklenebileceğini unutmayın.
+
+Ancak tarayıcıdaki bir client'ın görebilmesini istediğiniz özel header'larınız varsa, bunları CORS ayarlarınıza eklemeniz gerekir ([CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank} bölümünde daha fazla bilgi), bunun için Starlette'in CORS dokümanında açıklanan `expose_headers` parametresini kullanın.
diff --git a/docs/tr/docs/advanced/security/http-basic-auth.md b/docs/tr/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 000000000..b194c763e
--- /dev/null
+++ b/docs/tr/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP Basic Auth { #http-basic-auth }
+
+En basit senaryolarda HTTP Basic Auth kullanabilirsiniz.
+
+HTTP Basic Auth’ta uygulama, içinde kullanıcı adı ve şifre bulunan bir header bekler.
+
+Eğer bunu almazsa HTTP 401 "Unauthorized" hatası döndürür.
+
+Ayrıca değeri `Basic` olan ve isteğe bağlı `realm` parametresi içerebilen `WWW-Authenticate` header’ını da döndürür.
+
+Bu da tarayıcıya, kullanıcı adı ve şifre için entegre giriş penceresini göstermesini söyler.
+
+Ardından kullanıcı adı ve şifreyi yazdığınızda tarayıcı bunları otomatik olarak header içinde gönderir.
+
+## Basit HTTP Basic Auth { #simple-http-basic-auth }
+
+* `HTTPBasic` ve `HTTPBasicCredentials` import edin.
+* `HTTPBasic` kullanarak bir "`security` scheme" oluşturun.
+* *path operation*’ınızda bir dependency ile bu `security`’yi kullanın.
+* Bu, `HTTPBasicCredentials` tipinde bir nesne döndürür:
+ * İçinde gönderilen `username` ve `password` bulunur.
+
+{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *}
+
+URL’yi ilk kez açmaya çalıştığınızda (veya dokümanlardaki "Execute" butonuna tıkladığınızda) tarayıcı sizden kullanıcı adınızı ve şifrenizi ister:
+
+
+
+## Kullanıcı adını kontrol edin { #check-the-username }
+
+Daha kapsamlı bir örneğe bakalım.
+
+Kullanıcı adı ve şifrenin doğru olup olmadığını kontrol etmek için bir dependency kullanın.
+
+Bunun için kullanıcı adı ve şifreyi kontrol ederken Python standart modülü olan `secrets`’i kullanın.
+
+`secrets.compare_digest()`; `bytes` ya da yalnızca ASCII karakterleri (İngilizce’deki karakterler) içeren bir `str` almalıdır. Bu da `Sebastián` içindeki `á` gibi karakterlerle çalışmayacağı anlamına gelir.
+
+Bunu yönetmek için önce `username` ve `password` değerlerini UTF-8 ile encode ederek `bytes`’a dönüştürürüz.
+
+Sonra `secrets.compare_digest()` kullanarak `credentials.username`’in `"stanleyjobson"` ve `credentials.password`’ün `"swordfish"` olduğundan emin olabiliriz.
+
+{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *}
+
+Bu, kabaca şuna benzer olurdu:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Return some error
+ ...
+```
+
+Ancak `secrets.compare_digest()` kullanarak, "timing attacks" denilen bir saldırı türüne karşı güvenli olursunuz.
+
+### Timing Attacks { #timing-attacks }
+
+Peki "timing attack" nedir?
+
+Bazı saldırganların kullanıcı adı ve şifreyi tahmin etmeye çalıştığını düşünelim.
+
+Ve `johndoe` kullanıcı adı ve `love123` şifresi ile bir request gönderiyorlar.
+
+Uygulamanızdaki Python kodu o zaman kabaca şuna denk olur:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Ancak Python, `johndoe` içindeki ilk `j` ile `stanleyjobson` içindeki ilk `s`’i karşılaştırdığı anda `False` döndürür; çünkü iki string’in aynı olmadığını zaten anlar ve "kalan harfleri karşılaştırmak için daha fazla hesaplama yapmaya gerek yok" diye düşünür. Uygulamanız da "Incorrect username or password" der.
+
+Sonra saldırganlar bu sefer `stanleyjobsox` kullanıcı adı ve `love123` şifresi ile dener.
+
+Uygulama kodunuz da şuna benzer bir şey yapar:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Bu kez Python, iki string’in aynı olmadığını fark etmeden önce hem `stanleyjobsox` hem de `stanleyjobson` içinde `stanleyjobso` kısmının tamamını karşılaştırmak zorunda kalır. Bu nedenle "Incorrect username or password" yanıtını vermesi birkaç mikro saniye daha uzun sürer.
+
+#### Yanıt süresi saldırganlara yardımcı olur { #the-time-to-answer-helps-the-attackers }
+
+Bu noktada saldırganlar, server’ın "Incorrect username or password" response’unu göndermesinin birkaç mikro saniye daha uzun sürdüğünü fark ederek _bir şeyleri_ doğru yaptıklarını anlar; yani başlangıçtaki bazı harfler doğrudur.
+
+Sonra tekrar denerken, bunun `johndoe`’dan ziyade `stanleyjobsox`’a daha yakın bir şey olması gerektiğini bilerek devam edebilirler.
+
+#### "Profesyonel" bir saldırı { #a-professional-attack }
+
+Elbette saldırganlar bunu elle tek tek denemez; bunu yapan bir program yazarlar. Muhtemelen saniyede binlerce ya da milyonlarca test yaparlar ve her seferinde yalnızca bir doğru harf daha elde ederler.
+
+Böylece birkaç dakika ya da birkaç saat içinde doğru kullanıcı adı ve şifreyi, yanıt süresini kullanarak ve uygulamamızın "yardımıyla" tahmin etmiş olurlar.
+
+#### `secrets.compare_digest()` ile düzeltin { #fix-it-with-secrets-compare-digest }
+
+Ancak bizim kodumuzda `secrets.compare_digest()` kullanıyoruz.
+
+Kısacası, `stanleyjobsox` ile `stanleyjobson`’u karşılaştırmak için geçen süre, `johndoe` ile `stanleyjobson`’u karşılaştırmak için geçen süreyle aynı olur. Şifre için de aynı şekilde.
+
+Bu sayede uygulama kodunuzda `secrets.compare_digest()` kullanarak bu güvenlik saldırıları ailesine karşı güvenli olursunuz.
+
+### Hatayı döndürün { #return-the-error }
+
+Credential’ların hatalı olduğunu tespit ettikten sonra, 401 status code ile (credential verilmediğinde dönenle aynı) bir `HTTPException` döndürün ve tarayıcının giriş penceresini yeniden göstermesi için `WWW-Authenticate` header’ını ekleyin:
+
+{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *}
diff --git a/docs/tr/docs/advanced/security/oauth2-scopes.md b/docs/tr/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 000000000..ecba7851b
--- /dev/null
+++ b/docs/tr/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2 scope'ları { #oauth2-scopes }
+
+OAuth2 scope'larını **FastAPI** ile doğrudan kullanabilirsiniz; sorunsuz çalışacak şekilde entegre edilmiştir.
+
+Bu sayede OAuth2 standardını takip eden, daha ince taneli bir izin sistemini OpenAPI uygulamanıza (ve API dokümanlarınıza) entegre edebilirsiniz.
+
+Scope'lu OAuth2; Facebook, Google, GitHub, Microsoft, X (Twitter) vb. birçok büyük kimlik doğrulama sağlayıcısının kullandığı mekanizmadır. Kullanıcı ve uygulamalara belirli izinler vermek için bunu kullanırlar.
+
+Facebook, Google, GitHub, Microsoft, X (Twitter) ile "giriş yaptığınızda", o uygulama scope'lu OAuth2 kullanıyor demektir.
+
+Bu bölümde, **FastAPI** uygulamanızda aynı scope'lu OAuth2 ile authentication ve authorization'ı nasıl yöneteceğinizi göreceksiniz.
+
+/// warning | Uyarı
+
+Bu bölüm az çok ileri seviye sayılır. Yeni başlıyorsanız atlayabilirsiniz.
+
+OAuth2 scope'larına mutlaka ihtiyacınız yok; authentication ve authorization'ı istediğiniz şekilde ele alabilirsiniz.
+
+Ancak scope'lu OAuth2, API'nize (OpenAPI ile) ve API dokümanlarınıza güzel biçimde entegre edilebilir.
+
+Buna rağmen, bu scope'ları (veya başka herhangi bir security/authorization gereksinimini) kodunuzda ihtiyaç duyduğunuz şekilde yine siz zorunlu kılarsınız.
+
+Birçok durumda scope'lu OAuth2 gereğinden fazla (overkill) olabilir.
+
+Ama ihtiyacınız olduğunu biliyorsanız ya da merak ediyorsanız okumaya devam edin.
+
+///
+
+## OAuth2 scope'ları ve OpenAPI { #oauth2-scopes-and-openapi }
+
+OAuth2 spesifikasyonu, "scope"ları boşluklarla ayrılmış string'lerden oluşan bir liste olarak tanımlar.
+
+Bu string'lerin her birinin içeriği herhangi bir formatta olabilir, ancak boşluk içermemelidir.
+
+Bu scope'lar "izinleri" temsil eder.
+
+OpenAPI'de (ör. API dokümanlarında) "security scheme" tanımlayabilirsiniz.
+
+Bu security scheme'lerden biri OAuth2 kullanıyorsa, scope'ları da tanımlayıp kullanabilirsiniz.
+
+Her bir "scope" sadece bir string'dir (boşluksuz).
+
+Genellikle belirli güvenlik izinlerini tanımlamak için kullanılır, örneğin:
+
+* `users:read` veya `users:write` sık görülen örneklerdir.
+* `instagram_basic` Facebook / Instagram tarafından kullanılır.
+* `https://www.googleapis.com/auth/drive` Google tarafından kullanılır.
+
+/// info | Bilgi
+
+OAuth2'de "scope", gereken belirli bir izni bildiren bir string'den ibarettir.
+
+`:` gibi başka karakterler içermesi ya da bir URL olması önemli değildir.
+
+Bu detaylar implementasyon'a bağlıdır.
+
+OAuth2 için bunlar sadece string'dir.
+
+///
+
+## Genel görünüm { #global-view }
+
+Önce, ana **Tutorial - User Guide** içindeki [Password (ve hashing) ile OAuth2, JWT token'lı Bearer](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank} örneklerinden, OAuth2 scope'larına geçince hangi kısımların değiştiğine hızlıca bakalım:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+Şimdi bu değişiklikleri adım adım inceleyelim.
+
+## OAuth2 Security scheme { #oauth2-security-scheme }
+
+İlk değişiklik, artık OAuth2 security scheme'ini iki adet kullanılabilir scope ile tanımlamamız: `me` ve `items`.
+
+`scopes` parametresi; her scope'un key, açıklamasının ise value olduğu bir `dict` alır:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+Bu scope'ları tanımladığımız için, login/authorize yaptığınızda API dokümanlarında görünecekler.
+
+Ve hangi scope'lara erişim vermek istediğinizi seçebileceksiniz: `me` ve `items`.
+
+Bu, Facebook/Google/GitHub vb. ile giriş yaparken izin verdiğinizde kullanılan mekanizmanın aynısıdır:
+
+
+
+## Scope'lu JWT token { #jwt-token-with-scopes }
+
+Şimdi token *path operation*'ını, istenen scope'ları döndürecek şekilde değiştirin.
+
+Hâlâ aynı `OAuth2PasswordRequestForm` kullanılıyor. Bu form, request'te aldığı her scope için `str`'lerden oluşan bir `list` içeren `scopes` özelliğine sahiptir.
+
+Ve scope'ları JWT token'ın bir parçası olarak döndürüyoruz.
+
+/// danger | Uyarı
+
+Basitlik için burada, gelen scope'ları doğrudan token'a ekliyoruz.
+
+Ama uygulamanızda güvenlik açısından, yalnızca kullanıcının gerçekten sahip olabileceği scope'ları (veya sizin önceden tanımladıklarınızı) eklediğinizden emin olmalısınız.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## *Path operation*'larda ve dependency'lerde scope tanımlama { #declare-scopes-in-path-operations-and-dependencies }
+
+Artık `/users/me/items/` için olan *path operation*'ın `items` scope'unu gerektirdiğini tanımlıyoruz.
+
+Bunun için `fastapi` içinden `Security` import edip kullanıyoruz.
+
+Dependency'leri (`Depends` gibi) tanımlamak için `Security` kullanabilirsiniz; fakat `Security`, ayrıca string'lerden oluşan bir scope listesi alan `scopes` parametresini de alır.
+
+Bu durumda `Security`'ye dependency fonksiyonu olarak `get_current_active_user` veriyoruz (`Depends` ile yaptığımız gibi).
+
+Ama ayrıca bir `list` olarak scope'ları da veriyoruz; burada tek bir scope var: `items` (daha fazla da olabilir).
+
+Ve `get_current_active_user` dependency fonksiyonu, sadece `Depends` ile değil `Security` ile de alt-dependency'ler tanımlayabilir. Kendi alt-dependency fonksiyonunu (`get_current_user`) ve daha fazla scope gereksinimini tanımlar.
+
+Bu örnekte `me` scope'unu gerektiriyor (birden fazla scope da isteyebilirdi).
+
+/// note | Not
+
+Farklı yerlerde farklı scope'lar eklemek zorunda değilsiniz.
+
+Burada, **FastAPI**'nin farklı seviyelerde tanımlanan scope'ları nasıl ele aldığını göstermek için böyle yapıyoruz.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | Teknik Detaylar
+
+`Security` aslında `Depends`'in bir alt sınıfıdır ve sadece birazdan göreceğimiz bir ek parametreye sahiptir.
+
+Ancak `Depends` yerine `Security` kullanınca **FastAPI**, security scope'larının tanımlanabileceğini bilir, bunları içeride kullanır ve API'yi OpenAPI ile dokümante eder.
+
+Fakat `fastapi` içinden `Query`, `Path`, `Depends`, `Security` vb. import ettiğiniz şeyler, aslında özel sınıflar döndüren fonksiyonlardır.
+
+///
+
+## `SecurityScopes` kullanımı { #use-securityscopes }
+
+Şimdi `get_current_user` dependency'sini güncelleyelim.
+
+Bu fonksiyon, yukarıdaki dependency'ler tarafından kullanılıyor.
+
+Burada, daha önce oluşturduğumuz aynı OAuth2 scheme'i dependency olarak tanımlıyoruz: `oauth2_scheme`.
+
+Bu dependency fonksiyonunun kendi içinde bir scope gereksinimi olmadığı için, `oauth2_scheme` ile `Depends` kullanabiliriz; security scope'larını belirtmemiz gerekmiyorsa `Security` kullanmak zorunda değiliz.
+
+Ayrıca `fastapi.security` içinden import edilen, `SecurityScopes` tipinde özel bir parametre tanımlıyoruz.
+
+Bu `SecurityScopes` sınıfı, `Request`'e benzer (`Request`, request nesnesini doğrudan almak için kullanılmıştı).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## `scopes`'ları kullanma { #use-the-scopes }
+
+`security_scopes` parametresi `SecurityScopes` tipinde olacaktır.
+
+Bu nesnenin `scopes` adlı bir özelliği vardır; bu liste, kendisinin ve bunu alt-dependency olarak kullanan tüm dependency'lerin gerektirdiği tüm scope'ları içerir. Yani tüm "dependant"lar... kafa karıştırıcı gelebilir; aşağıda tekrar açıklanıyor.
+
+`security_scopes` nesnesi (`SecurityScopes` sınıfından) ayrıca, bu scope'ları boşluklarla ayrılmış tek bir string olarak veren `scope_str` attribute'una sahiptir (bunu kullanacağız).
+
+Sonrasında birkaç farklı noktada tekrar kullanabileceğimiz (`raise` edebileceğimiz) bir `HTTPException` oluşturuyoruz.
+
+Bu exception içinde, gerekiyorsa, gerekli scope'ları boşlukla ayrılmış bir string olarak (`scope_str` ile) ekliyoruz. Bu scope'ları içeren string'i `WWW-Authenticate` header'ına koyuyoruz (spesifikasyonun bir parçası).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## `username` ve veri şeklinin doğrulanması { #verify-the-username-and-data-shape }
+
+Bir `username` aldığımızı doğruluyoruz ve scope'ları çıkarıyoruz.
+
+Ardından bu veriyi Pydantic model'i ile doğruluyoruz (`ValidationError` exception'ını yakalayarak). JWT token'ı okurken veya Pydantic ile veriyi doğrularken bir hata olursa, daha önce oluşturduğumuz `HTTPException`'ı fırlatıyoruz.
+
+Bunun için Pydantic model'i `TokenData`'yı, `scopes` adlı yeni bir özellik ekleyerek güncelliyoruz.
+
+Veriyi Pydantic ile doğrulayarak örneğin scope'ların tam olarak `str`'lerden oluşan bir `list` olduğunu ve `username`'in bir `str` olduğunu garanti edebiliriz.
+
+Aksi halde, örneğin bir `dict` veya başka bir şey gelebilir; bu da daha sonra uygulamanın bir yerinde kırılmaya yol açıp güvenlik riski oluşturabilir.
+
+Ayrıca bu `username` ile bir kullanıcı olduğunu doğruluyoruz; yoksa yine aynı exception'ı fırlatıyoruz.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## `scopes`'ların doğrulanması { #verify-the-scopes }
+
+Şimdi bu dependency'nin ve tüm dependant'ların ( *path operation*'lar dahil) gerektirdiği tüm scope'ların, alınan token'da sağlanan scope'lar içinde olup olmadığını doğruluyoruz; değilse `HTTPException` fırlatıyoruz.
+
+Bunun için, tüm bu scope'ları `str` olarak içeren bir `list` olan `security_scopes.scopes` kullanılır.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## Dependency ağacı ve scope'lar { #dependency-tree-and-scopes }
+
+Bu dependency ağacını ve scope'ları tekrar gözden geçirelim.
+
+`get_current_active_user` dependency'si, alt-dependency olarak `get_current_user`'ı kullandığı için, `get_current_active_user` üzerinde tanımlanan `"me"` scope'u, `get_current_user`'a geçirilen `security_scopes.scopes` içindeki gerekli scope listesine dahil edilir.
+
+*Path operation*'ın kendisi de `"items"` scope'unu tanımlar; bu da `get_current_user`'a geçirilen `security_scopes.scopes` listesinde yer alır.
+
+Dependency'lerin ve scope'ların hiyerarşisi şöyle görünür:
+
+* *Path operation* `read_own_items` şunlara sahiptir:
+ * Dependency ile gerekli scope'lar `["items"]`:
+ * `get_current_active_user`:
+ * `get_current_active_user` dependency fonksiyonu şunlara sahiptir:
+ * Dependency ile gerekli scope'lar `["me"]`:
+ * `get_current_user`:
+ * `get_current_user` dependency fonksiyonu şunlara sahiptir:
+ * Kendisinin gerektirdiği scope yok.
+ * `oauth2_scheme` kullanan bir dependency.
+ * `SecurityScopes` tipinde bir `security_scopes` parametresi:
+ * Bu `security_scopes` parametresinin `scopes` adlı bir özelliği vardır ve yukarıda tanımlanan tüm scope'ları içeren bir `list` taşır, yani:
+ * *Path operation* `read_own_items` için `security_scopes.scopes` `["me", "items"]` içerir.
+ * *Path operation* `read_users_me` için `security_scopes.scopes` `["me"]` içerir; çünkü bu scope `get_current_active_user` dependency'sinde tanımlanmıştır.
+ * *Path operation* `read_system_status` için `security_scopes.scopes` `[]` (boş) olur; çünkü herhangi bir `Security` ile `scopes` tanımlamamıştır ve dependency'si olan `get_current_user` da `scopes` tanımlamaz.
+
+/// tip | İpucu
+
+Buradaki önemli ve "sihirli" nokta şu: `get_current_user`, her *path operation* için kontrol etmesi gereken farklı bir `scopes` listesi alır.
+
+Bu, belirli bir *path operation* için dependency ağacındaki her *path operation* ve her dependency üzerinde tanımlanan `scopes`'lara bağlıdır.
+
+///
+
+## `SecurityScopes` hakkında daha fazla detay { #more-details-about-securityscopes }
+
+`SecurityScopes`'u herhangi bir noktada ve birden fazla yerde kullanabilirsiniz; mutlaka "kök" dependency'de olmak zorunda değildir.
+
+Her zaman, **o spesifik** *path operation* ve **o spesifik** dependency ağacı için, mevcut `Security` dependency'lerinde ve tüm dependant'larda tanımlanan security scope'larını içerir.
+
+`SecurityScopes`, dependant'ların tanımladığı tüm scope'ları barındırdığı için, gereken scope'ların token'da olup olmadığını merkezi bir dependency fonksiyonunda doğrulayıp, farklı *path operation*'larda farklı scope gereksinimleri tanımlayabilirsiniz.
+
+Bu kontroller her *path operation* için bağımsız yapılır.
+
+## Deneyin { #check-it }
+
+API dokümanlarını açarsanız, authenticate olup hangi scope'ları authorize etmek istediğinizi seçebilirsiniz.
+
+
+
+Hiç scope seçmezseniz "authenticated" olursunuz; ancak `/users/me/` veya `/users/me/items/`'e erişmeye çalıştığınızda, yeterli izniniz olmadığını söyleyen bir hata alırsınız. Yine de `/status/`'a erişebilirsiniz.
+
+`me` scope'unu seçip `items` scope'unu seçmezseniz `/users/me/`'a erişebilirsiniz ama `/users/me/items/`'e erişemezsiniz.
+
+Bu, bir üçüncü taraf uygulamanın, bir kullanıcı tarafından sağlanan token ile bu *path operation*'lardan birine erişmeye çalıştığında; kullanıcının uygulamaya kaç izin verdiğine bağlı olarak yaşayacağı durumdur.
+
+## Üçüncü taraf entegrasyonları hakkında { #about-third-party-integrations }
+
+Bu örnekte OAuth2 "password" flow'unu kullanıyoruz.
+
+Bu, kendi uygulamamıza giriş yaptığımız durumlar için uygundur; muhtemelen kendi frontend'imiz vardır.
+
+Çünkü `username` ve `password` alacağını bildiğimiz frontend'i biz kontrol ediyoruz, dolayısıyla güvenebiliriz.
+
+Ancak başkalarının bağlanacağı bir OAuth2 uygulaması geliştiriyorsanız (yani Facebook, Google, GitHub vb. gibi bir authentication provider muadili geliştiriyorsanız) diğer flow'lardan birini kullanmalısınız.
+
+En yaygını implicit flow'dur.
+
+En güvenlisi code flow'dur; ancak daha fazla adım gerektirdiği için implementasyonu daha karmaşıktır. Daha karmaşık olduğundan, birçok sağlayıcı implicit flow'yu önermeye yönelir.
+
+/// note | Not
+
+Her authentication provider'ın flow'ları markasının bir parçası yapmak için farklı şekilde adlandırması yaygındır.
+
+Ama sonuçta aynı OAuth2 standardını implement ediyorlar.
+
+///
+
+**FastAPI**, bu OAuth2 authentication flow'larının tamamı için `fastapi.security.oauth2` içinde yardımcı araçlar sunar.
+
+## Decorator `dependencies` içinde `Security` { #security-in-decorator-dependencies }
+
+Decorator'ın `dependencies` parametresinde bir `list` `Depends` tanımlayabildiğiniz gibi ( [Path operation decorator'larında Dependencies](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} bölümünde açıklandığı üzere), burada `scopes` ile birlikte `Security` de kullanabilirsiniz.
diff --git a/docs/tr/docs/advanced/settings.md b/docs/tr/docs/advanced/settings.md
new file mode 100644
index 000000000..e3bcaac61
--- /dev/null
+++ b/docs/tr/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# Ayarlar ve Ortam Değişkenleri { #settings-and-environment-variables }
+
+Birçok durumda uygulamanızın bazı harici ayarlara veya konfigürasyonlara ihtiyacı olabilir; örneğin secret key'ler, veritabanı kimlik bilgileri, e-posta servisleri için kimlik bilgileri vb.
+
+Bu ayarların çoğu değişkendir (değişebilir); örneğin veritabanı URL'leri. Ayrıca birçoğu hassas olabilir; örneğin secret'lar.
+
+Bu nedenle bunları, uygulama tarafından okunan environment variable'lar ile sağlamak yaygındır.
+
+/// tip | İpucu
+
+Environment variable'ları anlamak için [Environment Variables](../environment-variables.md){.internal-link target=_blank} dokümanını okuyabilirsiniz.
+
+///
+
+## Tipler ve doğrulama { #types-and-validation }
+
+Bu environment variable'lar yalnızca metin (string) taşıyabilir; çünkü Python'ın dışındadırlar ve diğer programlarla ve sistemin geri kalanıyla uyumlu olmaları gerekir (hatta Linux, Windows, macOS gibi farklı işletim sistemleriyle de).
+
+Bu da, Python içinde bir environment variable'dan okunan herhangi bir değerin `str` olacağı anlamına gelir; farklı bir tipe dönüştürme veya herhangi bir doğrulama işlemi kod içinde yapılmalıdır.
+
+## Pydantic `Settings` { #pydantic-settings }
+
+Neyse ki Pydantic, environment variable'lardan gelen bu ayarları yönetmek için Pydantic: Settings management ile çok iyi bir yardımcı araç sunar.
+
+### `pydantic-settings`'i kurun { #install-pydantic-settings }
+
+Önce, [virtual environment](../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan, aktive ettiğinizden emin olun ve ardından `pydantic-settings` paketini kurun:
+
+
+
+Sonra alt uygulamanın dokümanlarını http://127.0.0.1:8000/subapi/docs adresinden açın.
+
+Alt uygulama için otomatik API dokümanlarını göreceksiniz; yalnızca onun kendi _path operation_’larını içerir ve hepsi doğru alt-path öneki `/subapi` altında yer alır:
+
+
+
+İki arayüzden herhangi biriyle etkileşime girmeyi denerseniz doğru şekilde çalıştıklarını görürsünüz; çünkü tarayıcı her bir uygulama ya da alt uygulama ile ayrı ayrı iletişim kurabilir.
+
+### Teknik Detaylar: `root_path` { #technical-details-root-path }
+
+Yukarıda anlatıldığı gibi bir alt uygulamayı mount ettiğinizde FastAPI, ASGI spesifikasyonundaki `root_path` adlı bir mekanizmayı kullanarak alt uygulamaya mount path’ini iletmeyi otomatik olarak yönetir.
+
+Bu sayede alt uygulama, dokümantasyon arayüzü için o path önekini kullanması gerektiğini bilir.
+
+Ayrıca alt uygulamanın kendi mount edilmiş alt uygulamaları da olabilir; FastAPI tüm bu `root_path`’leri otomatik olarak yönettiği için her şey doğru şekilde çalışır.
+
+`root_path` hakkında daha fazlasını ve bunu açıkça nasıl kullanacağınızı [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank} bölümünde öğreneceksiniz.
diff --git a/docs/tr/docs/advanced/templates.md b/docs/tr/docs/advanced/templates.md
new file mode 100644
index 000000000..b91e0a2a8
--- /dev/null
+++ b/docs/tr/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# Şablonlar { #templates }
+
+**FastAPI** ile istediğiniz herhangi bir template engine'i kullanabilirsiniz.
+
+Yaygın bir tercih, Flask ve diğer araçların da kullandığı Jinja2'dir.
+
+Bunu kolayca yapılandırmak için, doğrudan **FastAPI** uygulamanızda kullanabileceğiniz yardımcı araçlar vardır (Starlette tarafından sağlanır).
+
+## Bağımlılıkları Yükleme { #install-dependencies }
+
+Bir [virtual environment](../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan, etkinleştirdiğinizden ve `jinja2`'yi yüklediğinizden emin olun:
+
+
+
+Input kutusuna mesaj yazıp gönderebilirsiniz:
+
+
+
+Ve WebSockets kullanan **FastAPI** uygulamanız yanıt döndürecektir:
+
+
+
+Birçok mesaj gönderebilir (ve alabilirsiniz):
+
+
+
+Ve hepsinde aynı WebSocket bağlantısı kullanılacaktır.
+
+## `Depends` ve Diğerlerini Kullanma { #using-depends-and-others }
+
+WebSocket endpoint'lerinde `fastapi` içinden import edip şunları kullanabilirsiniz:
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+Diğer FastAPI endpoint'leri/*path operations* ile aynı şekilde çalışırlar:
+
+{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info | Bilgi
+
+Bu bir WebSocket olduğu için `HTTPException` raise etmek pek anlamlı değildir; bunun yerine `WebSocketException` raise ederiz.
+
+Spesifikasyonda tanımlanan geçerli kodlar arasından bir kapatma kodu kullanabilirsiniz.
+
+///
+
+### Dependency'lerle WebSockets'i Deneyin { #try-the-websockets-with-dependencies }
+
+Dosyanızın adı `main.py` ise uygulamanızı şu şekilde çalıştırın:
+
+
+
+## Bağlantı Kopmalarını ve Birden Fazla Client'ı Yönetme { #handling-disconnections-and-multiple-clients }
+
+Bir WebSocket bağlantısı kapandığında, `await websocket.receive_text()` bir `WebSocketDisconnect` exception'ı raise eder; ardından bunu bu örnekteki gibi yakalayıp (catch) yönetebilirsiniz.
+
+{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *}
+
+Denemek için:
+
+* Uygulamayı birden fazla tarayıcı sekmesiyle açın.
+* Bu sekmelerden mesaj yazın.
+* Sonra sekmelerden birini kapatın.
+
+Bu, `WebSocketDisconnect` exception'ını raise eder ve diğer tüm client'lar şuna benzer bir mesaj alır:
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip | İpucu
+
+Yukarıdaki uygulama, birden fazla WebSocket bağlantısına mesajları nasıl yönetip broadcast edeceğinizi göstermek için minimal ve basit bir örnektir.
+
+Ancak her şey memory'de, tek bir list içinde yönetildiği için yalnızca process çalıştığı sürece ve yalnızca tek bir process ile çalışacaktır.
+
+FastAPI ile kolay entegre olan ama Redis, PostgreSQL vb. tarafından desteklenen daha sağlam bir şeye ihtiyacınız varsa encode/broadcaster'a göz atın.
+
+///
+
+## Daha Fazla Bilgi { #more-info }
+
+Seçenekler hakkında daha fazlasını öğrenmek için Starlette dokümantasyonunda şunlara bakın:
+
+* `WebSocket` class'ı.
+* Class tabanlı WebSocket yönetimi.
diff --git a/docs/tr/docs/deployment/concepts.md b/docs/tr/docs/deployment/concepts.md
new file mode 100644
index 000000000..d0f568146
--- /dev/null
+++ b/docs/tr/docs/deployment/concepts.md
@@ -0,0 +1,321 @@
+# Deployment Kavramları { #deployments-concepts }
+
+Bir **FastAPI** uygulamasını (hatta genel olarak herhangi bir web API'yi) deploy ederken, muhtemelen önemseyeceğiniz bazı kavramlar vardır. Bu kavramları kullanarak, **uygulamanızı deploy etmek** için **en uygun** yöntemi bulabilirsiniz.
+
+Önemli kavramlardan bazıları şunlardır:
+
+* Güvenlik - HTTPS
+* Startup'ta çalıştırma
+* Yeniden başlatmalar
+* Replikasyon (çalışan process sayısı)
+* Bellek
+* Başlatmadan önceki adımlar
+
+Bunların **deployment**'ları nasıl etkilediğine bakalım.
+
+Nihai hedef, **API client**'larınıza **güvenli** bir şekilde hizmet verebilmek, **kesintileri** önlemek ve **hesaplama kaynaklarını** (ör. uzak server'lar/sanal makineler) olabildiğince verimli kullanmaktır.
+
+Burada bu **kavramlar** hakkında biraz daha bilgi vereceğim. Böylece, çok farklı ortamlarda—hatta bugün var olmayan **gelecekteki** ortamlarda bile—API'nizi nasıl deploy edeceğinize karar verirken ihtiyaç duyacağınız **sezgiyi** kazanmış olursunuz.
+
+Bu kavramları dikkate alarak, **kendi API**'leriniz için en iyi deployment yaklaşımını **değerlendirebilir ve tasarlayabilirsiniz**.
+
+Sonraki bölümlerde, FastAPI uygulamalarını deploy etmek için daha **somut tarifler** (recipes) paylaşacağım.
+
+Ama şimdilik, bu önemli **kavramsal fikirleri** inceleyelim. Bu kavramlar diğer tüm web API türleri için de geçerlidir.
+
+## Güvenlik - HTTPS { #security-https }
+
+[HTTPS hakkındaki önceki bölümde](https.md){.internal-link target=_blank} HTTPS'in API'niz için nasıl şifreleme sağladığını öğrenmiştik.
+
+Ayrıca HTTPS'in genellikle uygulama server'ınızın **dışında** yer alan bir bileşen tarafından sağlandığını, yani bir **TLS Termination Proxy** ile yapıldığını da görmüştük.
+
+Ve **HTTPS sertifikalarını yenilemekten** sorumlu bir şey olmalıdır; bu aynı bileşen olabileceği gibi farklı bir bileşen de olabilir.
+
+### HTTPS için Örnek Araçlar { #example-tools-for-https }
+
+TLS Termination Proxy olarak kullanabileceğiniz bazı araçlar:
+
+* Traefik
+ * Sertifika yenilemelerini otomatik yönetir
+* Caddy
+ * Sertifika yenilemelerini otomatik yönetir
+* Nginx
+ * Sertifika yenilemeleri için Certbot gibi harici bir bileşenle
+* HAProxy
+ * Sertifika yenilemeleri için Certbot gibi harici bir bileşenle
+* Nginx gibi bir Ingress Controller ile Kubernetes
+ * Sertifika yenilemeleri için cert-manager gibi harici bir bileşenle
+* Bir cloud provider tarafından servislerinin parçası olarak içeride yönetilmesi (aşağıyı okuyun)
+
+Bir diğer seçenek de, HTTPS kurulumunu da dahil olmak üzere işin daha büyük kısmını yapan bir **cloud service** kullanmaktır. Bunun bazı kısıtları olabilir veya daha pahalı olabilir vb. Ancak bu durumda TLS Termination Proxy'yi kendiniz kurmak zorunda kalmazsınız.
+
+Sonraki bölümlerde bazı somut örnekler göstereceğim.
+
+---
+
+Sonraki kavramlar, gerçek API'nizi çalıştıran programla (ör. Uvicorn) ilgilidir.
+
+## Program ve Process { #program-and-process }
+
+Çalışan "**process**" hakkında çok konuşacağız. Bu yüzden ne anlama geldiğini ve "**program**" kelimesinden farkının ne olduğunu netleştirmek faydalı.
+
+### Program Nedir { #what-is-a-program }
+
+**Program** kelimesi günlük kullanımda birçok şeyi anlatmak için kullanılır:
+
+* Yazdığınız **code**, yani **Python dosyaları**.
+* İşletim sistemi tarafından **çalıştırılabilen** **dosya**, örn: `python`, `python.exe` veya `uvicorn`.
+* İşletim sistemi üzerinde **çalışır durumdayken** CPU kullanan ve bellekte veri tutan belirli bir program. Buna **process** de denir.
+
+### Process Nedir { #what-is-a-process }
+
+**Process** kelimesi genellikle daha spesifik kullanılır; yalnızca işletim sistemi üzerinde çalışan şeye (yukarıdaki son madde gibi) işaret eder:
+
+* İşletim sistemi üzerinde **çalışır durumda** olan belirli bir program.
+ * Bu; dosyayı ya da code'u değil, işletim sistemi tarafından **çalıştırılan** ve yönetilen şeyi ifade eder.
+* Herhangi bir program, herhangi bir code, **yalnızca çalıştırılırken** bir şey yapabilir. Yani bir **process çalışıyorken**.
+* Process siz tarafından veya işletim sistemi tarafından **sonlandırılabilir** (ya da "killed" edilebilir). O anda çalışması/çalıştırılması durur ve artık **hiçbir şey yapamaz**.
+* Bilgisayarınızda çalışan her uygulamanın arkasında bir process vardır; çalışan her program, her pencere vb. Bilgisayar açıkken normalde **aynı anda** birçok process çalışır.
+* Aynı anda **aynı programın birden fazla process**'i çalışabilir.
+
+İşletim sisteminizdeki "task manager" veya "system monitor" (ya da benzeri araçlar) ile bu process'lerin birçoğunu çalışır halde görebilirsiniz.
+
+Örneğin muhtemelen aynı browser programını (Firefox, Chrome, Edge vb.) çalıştıran birden fazla process göreceksiniz. Genelde her tab için bir process, üstüne bazı ek process'ler çalıştırırlar.
+
+
+
+---
+
+Artık **process** ve **program** arasındaki farkı bildiğimize göre, deployment konusuna devam edelim.
+
+## Startup'ta Çalıştırma { #running-on-startup }
+
+Çoğu durumda bir web API oluşturduğunuzda, client'larınızın her zaman erişebilmesi için API'nizin kesintisiz şekilde **sürekli çalışıyor** olmasını istersiniz. Elbette sadece belirli durumlarda çalışmasını istemenizin özel bir sebebi olabilir; ancak çoğunlukla onu sürekli açık ve **kullanılabilir** halde tutarsınız.
+
+### Uzak Bir Server'da { #in-a-remote-server }
+
+Uzak bir server (cloud server, sanal makine vb.) kurduğunuzda, yapabileceğiniz en basit şey; local geliştirme sırasında yaptığınız gibi, manuel olarak `fastapi run` (Uvicorn'u kullanır) veya benzeri bir komutla çalıştırmaktır.
+
+Bu yöntem çalışır ve **geliştirme sırasında** faydalıdır.
+
+Ancak server'a olan bağlantınız koparsa, **çalışan process** muhtemelen ölür.
+
+Ve server yeniden başlatılırsa (örneğin update'lerden sonra ya da cloud provider'ın migration'larından sonra) bunu muhtemelen **fark etmezsiniz**. Dolayısıyla process'i manuel yeniden başlatmanız gerektiğini de bilmezsiniz. Sonuçta API'niz ölü kalır.
+
+### Startup'ta Otomatik Çalıştırma { #run-automatically-on-startup }
+
+Genellikle server programının (ör. Uvicorn) server açılışında otomatik başlamasını ve herhangi bir **insan müdahalesi** gerektirmeden API'nizi çalıştıran bir process'in sürekli ayakta olmasını istersiniz (ör. FastAPI uygulamanızı çalıştıran Uvicorn).
+
+### Ayrı Bir Program { #separate-program }
+
+Bunu sağlamak için genellikle startup'ta uygulamanızın çalıştığından emin olacak **ayrı bir program** kullanırsınız. Pek çok durumda bu program, örneğin bir veritabanı gibi diğer bileşenlerin/uygulamaların da çalıştığından emin olur.
+
+### Startup'ta Çalıştırmak için Örnek Araçlar { #example-tools-to-run-at-startup }
+
+Bu işi yapabilen araçlara örnekler:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker in Swarm Mode
+* Systemd
+* Supervisor
+* Bir cloud provider tarafından servislerinin parçası olarak içeride yönetilmesi
+* Diğerleri...
+
+Sonraki bölümlerde daha somut örnekler vereceğim.
+
+## Yeniden Başlatmalar { #restarts }
+
+Uygulamanızın startup'ta çalıştığından emin olmaya benzer şekilde, hatalardan sonra **yeniden başlatıldığından** da emin olmak istersiniz.
+
+### Hata Yaparız { #we-make-mistakes }
+
+Biz insanlar sürekli **hata** yaparız. Yazılımın neredeyse *her zaman* farklı yerlerinde gizli **bug**'lar vardır.
+
+Ve biz geliştiriciler bu bug'ları buldukça ve yeni özellikler ekledikçe code'u iyileştiririz (muhtemelen yeni bug'lar da ekleyerek).
+
+### Küçük Hatalar Otomatik Yönetilir { #small-errors-automatically-handled }
+
+FastAPI ile web API geliştirirken, code'umuzda bir hata olursa FastAPI genellikle bunu hatayı tetikleyen tek request ile sınırlar.
+
+Client o request için **500 Internal Server Error** alır; ancak uygulama tamamen çöküp durmak yerine sonraki request'ler için çalışmaya devam eder.
+
+### Daha Büyük Hatalar - Çökmeler { #bigger-errors-crashes }
+
+Yine de bazı durumlarda, yazdığımız bir code **tüm uygulamayı çökertip** Uvicorn ve Python'ın crash olmasına neden olabilir.
+
+Böyle bir durumda, tek bir noktadaki hata yüzünden uygulamanın ölü kalmasını istemezsiniz; bozuk olmayan *path operations* en azından çalışmaya devam etsin istersiniz.
+
+### Crash Sonrası Yeniden Başlatma { #restart-after-crash }
+
+Ancak çalışan **process**'i çökerten gerçekten kötü hatalarda, process'i **yeniden başlatmaktan** sorumlu harici bir bileşen istersiniz; en azından birkaç kez...
+
+/// tip | İpucu
+
+...Yine de uygulama **hemen crash oluyorsa**, onu sonsuza kadar yeniden başlatmaya çalışmanın pek anlamı yoktur. Böyle durumları büyük ihtimalle geliştirme sırasında ya da en geç deploy'dan hemen sonra fark edersiniz.
+
+O yüzden ana senaryoya odaklanalım: Gelecekte bazı özel durumlarda tamamen çökebilir ve yine de yeniden başlatmak mantıklıdır.
+
+///
+
+Uygulamanızı yeniden başlatmakla görevli bileşenin **harici bir bileşen** olmasını istersiniz. Çünkü o noktada Uvicorn ve Python ile birlikte aynı uygulama zaten crash olmuştur; aynı app'in içindeki aynı code'un bunu düzeltmek için yapabileceği bir şey kalmaz.
+
+### Otomatik Yeniden Başlatma için Örnek Araçlar { #example-tools-to-restart-automatically }
+
+Çoğu durumda, **startup'ta programı çalıştırmak** için kullanılan aracın aynısı otomatik **restart**'ları yönetmek için de kullanılır.
+
+Örneğin bu şunlarla yönetilebilir:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker in Swarm Mode
+* Systemd
+* Supervisor
+* Bir cloud provider tarafından servislerinin parçası olarak içeride yönetilmesi
+* Diğerleri...
+
+## Replikasyon - Process'ler ve Bellek { #replication-processes-and-memory }
+
+FastAPI uygulamasında, Uvicorn'u çalıştıran `fastapi` komutu gibi bir server programı kullanırken, uygulamayı **tek bir process** içinde bir kez çalıştırmak bile aynı anda birden fazla client'a hizmet verebilir.
+
+Ancak birçok durumda, aynı anda birden fazla worker process çalıştırmak istersiniz.
+
+### Birden Fazla Process - Worker'lar { #multiple-processes-workers }
+
+Tek bir process'in karşılayabileceğinden daha fazla client'ınız varsa (örneğin sanal makine çok büyük değilse) ve server CPU'sunda **birden fazla core** varsa, aynı uygulamayla **birden fazla process** çalıştırıp tüm request'leri bunlara dağıtabilirsiniz.
+
+Aynı API programının **birden fazla process**'ini çalıştırdığınızda, bunlara genellikle **worker** denir.
+
+### Worker Process'ler ve Port'lar { #worker-processes-and-ports }
+
+[HTTPS hakkındaki dokümanda](https.md){.internal-link target=_blank} bir server'da aynı port ve IP adresi kombinasyonunu yalnızca tek bir process'in dinleyebileceğini hatırlıyor musunuz?
+
+Bu hâlâ geçerli.
+
+Dolayısıyla **aynı anda birden fazla process** çalıştırabilmek için, **port** üzerinde dinleyen **tek bir process** olmalı ve bu process iletişimi bir şekilde worker process'lere aktarmalıdır.
+
+### Process Başına Bellek { #memory-per-process }
+
+Program belleğe bir şeyler yüklediğinde—örneğin bir değişkende bir machine learning modelini veya büyük bir dosyanın içeriğini tutmak gibi—bunların hepsi server'ın **belleğini (RAM)** tüketir.
+
+Ve birden fazla process normalde **belleği paylaşmaz**. Yani her çalışan process'in kendi verileri, değişkenleri ve belleği vardır. Code'unuz çok bellek tüketiyorsa, **her process** buna denk bir miktar bellek tüketir.
+
+### Server Belleği { #server-memory }
+
+Örneğin code'unuz **1 GB** boyutunda bir Machine Learning modelini yüklüyorsa, API'niz tek process ile çalışırken en az 1 GB RAM tüketir. **4 process** (4 worker) başlatırsanız her biri 1 GB RAM tüketir. Yani toplamda API'niz **4 GB RAM** tüketir.
+
+Uzak server'ınız veya sanal makineniz yalnızca 3 GB RAM'e sahipse, 4 GB'tan fazla RAM yüklemeye çalışmak sorun çıkarır.
+
+### Birden Fazla Process - Bir Örnek { #multiple-processes-an-example }
+
+Bu örnekte, iki adet **Worker Process** başlatıp kontrol eden bir **Manager Process** vardır.
+
+Bu Manager Process büyük ihtimalle IP üzerindeki **port**'u dinleyen süreçtir ve tüm iletişimi worker process'lere aktarır.
+
+Worker process'ler uygulamanızı çalıştıran process'lerdir; bir **request** alıp bir **response** döndürmek için asıl hesaplamaları yaparlar ve sizin RAM'de değişkenlere koyduğunuz her şeyi yüklerler.
+
+
+
+Elbette aynı makinede, uygulamanız dışında da muhtemelen **başka process**'ler çalışır.
+
+İlginç bir detay: Her process'in kullandığı **CPU** yüzdesi zaman içinde çok **değişken** olabilir; ancak **bellek (RAM)** genellikle az çok **stabil** kalır.
+
+Eğer API'niz her seferinde benzer miktarda hesaplama yapıyorsa ve çok sayıda client'ınız varsa, **CPU kullanımı** da muhtemelen *stabil olur* (hızlı hızlı sürekli yükselip alçalmak yerine).
+
+### Replikasyon Araçları ve Stratejileri Örnekleri { #examples-of-replication-tools-and-strategies }
+
+Bunu başarmak için farklı yaklaşımlar olabilir. Sonraki bölümlerde, örneğin Docker ve container'lar konuşurken, belirli stratejileri daha detaylı anlatacağım.
+
+Dikkate almanız gereken ana kısıt şudur: **public IP** üzerindeki **port**'u yöneten **tek** bir bileşen olmalı. Sonrasında bu bileşenin, replikasyonla çoğaltılmış **process/worker**'lara iletişimi **aktarmanın** bir yoluna sahip olması gerekir.
+
+Olası kombinasyonlar ve stratejiler:
+
+* `--workers` ile **Uvicorn**
+ * Bir Uvicorn **process manager** **IP** ve **port** üzerinde dinler ve **birden fazla Uvicorn worker process** başlatır.
+* **Kubernetes** ve diğer dağıtık **container sistemleri**
+ * **Kubernetes** katmanında bir şey **IP** ve **port** üzerinde dinler. Replikasyon, her birinde **tek bir Uvicorn process** çalışan **birden fazla container** ile yapılır.
+* Bunu sizin yerinize yapan **cloud service**'ler
+ * Cloud service muhtemelen **replikasyonu sizin yerinize yönetir**. Size çalıştırılacak **bir process** veya kullanılacak bir **container image** tanımlama imkânı verebilir; her durumda büyük ihtimalle **tek bir Uvicorn process** olur ve bunu çoğaltmaktan cloud service sorumlu olur.
+
+/// tip | İpucu
+
+**Container**, Docker veya Kubernetes ile ilgili bazı maddeler şimdilik çok anlamlı gelmiyorsa dert etmeyin.
+
+Container image'ları, Docker, Kubernetes vb. konuları ilerideki bir bölümde daha detaylı anlatacağım: [Container'larda FastAPI - Docker](docker.md){.internal-link target=_blank}.
+
+///
+
+## Başlatmadan Önceki Adımlar { #previous-steps-before-starting }
+
+Uygulamanızı **başlatmadan önce** bazı adımlar yapmak isteyeceğiniz birçok durum vardır.
+
+Örneğin **database migrations** çalıştırmak isteyebilirsiniz.
+
+Ancak çoğu durumda, bu adımları yalnızca **bir kez** çalıştırmak istersiniz.
+
+Bu yüzden, uygulamayı başlatmadan önce bu **ön adımları** çalıştıracak **tek bir process** olmasını istersiniz.
+
+Ve daha sonra uygulamanın kendisi için **birden fazla process** (birden fazla worker) başlatsanız bile, bu ön adımları çalıştıranın *yine* tek process olduğundan emin olmalısınız. Bu adımlar **birden fazla process** tarafından çalıştırılsaydı, işi **paralel** şekilde tekrarlarlardı. Adımlar database migration gibi hassas bir şeyse, birbirleriyle çakışıp çatışma çıkarabilirler.
+
+Elbette bazı durumlarda ön adımları birden fazla kez çalıştırmak sorun değildir; bu durumda yönetmesi çok daha kolay olur.
+
+/// tip | İpucu
+
+Ayrıca, kurulumunuza bağlı olarak bazı durumlarda uygulamanızı başlatmadan önce **hiç ön adıma ihtiyaç duymayabilirsiniz**.
+
+Bu durumda bunların hiçbirini düşünmeniz gerekmez.
+
+///
+
+### Ön Adımlar için Strateji Örnekleri { #examples-of-previous-steps-strategies }
+
+Bu konu, **sisteminizi nasıl deploy ettiğinize** çok bağlıdır ve muhtemelen programları nasıl başlattığınız, restart'ları nasıl yönettiğiniz vb. ile bağlantılıdır.
+
+Bazı olası fikirler:
+
+* Kubernetes'te, app container'ınızdan önce çalışan bir "Init Container"
+* Ön adımları çalıştırıp sonra uygulamanızı başlatan bir bash script
+ * Yine de o bash script'i başlatmak/restart etmek, hataları tespit etmek vb. için bir mekanizmaya ihtiyacınız olur.
+
+/// tip | İpucu
+
+Bunu container'larla nasıl yapabileceğinize dair daha somut örnekleri ilerideki bir bölümde anlatacağım: [Container'larda FastAPI - Docker](docker.md){.internal-link target=_blank}.
+
+///
+
+## Kaynak Kullanımı { #resource-utilization }
+
+Server(lar)ınız bir **kaynaktır**. Programlarınızla CPU'lardaki hesaplama zamanını ve mevcut RAM belleğini tüketebilir veya **kullanabilirsiniz**.
+
+Sistem kaynaklarının ne kadarını tüketmek/kullanmak istersiniz? "Az" demek kolaydır; ancak pratikte hedef genellikle **çökmeden mümkün olduğunca fazla** kullanmaktır.
+
+3 server için para ödüyor ama onların RAM ve CPU'sunun yalnızca küçük bir kısmını kullanıyorsanız, muhtemelen **para israf ediyorsunuz** ve muhtemelen **elektrik tüketimini** de gereksiz yere artırıyorsunuz vb.
+
+Bu durumda 2 server ile devam edip onların kaynaklarını (CPU, bellek, disk, ağ bant genişliği vb.) daha yüksek oranlarda kullanmak daha iyi olabilir.
+
+Öte yandan, 2 server'ınız var ve CPU ile RAM'in **%100**'ünü kullanıyorsanız, bir noktada bir process daha fazla bellek ister; server diski "bellek" gibi kullanmak zorunda kalır (binlerce kat daha yavaş olabilir) ya da hatta **crash** edebilir. Ya da bir process bir hesaplama yapmak ister ve CPU tekrar boşalana kadar beklemek zorunda kalır.
+
+Bu senaryoda **bir server daha** eklemek ve bazı process'leri orada çalıştırmak daha iyi olur; böylece hepsinin **yeterli RAM'i ve CPU zamanı** olur.
+
+Ayrıca, herhangi bir sebeple API'nizde bir kullanım **spike**'ı olma ihtimali de vardır. Belki viral olur, belki başka servisler veya bot'lar kullanmaya başlar. Bu durumlarda güvende olmak için ekstra kaynak isteyebilirsiniz.
+
+Hedef olarak **keyfi bir sayı** belirleyebilirsiniz; örneğin kaynak kullanımını **%50 ile %90 arasında** tutmak gibi. Önemli olan, bunların muhtemelen ölçmek isteyeceğiniz ve deployment'larınızı ayarlamak için kullanacağınız ana metrikler olmasıdır.
+
+Server'ınızda CPU ve RAM kullanımını veya her process'in ne kadar kullandığını görmek için `htop` gibi basit araçları kullanabilirsiniz. Ya da server'lar arasında dağıtık çalışan daha karmaşık monitoring araçları kullanabilirsiniz.
+
+## Özet { #recap }
+
+Uygulamanızı nasıl deploy edeceğinize karar verirken aklınızda tutmanız gereken ana kavramların bazılarını okudunuz:
+
+* Güvenlik - HTTPS
+* Startup'ta çalıştırma
+* Yeniden başlatmalar
+* Replikasyon (çalışan process sayısı)
+* Bellek
+* Başlatmadan önceki adımlar
+
+Bu fikirleri ve nasıl uygulayacağınızı anlamak, deployment'larınızı yapılandırırken ve ince ayar yaparken ihtiyaç duyacağınız sezgiyi kazanmanızı sağlamalıdır.
+
+Sonraki bölümlerde, izleyebileceğiniz stratejilere dair daha somut örnekler paylaşacağım.
diff --git a/docs/tr/docs/deployment/docker.md b/docs/tr/docs/deployment/docker.md
new file mode 100644
index 000000000..b48d2ddf5
--- /dev/null
+++ b/docs/tr/docs/deployment/docker.md
@@ -0,0 +1,620 @@
+# Container'larda FastAPI - Docker { #fastapi-in-containers-docker }
+
+FastAPI uygulamalarını deploy ederken yaygın bir yaklaşım, bir **Linux container image** oluşturmaktır. Bu genellikle **Docker** kullanılarak yapılır. Ardından bu container image'ı birkaç farklı yöntemden biriyle deploy edebilirsiniz.
+
+Linux container'ları kullanmanın **güvenlik**, **tekrarlanabilirlik**, **basitlik** gibi birçok avantajı vardır.
+
+/// tip | İpucu
+
+Aceleniz var ve bunları zaten biliyor musunuz? Aşağıdaki [`Dockerfile`'a atlayın 👇](#build-a-docker-image-for-fastapi).
+
+///
+
+
Dockerfile Önizleme 👀
+
+```Dockerfile
+FROM python:3.9
+
+WORKDIR /code
+
+COPY ./requirements.txt /code/requirements.txt
+
+RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
+
+COPY ./app /code/app
+
+CMD ["fastapi", "run", "app/main.py", "--port", "80"]
+
+# If running behind a proxy like Nginx or Traefik add --proxy-headers
+# CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"]
+```
+
+
+
+### TLS Handshake Başlangıcı { #tls-handshake-start }
+
+Tarayıcı daha sonra bu IP adresiyle **443 portu** (HTTPS portu) üzerinden iletişim kurar.
+
+İletişimin ilk kısmı, client ile server arasında bağlantıyı kurmak ve hangi kriptografik anahtarların kullanılacağına karar vermek vb. içindir.
+
+
+
+Client ile server arasındaki, TLS bağlantısını kurmaya yönelik bu etkileşime **TLS handshake** denir.
+
+### SNI Extension’ı ile TLS { #tls-with-sni-extension }
+
+Server’da, belirli bir **IP adresindeki** belirli bir **portu** dinleyen **yalnızca bir process** olabilir. Aynı IP adresinde başka portları dinleyen başka process’ler olabilir, ancak IP+port kombinasyonu başına yalnızca bir tane olur.
+
+TLS (HTTPS) varsayılan olarak `443` portunu kullanır. Yani ihtiyaç duyacağımız port budur.
+
+Bu portu yalnızca bir process dinleyebileceği için, bunu yapacak process **TLS Termination Proxy** olur.
+
+TLS Termination Proxy, bir ya da daha fazla **TLS sertifikasına** (HTTPS sertifikası) erişebilir.
+
+Yukarıda bahsettiğimiz **SNI extension**’ını kullanarak TLS Termination Proxy, bu bağlantı için elindeki TLS (HTTPS) sertifikalarından hangisini kullanacağını kontrol eder; client’ın beklediği domain ile eşleşen sertifikayı seçer.
+
+Bu örnekte `someapp.example.com` sertifikasını kullanır.
+
+
+
+Client, bu TLS sertifikasını üreten kuruluşa zaten **güvenir** (bu örnekte Let's Encrypt; birazdan ona da geleceğiz). Bu sayede sertifikanın geçerli olduğunu **doğrulayabilir**.
+
+Ardından client ve TLS Termination Proxy, sertifikayı kullanarak **TCP iletişiminin geri kalanını nasıl şifreleyeceklerine** karar verir. Böylece **TLS Handshake** kısmı tamamlanır.
+
+Bundan sonra client ve server arasında **şifreli bir TCP bağlantısı** vardır; TLS’in sağladığı şey budur. Sonra bu bağlantıyı kullanarak gerçek **HTTP iletişimini** başlatabilirler.
+
+Ve **HTTPS** de tam olarak budur: şifrelenmemiş bir TCP bağlantısı yerine, **güvenli bir TLS bağlantısının içinde** düz **HTTP**’dir.
+
+/// tip | İpucu
+
+Şifrelemenin HTTP seviyesinde değil, **TCP seviyesinde** gerçekleştiğine dikkat edin.
+
+///
+
+### HTTPS Request { #https-request }
+
+Artık client ile server (özellikle tarayıcı ile TLS Termination Proxy) arasında **şifreli bir TCP bağlantısı** olduğuna göre, **HTTP iletişimi** başlayabilir.
+
+Dolayısıyla client bir **HTTPS request** gönderir. Bu, şifreli bir TLS bağlantısı üzerinden giden bir HTTP request’tir.
+
+
+
+### Request’in Şifresini Çözme { #decrypt-the-request }
+
+TLS Termination Proxy, üzerinde anlaşılan şifrelemeyi kullanarak **request’in şifresini çözer** ve **düz (şifresi çözülmüş) HTTP request**’i uygulamayı çalıştıran process’e iletir (ör. FastAPI uygulamasını çalıştıran Uvicorn process’i).
+
+
+
+### HTTP Response { #http-response }
+
+Uygulama request’i işler ve TLS Termination Proxy’ye **düz (şifrelenmemiş) bir HTTP response** gönderir.
+
+
+
+### HTTPS Response { #https-response }
+
+TLS Termination Proxy daha sonra response’u, daha önce üzerinde anlaşılan kriptografi ile (başlangıcı `someapp.example.com` sertifikasına dayanan) **şifreler** ve tarayıcıya geri gönderir.
+
+Sonrasında tarayıcı response’un geçerli olduğunu ve doğru kriptografik anahtarla şifrelendiğini doğrular vb. Ardından **response’un şifresini çözer** ve işler.
+
+
+
+Client (tarayıcı), response’un doğru server’dan geldiğini bilir; çünkü daha önce **HTTPS sertifikası** ile üzerinde anlaştıkları kriptografiyi kullanmaktadır.
+
+### Birden Fazla Uygulama { #multiple-applications }
+
+Aynı server’da (veya server’larda) örneğin başka API programları ya da bir veritabanı gibi **birden fazla uygulama** olabilir.
+
+Belirli IP ve port kombinasyonunu yalnızca bir process yönetebilir (örneğimizde TLS Termination Proxy). Ancak diğer uygulamalar/process’ler, aynı **public IP + port kombinasyonunu** kullanmaya çalışmadıkları sürece server(lar)da çalışabilir.
+
+
+
+Bu şekilde TLS Termination Proxy, birden fazla uygulama için **birden fazla domain**’in HTTPS ve sertifika işlerini yönetebilir ve her durumda request’leri doğru uygulamaya iletebilir.
+
+### Sertifika Yenileme { #certificate-renewal }
+
+Gelecekte bir noktada, her sertifikanın süresi **dolar** (temin edildikten yaklaşık 3 ay sonra).
+
+Ardından başka bir program (bazı durumlarda ayrı bir programdır, bazı durumlarda aynı TLS Termination Proxy olabilir) Let's Encrypt ile konuşup sertifika(ları) yeniler.
+
+
+
+**TLS sertifikaları** bir IP adresiyle değil, **domain adıyla ilişkilidir**.
+
+Bu yüzden sertifikaları yenilemek için, yenileme programı otoriteye (Let's Encrypt) gerçekten o domain’i **"sahiplendiğini" ve kontrol ettiğini** **kanıtlamalıdır**.
+
+Bunu yapmak ve farklı uygulama ihtiyaçlarını karşılamak için birden fazla yöntem vardır. Yaygın yöntemlerden bazıları:
+
+* Bazı **DNS kayıtlarını değiştirmek**.
+ * Bunun için yenileme programının DNS provider API’lerini desteklemesi gerekir. Dolayısıyla kullandığınız DNS provider’a bağlı olarak bu seçenek mümkün de olabilir, olmayabilir de.
+* Domain ile ilişkili public IP adresinde **server olarak çalışmak** (en azından sertifika temin sürecinde).
+ * Yukarıda söylediğimiz gibi, belirli bir IP ve portu yalnızca bir process dinleyebilir.
+ * Bu, aynı TLS Termination Proxy’nin sertifika yenileme sürecini de yönetmesinin neden çok faydalı olduğunun sebeplerinden biridir.
+ * Aksi halde TLS Termination Proxy’yi kısa süreliğine durdurmanız, sertifikaları temin etmek için yenileme programını başlatmanız, sonra bunları TLS Termination Proxy ile yapılandırmanız ve ardından TLS Termination Proxy’yi tekrar başlatmanız gerekebilir. Bu ideal değildir; çünkü TLS Termination Proxy kapalıyken uygulama(lar)ınıza erişilemez.
+
+Uygulamayı servis etmeye devam ederken tüm bu yenileme sürecini yönetebilmek, TLS sertifikalarını doğrudan uygulama server’ıyla (örn. Uvicorn) kullanmak yerine, TLS Termination Proxy ile HTTPS’i yönetecek **ayrı bir sistem** istemenizin başlıca nedenlerinden biridir.
+
+## Proxy Forwarded Headers { #proxy-forwarded-headers }
+
+HTTPS’i bir proxy ile yönetirken, **application server**’ınız (örneğin FastAPI CLI üzerinden Uvicorn) HTTPS süreci hakkında hiçbir şey bilmez; **TLS Termination Proxy** ile düz HTTP üzerinden iletişim kurar.
+
+Bu **proxy** normalde request’i **application server**’a iletmeden önce, request’in proxy tarafından **forward** edildiğini application server’a bildirmek için bazı HTTP header’larını anlık olarak ekler.
+
+/// note | Teknik Detaylar
+
+Proxy header’ları şunlardır:
+
+* X-Forwarded-For
+* X-Forwarded-Proto
+* X-Forwarded-Host
+
+///
+
+Buna rağmen **application server**, güvenilen bir **proxy** arkasında olduğunu bilmediği için varsayılan olarak bu header’lara güvenmez.
+
+Ancak **application server**’ı, **proxy**’nin gönderdiği *forwarded* header’larına güvenecek şekilde yapılandırabilirsiniz. FastAPI CLI kullanıyorsanız, hangi IP’lerden gelen *forwarded* header’lara güvenmesi gerektiğini söylemek için *CLI Option* `--forwarded-allow-ips` seçeneğini kullanabilirsiniz.
+
+Örneğin **application server** yalnızca güvenilen **proxy**’den iletişim alıyorsa, yalnızca **proxy**’nin kullandığı IP’den request alacağı için `--forwarded-allow-ips="*"` ayarlayıp gelen tüm IP’lere güvenmesini sağlayabilirsiniz.
+
+Bu sayede uygulama kendi public URL’inin ne olduğunu, HTTPS kullanıp kullanmadığını, domain’i vb. bilebilir.
+
+Bu, örneğin redirect’leri doğru şekilde yönetmek için faydalıdır.
+
+/// tip | İpucu
+
+Bununla ilgili daha fazlasını [Behind a Proxy - Enable Proxy Forwarded Headers](../advanced/behind-a-proxy.md#enable-proxy-forwarded-headers){.internal-link target=_blank} dokümantasyonunda öğrenebilirsiniz.
+
+///
+
+## Özet { #recap }
+
+**HTTPS** kullanmak çok önemlidir ve çoğu durumda oldukça **kritiktir**. Geliştirici olarak HTTPS etrafında harcadığınız çabanın büyük kısmı, aslında **bu kavramları** ve nasıl çalıştıklarını **anlamaktır**.
+
+Ancak **geliştiriciler için HTTPS**’in temel bilgilerini öğrendikten sonra, her şeyi basitçe yönetmek için farklı araçları kolayca birleştirip yapılandırabilirsiniz.
+
+Sonraki bölümlerin bazılarında, **FastAPI** uygulamaları için **HTTPS**’i nasıl kuracağınıza dair birkaç somut örnek göstereceğim. 🔒
diff --git a/docs/tr/docs/deployment/manually.md b/docs/tr/docs/deployment/manually.md
new file mode 100644
index 000000000..561ba8677
--- /dev/null
+++ b/docs/tr/docs/deployment/manually.md
@@ -0,0 +1,157 @@
+# Bir Sunucuyu Manuel Olarak Çalıştırın { #run-a-server-manually }
+
+## `fastapi run` Komutunu Kullanın { #use-the-fastapi-run-command }
+
+Kısacası, FastAPI uygulamanızı sunmak için `fastapi run` kullanın:
+
+
+
+Ancak `syntaxHighlight` değerini `False` yaparak devre dışı bırakabilirsiniz:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py39.py hl[3] *}
+
+...ve ardından Swagger UI artık syntax highlighting'i göstermeyecektir:
+
+
+
+## Temayı Değiştirin { #change-the-theme }
+
+Aynı şekilde, `"syntaxHighlight.theme"` anahtarıyla (ortasında bir nokta olduğuna dikkat edin) syntax highlighting temasını ayarlayabilirsiniz:
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py39.py hl[3] *}
+
+Bu yapılandırma, syntax highlighting renk temasını değiştirir:
+
+
+
+## Varsayılan Swagger UI Parametrelerini Değiştirin { #change-default-swagger-ui-parameters }
+
+FastAPI, çoğu kullanım senaryosu için uygun bazı varsayılan yapılandırma parametreleriyle gelir.
+
+Şu varsayılan yapılandırmaları içerir:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+`swagger_ui_parameters` argümanında farklı bir değer vererek bunların herhangi birini ezebilirsiniz (override).
+
+Örneğin `deepLinking`'i devre dışı bırakmak için `swagger_ui_parameters`'a şu ayarları geçebilirsiniz:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py39.py hl[3] *}
+
+## Diğer Swagger UI Parametreleri { #other-swagger-ui-parameters }
+
+Kullanabileceğiniz diğer tüm olası yapılandırmaları görmek için, resmi Swagger UI parametreleri dokümantasyonunu okuyun.
+
+## Yalnızca JavaScript ayarları { #javascript-only-settings }
+
+Swagger UI ayrıca bazı yapılandırmaların **yalnızca JavaScript** nesneleri olmasına izin verir (örneğin JavaScript fonksiyonları).
+
+FastAPI, bu yalnızca JavaScript olan `presets` ayarlarını da içerir:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+Bunlar string değil, **JavaScript** nesneleridir; dolayısıyla bunları Python kodundan doğrudan geçemezsiniz.
+
+Böyle yalnızca JavaScript yapılandırmalarına ihtiyacınız varsa, yukarıdaki yöntemlerden birini kullanabilirsiniz: Swagger UI'nin tüm *path operation*'larını override edin ve ihtiyaç duyduğunuz JavaScript'i elle yazın.
diff --git a/docs/tr/docs/how-to/custom-docs-ui-assets.md b/docs/tr/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 000000000..bdd2d0244
--- /dev/null
+++ b/docs/tr/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# Özel Docs UI Statik Varlıkları (Self-Hosting) { #custom-docs-ui-static-assets-self-hosting }
+
+API dokümanları **Swagger UI** ve **ReDoc** kullanır ve bunların her biri bazı JavaScript ve CSS dosyalarına ihtiyaç duyar.
+
+Varsayılan olarak bu dosyalar bir CDN üzerinden servis edilir.
+
+Ancak bunu özelleştirmek mümkündür; belirli bir CDN ayarlayabilir veya dosyaları kendiniz servis edebilirsiniz.
+
+## JavaScript ve CSS için Özel CDN { #custom-cdn-for-javascript-and-css }
+
+Diyelim ki farklı bir CDN kullanmak istiyorsunuz; örneğin `https://unpkg.com/` kullanmak istiyorsunuz.
+
+Bu, örneğin bazı URL'leri kısıtlayan bir ülkede yaşıyorsanız faydalı olabilir.
+
+### Otomatik dokümanları devre dışı bırakın { #disable-the-automatic-docs }
+
+İlk adım, otomatik dokümanları devre dışı bırakmaktır; çünkü varsayılan olarak bunlar varsayılan CDN'i kullanır.
+
+Bunları devre dışı bırakmak için `FastAPI` uygulamanızı oluştururken URL'lerini `None` olarak ayarlayın:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[8] *}
+
+### Özel dokümanları ekleyin { #include-the-custom-docs }
+
+Şimdi özel dokümanlar için *path operation*'ları oluşturabilirsiniz.
+
+Dokümanlar için HTML sayfalarını üretmek üzere FastAPI'nin dahili fonksiyonlarını yeniden kullanabilir ve gerekli argümanları iletebilirsiniz:
+
+* `openapi_url`: Dokümanların HTML sayfasının API'niz için OpenAPI şemasını alacağı URL. Burada `app.openapi_url` niteliğini kullanabilirsiniz.
+* `title`: API'nizin başlığı.
+* `oauth2_redirect_url`: varsayılanı kullanmak için burada `app.swagger_ui_oauth2_redirect_url` kullanabilirsiniz.
+* `swagger_js_url`: Swagger UI dokümanlarınızın HTML'inin **JavaScript** dosyasını alacağı URL. Bu, özel CDN URL'idir.
+* `swagger_css_url`: Swagger UI dokümanlarınızın HTML'inin **CSS** dosyasını alacağı URL. Bu, özel CDN URL'idir.
+
+ReDoc için de benzer şekilde...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | İpucu
+
+`swagger_ui_redirect` için olan *path operation*, OAuth2 kullandığınızda yardımcı olması için vardır.
+
+API'nizi bir OAuth2 sağlayıcısıyla entegre ederseniz kimlik doğrulaması yapabilir, aldığınız kimlik bilgileriyle API dokümanlarına geri dönebilir ve gerçek OAuth2 kimlik doğrulamasını kullanarak onunla etkileşime geçebilirsiniz.
+
+Swagger UI bunu arka planda sizin için yönetir, ancak bu "redirect" yardımcısına ihtiyaç duyar.
+
+///
+
+### Test etmek için bir *path operation* oluşturun { #create-a-path-operation-to-test-it }
+
+Şimdi her şeyin çalıştığını test edebilmek için bir *path operation* oluşturun:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[36:38] *}
+
+### Test edin { #test-it }
+
+Artık http://127.0.0.1:8000/docs adresinden dokümanlarınıza gidebilmeli ve sayfayı yenilediğinizde bu varlıkların yeni CDN'den yüklendiğini görebilmelisiniz.
+
+## Dokümanlar için JavaScript ve CSS'i Self-Hosting ile barındırma { #self-hosting-javascript-and-css-for-docs }
+
+JavaScript ve CSS'i self-hosting ile barındırmak, örneğin uygulamanızın İnternet erişimi olmadan (offline), açık İnternet olmadan veya bir lokal ağ içinde bile çalışmaya devam etmesi gerekiyorsa faydalı olabilir.
+
+Burada bu dosyaları aynı FastAPI uygulamasında nasıl kendiniz servis edeceğinizi ve dokümanların bunları kullanacak şekilde nasıl yapılandırılacağını göreceksiniz.
+
+### Proje dosya yapısı { #project-file-structure }
+
+Diyelim ki projenizin dosya yapısı şöyle:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+Şimdi bu statik dosyaları saklamak için bir dizin oluşturun.
+
+Yeni dosya yapınız şöyle olabilir:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### Dosyaları indirin { #download-the-files }
+
+Dokümanlar için gereken statik dosyaları indirin ve `static/` dizinine koyun.
+
+Muhtemelen her bir linke sağ tıklayıp "Save link as..." benzeri bir seçenek seçebilirsiniz.
+
+**Swagger UI** şu dosyaları kullanır:
+
+* `swagger-ui-bundle.js`
+* `swagger-ui.css`
+
+**ReDoc** ise şu dosyayı kullanır:
+
+* `redoc.standalone.js`
+
+Bundan sonra dosya yapınız şöyle görünebilir:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### Statik dosyaları servis edin { #serve-the-static-files }
+
+* `StaticFiles` içe aktarın.
+* Belirli bir path'te bir `StaticFiles()` instance'ını "mount" edin.
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[7,11] *}
+
+### Statik dosyaları test edin { #test-the-static-files }
+
+Uygulamanızı başlatın ve http://127.0.0.1:8000/static/redoc.standalone.js adresine gidin.
+
+**ReDoc** için çok uzun bir JavaScript dosyası görmelisiniz.
+
+Şuna benzer bir şekilde başlayabilir:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+Bu, uygulamanızdan statik dosyaları servis edebildiğinizi ve dokümanlar için statik dosyaları doğru yere koyduğunuzu doğrular.
+
+Şimdi uygulamayı, dokümanlar için bu statik dosyaları kullanacak şekilde yapılandırabiliriz.
+
+### Statik dosyalar için otomatik dokümanları devre dışı bırakın { #disable-the-automatic-docs-for-static-files }
+
+Özel CDN kullanırken olduğu gibi, ilk adım otomatik dokümanları devre dışı bırakmaktır; çünkü bunlar varsayılan olarak CDN kullanır.
+
+Bunları devre dışı bırakmak için `FastAPI` uygulamanızı oluştururken URL'lerini `None` olarak ayarlayın:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[9] *}
+
+### Statik dosyalar için özel dokümanları ekleyin { #include-the-custom-docs-for-static-files }
+
+Özel CDN'de olduğu gibi, artık özel dokümanlar için *path operation*'ları oluşturabilirsiniz.
+
+Yine FastAPI'nin dahili fonksiyonlarını kullanarak dokümanlar için HTML sayfalarını oluşturabilir ve gerekli argümanları geçebilirsiniz:
+
+* `openapi_url`: Dokümanların HTML sayfasının API'niz için OpenAPI şemasını alacağı URL. Burada `app.openapi_url` niteliğini kullanabilirsiniz.
+* `title`: API'nizin başlığı.
+* `oauth2_redirect_url`: varsayılanı kullanmak için burada `app.swagger_ui_oauth2_redirect_url` kullanabilirsiniz.
+* `swagger_js_url`: Swagger UI dokümanlarınızın HTML'inin **JavaScript** dosyasını alacağı URL. **Artık bunu sizin kendi uygulamanız servis ediyor**.
+* `swagger_css_url`: Swagger UI dokümanlarınızın HTML'inin **CSS** dosyasını alacağı URL. **Artık bunu sizin kendi uygulamanız servis ediyor**.
+
+ReDoc için de benzer şekilde...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | İpucu
+
+`swagger_ui_redirect` için olan *path operation*, OAuth2 kullandığınızda yardımcı olması için vardır.
+
+API'nizi bir OAuth2 sağlayıcısıyla entegre ederseniz kimlik doğrulaması yapabilir, aldığınız kimlik bilgileriyle API dokümanlarına geri dönebilir ve gerçek OAuth2 kimlik doğrulamasını kullanarak onunla etkileşime geçebilirsiniz.
+
+Swagger UI bunu arka planda sizin için yönetir, ancak bu "redirect" yardımcısına ihtiyaç duyar.
+
+///
+
+### Statik dosyaları test etmek için bir *path operation* oluşturun { #create-a-path-operation-to-test-static-files }
+
+Şimdi her şeyin çalıştığını test edebilmek için bir *path operation* oluşturun:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[39:41] *}
+
+### Statik Dosyalar UI'ını Test Edin { #test-static-files-ui }
+
+Artık WiFi bağlantınızı kesip http://127.0.0.1:8000/docs adresindeki dokümanlarınıza gidebilmeli ve sayfayı yenileyebilmelisiniz.
+
+Ve İnternet olmasa bile API dokümanlarınızı görebilir ve onunla etkileşime geçebilirsiniz.
diff --git a/docs/tr/docs/how-to/custom-request-and-route.md b/docs/tr/docs/how-to/custom-request-and-route.md
new file mode 100644
index 000000000..a4419373f
--- /dev/null
+++ b/docs/tr/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# Özel Request ve APIRoute sınıfı { #custom-request-and-apiroute-class }
+
+Bazı durumlarda, `Request` ve `APIRoute` sınıflarının kullandığı mantığı override etmek isteyebilirsiniz.
+
+Özellikle bu yaklaşım, bir middleware içindeki mantığa iyi bir alternatif olabilir.
+
+Örneğin, request body uygulamanız tarafından işlenmeden önce okumak veya üzerinde değişiklik yapmak istiyorsanız.
+
+/// danger | Uyarı
+
+Bu "ileri seviye" bir özelliktir.
+
+**FastAPI**'ye yeni başlıyorsanız bu bölümü atlamak isteyebilirsiniz.
+
+///
+
+## Kullanım senaryoları { #use-cases }
+
+Bazı kullanım senaryoları:
+
+* JSON olmayan request body'leri JSON'a dönüştürmek (örn. `msgpack`).
+* gzip ile sıkıştırılmış request body'leri açmak (decompress).
+* Tüm request body'lerini otomatik olarak loglamak.
+
+## Özel request body encoding'lerini ele alma { #handling-custom-request-body-encodings }
+
+Gzip request'lerini açmak için özel bir `Request` alt sınıfını nasıl kullanabileceğimize bakalım.
+
+Ayrıca, o özel request sınıfını kullanmak için bir `APIRoute` alt sınıfı da oluşturacağız.
+
+### Özel bir `GzipRequest` sınıfı oluşturun { #create-a-custom-gziprequest-class }
+
+/// tip | İpucu
+
+Bu, nasıl çalıştığını göstermek için hazırlanmış basit bir örnektir; Gzip desteğine ihtiyacınız varsa sağlanan [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} bileşenini kullanabilirsiniz.
+
+///
+
+Önce, uygun bir header mevcut olduğunda body'yi açmak için `Request.body()` metodunu overwrite edecek bir `GzipRequest` sınıfı oluşturuyoruz.
+
+Header'da `gzip` yoksa body'yi açmayı denemez.
+
+Böylece aynı route sınıfı, gzip ile sıkıştırılmış veya sıkıştırılmamış request'leri handle edebilir.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### Özel bir `GzipRoute` sınıfı oluşturun { #create-a-custom-gziproute-class }
+
+Sonra, `GzipRequest`'i kullanacak `fastapi.routing.APIRoute` için özel bir alt sınıf oluşturuyoruz.
+
+Bu kez `APIRoute.get_route_handler()` metodunu overwrite edeceğiz.
+
+Bu metot bir fonksiyon döndürür. Bu fonksiyon da request'i alır ve response döndürür.
+
+Burada bu fonksiyonu, orijinal request'ten bir `GzipRequest` oluşturmak için kullanıyoruz.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | Teknik Detaylar
+
+Bir `Request`'in, request ile ilgili metadata'yı içeren bir Python `dict` olan `request.scope` attribute'u vardır.
+
+Bir `Request` ayrıca `request.receive` içerir; bu, request'in body'sini "almak" (receive etmek) için kullanılan bir fonksiyondur.
+
+`scope` `dict`'i ve `receive` fonksiyonu, ASGI spesifikasyonunun parçalarıdır.
+
+Ve bu iki şey, `scope` ve `receive`, yeni bir `Request` instance'ı oluşturmak için gerekenlerdir.
+
+`Request` hakkında daha fazla bilgi için Starlette'ın Request dokümantasyonuna bakın.
+
+///
+
+`GzipRequest.get_route_handler` tarafından döndürülen fonksiyonun farklı yaptığı tek şey, `Request`'i bir `GzipRequest`'e dönüştürmektir.
+
+Bunu yaptığımızda `GzipRequest`, veriyi (gerekliyse) *path operations*'larımıza geçirmeden önce açma (decompress) işini üstlenir.
+
+Bundan sonra tüm işleme mantığı aynıdır.
+
+Ancak `GzipRequest.body` içindeki değişikliklerimiz sayesinde, request body gerektiğinde **FastAPI** tarafından yüklendiğinde otomatik olarak decompress edilir.
+
+## Bir exception handler içinde request body'ye erişme { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | İpucu
+
+Aynı problemi çözmek için, muhtemelen `RequestValidationError` için özel bir handler içinde `body` kullanmak çok daha kolaydır ([Hataları Ele Alma](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}).
+
+Yine de bu örnek geçerlidir ve dahili bileşenlerle nasıl etkileşime geçileceğini gösterir.
+
+///
+
+Aynı yaklaşımı bir exception handler içinde request body'ye erişmek için de kullanabiliriz.
+
+Tek yapmamız gereken, request'i bir `try`/`except` bloğu içinde handle etmek:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+Bir exception oluşursa, `Request` instance'ı hâlâ scope içinde olacağı için, hatayı handle ederken request body'yi okuyup kullanabiliriz:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## Bir router içinde özel `APIRoute` sınıfı { #custom-apiroute-class-in-a-router }
+
+Bir `APIRouter` için `route_class` parametresini de ayarlayabilirsiniz:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+Bu örnekte, `router` altındaki *path operations*'lar özel `TimedRoute` sınıfını kullanır ve response'u üretmek için geçen süreyi içeren ekstra bir `X-Response-Time` header'ı response'ta bulunur:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/tr/docs/how-to/extending-openapi.md b/docs/tr/docs/how-to/extending-openapi.md
new file mode 100644
index 000000000..99691946c
--- /dev/null
+++ b/docs/tr/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# OpenAPI'yi Genişletme { #extending-openapi }
+
+Oluşturulan OpenAPI şemasını değiştirmeniz gereken bazı durumlar olabilir.
+
+Bu bölümde bunun nasıl yapılacağını göreceksiniz.
+
+## Normal süreç { #the-normal-process }
+
+Normal (varsayılan) süreç şöyledir.
+
+Bir `FastAPI` uygulamasının (instance) OpenAPI şemasını döndürmesi beklenen bir `.openapi()` metodu vardır.
+
+Uygulama nesnesi oluşturulurken, `/openapi.json` (ya da `openapi_url` için ne ayarladıysanız o) için bir *path operation* kaydedilir.
+
+Bu path operation, uygulamanın `.openapi()` metodunun sonucunu içeren bir JSON response döndürür.
+
+Varsayılan olarak `.openapi()` metodunun yaptığı şey, `.openapi_schema` özelliğinde içerik olup olmadığını kontrol etmek ve varsa onu döndürmektir.
+
+Eğer yoksa, `fastapi.openapi.utils.get_openapi` konumundaki yardımcı (utility) fonksiyonu kullanarak şemayı üretir.
+
+Ve `get_openapi()` fonksiyonu şu parametreleri alır:
+
+* `title`: Dokümanlarda gösterilen OpenAPI başlığı.
+* `version`: API'nizin sürümü, örn. `2.5.0`.
+* `openapi_version`: Kullanılan OpenAPI specification sürümü. Varsayılan olarak en günceli: `3.1.0`.
+* `summary`: API'nin kısa özeti.
+* `description`: API'nizin açıklaması; markdown içerebilir ve dokümanlarda gösterilir.
+* `routes`: route'ların listesi; bunların her biri kayıtlı *path operations*'lardır. `app.routes` içinden alınırlar.
+
+/// info | Bilgi
+
+`summary` parametresi OpenAPI 3.1.0 ve üzeri sürümlerde vardır; FastAPI 0.99.0 ve üzeri tarafından desteklenmektedir.
+
+///
+
+## Varsayılanları ezme { #overriding-the-defaults }
+
+Yukarıdaki bilgileri kullanarak aynı yardımcı fonksiyonla OpenAPI şemasını üretebilir ve ihtiyacınız olan her parçayı override edebilirsiniz.
+
+Örneğin, özel bir logo eklemek için ReDoc'un OpenAPI extension'ını ekleyelim.
+
+### Normal **FastAPI** { #normal-fastapi }
+
+Önce, tüm **FastAPI** uygulamanızı her zamanki gibi yazın:
+
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[1,4,7:9] *}
+
+### OpenAPI şemasını üretme { #generate-the-openapi-schema }
+
+Ardından, bir `custom_openapi()` fonksiyonunun içinde aynı yardımcı fonksiyonu kullanarak OpenAPI şemasını üretin:
+
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[2,15:21] *}
+
+### OpenAPI şemasını değiştirme { #modify-the-openapi-schema }
+
+Artık OpenAPI şemasındaki `info` "object"'ine özel bir `x-logo` ekleyerek ReDoc extension'ını ekleyebilirsiniz:
+
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[22:24] *}
+
+### OpenAPI şemasını cache'leme { #cache-the-openapi-schema }
+
+Ürettiğiniz şemayı saklamak için `.openapi_schema` özelliğini bir "cache" gibi kullanabilirsiniz.
+
+Böylece bir kullanıcı API docs'larınızı her açtığında uygulamanız şemayı tekrar tekrar üretmek zorunda kalmaz.
+
+Şema yalnızca bir kez üretilecektir; sonraki request'ler için de aynı cache'lenmiş şema kullanılacaktır.
+
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[13:14,25:26] *}
+
+### Metodu override etme { #override-the-method }
+
+Şimdi `.openapi()` metodunu yeni fonksiyonunuzla değiştirebilirsiniz.
+
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[29] *}
+
+### Kontrol edin { #check-it }
+
+http://127.0.0.1:8000/redoc adresine gittiğinizde, özel logonuzu kullandığınızı göreceksiniz (bu örnekte **FastAPI**'nin logosu):
+
+
diff --git a/docs/tr/docs/how-to/graphql.md b/docs/tr/docs/how-to/graphql.md
new file mode 100644
index 000000000..fbf018874
--- /dev/null
+++ b/docs/tr/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+**FastAPI**, **ASGI** standardını temel aldığı için ASGI ile uyumlu herhangi bir **GraphQL** kütüphanesini entegre etmek oldukça kolaydır.
+
+Aynı uygulama içinde normal FastAPI *path operation*'larını GraphQL ile birlikte kullanabilirsiniz.
+
+/// tip | İpucu
+
+**GraphQL** bazı çok özel kullanım senaryolarını çözer.
+
+Yaygın **web API**'lerle karşılaştırıldığında **avantajları** ve **dezavantajları** vardır.
+
+Kendi senaryonuz için **faydaların**, **olumsuz yönleri** telafi edip etmediğini mutlaka değerlendirin. 🤓
+
+///
+
+## GraphQL Kütüphaneleri { #graphql-libraries }
+
+Aşağıda **ASGI** desteği olan bazı **GraphQL** kütüphaneleri var. Bunları **FastAPI** ile kullanabilirsiniz:
+
+* Strawberry 🍓
+ * FastAPI dokümantasyonu ile
+* Ariadne
+ * FastAPI dokümantasyonu ile
+* Tartiflette
+ * ASGI entegrasyonu sağlamak için Tartiflette ASGI ile
+* Graphene
+ * starlette-graphene3 ile
+
+## Strawberry ile GraphQL { #graphql-with-strawberry }
+
+**GraphQL** ile çalışmanız gerekiyorsa ya da bunu istiyorsanız, **Strawberry** önerilen kütüphanedir; çünkü tasarımı **FastAPI**'nin tasarımına en yakındır ve her şey **type annotation**'lar üzerine kuruludur.
+
+Kullanım senaryonuza göre farklı bir kütüphaneyi tercih edebilirsiniz; ancak bana sorarsanız muhtemelen **Strawberry**'yi denemenizi önerirdim.
+
+Strawberry'yi FastAPI ile nasıl entegre edebileceğinize dair küçük bir ön izleme:
+
+{* ../../docs_src/graphql_/tutorial001_py39.py hl[3,22,25] *}
+
+Strawberry hakkında daha fazlasını Strawberry dokümantasyonunda öğrenebilirsiniz.
+
+Ayrıca FastAPI ile Strawberry dokümanlarına da göz atın.
+
+## Starlette'teki Eski `GraphQLApp` { #older-graphqlapp-from-starlette }
+
+Starlette'in önceki sürümlerinde Graphene ile entegrasyon için bir `GraphQLApp` sınıfı vardı.
+
+Bu sınıf Starlette'te kullanımdan kaldırıldı (deprecated). Ancak bunu kullanan bir kodunuz varsa, aynı kullanım senaryosunu kapsayan ve **neredeyse aynı bir interface** sağlayan starlette-graphene3'e kolayca **migrate** edebilirsiniz.
+
+/// tip | İpucu
+
+GraphQL'e ihtiyacınız varsa, custom class ve type'lar yerine type annotation'lara dayandığı için yine de Strawberry'yi incelemenizi öneririm.
+
+///
+
+## Daha Fazlasını Öğrenin { #learn-more }
+
+**GraphQL** hakkında daha fazlasını resmi GraphQL dokümantasyonunda öğrenebilirsiniz.
+
+Ayrıca yukarıda bahsedilen kütüphanelerin her biri hakkında, kendi bağlantılarından daha fazla bilgi okuyabilirsiniz.
diff --git a/docs/tr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/tr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 000000000..275ac5fd1
--- /dev/null
+++ b/docs/tr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Pydantic v1'den Pydantic v2'ye Geçiş { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+Eski bir FastAPI uygulamanız varsa, Pydantic'in 1. sürümünü kullanıyor olabilirsiniz.
+
+FastAPI 0.100.0 sürümü, Pydantic v1 veya v2 ile çalışmayı destekliyordu. Hangisi kuruluysa onu kullanıyordu.
+
+FastAPI 0.119.0 sürümü, v2'ye geçişi kolaylaştırmak için, Pydantic v2’nin içinden Pydantic v1’e (`pydantic.v1` olarak) kısmi destek ekledi.
+
+FastAPI 0.126.0 sürümü Pydantic v1 desteğini kaldırdı, ancak bir süre daha `pydantic.v1` desteğini sürdürdü.
+
+/// warning | Uyarı
+
+Pydantic ekibi, **Python 3.14** ile başlayarak Python'ın en yeni sürümleri için Pydantic v1 desteğini sonlandırdı.
+
+Buna `pydantic.v1` de dahildir; Python 3.14 ve üzeri sürümlerde artık desteklenmemektedir.
+
+Python'ın en yeni özelliklerini kullanmak istiyorsanız, Pydantic v2 kullandığınızdan emin olmanız gerekir.
+
+///
+
+Pydantic v1 kullanan eski bir FastAPI uygulamanız varsa, burada onu Pydantic v2'ye nasıl taşıyacağınızı ve kademeli geçişi kolaylaştıran **FastAPI 0.119.0 özelliklerini** göstereceğim.
+
+## Resmi Kılavuz { #official-guide }
+
+Pydantic'in v1'den v2'ye resmi bir Migration Guide'ı vardır.
+
+Ayrıca nelerin değiştiğini, validasyonların artık nasıl daha doğru ve katı olduğunu, olası dikkat edilmesi gereken noktaları (caveat) vb. de içerir.
+
+Nelerin değiştiğini daha iyi anlamak için okuyabilirsiniz.
+
+## Testler { #tests }
+
+Uygulamanız için [testlerinizin](../tutorial/testing.md){.internal-link target=_blank} olduğundan ve bunları continuous integration (CI) üzerinde çalıştırdığınızdan emin olun.
+
+Bu şekilde yükseltmeyi yapabilir ve her şeyin hâlâ beklendiği gibi çalıştığını doğrulayabilirsiniz.
+
+## `bump-pydantic` { #bump-pydantic }
+
+Birçok durumda, özel özelleştirmeler olmadan standart Pydantic modelleri kullanıyorsanız, Pydantic v1'den Pydantic v2'ye geçiş sürecinin büyük kısmını otomatikleştirebilirsiniz.
+
+Aynı Pydantic ekibinin geliştirdiği `bump-pydantic` aracını kullanabilirsiniz.
+
+Bu araç, değişmesi gereken kodun büyük bir kısmını otomatik olarak dönüştürmenize yardımcı olur.
+
+Bundan sonra testleri çalıştırıp her şeyin çalışıp çalışmadığını kontrol edebilirsiniz. Çalışıyorsa işiniz biter. 😎
+
+## v2 İçinde Pydantic v1 { #pydantic-v1-in-v2 }
+
+Pydantic v2, `pydantic.v1` adlı bir alt modül olarak Pydantic v1'in tamamını içerir. Ancak bu yapı, Python 3.13'ün üzerindeki sürümlerde artık desteklenmemektedir.
+
+Bu da şu anlama gelir: Pydantic v2'nin en güncel sürümünü kurup, bu alt modülden eski Pydantic v1 bileşenlerini import ederek, sanki eski Pydantic v1 kuruluymuş gibi kullanabilirsiniz.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### v2 İçinde Pydantic v1 için FastAPI Desteği { #fastapi-support-for-pydantic-v1-in-v2 }
+
+FastAPI 0.119.0'dan itibaren, v2'ye geçişi kolaylaştırmak için Pydantic v2’nin içinden Pydantic v1 kullanımına yönelik kısmi destek de vardır.
+
+Dolayısıyla Pydantic'i en güncel 2 sürümüne yükseltip import'ları `pydantic.v1` alt modülünü kullanacak şekilde değiştirebilirsiniz; çoğu durumda bu doğrudan çalışır.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | Uyarı
+
+Pydantic ekibi Python 3.14'ten itibaren yeni Python sürümlerinde Pydantic v1'i artık desteklemediği için, `pydantic.v1` kullanımı da Python 3.14 ve üzeri sürümlerde desteklenmez.
+
+///
+
+### Aynı Uygulamada Pydantic v1 ve v2 { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic açısından, alanları (field) Pydantic v1 modelleriyle tanımlanmış bir Pydantic v2 modeli (ya da tersi) kullanmak **desteklenmez**.
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...ancak aynı uygulamada Pydantic v1 ve v2 kullanarak **ayrı (separated)** modeller tanımlayabilirsiniz.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+Bazı durumlarda, FastAPI uygulamanızda aynı **path operation** içinde hem Pydantic v1 hem de v2 modellerini kullanmak bile mümkündür:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+Yukarıdaki örnekte input modeli bir Pydantic v1 modelidir; output modeli ( `response_model=ItemV2` ile tanımlanan) ise bir Pydantic v2 modelidir.
+
+### Pydantic v1 Parametreleri { #pydantic-v1-parameters }
+
+Pydantic v1 modelleriyle `Body`, `Query`, `Form` vb. parametreler için FastAPI'ye özgü bazı araçları kullanmanız gerekiyorsa, Pydantic v2'ye geçişi tamamlayana kadar bunları `fastapi.temp_pydantic_v1_params` içinden import edebilirsiniz:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### Adım Adım Geçiş { #migrate-in-steps }
+
+/// tip | İpucu
+
+Önce `bump-pydantic` ile deneyin; testleriniz geçerse ve bu yol çalışırsa tek komutla işi bitirmiş olursunuz. ✨
+
+///
+
+`bump-pydantic` sizin senaryonuz için uygun değilse, aynı uygulamada hem Pydantic v1 hem de v2 modellerini birlikte kullanma desteğinden yararlanarak Pydantic v2'ye kademeli şekilde geçebilirsiniz.
+
+Önce Pydantic'i en güncel 2 sürümüne yükseltip tüm modelleriniz için import'ları `pydantic.v1` kullanacak şekilde değiştirebilirsiniz.
+
+Ardından modellerinizi Pydantic v1'den v2'ye gruplar hâlinde, adım adım taşımaya başlayabilirsiniz. 🚶
diff --git a/docs/tr/docs/how-to/separate-openapi-schemas.md b/docs/tr/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 000000000..c26411d29
--- /dev/null
+++ b/docs/tr/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# Input ve Output için Ayrı OpenAPI Schema'ları (Ya da Değil) { #separate-openapi-schemas-for-input-and-output-or-not }
+
+**Pydantic v2** yayınlandığından beri, üretilen OpenAPI eskisine göre biraz daha net ve **doğru**. 😎
+
+Hatta bazı durumlarda, aynı Pydantic model için OpenAPI içinde input ve output tarafında, **default değerler** olup olmamasına bağlı olarak **iki farklı JSON Schema** bile görebilirsiniz.
+
+Bunun nasıl çalıştığına ve gerekirse nasıl değiştirebileceğinize bir bakalım.
+
+## Input ve Output için Pydantic Modelleri { #pydantic-models-for-input-and-output }
+
+Default değerleri olan bir Pydantic modeliniz olduğunu varsayalım; örneğin şöyle:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### Input için Model { #model-for-input }
+
+Bu modeli şöyle input olarak kullanırsanız:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+...`description` alanı **zorunlu olmaz**. Çünkü `None` default değerine sahiptir.
+
+### Dokümanlarda Input Modeli { #input-model-in-docs }
+
+Bunu dokümanlarda da doğrulayabilirsiniz; `description` alanında **kırmızı yıldız** yoktur, yani required olarak işaretlenmemiştir:
+
+
+
+
+
+
+
+
+Aynı dosya yapısı, yorumlarla birlikte:
+
+```bash
+.
+├── app # "app" bir Python package'idir
+│ ├── __init__.py # bu dosya, "app"i bir "Python package" yapar
+│ ├── main.py # "main" module'ü, örn. import app.main
+│ ├── dependencies.py # "dependencies" module'ü, örn. import app.dependencies
+│ └── routers # "routers" bir "Python subpackage"idir
+│ │ ├── __init__.py # "routers"ı bir "Python subpackage" yapar
+│ │ ├── items.py # "items" submodule'ü, örn. import app.routers.items
+│ │ └── users.py # "users" submodule'ü, örn. import app.routers.users
+│ └── internal # "internal" bir "Python subpackage"idir
+│ ├── __init__.py # "internal"ı bir "Python subpackage" yapar
+│ └── admin.py # "admin" submodule'ü, örn. import app.internal.admin
+```
+
+## `APIRouter` { #apirouter }
+
+Diyelim ki sadece kullanıcıları yönetmeye ayrılmış dosyanız `/app/routers/users.py` içindeki submodule olsun.
+
+Kullanıcılarla ilgili *path operation*’ları, kodun geri kalanından ayrı tutmak istiyorsunuz; böylece düzenli kalır.
+
+Ancak bu hâlâ aynı **FastAPI** uygulaması/web API’sinin bir parçasıdır (aynı "Python Package" içinde).
+
+Bu module için *path operation*’ları `APIRouter` kullanarak oluşturabilirsiniz.
+
+### `APIRouter` Import Edin { #import-apirouter }
+
+`FastAPI` class’ında yaptığınız gibi import edip bir "instance" oluşturursunuz:
+
+{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+
+### `APIRouter` ile *Path Operations* { #path-operations-with-apirouter }
+
+Sonra bunu kullanarak *path operation*’larınızı tanımlarsınız.
+
+`FastAPI` class’ını nasıl kullanıyorsanız aynı şekilde kullanın:
+
+{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+
+`APIRouter`’ı "mini bir `FastAPI`" class’ı gibi düşünebilirsiniz.
+
+Aynı seçeneklerin hepsi desteklenir.
+
+Aynı `parameters`, `responses`, `dependencies`, `tags`, vb.
+
+/// tip | İpucu
+
+Bu örnekte değişkenin adı `router`. Ancak istediğiniz gibi adlandırabilirsiniz.
+
+///
+
+Bu `APIRouter`’ı ana `FastAPI` uygulamasına ekleyeceğiz; ama önce dependency’lere ve bir diğer `APIRouter`’a bakalım.
+
+## Dependencies { #dependencies }
+
+Uygulamanın birden fazla yerinde kullanılacak bazı dependency’lere ihtiyacımız olacağını görüyoruz.
+
+Bu yüzden onları ayrı bir `dependencies` module’üne koyuyoruz (`app/dependencies.py`).
+
+Şimdi, özel bir `X-Token` header'ını okumak için basit bir dependency kullanalım:
+
+{* ../../docs_src/bigger_applications/app_an_py39/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+
+/// tip | İpucu
+
+Örneği basit tutmak için uydurma bir header kullanıyoruz.
+
+Ancak gerçek senaryolarda, entegre [Security yardımcı araçlarını](security/index.md){.internal-link target=_blank} kullanarak daha iyi sonuç alırsınız.
+
+///
+
+## `APIRouter` ile Başka Bir Module { #another-module-with-apirouter }
+
+Diyelim ki uygulamanızdaki "items" ile ilgili endpoint'ler de `app/routers/items.py` module’ünde olsun.
+
+Şunlar için *path operation*’larınız var:
+
+* `/items/`
+* `/items/{item_id}`
+
+Bu, `app/routers/users.py` ile aynı yapıdadır.
+
+Ancak biraz daha akıllı davranıp kodu sadeleştirmek istiyoruz.
+
+Bu module’deki tüm *path operation*’ların şu ortak özelliklere sahip olduğunu biliyoruz:
+
+* Path `prefix`: `/items`.
+* `tags`: (tek bir tag: `items`).
+* Ek `responses`.
+* `dependencies`: hepsinin, oluşturduğumuz `X-Token` dependency’sine ihtiyacı var.
+
+Dolayısıyla bunları her *path operation*’a tek tek eklemek yerine `APIRouter`’a ekleyebiliriz.
+
+{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+
+Her *path operation*’ın path’i aşağıdaki gibi `/` ile başlamak zorunda olduğundan:
+
+```Python hl_lines="1"
+@router.get("/{item_id}")
+async def read_item(item_id: str):
+ ...
+```
+
+...prefix’in sonunda `/` olmamalıdır.
+
+Yani bu örnekte prefix `/items` olur.
+
+Ayrıca, bu router içindeki tüm *path operation*’lara uygulanacak bir `tags` listesi ve ek `responses` da ekleyebiliriz.
+
+Ve router’daki tüm *path operation*’lara eklenecek, her request için çalıştırılıp çözülecek bir `dependencies` listesi de ekleyebiliriz.
+
+/// tip | İpucu
+
+[ *path operation decorator*’larındaki dependency’lerde](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} olduğu gibi, *path operation function*’ınıza herhangi bir değer aktarılmayacağını unutmayın.
+
+///
+
+Sonuç olarak item path’leri artık:
+
+* `/items/`
+* `/items/{item_id}`
+
+...tam da istediğimiz gibi olur.
+
+* Hepsi, içinde tek bir string `"items"` bulunan bir tag listesiyle işaretlenir.
+ * Bu "tags", özellikle otomatik interaktif dokümantasyon sistemleri (OpenAPI) için çok faydalıdır.
+* Hepsi önceden tanımlı `responses`’ları içerir.
+* Bu *path operation*’ların hepsinde, öncesinde `dependencies` listesi değerlendirilip çalıştırılır.
+ * Ayrıca belirli bir *path operation* içinde dependency tanımlarsanız, **onlar da çalıştırılır**.
+ * Önce router dependency’leri, sonra decorator’daki [`dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, sonra da normal parametre dependency’leri çalışır.
+ * Ayrıca [`scopes` ile `Security` dependency’leri](../advanced/security/oauth2-scopes.md){.internal-link target=_blank} de ekleyebilirsiniz.
+
+/// tip | İpucu
+
+`APIRouter` içinde `dependencies` kullanmak, örneğin bir grup *path operation* için kimlik doğrulamayı zorunlu kılmakta kullanılabilir. Dependency’leri tek tek her birine eklemeseniz bile.
+
+///
+
+/// check | Ek bilgi
+
+`prefix`, `tags`, `responses` ve `dependencies` parametreleri (çoğu başka örnekte olduğu gibi) kod tekrarını önlemenize yardımcı olan, **FastAPI**’nin bir özelliğidir.
+
+///
+
+### Dependency'leri Import Edin { #import-the-dependencies }
+
+Bu kod `app.routers.items` module’ünde, yani `app/routers/items.py` dosyasında duruyor.
+
+Dependency function’ını ise `app.dependencies` module’ünden, yani `app/dependencies.py` dosyasından almamız gerekiyor.
+
+Bu yüzden dependency’ler için `..` ile relative import kullanıyoruz:
+
+{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[3] title["app/routers/items.py"] *}
+
+#### Relative Import Nasıl Çalışır { #how-relative-imports-work }
+
+/// tip | İpucu
+
+Import’ların nasıl çalıştığını çok iyi biliyorsanız, bir sonraki bölüme geçin.
+
+///
+
+Tek bir nokta `.`, örneğin:
+
+```Python
+from .dependencies import get_token_header
+```
+
+şu anlama gelir:
+
+* Bu module’ün (yani `app/routers/items.py` dosyasının) bulunduğu package içinden başla ( `app/routers/` dizini)...
+* `dependencies` module’ünü bul (`app/routers/dependencies.py` gibi hayali bir dosya)...
+* ve oradan `get_token_header` function’ını import et.
+
+Ama o dosya yok; bizim dependency’lerimiz `app/dependencies.py` dosyasında.
+
+Uygulama/dosya yapımızın nasıl göründüğünü hatırlayın:
+
+
+
+---
+
+İki nokta `..`, örneğin:
+
+```Python
+from ..dependencies import get_token_header
+```
+
+şu anlama gelir:
+
+* Bu module’ün bulunduğu package içinden başla (`app/routers/` dizini)...
+* üst (parent) package’e çık (`app/` dizini)...
+* burada `dependencies` module’ünü bul (`app/dependencies.py` dosyası)...
+* ve oradan `get_token_header` function’ını import et.
+
+Bu doğru şekilde çalışır! 🎉
+
+---
+
+Aynı şekilde, üç nokta `...` kullansaydık:
+
+```Python
+from ...dependencies import get_token_header
+```
+
+şu anlama gelirdi:
+
+* Bu module’ün bulunduğu package içinden başla (`app/routers/` dizini)...
+* üst package’e çık (`app/` dizini)...
+* sonra bir üstüne daha çık (orada bir üst package yok; `app` en üst seviye 😱)...
+* ve orada `dependencies` module’ünü bul (`app/dependencies.py` dosyası)...
+* ve oradan `get_token_header` function’ını import et.
+
+Bu, `app/` dizininin üstünde, kendi `__init__.py` dosyası olan başka bir package’e işaret ederdi. Ama bizde böyle bir şey yok. Dolayısıyla bu örnekte hata verirdi. 🚨
+
+Artık nasıl çalıştığını bildiğinize göre, uygulamalarınız ne kadar karmaşık olursa olsun relative import’ları kullanabilirsiniz. 🤓
+
+### Özel `tags`, `responses` ve `dependencies` Ekleyin { #add-some-custom-tags-responses-and-dependencies }
+
+`/items` prefix’ini ya da `tags=["items"]` değerini her *path operation*’a tek tek eklemiyoruz; çünkü bunları `APIRouter`’a ekledik.
+
+Ama yine de belirli bir *path operation*’a uygulanacak _ek_ `tags` tanımlayabilir, ayrıca o *path operation*’a özel `responses` ekleyebiliriz:
+
+{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+
+/// tip | İpucu
+
+Bu son *path operation*’da tag kombinasyonu şöyle olur: `["items", "custom"]`.
+
+Ayrıca dokümantasyonda iki response da görünür: biri `404`, diğeri `403`.
+
+///
+
+## Ana `FastAPI` { #the-main-fastapi }
+
+Şimdi `app/main.py` module’üne bakalım.
+
+Burada `FastAPI` class’ını import edip kullanırsınız.
+
+Bu dosya, uygulamanızda her şeyi bir araya getiren ana dosya olacak.
+
+Mantığın büyük kısmı artık kendi module’lerinde yaşayacağı için ana dosya oldukça basit kalır.
+
+### `FastAPI` Import Edin { #import-fastapi }
+
+Normal şekilde bir `FastAPI` class’ı oluşturursunuz.
+
+Hatta her `APIRouter` için olan dependency’lerle birleştirilecek [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank} bile tanımlayabilirsiniz:
+
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[1,3,7] title["app/main.py"] *}
+
+### `APIRouter` Import Edin { #import-the-apirouter }
+
+Şimdi `APIRouter` içeren diğer submodule’leri import ediyoruz:
+
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[4:5] title["app/main.py"] *}
+
+`app/routers/users.py` ve `app/routers/items.py` dosyaları aynı Python package’i olan `app`’in parçası olan submodule’ler olduğu için, onları "relative import" ile tek bir nokta `.` kullanarak import edebiliriz.
+
+### Import Nasıl Çalışır { #how-the-importing-works }
+
+Şu bölüm:
+
+```Python
+from .routers import items, users
+```
+
+şu anlama gelir:
+
+* Bu module’ün (yani `app/main.py` dosyasının) bulunduğu package içinden başla (`app/` dizini)...
+* `routers` subpackage’ini bul (`app/routers/` dizini)...
+* ve buradan `items` submodule’ünü (`app/routers/items.py`) ve `users` submodule’ünü (`app/routers/users.py`) import et...
+
+`items` module’ünün içinde `router` adında bir değişken vardır (`items.router`). Bu, `app/routers/items.py` dosyasında oluşturduğumuz aynı değişkendir; bir `APIRouter` nesnesidir.
+
+Sonra aynı işlemi `users` module’ü için de yaparız.
+
+Ayrıca şöyle de import edebilirdik:
+
+```Python
+from app.routers import items, users
+```
+
+/// info | Bilgi
+
+İlk sürüm "relative import"tur:
+
+```Python
+from .routers import items, users
+```
+
+İkinci sürüm "absolute import"tur:
+
+```Python
+from app.routers import items, users
+```
+
+Python Packages ve Modules hakkında daha fazlası için, Python'ın Modules ile ilgili resmi dokümantasyonunu okuyun.
+
+///
+
+### İsim Çakışmalarını Önleyin { #avoid-name-collisions }
+
+`items` submodule’ünü doğrudan import ediyoruz; sadece içindeki `router` değişkenini import etmiyoruz.
+
+Çünkü `users` submodule’ünde de `router` adlı başka bir değişken var.
+
+Eğer şöyle sırayla import etseydik:
+
+```Python
+from .routers.items import router
+from .routers.users import router
+```
+
+`users` içindeki `router`, `items` içindeki `router`’ın üstüne yazardı ve ikisini aynı anda kullanamazdık.
+
+Bu yüzden ikisini de aynı dosyada kullanabilmek için submodule’leri doğrudan import ediyoruz:
+
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[5] title["app/main.py"] *}
+
+### `users` ve `items` için `APIRouter`’ları Dahil Edin { #include-the-apirouters-for-users-and-items }
+
+Şimdi `users` ve `items` submodule’lerindeki `router`’ları dahil edelim:
+
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[10:11] title["app/main.py"] *}
+
+/// info | Bilgi
+
+`users.router`, `app/routers/users.py` dosyasının içindeki `APIRouter`’ı içerir.
+
+`items.router` ise `app/routers/items.py` dosyasının içindeki `APIRouter`’ı içerir.
+
+///
+
+`app.include_router()` ile her bir `APIRouter`’ı ana `FastAPI` uygulamasına ekleyebiliriz.
+
+Böylece o router içindeki tüm route’lar uygulamanın bir parçası olarak dahil edilir.
+
+/// note | Teknik Detaylar
+
+Aslında içeride, `APIRouter` içinde tanımlanan her *path operation* için bir *path operation* oluşturur.
+
+Yani perde arkasında, her şey tek bir uygulamaymış gibi çalışır.
+
+///
+
+/// check | Ek bilgi
+
+Router’ları dahil ederken performans konusunda endişelenmeniz gerekmez.
+
+Bu işlem mikrosaniyeler sürer ve sadece startup sırasında olur.
+
+Dolayısıyla performansı etkilemez. ⚡
+
+///
+
+### Özel `prefix`, `tags`, `responses` ve `dependencies` ile Bir `APIRouter` Dahil Edin { #include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies }
+
+Şimdi, kurumunuzun size `app/internal/admin.py` dosyasını verdiğini düşünelim.
+
+Bu dosyada, kurumunuzun birden fazla proje arasında paylaştığı bazı admin *path operation*’larını içeren bir `APIRouter` var.
+
+Bu örnekte çok basit olacak. Ancak kurum içinde başka projelerle paylaşıldığı için, bunu değiştirip `prefix`, `dependencies`, `tags` vs. doğrudan `APIRouter`’a ekleyemediğimizi varsayalım:
+
+{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+
+Yine de bu `APIRouter`’ı dahil ederken özel bir `prefix` ayarlamak istiyoruz ki tüm *path operation*’ları `/admin` ile başlasın; ayrıca bu projede hâlihazırda kullandığımız `dependencies` ile güvene almak, `tags` ve `responses` eklemek istiyoruz.
+
+Orijinal `APIRouter`’ı değiştirmeden, bu parametreleri `app.include_router()`’a vererek hepsini tanımlayabiliriz:
+
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[14:17] title["app/main.py"] *}
+
+Böylece orijinal `APIRouter` değişmeden kalır; yani aynı `app/internal/admin.py` dosyasını kurum içindeki diğer projelerle de paylaşmaya devam edebiliriz.
+
+Sonuç olarak, uygulamamızda `admin` module’ündeki her bir *path operation* şunlara sahip olur:
+
+* `/admin` prefix’i.
+* `admin` tag’i.
+* `get_token_header` dependency’si.
+* `418` response’u. 🍵
+
+Ancak bu sadece bizim uygulamamızdaki o `APIRouter` için geçerlidir; onu kullanan diğer kodlar için değil.
+
+Dolayısıyla örneğin diğer projeler aynı `APIRouter`’ı farklı bir authentication yöntemiyle kullanabilir.
+
+### Bir *Path Operation* Dahil Edin { #include-a-path-operation }
+
+*Path operation*’ları doğrudan `FastAPI` uygulamasına da ekleyebiliriz.
+
+Burada bunu yapıyoruz... sadece yapabildiğimizi göstermek için 🤷:
+
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[21:23] title["app/main.py"] *}
+
+ve `app.include_router()` ile eklenen diğer tüm *path operation*’larla birlikte doğru şekilde çalışır.
+
+/// info | Çok Teknik Detaylar
+
+**Not**: Bu oldukça teknik bir detay; büyük ihtimalle **direkt geçebilirsiniz**.
+
+---
+
+`APIRouter`’lar "mount" edilmez; uygulamanın geri kalanından izole değildir.
+
+Çünkü *path operation*’larını OpenAPI şemasına ve kullanıcı arayüzlerine dahil etmek istiyoruz.
+
+Onları tamamen izole edip bağımsız şekilde "mount" edemediğimiz için, *path operation*’lar doğrudan eklenmek yerine "klonlanır" (yeniden oluşturulur).
+
+///
+
+## Otomatik API Dokümanını Kontrol Edin { #check-the-automatic-api-docs }
+
+Şimdi uygulamanızı çalıştırın:
+
+
+
+## Aynı Router'ı Farklı `prefix` ile Birden Fazla Kez Dahil Edin { #include-the-same-router-multiple-times-with-different-prefix }
+
+`.include_router()` ile aynı router’ı farklı prefix’ler kullanarak birden fazla kez de dahil edebilirsiniz.
+
+Örneğin aynı API’yi `/api/v1` ve `/api/latest` gibi farklı prefix’ler altında sunmak için faydalı olabilir.
+
+Bu, muhtemelen ihtiyacınız olmayan ileri seviye bir kullanımdır; ancak gerekirse diye mevcut.
+
+## Bir `APIRouter`’ı Başka Birine Dahil Edin { #include-an-apirouter-in-another }
+
+Bir `APIRouter`’ı `FastAPI` uygulamasına dahil ettiğiniz gibi, bir `APIRouter`’ı başka bir `APIRouter`’a da şu şekilde dahil edebilirsiniz:
+
+```Python
+router.include_router(other_router)
+```
+
+`router`’ı `FastAPI` uygulamasına dahil etmeden önce bunu yaptığınızdan emin olun; böylece `other_router` içindeki *path operation*’lar da dahil edilmiş olur.
diff --git a/docs/tr/docs/tutorial/body-fields.md b/docs/tr/docs/tutorial/body-fields.md
new file mode 100644
index 000000000..6a0f3314a
--- /dev/null
+++ b/docs/tr/docs/tutorial/body-fields.md
@@ -0,0 +1,60 @@
+# Body - Alanlar { #body-fields }
+
+`Query`, `Path` ve `Body` ile *path operation function* parametrelerinde ek doğrulama ve metadata tanımlayabildiğiniz gibi, Pydantic modellerinin içinde de Pydantic'in `Field`'ını kullanarak doğrulama ve metadata tanımlayabilirsiniz.
+
+## `Field`'ı import edin { #import-field }
+
+Önce import etmeniz gerekir:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
+
+/// warning | Uyarı
+
+`Field`'ın, diğerlerinin (`Query`, `Path`, `Body` vb.) aksine `fastapi`'den değil doğrudan `pydantic`'den import edildiğine dikkat edin.
+
+///
+
+## Model attribute'larını tanımlayın { #declare-model-attributes }
+
+Ardından `Field`'ı model attribute'larıyla birlikte kullanabilirsiniz:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
+
+`Field`, `Query`, `Path` ve `Body` ile aynı şekilde çalışır; aynı parametrelerin tamamına sahiptir, vb.
+
+/// note | Teknik Detaylar
+
+Aslında, `Query`, `Path` ve birazdan göreceğiniz diğerleri, ortak bir `Param` sınıfının alt sınıflarından nesneler oluşturur; `Param` sınıfı da Pydantic'in `FieldInfo` sınıfının bir alt sınıfıdır.
+
+Pydantic'in `Field`'ı da `FieldInfo`'nun bir instance'ını döndürür.
+
+`Body` ayrıca doğrudan `FieldInfo`'nun bir alt sınıfından nesneler döndürür. Daha sonra göreceğiniz başka bazıları da `Body` sınıfının alt sınıflarıdır.
+
+`fastapi`'den `Query`, `Path` ve diğerlerini import ettiğinizde, bunların aslında özel sınıflar döndüren fonksiyonlar olduğunu unutmayın.
+
+///
+
+/// tip | İpucu
+
+Type, varsayılan değer ve `Field` ile tanımlanan her model attribute'unun yapısının, *path operation function* parametresiyle aynı olduğuna dikkat edin; sadece `Path`, `Query` ve `Body` yerine `Field` kullanılmıştır.
+
+///
+
+## Ek bilgi ekleyin { #add-extra-information }
+
+`Field`, `Query`, `Body` vb. içinde ek bilgi tanımlayabilirsiniz. Bu bilgiler oluşturulan JSON Schema'ya dahil edilir.
+
+Örnek (examples) tanımlamayı öğrenirken, dokümanların ilerleyen kısımlarında ek bilgi ekleme konusunu daha ayrıntılı göreceksiniz.
+
+/// warning | Uyarı
+
+`Field`'a geçirilen ekstra key'ler, uygulamanız için üretilen OpenAPI schema'sında da yer alır.
+Bu key'ler OpenAPI spesifikasyonunun bir parçası olmak zorunda olmadığından, örneğin [OpenAPI validator](https://validator.swagger.io/) gibi bazı OpenAPI araçları üretilen schema'nızla çalışmayabilir.
+
+///
+
+## Özet { #recap }
+
+Model attribute'ları için ek doğrulamalar ve metadata tanımlamak üzere Pydantic'in `Field`'ını kullanabilirsiniz.
+
+Ayrıca, ek keyword argument'ları kullanarak JSON Schema'ya ekstra metadata da iletebilirsiniz.
diff --git a/docs/tr/docs/tutorial/body-multiple-params.md b/docs/tr/docs/tutorial/body-multiple-params.md
new file mode 100644
index 000000000..3bac80d6a
--- /dev/null
+++ b/docs/tr/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,175 @@
+# Body - Birden Fazla Parametre { #body-multiple-parameters }
+
+Artık `Path` ve `Query` kullanmayı gördüğümüze göre, request body bildirimlerinin daha ileri kullanım senaryolarına bakalım.
+
+## `Path`, `Query` ve body parametrelerini karıştırma { #mix-path-query-and-body-parameters }
+
+Öncelikle, elbette `Path`, `Query` ve request body parametre bildirimlerini serbestçe karıştırabilirsiniz ve **FastAPI** ne yapacağını bilir.
+
+Ayrıca, varsayılan değeri `None` yaparak body parametrelerini opsiyonel olarak da tanımlayabilirsiniz:
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// note | Not
+
+Bu durumda body'den alınacak `item` opsiyoneldir. Çünkü varsayılan değeri `None` olarak ayarlanmıştır.
+
+///
+
+## Birden fazla body parametresi { #multiple-body-parameters }
+
+Önceki örnekte, *path operation*'lar `Item`'ın özelliklerini içeren bir JSON body beklerdi, örneğin:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+Ancak birden fazla body parametresi de tanımlayabilirsiniz; örneğin `item` ve `user`:
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+
+Bu durumda **FastAPI**, fonksiyonda birden fazla body parametresi olduğunu fark eder (iki parametre de Pydantic modelidir).
+
+Bunun üzerine, body içinde anahtar (field name) olarak parametre adlarını kullanır ve şu şekilde bir body bekler:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ }
+}
+```
+
+/// note | Not
+
+`item` daha öncekiyle aynı şekilde tanımlanmış olsa bile, artık body içinde `item` anahtarı altında gelmesi beklenir.
+
+///
+
+**FastAPI**, request'ten otomatik dönüşümü yapar; böylece `item` parametresi kendi içeriğini alır, `user` için de aynı şekilde olur.
+
+Birleşik verinin validasyonunu yapar ve OpenAPI şeması ile otomatik dokümantasyonda da bunu bu şekilde dokümante eder.
+
+## Body içinde tekil değerler { #singular-values-in-body }
+
+Query ve path parametreleri için ek veri tanımlamak üzere `Query` ve `Path` olduğu gibi, **FastAPI** bunların karşılığı olarak `Body` de sağlar.
+
+Örneğin, önceki modeli genişleterek, aynı body içinde `item` ve `user` dışında bir de `importance` anahtarı olmasını isteyebilirsiniz.
+
+Bunu olduğu gibi tanımlarsanız, tekil bir değer olduğu için **FastAPI** bunun bir query parametresi olduğunu varsayar.
+
+Ama `Body` kullanarak, **FastAPI**'ye bunu body içinde başka bir anahtar olarak ele almasını söyleyebilirsiniz:
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+
+Bu durumda **FastAPI** şu şekilde bir body bekler:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+
+Yine veri tiplerini dönüştürür, validate eder, dokümante eder, vb.
+
+## Birden fazla body parametresi ve query { #multiple-body-params-and-query }
+
+Elbette ihtiyaç duyduğunuzda, body parametrelerine ek olarak query parametreleri de tanımlayabilirsiniz.
+
+Varsayılan olarak tekil değerler query parametresi olarak yorumlandığı için, ayrıca `Query` eklemeniz gerekmez; şöyle yazmanız yeterlidir:
+
+```Python
+q: Union[str, None] = None
+```
+
+Ya da Python 3.10 ve üzeri için:
+
+```Python
+q: str | None = None
+```
+
+Örneğin:
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
+
+
+/// info | Bilgi
+
+`Body`, `Query`, `Path` ve daha sonra göreceğiniz diğerleriyle aynı ek validasyon ve metadata parametrelerine de sahiptir.
+
+///
+
+## Tek bir body parametresini gömme { #embed-a-single-body-parameter }
+
+Diyelim ki Pydantic'teki `Item` modelinden gelen yalnızca tek bir `item` body parametreniz var.
+
+Varsayılan olarak **FastAPI**, body'nin doğrudan bu modelin içeriği olmasını bekler.
+
+Ancak, ek body parametreleri tanımladığınızda olduğu gibi, `item` anahtarı olan bir JSON ve onun içinde modelin içeriğini beklemesini istiyorsanız, `Body`'nin özel parametresi olan `embed`'i kullanabilirsiniz:
+
+```Python
+item: Item = Body(embed=True)
+```
+
+yani şöyle:
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+
+Bu durumda **FastAPI** şu şekilde bir body bekler:
+
+```JSON hl_lines="2"
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ }
+}
+```
+
+şunun yerine:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+## Özet { #recap }
+
+Bir request yalnızca tek bir body içerebilse de, *path operation function*'ınıza birden fazla body parametresi ekleyebilirsiniz.
+
+Ancak **FastAPI** bunu yönetir; fonksiyonunuza doğru veriyi verir ve *path operation* içinde doğru şemayı validate edip dokümante eder.
+
+Ayrıca tekil değerlerin body'nin bir parçası olarak alınmasını da tanımlayabilirsiniz.
+
+Ve yalnızca tek bir parametre tanımlanmış olsa bile, **FastAPI**'ye body'yi bir anahtarın içine gömmesini söyleyebilirsiniz.
diff --git a/docs/tr/docs/tutorial/body-nested-models.md b/docs/tr/docs/tutorial/body-nested-models.md
new file mode 100644
index 000000000..b4ffef3f1
--- /dev/null
+++ b/docs/tr/docs/tutorial/body-nested-models.md
@@ -0,0 +1,220 @@
+# Body - İç İçe Modeller { #body-nested-models }
+
+**FastAPI** ile (Pydantic sayesinde) istediğiniz kadar derin iç içe geçmiş modelleri tanımlayabilir, doğrulayabilir, dokümante edebilir ve kullanabilirsiniz.
+
+## List alanları { #list-fields }
+
+Bir attribute’u bir alt tipe sahip olacak şekilde tanımlayabilirsiniz. Örneğin, bir Python `list`:
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+Bu, `tags`’in bir list olmasını sağlar; ancak list’in elemanlarının tipini belirtmez.
+
+## Tip parametresi olan list alanları { #list-fields-with-type-parameter }
+
+Ancak Python’da, iç tipleri olan list’leri (ya da "type parameter" içeren tipleri) tanımlamanın belirli bir yolu vardır:
+
+### Tip parametresiyle bir `list` tanımlayın { #declare-a-list-with-a-type-parameter }
+
+`list`, `dict`, `tuple` gibi type parameter (iç tip) alan tipleri tanımlamak için, iç tipi(leri) köşeli parantezlerle "type parameter" olarak verin: `[` ve `]`
+
+```Python
+my_list: list[str]
+```
+
+Bu, tip tanımları için standart Python sözdizimidir.
+
+İç tipleri olan model attribute’ları için de aynı standart sözdizimini kullanın.
+
+Dolayısıyla örneğimizde, `tags`’i özel olarak bir "string list’i" yapabiliriz:
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## Set tipleri { #set-types }
+
+Sonra bunu düşününce, tag’lerin tekrar etmemesi gerektiğini fark ederiz; büyük ihtimalle benzersiz string’ler olmalıdır.
+
+Python’da benzersiz öğelerden oluşan kümeler için özel bir veri tipi vardır: `set`.
+
+O zaman `tags`’i string’lerden oluşan bir set olarak tanımlayabiliriz:
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+Böylece duplicate veri içeren bir request alsanız bile, bu veri benzersiz öğelerden oluşan bir set’e dönüştürülür.
+
+Ve bu veriyi ne zaman output etseniz, kaynakta duplicate olsa bile, benzersiz öğelerden oluşan bir set olarak output edilir.
+
+Ayrıca buna göre annotate / dokümante edilir.
+
+## İç İçe Modeller { #nested-models }
+
+Bir Pydantic modelinin her attribute’unun bir tipi vardır.
+
+Ancak bu tip, kendi başına başka bir Pydantic modeli de olabilir.
+
+Yani belirli attribute adları, tipleri ve validation kurallarıyla derin iç içe JSON "object"leri tanımlayabilirsiniz.
+
+Hem de istediğiniz kadar iç içe.
+
+### Bir alt model tanımlayın { #define-a-submodel }
+
+Örneğin bir `Image` modeli tanımlayabiliriz:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### Alt modeli tip olarak kullanın { #use-the-submodel-as-a-type }
+
+Ardından bunu bir attribute’un tipi olarak kullanabiliriz:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+Bu da **FastAPI**’nin aşağıdakine benzer bir body bekleyeceği anlamına gelir:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": ["rock", "metal", "bar"],
+ "image": {
+ "url": "http://example.com/baz.jpg",
+ "name": "The Foo live"
+ }
+}
+```
+
+Yine, sadece bu tanımı yaparak **FastAPI** ile şunları elde edersiniz:
+
+* Editör desteği (tamamlama vb.), iç içe modeller için bile
+* Veri dönüştürme
+* Veri doğrulama (validation)
+* Otomatik dokümantasyon
+
+## Özel tipler ve doğrulama { #special-types-and-validation }
+
+`str`, `int`, `float` vb. normal tekil tiplerin yanında, `str`’den türeyen daha karmaşık tekil tipleri de kullanabilirsiniz.
+
+Tüm seçenekleri görmek için Pydantic Type Overview sayfasına göz atın. Sonraki bölümde bazı örnekleri göreceksiniz.
+
+Örneğin `Image` modelinde bir `url` alanımız olduğuna göre, bunu `str` yerine Pydantic’in `HttpUrl` tipinden bir instance olacak şekilde tanımlayabiliriz:
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+String’in geçerli bir URL olup olmadığı kontrol edilir ve JSON Schema / OpenAPI’de de buna göre dokümante edilir.
+
+## Alt modellerden oluşan list’lere sahip attribute’lar { #attributes-with-lists-of-submodels }
+
+Pydantic modellerini `list`, `set` vb. tiplerin alt tipi olarak da kullanabilirsiniz:
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+Bu, aşağıdaki gibi bir JSON body bekler (dönüştürür, doğrular, dokümante eder vb.):
+
+```JSON hl_lines="11"
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": [
+ "rock",
+ "metal",
+ "bar"
+ ],
+ "images": [
+ {
+ "url": "http://example.com/baz.jpg",
+ "name": "The Foo live"
+ },
+ {
+ "url": "http://example.com/dave.jpg",
+ "name": "The Baz"
+ }
+ ]
+}
+```
+
+/// info | Bilgi
+
+`images` key’inin artık image object’lerinden oluşan bir list içerdiğine dikkat edin.
+
+///
+
+## Çok derin iç içe modeller { #deeply-nested-models }
+
+İstediğiniz kadar derin iç içe modeller tanımlayabilirsiniz:
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info | Bilgi
+
+`Offer`’ın bir `Item` list’i olduğuna, `Item`’ların da opsiyonel bir `Image` list’ine sahip olduğuna dikkat edin.
+
+///
+
+## Sadece list olan body’ler { #bodies-of-pure-lists }
+
+Beklediğiniz JSON body’nin en üst seviye değeri bir JSON `array` (Python’da `list`) ise, tipi Pydantic modellerinde olduğu gibi fonksiyonun parametresinde tanımlayabilirsiniz:
+
+```Python
+images: list[Image]
+```
+
+şu örnekte olduğu gibi:
+
+{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
+
+## Her yerde editör desteği { #editor-support-everywhere }
+
+Ve her yerde editör desteği alırsınız.
+
+List içindeki öğeler için bile:
+
+
+
+Pydantic modelleri yerine doğrudan `dict` ile çalışsaydınız bu tür bir editör desteğini alamazdınız.
+
+Ancak bunlarla uğraşmanız da gerekmez; gelen dict’ler otomatik olarak dönüştürülür ve output’unuz da otomatik olarak JSON’a çevrilir.
+
+## Rastgele `dict` body’leri { #bodies-of-arbitrary-dicts }
+
+Body’yi, key’leri bir tipte ve value’ları başka bir tipte olan bir `dict` olarak da tanımlayabilirsiniz.
+
+Bu şekilde (Pydantic modellerinde olduğu gibi) geçerli field/attribute adlarının önceden ne olduğunu bilmeniz gerekmez.
+
+Bu, önceden bilmediğiniz key’leri almak istediğiniz durumlarda faydalıdır.
+
+---
+
+Bir diğer faydalı durum da key’lerin başka bir tipte olmasını istediğiniz zamandır (ör. `int`).
+
+Burada göreceğimiz şey de bu.
+
+Bu durumda, `int` key’lere ve `float` value’lara sahip olduğu sürece herhangi bir `dict` kabul edersiniz:
+
+{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
+
+/// tip | İpucu
+
+JSON key olarak yalnızca `str` destekler, bunu unutmayın.
+
+Ancak Pydantic otomatik veri dönüştürme yapar.
+
+Yani API client’larınız key’leri sadece string olarak gönderebilse bile, bu string’ler saf tamsayı içeriyorsa Pydantic bunları dönüştürür ve doğrular.
+
+Ve `weights` olarak aldığınız `dict`, gerçekte `int` key’lere ve `float` value’lara sahip olur.
+
+///
+
+## Özet { #recap }
+
+**FastAPI** ile Pydantic modellerinin sağladığı en yüksek esnekliği elde ederken, kodunuzu da basit, kısa ve şık tutarsınız.
+
+Üstelik tüm avantajlarla birlikte:
+
+* Editör desteği (her yerde tamamlama!)
+* Veri dönüştürme (diğer adıyla parsing / serialization)
+* Veri doğrulama (validation)
+* Schema dokümantasyonu
+* Otomatik dokümanlar
diff --git a/docs/tr/docs/tutorial/body-updates.md b/docs/tr/docs/tutorial/body-updates.md
new file mode 100644
index 000000000..a9ad13d2e
--- /dev/null
+++ b/docs/tr/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Body - Güncellemeler { #body-updates }
+
+## `PUT` ile değiştirerek güncelleme { #update-replacing-with-put }
+
+Bir öğeyi güncellemek için HTTP `PUT` operasyonunu kullanabilirsiniz.
+
+Girdi verisini JSON olarak saklanabilecek bir formata (ör. bir NoSQL veritabanı ile) dönüştürmek için `jsonable_encoder` kullanabilirsiniz. Örneğin, `datetime` değerlerini `str`'ye çevirmek gibi.
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+`PUT`, mevcut verinin yerine geçmesi gereken veriyi almak için kullanılır.
+
+### Değiştirerek güncelleme uyarısı { #warning-about-replacing }
+
+Bu, `bar` öğesini `PUT` ile, body içinde şu verilerle güncellemek isterseniz:
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+zaten kayıtlı olan `"tax": 20.2` alanını içermediği için, input model `"tax": 10.5` varsayılan değerini kullanacaktır.
+
+Ve veri, bu "yeni" `tax` değeri olan `10.5` ile kaydedilecektir.
+
+## `PATCH` ile kısmi güncellemeler { #partial-updates-with-patch }
+
+Veriyi *kısmen* güncellemek için HTTP `PATCH` operasyonunu da kullanabilirsiniz.
+
+Bu, yalnızca güncellemek istediğiniz veriyi gönderip, geri kalanını olduğu gibi bırakabileceğiniz anlamına gelir.
+
+/// note | Not
+
+`PATCH`, `PUT`'a göre daha az yaygın kullanılır ve daha az bilinir.
+
+Hatta birçok ekip, kısmi güncellemeler için bile yalnızca `PUT` kullanır.
+
+Bunları nasıl isterseniz öyle kullanmakta **özgürsünüz**; **FastAPI** herhangi bir kısıtlama dayatmaz.
+
+Ancak bu kılavuz, aşağı yukarı, bunların nasıl kullanılması amaçlandığını gösterir.
+
+///
+
+### Pydantic'in `exclude_unset` parametresini kullanma { #using-pydantics-exclude-unset-parameter }
+
+Kısmi güncellemeler almak istiyorsanız, Pydantic modelinin `.model_dump()` metodundaki `exclude_unset` parametresini kullanmak çok faydalıdır.
+
+Örneğin: `item.model_dump(exclude_unset=True)`.
+
+Bu, `item` modeli oluşturulurken set edilmiş verileri içeren; varsayılan değerleri hariç tutan bir `dict` üretir.
+
+Sonrasında bunu, yalnızca set edilmiş (request'te gönderilmiş) veriyi içeren; varsayılan değerleri atlayan bir `dict` üretmek için kullanabilirsiniz:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### Pydantic'in `update` parametresini kullanma { #using-pydantics-update-parameter }
+
+Artık `.model_copy()` ile mevcut modelin bir kopyasını oluşturup, güncellenecek verileri içeren bir `dict` ile `update` parametresini geçebilirsiniz.
+
+Örneğin: `stored_item_model.model_copy(update=update_data)`:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### Kısmi güncellemeler özeti { #partial-updates-recap }
+
+Özetle, kısmi güncelleme uygulamak için şunları yaparsınız:
+
+* (İsteğe bağlı olarak) `PUT` yerine `PATCH` kullanın.
+* Kayıtlı veriyi alın.
+* Bu veriyi bir Pydantic modeline koyun.
+* Input modelinden, varsayılan değerler olmadan bir `dict` üretin (`exclude_unset` kullanarak).
+ * Bu şekilde, modelinizdeki varsayılan değerlerle daha önce saklanmış değerlerin üzerine yazmak yerine, yalnızca kullanıcının gerçekten set ettiği değerleri güncellersiniz.
+* Kayıtlı modelin bir kopyasını oluşturun ve alınan kısmi güncellemeleri kullanarak attribute'larını güncelleyin (`update` parametresini kullanarak).
+* Kopyalanan modeli DB'nizde saklanabilecek bir şeye dönüştürün (ör. `jsonable_encoder` kullanarak).
+ * Bu, modelin `.model_dump()` metodunu yeniden kullanmaya benzer; ancak değerlerin JSON'a dönüştürülebilecek veri tiplerine çevrilmesini garanti eder (ör. `datetime` -> `str`).
+* Veriyi DB'nize kaydedin.
+* Güncellenmiş modeli döndürün.
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | İpucu
+
+Aynı tekniği HTTP `PUT` operasyonu ile de kullanabilirsiniz.
+
+Ancak buradaki örnek `PATCH` kullanıyor, çünkü bu kullanım senaryoları için tasarlanmıştır.
+
+///
+
+/// note | Not
+
+Input modelin yine de doğrulandığına dikkat edin.
+
+Dolayısıyla, tüm attribute'ların atlanabildiği kısmi güncellemeler almak istiyorsanız, tüm attribute'ları optional olarak işaretlenmiş (varsayılan değerlerle veya `None` ile) bir modele ihtiyacınız vardır.
+
+**Güncelleme** için tüm değerleri optional olan modeller ile **oluşturma** için zorunlu değerlere sahip modelleri ayırmak için, [Extra Models](extra-models.md){.internal-link target=_blank} bölümünde anlatılan fikirleri kullanabilirsiniz.
+
+///
diff --git a/docs/tr/docs/tutorial/body.md b/docs/tr/docs/tutorial/body.md
new file mode 100644
index 000000000..0557ef737
--- /dev/null
+++ b/docs/tr/docs/tutorial/body.md
@@ -0,0 +1,166 @@
+# Request Body { #request-body }
+
+Bir client'ten (örneğin bir tarayıcıdan) API'nize veri göndermeniz gerektiğinde, bunu **request body** olarak gönderirsiniz.
+
+Bir **request** body, client'in API'nize gönderdiği veridir. Bir **response** body ise API'nizin client'e gönderdiği veridir.
+
+API'niz neredeyse her zaman bir **response** body göndermek zorundadır. Ancak client'lerin her zaman **request body** göndermesi gerekmez; bazen sadece bir path isterler, belki birkaç query parametresiyle birlikte, ama body göndermezler.
+
+Bir **request** body tanımlamak için, tüm gücü ve avantajlarıyla Pydantic modellerini kullanırsınız.
+
+/// info | Bilgi
+
+Veri göndermek için şunlardan birini kullanmalısınız: `POST` (en yaygını), `PUT`, `DELETE` veya `PATCH`.
+
+`GET` request'i ile body göndermek, spesifikasyonlarda tanımsız bir davranıştır; yine de FastAPI bunu yalnızca çok karmaşık/uç kullanım senaryoları için destekler.
+
+Önerilmediği için Swagger UI ile etkileşimli dokümanlar, `GET` kullanırken body için dokümantasyonu göstermez ve aradaki proxy'ler bunu desteklemeyebilir.
+
+///
+
+## Pydantic'in `BaseModel`'ini import edin { #import-pydantics-basemodel }
+
+Önce, `pydantic` içinden `BaseModel`'i import etmeniz gerekir:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
+
+## Veri modelinizi oluşturun { #create-your-data-model }
+
+Sonra veri modelinizi, `BaseModel`'den kalıtım alan bir class olarak tanımlarsınız.
+
+Tüm attribute'lar için standart Python type'larını kullanın:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
+
+
+Query parametrelerini tanımlarken olduğu gibi, bir model attribute'ü default bir değere sahipse zorunlu değildir. Aksi halde zorunludur. Sadece opsiyonel yapmak için `None` kullanın.
+
+Örneğin, yukarıdaki model şu şekilde bir JSON "`object`" (veya Python `dict`) tanımlar:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "An optional description",
+ "price": 45.2,
+ "tax": 3.5
+}
+```
+
+...`description` ve `tax` opsiyonel olduğu için (default değerleri `None`), şu JSON "`object`" da geçerli olur:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 45.2
+}
+```
+
+## Parametre olarak tanımlayın { #declare-it-as-a-parameter }
+
+Bunu *path operation*'ınıza eklemek için, path ve query parametrelerini tanımladığınız şekilde tanımlayın:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
+
+...ve type'ını, oluşturduğunuz model olan `Item` olarak belirtin.
+
+## Sonuçlar { #results }
+
+Sadece bu Python type tanımıyla, **FastAPI** şunları yapar:
+
+* Request'in body'sini JSON olarak okur.
+* İlgili type'lara dönüştürür (gerekirse).
+* Veriyi doğrular (validate eder).
+ * Veri geçersizse, tam olarak nerede ve hangi verinin hatalı olduğunu söyleyen, anlaşılır bir hata döndürür.
+* Aldığı veriyi `item` parametresi içinde size verir.
+ * Fonksiyonda bunun type'ını `Item` olarak tanımladığınız için, tüm attribute'lar ve type'ları için editor desteğini (tamamlama vb.) de alırsınız.
+* Modeliniz için JSON Schema tanımları üretir; projeniz için anlamlıysa bunları başka yerlerde de kullanabilirsiniz.
+* Bu şemalar üretilen OpenAPI şemasının bir parçası olur ve otomatik dokümantasyon UIs tarafından kullanılır.
+
+## Otomatik dokümanlar { #automatic-docs }
+
+Modellerinizin JSON Schema'ları, OpenAPI tarafından üretilen şemanın bir parçası olur ve etkileşimli API dokümanlarında gösterilir:
+
+
+
+Ayrıca, ihtiyaç duyan her *path operation* içindeki API dokümanlarında da kullanılır:
+
+
+
+## Editor desteği { #editor-support }
+
+Editor'ünüzde, fonksiyonunuzun içinde her yerde type hint'leri ve tamamlama (completion) alırsınız (Pydantic modeli yerine `dict` alsaydınız bu olmazdı):
+
+
+
+Yanlış type işlemleri için hata kontrolleri de alırsınız:
+
+
+
+Bu bir tesadüf değil; tüm framework bu tasarımın etrafında inşa edildi.
+
+Ayrıca, bunun tüm editor'lerle çalışacağından emin olmak için herhangi bir implementasyon yapılmadan önce tasarım aşamasında kapsamlı şekilde test edildi.
+
+Hatta bunu desteklemek için Pydantic'in kendisinde bile bazı değişiklikler yapıldı.
+
+Önceki ekran görüntüleri Visual Studio Code ile alınmıştır.
+
+Ancak PyCharm ve diğer Python editor'lerinin çoğunda da aynı editor desteğini alırsınız:
+
+
+
+/// tip | İpucu
+
+Editor olarak PyCharm kullanıyorsanız, Pydantic PyCharm Plugin kullanabilirsiniz.
+
+Pydantic modelleri için editor desteğini şu açılardan iyileştirir:
+
+* auto-completion
+* type checks
+* refactoring
+* searching
+* inspections
+
+///
+
+## Modeli kullanın { #use-the-model }
+
+Fonksiyonun içinde model nesnesinin tüm attribute'larına doğrudan erişebilirsiniz:
+
+{* ../../docs_src/body/tutorial002_py310.py *}
+
+## Request body + path parametreleri { #request-body-path-parameters }
+
+Path parametrelerini ve request body'yi aynı anda tanımlayabilirsiniz.
+
+**FastAPI**, path parametreleriyle eşleşen fonksiyon parametrelerinin **path'ten alınması** gerektiğini ve Pydantic model olarak tanımlanan fonksiyon parametrelerinin **request body'den alınması** gerektiğini anlayacaktır.
+
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
+
+
+## Request body + path + query parametreleri { #request-body-path-query-parameters }
+
+**body**, **path** ve **query** parametrelerini aynı anda da tanımlayabilirsiniz.
+
+**FastAPI** bunların her birini tanır ve veriyi doğru yerden alır.
+
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
+
+Fonksiyon parametreleri şu şekilde tanınır:
+
+* Parametre, **path** içinde de tanımlıysa path parametresi olarak kullanılır.
+* Parametre **tekil bir type**'taysa (`int`, `float`, `str`, `bool` vb.), **query** parametresi olarak yorumlanır.
+* Parametre bir **Pydantic model** type'ı olarak tanımlandıysa, request **body** olarak yorumlanır.
+
+/// note | Not
+
+FastAPI, `q` değerinin zorunlu olmadığını `= None` default değerinden anlayacaktır.
+
+`str | None` (Python 3.10+) veya `Union[str, None]` (Python 3.9+) içindeki `Union`, FastAPI tarafından bu değerin zorunlu olmadığını belirlemek için kullanılmaz; FastAPI bunun zorunlu olmadığını `= None` default değeri olduğu için bilir.
+
+Ancak type annotation'larını eklemek, editor'ünüzün size daha iyi destek vermesini ve hataları yakalamasını sağlar.
+
+///
+
+## Pydantic olmadan { #without-pydantic }
+
+Pydantic modellerini kullanmak istemiyorsanız, **Body** parametrelerini de kullanabilirsiniz. [Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank} dokümanına bakın.
diff --git a/docs/tr/docs/tutorial/cookie-param-models.md b/docs/tr/docs/tutorial/cookie-param-models.md
new file mode 100644
index 000000000..a5bf51560
--- /dev/null
+++ b/docs/tr/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Cookie Parameter Models { #cookie-parameter-models }
+
+Birbirleriyle ilişkili bir **cookie** grubunuz varsa, bunları tanımlamak için bir **Pydantic model** oluşturabilirsiniz.
+
+Bu sayede **model'i yeniden kullanabilir**, **birden fazla yerde** tekrar tekrar kullanabilir ve tüm parametreler için validation ve metadata'yı tek seferde tanımlayabilirsiniz.
+
+/// note | Not
+
+Bu özellik FastAPI `0.115.0` sürümünden beri desteklenmektedir.
+
+///
+
+/// tip | İpucu
+
+Aynı teknik `Query`, `Cookie` ve `Header` için de geçerlidir.
+
+///
+
+## Pydantic Model ile Cookies { #cookies-with-a-pydantic-model }
+
+İhtiyacınız olan **cookie** parametrelerini bir **Pydantic model** içinde tanımlayın ve ardından parametreyi `Cookie` olarak bildirin:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI**, request ile gelen **cookies** içinden **her bir field** için veriyi **extract** eder ve size tanımladığınız Pydantic model'i verir.
+
+## Dokümanları Kontrol Edin { #check-the-docs }
+
+Tanımlanan cookie'leri `/docs` altındaki docs UI'da görebilirsiniz:
+
+
+
+
+---
+
+PyCharm kullanıyorsanız şunları yapabilirsiniz:
+
+* "Run" menüsünü açın.
+* "Debug..." seçeneğini seçin.
+* Bir context menü açılır.
+* Debug edilecek dosyayı seçin (bu örnekte `main.py`).
+
+Böylece server, **FastAPI** kodunuzla başlar; breakpoint'lerinizde durur vb.
+
+Aşağıdaki gibi görünebilir:
+
+
diff --git a/docs/tr/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/tr/docs/tutorial/dependencies/classes-as-dependencies.md
new file mode 100644
index 000000000..9ee57cb29
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,288 @@
+# Dependency Olarak Class'lar { #classes-as-dependencies }
+
+**Dependency Injection** sistemine daha derinlemesine geçmeden önce, bir önceki örneği geliştirelim.
+
+## Önceki Örnekten Bir `dict` { #a-dict-from-the-previous-example }
+
+Önceki örnekte, dependency'mizden ("dependable") bir `dict` döndürüyorduk:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}
+
+Ama sonra *path operation function* içindeki `commons` parametresinde bir `dict` alıyoruz.
+
+Ve biliyoruz ki editor'ler `dict`'ler için çok fazla destek (ör. completion) veremez; çünkü key'lerini ve value type'larını bilemezler.
+
+Daha iyisini yapabiliriz...
+
+## Bir Şeyi Dependency Yapan Nedir { #what-makes-a-dependency }
+
+Şimdiye kadar dependency'leri function olarak tanımlanmış şekilde gördünüz.
+
+Ancak dependency tanımlamanın tek yolu bu değil (muhtemelen en yaygını bu olsa da).
+
+Buradaki kritik nokta, bir dependency'nin "callable" olması gerektiğidir.
+
+Python'da "**callable**", Python'ın bir function gibi "çağırabildiği" her şeydir.
+
+Yani elinizde `something` adlı bir nesne varsa (function _olmak zorunda değil_) ve onu şöyle "çağırabiliyorsanız" (çalıştırabiliyorsanız):
+
+```Python
+something()
+```
+
+veya
+
+```Python
+something(some_argument, some_keyword_argument="foo")
+```
+
+o zaman bu bir "callable" demektir.
+
+## Dependency Olarak Class'lar { #classes-as-dependencies_1 }
+
+Python'da bir class'tan instance oluştururken de aynı söz dizimini kullandığınızı fark etmiş olabilirsiniz.
+
+Örneğin:
+
+```Python
+class Cat:
+ def __init__(self, name: str):
+ self.name = name
+
+
+fluffy = Cat(name="Mr Fluffy")
+```
+
+Bu durumda `fluffy`, `Cat` class'ının bir instance'ıdır.
+
+Ve `fluffy` oluşturmak için `Cat`'i "çağırmış" olursunuz.
+
+Dolayısıyla bir Python class'ı da bir **callable**'dır.
+
+O zaman **FastAPI** içinde bir Python class'ını dependency olarak kullanabilirsiniz.
+
+FastAPI'nin aslında kontrol ettiği şey, bunun bir "callable" olması (function, class ya da başka bir şey) ve tanımlı parametreleridir.
+
+Eğer **FastAPI**'de bir dependency olarak bir "callable" verirseniz, FastAPI o "callable" için parametreleri analiz eder ve bunları *path operation function* parametreleriyle aynı şekilde işler. Sub-dependency'ler dahil.
+
+Bu, hiç parametresi olmayan callable'lar için de geçerlidir. Tıpkı hiç parametresi olmayan *path operation function*'larda olduğu gibi.
+
+O zaman yukarıdaki `common_parameters` adlı "dependable" dependency'sini `CommonQueryParams` class'ına çevirebiliriz:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}
+
+Class instance'ını oluşturmak için kullanılan `__init__` metoduna dikkat edin:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}
+
+...bizim önceki `common_parameters` ile aynı parametrelere sahip:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}
+
+Bu parametreler, dependency'yi "çözmek" için **FastAPI**'nin kullanacağı şeylerdir.
+
+Her iki durumda da şunlar olacak:
+
+* `str` olan opsiyonel bir `q` query parametresi.
+* Default değeri `0` olan `int` tipinde bir `skip` query parametresi.
+* Default değeri `100` olan `int` tipinde bir `limit` query parametresi.
+
+Her iki durumda da veriler dönüştürülecek, doğrulanacak, OpenAPI şemasında dokümante edilecek, vb.
+
+## Kullanalım { #use-it }
+
+Artık bu class'ı kullanarak dependency'nizi tanımlayabilirsiniz.
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}
+
+**FastAPI**, `CommonQueryParams` class'ını çağırır. Bu, o class'ın bir "instance"ını oluşturur ve bu instance, sizin function'ınıza `commons` parametresi olarak geçirilir.
+
+## Type Annotation vs `Depends` { #type-annotation-vs-depends }
+
+Yukarıdaki kodda `CommonQueryParams`'ı iki kez yazdığımıza dikkat edin:
+
+//// tab | Python 3.9+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.9+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+Şuradaki son `CommonQueryParams`:
+
+```Python
+... Depends(CommonQueryParams)
+```
+
+...FastAPI'nin dependency'nin ne olduğunu anlamak için gerçekten kullandığı şeydir.
+
+FastAPI tanımlanan parametreleri buradan çıkarır ve aslında çağıracağı şey de budur.
+
+---
+
+Bu durumda, şuradaki ilk `CommonQueryParams`:
+
+//// tab | Python 3.9+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
+
+//// tab | Python 3.9+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
+
+...**FastAPI** için özel bir anlam taşımaz. FastAPI bunu veri dönüştürme, doğrulama vb. için kullanmaz (çünkü bunlar için `Depends(CommonQueryParams)` kullanıyor).
+
+Hatta şunu bile yazabilirsiniz:
+
+//// tab | Python 3.9+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.9+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
+
+...şu örnekte olduğu gibi:
+
+{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}
+
+Ancak type'ı belirtmeniz önerilir; böylece editor'ünüz `commons` parametresine ne geçirileceğini bilir ve size code completion, type check'leri vb. konularda yardımcı olur:
+
+
+
+## Kısayol { #shortcut }
+
+Ama burada bir miktar kod tekrarımız olduğunu görüyorsunuz; `CommonQueryParams`'ı iki kez yazıyoruz:
+
+//// tab | Python 3.9+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.9+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+**FastAPI**, bu durumlar için bir kısayol sağlar: dependency'nin *özellikle* FastAPI'nin bir instance oluşturmak için "çağıracağı" bir class olduğu durumlar.
+
+Bu özel durumlarda şunu yapabilirsiniz:
+
+Şunu yazmak yerine:
+
+//// tab | Python 3.9+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.9+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+...şunu yazarsınız:
+
+//// tab | Python 3.9+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.9+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+Dependency'yi parametrenin type'ı olarak tanımlarsınız ve `Depends(CommonQueryParams)` içinde class'ı *yeniden* yazmak yerine, parametre vermeden `Depends()` kullanırsınız.
+
+Aynı örnek şu hale gelir:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+...ve **FastAPI** ne yapması gerektiğini bilir.
+
+/// tip | İpucu
+
+Bu size faydalı olmaktan çok kafa karıştırıcı geliyorsa, kullanmayın; buna *ihtiyacınız* yok.
+
+Bu sadece bir kısayoldur. Çünkü **FastAPI** kod tekrarını en aza indirmenize yardımcı olmayı önemser.
+
+///
diff --git a/docs/tr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/tr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 000000000..4903aec4a
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# Path Operation Decorator'lerinde Dependency'ler { #dependencies-in-path-operation-decorators }
+
+Bazı durumlarda bir dependency'nin döndürdüğü değere *path operation function* içinde gerçekten ihtiyacınız olmaz.
+
+Ya da dependency zaten bir değer döndürmüyordur.
+
+Ancak yine de çalıştırılmasını/çözülmesini istersiniz.
+
+Bu gibi durumlarda, `Depends` ile bir *path operation function* parametresi tanımlamak yerine, *path operation decorator*'üne `dependencies` adında bir `list` ekleyebilirsiniz.
+
+## *Path Operation Decorator*'üne `dependencies` Ekleyin { #add-dependencies-to-the-path-operation-decorator }
+
+*Path operation decorator*, opsiyonel bir `dependencies` argümanı alır.
+
+Bu, `Depends()` öğelerinden oluşan bir `list` olmalıdır:
+
+{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *}
+
+Bu dependency'ler normal dependency'lerle aynı şekilde çalıştırılır/çözülür. Ancak (eğer bir değer döndürüyorlarsa) bu değer *path operation function*'ınıza aktarılmaz.
+
+/// tip | İpucu
+
+Bazı editörler, kullanılmayan function parametrelerini kontrol eder ve bunları hata olarak gösterebilir.
+
+Bu `dependencies` yaklaşımıyla, editör/araç hatalarına takılmadan dependency'lerin çalıştırılmasını sağlayabilirsiniz.
+
+Ayrıca kodunuzda kullanılmayan bir parametreyi gören yeni geliştiricilerin bunun gereksiz olduğunu düşünmesi gibi bir kafa karışıklığını da azaltabilir.
+
+///
+
+/// info | Bilgi
+
+Bu örnekte uydurma özel header'lar olan `X-Key` ve `X-Token` kullanıyoruz.
+
+Ancak gerçek senaryolarda, security uygularken, entegre [Security yardımcı araçlarını (bir sonraki bölüm)](../security/index.md){.internal-link target=_blank} kullanmak size daha fazla fayda sağlar.
+
+///
+
+## Dependency Hataları ve Return Değerleri { #dependencies-errors-and-return-values }
+
+Normalde kullandığınız aynı dependency *function*'larını burada da kullanabilirsiniz.
+
+### Dependency Gereksinimleri { #dependency-requirements }
+
+Request gereksinimleri (header'lar gibi) veya başka alt dependency'ler tanımlayabilirler:
+
+{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *}
+
+### Exception Fırlatmak { #raise-exceptions }
+
+Bu dependency'ler, normal dependency'lerde olduğu gibi `raise` ile exception fırlatabilir:
+
+{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *}
+
+### Return Değerleri { #return-values }
+
+Ayrıca değer döndürebilirler ya da döndürmeyebilirler; dönen değer kullanılmayacaktır.
+
+Yani başka bir yerde zaten kullandığınız, değer döndüren normal bir dependency'yi tekrar kullanabilirsiniz; değer kullanılmasa bile dependency çalıştırılacaktır:
+
+{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *}
+
+## Bir *Path Operation* Grubu İçin Dependency'ler { #dependencies-for-a-group-of-path-operations }
+
+Daha sonra, muhtemelen birden fazla dosya kullanarak daha büyük uygulamaları nasıl yapılandıracağınızı okurken ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), bir *path operation* grubu için tek bir `dependencies` parametresini nasıl tanımlayacağınızı öğreneceksiniz.
+
+## Global Dependency'ler { #global-dependencies }
+
+Sırada, dependency'leri tüm `FastAPI` uygulamasına nasıl ekleyeceğimizi göreceğiz; böylece her *path operation* için geçerli olacaklar.
diff --git a/docs/tr/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/tr/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 000000000..bd025f799
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,289 @@
+# `yield` ile Dependency'ler { #dependencies-with-yield }
+
+FastAPI, işini bitirdikten sonra ek adımlar çalıştıran dependency'leri destekler.
+
+Bunu yapmak için `return` yerine `yield` kullanın ve ek adımları (kodu) `yield` satırından sonra yazın.
+
+/// tip | İpucu
+
+Her dependency için yalnızca **bir kez** `yield` kullandığınızdan emin olun.
+
+///
+
+/// note | Teknik Detaylar
+
+Şunlarla kullanılabilen herhangi bir fonksiyon:
+
+* `@contextlib.contextmanager` veya
+* `@contextlib.asynccontextmanager`
+
+bir **FastAPI** dependency'si olarak kullanılabilir.
+
+Hatta FastAPI bu iki decorator'ı içeride (internally) kullanır.
+
+///
+
+## `yield` ile Bir Veritabanı Dependency'si { #a-database-dependency-with-yield }
+
+Örneğin bunu, bir veritabanı session'ı oluşturmak ve iş bittikten sonra kapatmak için kullanabilirsiniz.
+
+Response oluşturulmadan önce yalnızca `yield` satırına kadar olan (ve `yield` dahil) kod çalıştırılır:
+
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
+
+`yield` edilen değer, *path operation*'lara ve diğer dependency'lere enjekte edilen (injected) değerdir:
+
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
+
+Response'dan sonra `yield` satırını takip eden kod çalıştırılır:
+
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
+
+/// tip | İpucu
+
+`async` ya da normal fonksiyonlar kullanabilirsiniz.
+
+**FastAPI**, normal dependency'lerde olduğu gibi her ikisinde de doğru şekilde davranır.
+
+///
+
+## `yield` ve `try` ile Bir Dependency { #a-dependency-with-yield-and-try }
+
+`yield` kullanan bir dependency içinde bir `try` bloğu kullanırsanız, dependency kullanılırken fırlatılan (raised) herhangi bir exception'ı alırsınız.
+
+Örneğin, başka bir dependency'de veya bir *path operation* içinde çalışan bir kod, bir veritabanı transaction'ını "rollback" yaptıysa ya da başka bir exception oluşturduysa, o exception dependency'nizde size gelir.
+
+Dolayısıyla `except SomeException` ile dependency içinde o spesifik exception'ı yakalayabilirsiniz.
+
+Aynı şekilde, exception olsun ya da olmasın çıkış (exit) adımlarının çalıştırılmasını garanti etmek için `finally` kullanabilirsiniz.
+
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
+
+## `yield` ile Alt Dependency'ler { #sub-dependencies-with-yield }
+
+Her boyutta ve şekilde alt dependency'ler ve alt dependency "ağaçları" (trees) oluşturabilirsiniz; bunların herhangi biri veya hepsi `yield` kullanabilir.
+
+**FastAPI**, `yield` kullanan her dependency'deki "exit code"'un doğru sırayla çalıştırılmasını sağlar.
+
+Örneğin, `dependency_c`, `dependency_b`'ye; `dependency_b` de `dependency_a`'ya bağlı olabilir:
+
+{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *}
+
+Ve hepsi `yield` kullanabilir.
+
+Bu durumda `dependency_c`, exit code'unu çalıştırabilmek için `dependency_b`'den gelen değerin (burada `dep_b`) hâlâ erişilebilir olmasına ihtiyaç duyar.
+
+Aynı şekilde `dependency_b` de exit code'u için `dependency_a`'dan gelen değerin (burada `dep_a`) erişilebilir olmasına ihtiyaç duyar.
+
+{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *}
+
+Benzer şekilde, bazı dependency'ler `yield`, bazıları `return` kullanabilir ve bunların bazıları diğerlerine bağlı olabilir.
+
+Ayrıca birden fazla `yield` kullanan dependency gerektiren tek bir dependency'niz de olabilir, vb.
+
+İstediğiniz herhangi bir dependency kombinasyonunu kullanabilirsiniz.
+
+**FastAPI** her şeyin doğru sırada çalışmasını sağlar.
+
+/// note | Teknik Detaylar
+
+Bu, Python'un Context Managers yapısı sayesinde çalışır.
+
+**FastAPI** bunu sağlamak için içeride onları kullanır.
+
+///
+
+## `yield` ve `HTTPException` ile Dependency'ler { #dependencies-with-yield-and-httpexception }
+
+`yield` kullanan dependency'lerde `try` bloklarıyla bazı kodları çalıştırıp ardından `finally` sonrasında exit code çalıştırabileceğinizi gördünüz.
+
+Ayrıca `except` ile fırlatılan exception'ı yakalayıp onunla bir şey yapabilirsiniz.
+
+Örneğin `HTTPException` gibi farklı bir exception fırlatabilirsiniz.
+
+/// tip | İpucu
+
+Bu biraz ileri seviye bir tekniktir ve çoğu durumda gerçekten ihtiyaç duymazsınız; çünkü exception'ları (`HTTPException` dahil) uygulamanızın geri kalan kodundan, örneğin *path operation function* içinden fırlatabilirsiniz.
+
+Ama ihtiyaç duyarsanız diye burada. 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *}
+
+Exception yakalayıp buna göre özel bir response oluşturmak istiyorsanız bir [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} oluşturun.
+
+## `yield` ve `except` ile Dependency'ler { #dependencies-with-yield-and-except }
+
+`yield` kullanan bir dependency içinde `except` ile bir exception yakalar ve bunu tekrar fırlatmazsanız (ya da yeni bir exception fırlatmazsanız), FastAPI normal Python'da olduğu gibi bir exception olduğunu fark edemez:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *}
+
+Bu durumda client, biz `HTTPException` veya benzeri bir şey fırlatmadığımız için olması gerektiği gibi *HTTP 500 Internal Server Error* response'u görür; ancak server **hiç log üretmez** ve hatanın ne olduğuna dair başka bir işaret de olmaz. 😱
+
+### `yield` ve `except` Kullanan Dependency'lerde Her Zaman `raise` Edin { #always-raise-in-dependencies-with-yield-and-except }
+
+`yield` kullanan bir dependency içinde bir exception yakalarsanız, başka bir `HTTPException` veya benzeri bir şey fırlatmıyorsanız, **orijinal exception'ı tekrar raise etmelisiniz**.
+
+Aynı exception'ı `raise` ile tekrar fırlatabilirsiniz:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *}
+
+Artık client yine aynı *HTTP 500 Internal Server Error* response'unu alır, ama server log'larda bizim özel `InternalError`'ımızı görür. 😎
+
+## `yield` Kullanan Dependency'lerin Çalıştırılması { #execution-of-dependencies-with-yield }
+
+Çalıştırma sırası kabaca aşağıdaki diyagramdaki gibidir. Zaman yukarıdan aşağı akar. Her sütun, etkileşime giren veya kod çalıştıran parçalardan birini temsil eder.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant handler as Exception handler
+participant dep as Dep with yield
+participant operation as Path Operation
+participant tasks as Background tasks
+
+ Note over client,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ end
+
+ operation ->> client: Return response to client
+ Note over client,operation: Response is already sent, can't change it anymore
+ opt Tasks
+ operation -->> tasks: Send background tasks
+ end
+ opt Raise other exception
+ tasks -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info | Bilgi
+
+Client'a yalnızca **tek bir response** gönderilir. Bu, error response'lardan biri olabilir ya da *path operation*'dan dönen response olabilir.
+
+Bu response'lardan biri gönderildikten sonra başka bir response gönderilemez.
+
+///
+
+/// tip | İpucu
+
+*Path operation function* içindeki koddan herhangi bir exception raise ederseniz, `HTTPException` dahil olmak üzere bu exception `yield` kullanan dependency'lere aktarılır. Çoğu durumda, doğru şekilde ele alındığından emin olmak için `yield` kullanan dependency'den aynı exception'ı (veya yeni bir tanesini) yeniden raise etmek istersiniz.
+
+///
+
+## Erken Çıkış ve `scope` { #early-exit-and-scope }
+
+Normalde `yield` kullanan dependency'lerin exit code'u, client'a response gönderildikten **sonra** çalıştırılır.
+
+Ama *path operation function*'dan döndükten sonra dependency'yi kullanmayacağınızı biliyorsanız, `Depends(scope="function")` kullanarak FastAPI'ye dependency'yi *path operation function* döndükten sonra kapatmasını, ancak **response gönderilmeden önce** kapatmasını söyleyebilirsiniz.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py39.py hl[12,16] *}
+
+`Depends()` şu değerleri alabilen bir `scope` parametresi alır:
+
+* `"function"`: dependency'yi request'i işleyen *path operation function* çalışmadan önce başlat, *path operation function* bittikten sonra bitir, ancak response client'a geri gönderilmeden **önce** sonlandır. Yani dependency fonksiyonu, *path operation **function***'ın **etrafında** çalıştırılır.
+* `"request"`: dependency'yi request'i işleyen *path operation function* çalışmadan önce başlat (`"function"` kullanımına benzer), ancak response client'a geri gönderildikten **sonra** sonlandır. Yani dependency fonksiyonu, **request** ve response döngüsünün **etrafında** çalıştırılır.
+
+Belirtilmezse ve dependency `yield` kullanıyorsa, varsayılan olarak `scope` `"request"` olur.
+
+### Alt dependency'ler için `scope` { #scope-for-sub-dependencies }
+
+`scope="request"` (varsayılan) ile bir dependency tanımladığınızda, herhangi bir alt dependency'nin `scope` değeri de `"request"` olmalıdır.
+
+Ancak `scope` değeri `"function"` olan bir dependency, hem `"function"` hem de `"request"` scope'una sahip dependency'lere bağlı olabilir.
+
+Bunun nedeni, bir dependency'nin exit code'unu alt dependency'lerden önce çalıştırabilmesi gerekmesidir; çünkü exit code sırasında hâlâ onları kullanması gerekebilir.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## `yield`, `HTTPException`, `except` ve Background Tasks ile Dependency'ler { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+`yield` kullanan dependency'ler, zaman içinde farklı kullanım senaryolarını kapsamak ve bazı sorunları düzeltmek için gelişti.
+
+FastAPI'nin farklı sürümlerinde nelerin değiştiğini görmek isterseniz, advanced guide'da şu bölümü okuyabilirsiniz: [Advanced Dependencies - Dependencies with `yield`, `HTTPException`, `except` and Background Tasks](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks){.internal-link target=_blank}.
+
+## Context Managers { #context-managers }
+
+### "Context Managers" Nedir? { #what-are-context-managers }
+
+"Context Managers", `with` ifadesiyle kullanabildiğiniz Python nesneleridir.
+
+Örneğin, bir dosyayı okumak için `with` kullanabilirsiniz:
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+Temelde `open("./somefile.txt")`, "Context Manager" olarak adlandırılan bir nesne oluşturur.
+
+`with` bloğu bittiğinde, exception olsa bile dosyanın kapatılmasını garanti eder.
+
+`yield` ile bir dependency oluşturduğunuzda, **FastAPI** içeride bunun için bir context manager oluşturur ve bazı ilgili başka araçlarla birleştirir.
+
+### `yield` kullanan dependency'lerde context manager kullanma { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | Uyarı
+
+Bu, az çok "ileri seviye" bir fikirdir.
+
+**FastAPI**'ye yeni başlıyorsanız şimdilik bunu atlamak isteyebilirsiniz.
+
+///
+
+Python'da Context Manager'ları, iki method'a sahip bir class oluşturarak: `__enter__()` ve `__exit__()` yaratabilirsiniz.
+
+Ayrıca dependency fonksiyonunun içinde `with` veya `async with` ifadeleri kullanarak **FastAPI**'de `yield` kullanan dependency'lerin içinde de kullanabilirsiniz:
+
+{* ../../docs_src/dependencies/tutorial010_py39.py hl[1:9,13] *}
+
+/// tip | İpucu
+
+Bir context manager oluşturmanın başka bir yolu da şunlardır:
+
+* `@contextlib.contextmanager` veya
+* `@contextlib.asynccontextmanager`
+
+Bunları, tek bir `yield` içeren bir fonksiyonu decorate etmek için kullanabilirsiniz.
+
+FastAPI, `yield` kullanan dependency'ler için içeride bunu yapar.
+
+Ancak FastAPI dependency'leri için bu decorator'ları kullanmak zorunda değilsiniz (hatta kullanmamalısınız).
+
+FastAPI bunu sizin yerinize içeride yapar.
+
+///
diff --git a/docs/tr/docs/tutorial/dependencies/global-dependencies.md b/docs/tr/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 000000000..7f0025eaf
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,16 @@
+# Global Dependencies { #global-dependencies }
+
+Bazı uygulama türlerinde, tüm uygulama için dependency eklemek isteyebilirsiniz.
+
+[`dependencies`'i *path operation decorator*'larına ekleyebildiğiniz](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} gibi, `FastAPI` uygulamasına da ekleyebilirsiniz.
+
+Bu durumda, uygulamadaki tüm *path operation*'lara uygulanırlar:
+
+{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[17] *}
+
+
+Ve [*path operation decorator*'larına `dependencies` ekleme](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} bölümündeki tüm fikirler hâlâ geçerlidir; ancak bu sefer, uygulamadaki tüm *path operation*'lar için geçerli olur.
+
+## *Path operations* grupları için Dependencies { #dependencies-for-groups-of-path-operations }
+
+İleride, daha büyük uygulamaları nasıl yapılandıracağınızı ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}) okurken, muhtemelen birden fazla dosyayla birlikte, bir *path operations* grubu için tek bir `dependencies` parametresini nasıl tanımlayacağınızı öğreneceksiniz.
diff --git a/docs/tr/docs/tutorial/dependencies/index.md b/docs/tr/docs/tutorial/dependencies/index.md
new file mode 100644
index 000000000..f1e446d67
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/index.md
@@ -0,0 +1,250 @@
+# Bağımlılıklar { #dependencies }
+
+**FastAPI**, çok güçlü ama aynı zamanda sezgisel bir **Dependency Injection** sistemine sahiptir.
+
+Kullanımı çok basit olacak şekilde tasarlanmıştır ve herhangi bir geliştiricinin diğer bileşenleri **FastAPI** ile entegre etmesini kolaylaştırır.
+
+## "Dependency Injection" Nedir? { #what-is-dependency-injection }
+
+Programlamada **"Dependency Injection"**, kodunuzun (bu örnekte *path operation function*'larınızın) çalışmak ve kullanmak için ihtiyaç duyduğu şeyleri: "dependencies" (bağımlılıklar) olarak beyan edebilmesi anlamına gelir.
+
+Ardından bu sistem (bu örnekte **FastAPI**), kodunuza gerekli bağımlılıkları sağlamak ("inject" etmek) için gereken her şeyi sizin yerinize halleder.
+
+Bu yaklaşım, şunlara ihtiyaç duyduğunuzda özellikle faydalıdır:
+
+* Paylaşılan bir mantığa sahip olmak (aynı kod mantığını tekrar tekrar kullanmak).
+* Veritabanı bağlantılarını paylaşmak.
+* Güvenlik, authentication, rol gereksinimleri vb. kuralları zorunlu kılmak.
+* Ve daha birçok şey...
+
+Tüm bunları, kod tekrarını minimumda tutarak yaparsınız.
+
+## İlk Adımlar { #first-steps }
+
+Çok basit bir örneğe bakalım. Şimdilik o kadar basit olacak ki pek işe yaramayacak.
+
+Ama bu sayede **Dependency Injection** sisteminin nasıl çalıştığına odaklanabiliriz.
+
+### Bir dependency (bağımlılık) veya "dependable" Oluşturun { #create-a-dependency-or-dependable }
+
+Önce dependency'e odaklanalım.
+
+Bu, bir *path operation function*'ın alabileceği parametrelerin aynısını alabilen basit bir fonksiyondur:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+Bu kadar.
+
+**2 satır**.
+
+Ve tüm *path operation function*'larınızla aynı şekle ve yapıya sahiptir.
+
+Bunu, "decorator" olmadan (yani `@app.get("/some-path")` olmadan) yazılmış bir *path operation function* gibi düşünebilirsiniz.
+
+Ayrıca istediğiniz herhangi bir şeyi döndürebilir.
+
+Bu örnekte, bu dependency şunları bekler:
+
+* `str` olan, opsiyonel bir query parametresi `q`.
+* `int` olan, opsiyonel bir query parametresi `skip` ve varsayılanı `0`.
+* `int` olan, opsiyonel bir query parametresi `limit` ve varsayılanı `100`.
+
+Sonra da bu değerleri içeren bir `dict` döndürür.
+
+/// info | Bilgi
+
+FastAPI, `Annotated` desteğini 0.95.0 sürümünde ekledi (ve önermeye başladı).
+
+Daha eski bir sürüm kullanıyorsanız `Annotated` kullanmaya çalıştığınızda hata alırsınız.
+
+`Annotated` kullanmadan önce **FastAPI** sürümünü en az 0.95.1'e yükseltmek için [FastAPI sürümünü yükseltin](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}.
+
+///
+
+### `Depends`'i Import Edin { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### "Dependant" İçinde Dependency'yi Tanımlayın { #declare-the-dependency-in-the-dependant }
+
+*Path operation function* parametrelerinizde `Body`, `Query` vb. kullandığınız gibi, yeni bir parametreyle `Depends` kullanın:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+Fonksiyon parametrelerinde `Depends`'i `Body`, `Query` vb. ile aynı şekilde kullansanız da `Depends` biraz farklı çalışır.
+
+`Depends`'e yalnızca tek bir parametre verirsiniz.
+
+Bu parametre, bir fonksiyon gibi bir şey olmalıdır.
+
+Onu doğrudan **çağırmazsınız** (sonuna parantez eklemezsiniz), sadece `Depends()`'e parametre olarak verirsiniz.
+
+Ve bu fonksiyon da, *path operation function*'lar gibi parametre alır.
+
+/// tip | İpucu
+
+Fonksiyonların dışında başka hangi "şeylerin" dependency olarak kullanılabildiğini bir sonraki bölümde göreceksiniz.
+
+///
+
+Yeni bir request geldiğinde, **FastAPI** şunları sizin yerinize yapar:
+
+* Dependency ("dependable") fonksiyonunuzu doğru parametrelerle çağırır.
+* Fonksiyonunuzun sonucunu alır.
+* Bu sonucu *path operation function*'ınızdaki parametreye atar.
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+Bu şekilde paylaşılan kodu bir kez yazarsınız ve onu *path operation*'larda çağırma işini **FastAPI** halleder.
+
+/// check | Ek bilgi
+
+Dikkat edin: Bunu "register" etmek ya da benzeri bir şey yapmak için özel bir class oluşturup **FastAPI**'ye bir yere geçirmeniz gerekmez.
+
+Sadece `Depends`'e verirsiniz ve gerisini **FastAPI** nasıl yapacağını bilir.
+
+///
+
+## `Annotated` Dependency'lerini Paylaşın { #share-annotated-dependencies }
+
+Yukarıdaki örneklerde, ufak bir **kod tekrarı** olduğunu görüyorsunuz.
+
+`common_parameters()` dependency'sini kullanmanız gerektiğinde, type annotation ve `Depends()` içeren parametrenin tamamını yazmanız gerekir:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+Ancak `Annotated` kullandığımız için bu `Annotated` değerini bir değişkende saklayıp birden fazla yerde kullanabiliriz:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | İpucu
+
+Bu aslında standart Python'dır; buna "type alias" denir ve **FastAPI**'ye özel bir şey değildir.
+
+Ama **FastAPI**, `Annotated` dahil Python standartları üzerine kurulu olduğu için bu tekniği kodunuzda kullanabilirsiniz. 😎
+
+///
+
+Dependency'ler beklediğiniz gibi çalışmaya devam eder ve **en güzel kısmı** da şudur: **type bilgisi korunur**. Bu da editörünüzün size **autocompletion**, **inline errors** vb. sağlamaya devam edeceği anlamına gelir. `mypy` gibi diğer araçlar için de aynısı geçerlidir.
+
+Bu özellikle, **büyük bir kod tabanında**, aynı dependency'leri **birçok *path operation*** içinde tekrar tekrar kullandığınızda çok faydalı olacaktır.
+
+## `async` Olsa da Olmasa da { #to-async-or-not-to-async }
+
+Dependency'ler de **FastAPI** tarafından çağrılacağı için (tıpkı *path operation function*'larınız gibi), fonksiyonları tanımlarken aynı kurallar geçerlidir.
+
+`async def` ya da normal `def` kullanabilirsiniz.
+
+Ayrıca normal `def` *path operation function*'ları içinde `async def` dependency tanımlayabilir veya `async def` *path operation function*'ları içinde `def` dependency kullanabilirsiniz vb.
+
+Fark etmez. **FastAPI** ne yapacağını bilir.
+
+/// note | Not
+
+Eğer bilmiyorsanız, dokümanlarda `async` ve `await` için [Async: *"In a hurry?"*](../../async.md#in-a-hurry){.internal-link target=_blank} bölümüne bakın.
+
+///
+
+## OpenAPI ile Entegre { #integrated-with-openapi }
+
+Dependency'lerinizin (ve alt dependency'lerin) tüm request tanımları, doğrulamaları ve gereksinimleri aynı OpenAPI şemasına entegre edilir.
+
+Bu nedenle interaktif dokümanlar, bu dependency'lerden gelen tüm bilgileri de içerir:
+
+
+
+## Basit Kullanım { #simple-usage }
+
+Şöyle düşünürseniz: *Path operation function*'lar, bir *path* ve *operation* eşleştiğinde kullanılacak şekilde tanımlanır; ardından **FastAPI** fonksiyonu doğru parametrelerle çağırır ve request'ten veriyi çıkarır.
+
+Aslında tüm (veya çoğu) web framework'ü de aynı şekilde çalışır.
+
+Bu fonksiyonları hiçbir zaman doğrudan çağırmazsınız. Onları framework'ünüz (bu örnekte **FastAPI**) çağırır.
+
+Dependency Injection sistemiyle, *path operation function*'ınızın, ondan önce çalıştırılması gereken başka bir şeye de "bağlı" olduğunu **FastAPI**'ye söyleyebilirsiniz; **FastAPI** bunu çalıştırır ve sonuçları "inject" eder.
+
+Aynı "dependency injection" fikri için kullanılan diğer yaygın terimler:
+
+* resources
+* providers
+* services
+* injectables
+* components
+
+## **FastAPI** Plug-in'leri { #fastapi-plug-ins }
+
+Entegrasyonlar ve "plug-in"ler **Dependency Injection** sistemi kullanılarak inşa edilebilir. Ancak aslında **"plug-in" oluşturmanıza gerek yoktur**; çünkü dependency'leri kullanarak *path operation function*'larınıza sunulabilecek sınırsız sayıda entegrasyon ve etkileşim tanımlayabilirsiniz.
+
+Dependency'ler, çok basit ve sezgisel bir şekilde oluşturulabilir. Böylece ihtiyacınız olan Python package'larını import edip, API fonksiyonlarınızla birkaç satır kodla *kelimenin tam anlamıyla* entegre edebilirsiniz.
+
+İlerleyen bölümlerde ilişkisel ve NoSQL veritabanları, güvenlik vb. konularda bunun örneklerini göreceksiniz.
+
+## **FastAPI** Uyumluluğu { #fastapi-compatibility }
+
+Dependency injection sisteminin sadeliği, **FastAPI**'yi şunlarla uyumlu hale getirir:
+
+* tüm ilişkisel veritabanları
+* NoSQL veritabanları
+* harici paketler
+* harici API'ler
+* authentication ve authorization sistemleri
+* API kullanım izleme (monitoring) sistemleri
+* response verisi injection sistemleri
+* vb.
+
+## Basit ve Güçlü { #simple-and-powerful }
+
+Hiyerarşik dependency injection sistemi tanımlamak ve kullanmak çok basit olsa da, hâlâ oldukça güçlüdür.
+
+Kendileri de dependency tanımlayabilen dependency'ler tanımlayabilirsiniz.
+
+Sonuçta hiyerarşik bir dependency ağacı oluşur ve **Dependency Injection** sistemi tüm bu dependency'leri (ve alt dependency'lerini) sizin için çözer ve her adımda sonuçları sağlar ("inject" eder).
+
+Örneğin, 4 API endpoint'iniz (*path operation*) olduğunu varsayalım:
+
+* `/items/public/`
+* `/items/private/`
+* `/users/{user_id}/activate`
+* `/items/pro/`
+
+O zaman her biri için farklı izin gereksinimlerini yalnızca dependency'ler ve alt dependency'lerle ekleyebilirsiniz:
+
+```mermaid
+graph TB
+
+current_user(["current_user"])
+active_user(["active_user"])
+admin_user(["admin_user"])
+paying_user(["paying_user"])
+
+public["/items/public/"]
+private["/items/private/"]
+activate_user["/users/{user_id}/activate"]
+pro_items["/items/pro/"]
+
+current_user --> active_user
+active_user --> admin_user
+active_user --> paying_user
+
+current_user --> public
+active_user --> private
+admin_user --> activate_user
+paying_user --> pro_items
+```
+
+## **OpenAPI** ile Entegre { #integrated-with-openapi_1 }
+
+Bu dependency'lerin tümü, gereksinimlerini beyan ederken aynı zamanda *path operation*'larınıza parametreler, doğrulamalar vb. da ekler.
+
+**FastAPI**, bunların hepsini OpenAPI şemasına eklemekle ilgilenir; böylece interaktif dokümantasyon sistemlerinde gösterilir.
diff --git a/docs/tr/docs/tutorial/dependencies/sub-dependencies.md b/docs/tr/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 000000000..184db839b
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# Alt Bağımlılıklar { #sub-dependencies }
+
+**Alt bağımlılıkları** olan bağımlılıklar oluşturabilirsiniz.
+
+İhtiyacınız olduğu kadar **derine** gidebilirler.
+
+Bunları çözme işini **FastAPI** üstlenir.
+
+## İlk bağımlılık "dependable" { #first-dependency-dependable }
+
+Şöyle bir ilk bağımlılık ("dependable") oluşturabilirsiniz:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+Burada `q` adında opsiyonel bir query parametresi `str` olarak tanımlanır ve sonra doğrudan geri döndürülür.
+
+Bu oldukça basit (pek faydalı değil), ama alt bağımlılıkların nasıl çalıştığına odaklanmamıza yardımcı olacak.
+
+## İkinci bağımlılık: "dependable" ve "dependant" { #second-dependency-dependable-and-dependant }
+
+Ardından, aynı zamanda kendi içinde bir bağımlılık da tanımlayan başka bir bağımlılık fonksiyonu (bir "dependable") oluşturabilirsiniz (yani o da bir "dependant" olur):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+Tanımlanan parametrelere odaklanalım:
+
+* Bu fonksiyonun kendisi bir bağımlılık ("dependable") olmasına rağmen, ayrıca başka bir bağımlılık daha tanımlar (başka bir şeye "depends" olur).
+ * `query_extractor`'a bağlıdır ve ondan dönen değeri `q` parametresine atar.
+* Ayrıca `last_query` adında opsiyonel bir cookie'yi `str` olarak tanımlar.
+ * Kullanıcı herhangi bir query `q` sağlamadıysa, daha önce cookie'ye kaydettiğimiz en son kullanılan query'yi kullanırız.
+
+## Bağımlılığı Kullanma { #use-the-dependency }
+
+Sonra bu bağımlılığı şöyle kullanabiliriz:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info | Bilgi
+
+Dikkat edin, *path operation function* içinde yalnızca tek bir bağımlılık tanımlıyoruz: `query_or_cookie_extractor`.
+
+Ancak **FastAPI**, `query_or_cookie_extractor`'ı çağırmadan önce `query_extractor`'ı önce çözmesi gerektiğini bilir ve onun sonucunu `query_or_cookie_extractor`'a aktarır.
+
+///
+
+```mermaid
+graph TB
+
+query_extractor(["query_extractor"])
+query_or_cookie_extractor(["query_or_cookie_extractor"])
+
+read_query["/items/"]
+
+query_extractor --> query_or_cookie_extractor --> read_query
+```
+
+## Aynı Bağımlılığı Birden Fazla Kez Kullanma { #using-the-same-dependency-multiple-times }
+
+Bağımlılıklarınızdan biri aynı *path operation* için birden fazla kez tanımlanırsa (örneğin birden fazla bağımlılığın ortak bir alt bağımlılığı varsa), **FastAPI** o alt bağımlılığı request başına yalnızca bir kez çağıracağını bilir.
+
+Dönen değeri bir "cache" içinde saklar ve aynı request içinde buna ihtiyaç duyan tüm "dependant"lara aktarır; böylece aynı request için bağımlılığı tekrar tekrar çağırmaz.
+
+Daha ileri bir senaryoda, "cached" değeri kullanmak yerine aynı request içinde her adımda (muhtemelen birden fazla kez) bağımlılığın çağrılması gerektiğini biliyorsanız, `Depends` kullanırken `use_cache=False` parametresini ayarlayabilirsiniz:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.9+ Annotated olmayan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü tercih edin.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## Özet { #recap }
+
+Burada kullanılan havalı terimlerin ötesinde, **Dependency Injection** sistemi aslında oldukça basittir.
+
+*Path operation function*'lara benzeyen fonksiyonlardan ibarettir.
+
+Yine de çok güçlüdür ve keyfi derecede derin iç içe geçmiş bağımlılık "graph"ları (ağaçları) tanımlamanıza izin verir.
+
+/// tip | İpucu
+
+Bu basit örneklerle çok faydalı görünmeyebilir.
+
+Ancak **security** ile ilgili bölümlerde bunun ne kadar işe yaradığını göreceksiniz.
+
+Ayrıca size ne kadar kod kazandırdığını da göreceksiniz.
+
+///
diff --git a/docs/tr/docs/tutorial/encoder.md b/docs/tr/docs/tutorial/encoder.md
new file mode 100644
index 000000000..e4790a032
--- /dev/null
+++ b/docs/tr/docs/tutorial/encoder.md
@@ -0,0 +1,35 @@
+# JSON Uyumlu Encoder { #json-compatible-encoder }
+
+Bazı durumlarda, bir veri tipini (örneğin bir Pydantic model) JSON ile uyumlu bir şeye (örneğin `dict`, `list` vb.) dönüştürmeniz gerekebilir.
+
+Örneğin, bunu bir veritabanında saklamanız gerekiyorsa.
+
+Bunun için **FastAPI**, `jsonable_encoder()` fonksiyonunu sağlar.
+
+## `jsonable_encoder` Kullanımı { #using-the-jsonable-encoder }
+
+Yalnızca JSON ile uyumlu veri kabul eden bir veritabanınız olduğunu düşünelim: `fake_db`.
+
+Örneğin bu veritabanı, JSON ile uyumlu olmadıkları için `datetime` objelerini kabul etmez.
+
+Dolayısıyla bir `datetime` objesinin, ISO formatında veriyi içeren bir `str`'e dönüştürülmesi gerekir.
+
+Aynı şekilde bu veritabanı bir Pydantic model'i (attribute'lara sahip bir obje) de kabul etmez; yalnızca bir `dict` kabul eder.
+
+Bunun için `jsonable_encoder` kullanabilirsiniz.
+
+Bir Pydantic model gibi bir obje alır ve JSON ile uyumlu bir versiyonunu döndürür:
+
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
+
+Bu örnekte, Pydantic model'i bir `dict`'e, `datetime`'ı da bir `str`'e dönüştürür.
+
+Bu fonksiyonun çağrılmasıyla elde edilen sonuç, Python standardındaki `json.dumps()` ile encode edilebilecek bir şeydir.
+
+JSON formatında (string olarak) veriyi içeren büyük bir `str` döndürmez. Bunun yerine, tüm değerleri ve alt değerleri JSON ile uyumlu olacak şekilde, Python’un standart bir veri yapısını (örneğin bir `dict`) döndürür.
+
+/// note | Not
+
+`jsonable_encoder`, aslında **FastAPI** tarafından veriyi dönüştürmek için internal olarak kullanılır. Ancak birçok farklı senaryoda da oldukça faydalıdır.
+
+///
diff --git a/docs/tr/docs/tutorial/extra-data-types.md b/docs/tr/docs/tutorial/extra-data-types.md
new file mode 100644
index 000000000..464d3a82a
--- /dev/null
+++ b/docs/tr/docs/tutorial/extra-data-types.md
@@ -0,0 +1,62 @@
+# Ek Veri Tipleri { #extra-data-types }
+
+Şimdiye kadar şunlar gibi yaygın veri tiplerini kullanıyordunuz:
+
+* `int`
+* `float`
+* `str`
+* `bool`
+
+Ancak daha karmaşık veri tiplerini de kullanabilirsiniz.
+
+Ve yine, şimdiye kadar gördüğünüz özelliklerin aynısına sahip olursunuz:
+
+* Harika editör desteği.
+* Gelen request'lerden veri dönüştürme.
+* response verileri için veri dönüştürme.
+* Veri doğrulama.
+* Otomatik annotation ve dokümantasyon.
+
+## Diğer veri tipleri { #other-data-types }
+
+Kullanabileceğiniz ek veri tiplerinden bazıları şunlardır:
+
+* `UUID`:
+ * Birçok veritabanı ve sistemde ID olarak yaygın kullanılan, standart bir "Universally Unique Identifier".
+ * request ve response'larda `str` olarak temsil edilir.
+* `datetime.datetime`:
+ * Python `datetime.datetime`.
+ * request ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `2008-09-15T15:53:00+05:00`.
+* `datetime.date`:
+ * Python `datetime.date`.
+ * request ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `2008-09-15`.
+* `datetime.time`:
+ * Python `datetime.time`.
+ * request ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `14:23:55.003`.
+* `datetime.timedelta`:
+ * Python `datetime.timedelta`.
+ * request ve response'larda toplam saniye sayısını ifade eden bir `float` olarak temsil edilir.
+ * Pydantic, bunu ayrıca bir "ISO 8601 time diff encoding" olarak temsil etmeye de izin verir, daha fazla bilgi için dokümanlara bakın.
+* `frozenset`:
+ * request ve response'larda, `set` ile aynı şekilde ele alınır:
+ * request'lerde bir list okunur, tekrarlar kaldırılır ve `set`'e dönüştürülür.
+ * response'larda `set`, `list`'e dönüştürülür.
+ * Üretilen schema, `set` değerlerinin benzersiz olduğunu belirtir (JSON Schema'nın `uniqueItems` özelliğini kullanarak).
+* `bytes`:
+ * Standart Python `bytes`.
+ * request ve response'larda `str` gibi ele alınır.
+ * Üretilen schema, bunun `binary` "format"ına sahip bir `str` olduğunu belirtir.
+* `Decimal`:
+ * Standart Python `Decimal`.
+ * request ve response'larda `float` ile aynı şekilde işlenir.
+* Geçerli tüm Pydantic veri tiplerini burada görebilirsiniz: Pydantic data types.
+
+## Örnek { #example }
+
+Yukarıdaki tiplerden bazılarını kullanan parametrelere sahip bir örnek *path operation* şöyle:
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
+
+Fonksiyonun içindeki parametrelerin doğal veri tiplerinde olduğunu unutmayın; örneğin normal tarih işlemleri yapabilirsiniz:
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/tr/docs/tutorial/extra-models.md b/docs/tr/docs/tutorial/extra-models.md
new file mode 100644
index 000000000..9aae28e05
--- /dev/null
+++ b/docs/tr/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# Ek Modeller { #extra-models }
+
+Önceki örnekten devam edersek, birbiriyle ilişkili birden fazla modelin olması oldukça yaygındır.
+
+Bu durum özellikle kullanıcı modellerinde sık görülür, çünkü:
+
+* **input modeli** bir `password` içerebilmelidir.
+* **output modeli** `password` içermemelidir.
+* **database modeli** büyük ihtimalle hash'lenmiş bir `password` tutmalıdır.
+
+/// danger
+
+Kullanıcının düz metin (plaintext) `password`'ünü asla saklamayın. Her zaman sonradan doğrulayabileceğiniz "güvenli bir hash" saklayın.
+
+Eğer bilmiyorsanız, "password hash" nedir konusunu [güvenlik bölümlerinde](security/simple-oauth2.md#password-hashing){.internal-link target=_blank} öğreneceksiniz.
+
+///
+
+## Birden Çok Model { #multiple-models }
+
+`password` alanlarıyla birlikte modellerin genel olarak nasıl görünebileceğine ve nerelerde kullanılacaklarına dair bir fikir:
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### `**user_in.model_dump()` Hakkında { #about-user-in-model-dump }
+
+#### Pydantic'in `.model_dump()` Metodu { #pydantics-model-dump }
+
+`user_in`, `UserIn` sınıfına ait bir Pydantic modelidir.
+
+Pydantic modellerinde, model verilerini içeren bir `dict` döndüren `.model_dump()` metodu bulunur.
+
+Yani, şöyle bir Pydantic nesnesi `user_in` oluşturursak:
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+ve sonra şunu çağırırsak:
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+artık `user_dict` değişkeninde modelin verilerini içeren bir `dict` vardır (Pydantic model nesnesi yerine bir `dict` elde etmiş oluruz).
+
+Ve eğer şunu çağırırsak:
+
+```Python
+print(user_dict)
+```
+
+şöyle bir Python `dict` elde ederiz:
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### Bir `dict`'i Unpack Etmek { #unpacking-a-dict }
+
+`user_dict` gibi bir `dict` alıp bunu bir fonksiyona (ya da sınıfa) `**user_dict` ile gönderirsek, Python bunu "unpack" eder. Yani `user_dict` içindeki key ve value'ları doğrudan key-value argümanları olarak geçirir.
+
+Dolayısıyla, yukarıdaki `user_dict` ile devam edersek, şunu yazmak:
+
+```Python
+UserInDB(**user_dict)
+```
+
+şuna eşdeğer bir sonuç üretir:
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ full_name=None,
+)
+```
+
+Ya da daha net şekilde, `user_dict`'i doğrudan kullanarak, gelecekte içeriği ne olursa olsun:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+)
+```
+
+#### Bir Pydantic Modelinden Diğerinin İçeriğiyle Pydantic Model Oluşturmak { #a-pydantic-model-from-the-contents-of-another }
+
+Yukarıdaki örnekte `user_dict`'i `user_in.model_dump()` ile elde ettiğimiz için, şu kod:
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+şuna eşdeğerdir:
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+...çünkü `user_in.model_dump()` bir `dict` döndürür ve biz de bunu `UserInDB`'ye `**` önekiyle vererek Python'ın "unpack" etmesini sağlarız.
+
+Böylece, bir Pydantic modelindeki verilerden başka bir Pydantic model üretmiş oluruz.
+
+#### Bir `dict`'i Unpack Etmek ve Ek Keyword'ler { #unpacking-a-dict-and-extra-keywords }
+
+Sonrasında, aşağıdaki gibi ek keyword argümanı `hashed_password=hashed_password` eklemek:
+
+```Python
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
+```
+
+...şuna benzer bir sonuca dönüşür:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ hashed_password = hashed_password,
+)
+```
+
+/// warning
+
+Ek destek fonksiyonları olan `fake_password_hasher` ve `fake_save_user` sadece verinin olası bir akışını göstermek içindir; elbette gerçek bir güvenlik sağlamazlar.
+
+///
+
+## Tekrarı Azaltma { #reduce-duplication }
+
+Kod tekrarını azaltmak, **FastAPI**'nin temel fikirlerinden biridir.
+
+Kod tekrarı; bug, güvenlik problemi, kodun senkron dışına çıkması (bir yeri güncelleyip diğerlerini güncellememek) gibi sorunların olasılığını artırır.
+
+Bu modellerin hepsi verinin büyük bir kısmını paylaşıyor ve attribute adlarını ve type'larını tekrar ediyor.
+
+Daha iyisini yapabiliriz.
+
+Diğer modellerimiz için temel olacak bir `UserBase` modeli tanımlayabiliriz. Sonra da bu modelden türeyen (subclass) modeller oluşturup onun attribute'larını (type deklarasyonları, doğrulama vb.) miras aldırabiliriz.
+
+Tüm veri dönüştürme, doğrulama, dokümantasyon vb. her zamanki gibi çalışmaya devam eder.
+
+Bu sayede modeller arasındaki farkları (plaintext `password` olan, `hashed_password` olan ve `password` olmayan) sadece o farklılıklar olarak tanımlayabiliriz:
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` veya `anyOf` { #union-or-anyof }
+
+Bir response'u iki ya da daha fazla type'ın `Union`'ı olarak tanımlayabilirsiniz; bu, response'un bunlardan herhangi biri olabileceği anlamına gelir.
+
+OpenAPI'de bu `anyOf` ile tanımlanır.
+
+Bunu yapmak için standart Python type hint'i olan `typing.Union`'ı kullanın:
+
+/// note
+
+Bir `Union` tanımlarken en spesifik type'ı önce, daha az spesifik olanı sonra ekleyin. Aşağıdaki örnekte daha spesifik olan `PlaneItem`, `Union[PlaneItem, CarItem]` içinde `CarItem`'dan önce gelir.
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### Python 3.10'da `Union` { #union-in-python-3-10 }
+
+Bu örnekte `Union[PlaneItem, CarItem]` değerini `response_model` argümanına veriyoruz.
+
+Bunu bir **type annotation** içine koymak yerine bir **argümana değer** olarak geçtiğimiz için, Python 3.10'da bile `Union` kullanmamız gerekiyor.
+
+Eğer bu bir type annotation içinde olsaydı, dikey çizgiyi kullanabilirdik:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+Ancak bunu `response_model=PlaneItem | CarItem` atamasına koyarsak hata alırız; çünkü Python bunu bir type annotation olarak yorumlamak yerine `PlaneItem` ile `CarItem` arasında **geçersiz bir işlem** yapmaya çalışır.
+
+## Model Listesi { #list-of-models }
+
+Aynı şekilde, nesne listesi döndüren response'ları da tanımlayabilirsiniz.
+
+Bunun için standart Python `typing.List`'i (ya da Python 3.9 ve üzeri için sadece `list`) kullanın:
+
+{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *}
+
+## Rastgele `dict` ile Response { #response-with-arbitrary-dict }
+
+Bir Pydantic modeli kullanmadan, sadece key ve value type'larını belirterek düz, rastgele bir `dict` ile de response tanımlayabilirsiniz.
+
+Bu, geçerli field/attribute adlarını (Pydantic modeli için gerekli olurdu) önceden bilmiyorsanız kullanışlıdır.
+
+Bu durumda `typing.Dict` (ya da Python 3.9 ve üzeri için sadece `dict`) kullanabilirsiniz:
+
+{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *}
+
+## Özet { #recap }
+
+Her duruma göre birden fazla Pydantic modeli kullanın ve gerekirse özgürce inheritance uygulayın.
+
+Bir entity'nin farklı "state"lere sahip olması gerekiyorsa, o entity için tek bir veri modeli kullanmak zorunda değilsiniz. Örneğin `password` içeren, `password_hash` içeren ve `password` içermeyen state'lere sahip kullanıcı "entity"si gibi.
diff --git a/docs/tr/docs/tutorial/handling-errors.md b/docs/tr/docs/tutorial/handling-errors.md
new file mode 100644
index 000000000..a4d693792
--- /dev/null
+++ b/docs/tr/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# Hataları Yönetme { #handling-errors }
+
+API’nizi kullanan bir client’a hata bildirmek zorunda olduğunuz pek çok durum vardır.
+
+Bu client; frontend’i olan bir tarayıcı, başka birinin yazdığı bir kod, bir IoT cihazı vb. olabilir.
+
+Client’a şunları söylemeniz gerekebilir:
+
+* Client’ın bu işlem için yeterli yetkisi yok.
+* Client’ın bu kaynağa erişimi yok.
+* Client’ın erişmeye çalıştığı öğe mevcut değil.
+* vb.
+
+Bu durumlarda genellikle **400** aralığında (**400** ile **499** arası) bir **HTTP status code** döndürürsünüz.
+
+Bu, 200 HTTP status code’larına (200 ile 299 arası) benzer. Bu "200" status code’ları, request’in bir şekilde "başarılı" olduğunu ifade eder.
+
+400 aralığındaki status code’lar ise hatanın client tarafından kaynaklandığını gösterir.
+
+Şu meşhur **"404 Not Found"** hatalarını (ve şakalarını) hatırlıyor musunuz?
+
+## `HTTPException` Kullanma { #use-httpexception }
+
+Client’a hata içeren HTTP response’ları döndürmek için `HTTPException` kullanırsınız.
+
+### `HTTPException`’ı Import Etme { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py39.py hl[1] *}
+
+### Kodunuzda Bir `HTTPException` Raise Etme { #raise-an-httpexception-in-your-code }
+
+`HTTPException`, API’lerle ilgili ek veriler içeren normal bir Python exception’ıdır.
+
+Python exception’ı olduğu için `return` etmezsiniz, `raise` edersiniz.
+
+Bu aynı zamanda şunu da ifade eder: *path operation function*’ınızın içinde çağırdığınız bir yardımcı (utility) fonksiyonun içindeyken `HTTPException` raise ederseniz, *path operation function* içindeki kodun geri kalanı çalışmaz; request’i hemen sonlandırır ve `HTTPException` içindeki HTTP hatasını client’a gönderir.
+
+Bir değer döndürmek yerine exception raise etmenin faydası, Dependencies ve Security bölümünde daha da netleşecektir.
+
+Bu örnekte, client var olmayan bir ID ile bir item istediğinde, `404` status code’u ile bir exception raise edelim:
+
+{* ../../docs_src/handling_errors/tutorial001_py39.py hl[11] *}
+
+### Ortaya Çıkan Response { #the-resulting-response }
+
+Client `http://example.com/items/foo` (bir `item_id` `"foo"`) isterse, HTTP status code olarak 200 ve şu JSON response’u alır:
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Ancak client `http://example.com/items/bar` (mevcut olmayan bir `item_id` `"bar"`) isterse, HTTP status code olarak 404 ("not found" hatası) ve şu JSON response’u alır:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | İpucu
+
+Bir `HTTPException` raise ederken, `detail` parametresine sadece `str` değil, JSON’a dönüştürülebilen herhangi bir değer geçebilirsiniz.
+
+Örneğin `dict`, `list` vb. geçebilirsiniz.
+
+Bunlar **FastAPI** tarafından otomatik olarak işlenir ve JSON’a dönüştürülür.
+
+///
+
+## Özel Header’lar Eklemek { #add-custom-headers }
+
+Bazı durumlarda HTTP hata response’una özel header’lar eklemek faydalıdır. Örneğin bazı güvenlik türlerinde.
+
+Muhtemelen bunu doğrudan kendi kodunuzda kullanmanız gerekmeyecek.
+
+Ama ileri seviye bir senaryo için ihtiyaç duyarsanız, özel header’lar ekleyebilirsiniz:
+
+{* ../../docs_src/handling_errors/tutorial002_py39.py hl[14] *}
+
+## Özel Exception Handler’ları Kurmak { #install-custom-exception-handlers }
+
+Starlette’in aynı exception yardımcı araçlarıyla özel exception handler’lar ekleyebilirsiniz.
+
+Diyelim ki sizin (ya da kullandığınız bir kütüphanenin) `raise` edebileceği `UnicornException` adında özel bir exception’ınız var.
+
+Ve bu exception’ı FastAPI ile global olarak handle etmek istiyorsunuz.
+
+`@app.exception_handler()` ile özel bir exception handler ekleyebilirsiniz:
+
+{* ../../docs_src/handling_errors/tutorial003_py39.py hl[5:7,13:18,24] *}
+
+Burada `/unicorns/yolo` için request atarsanız, *path operation* bir `UnicornException` `raise` eder.
+
+Ancak bu, `unicorn_exception_handler` tarafından handle edilir.
+
+Böylece HTTP status code’u `418` olan, JSON içeriği şu şekilde temiz bir hata response’u alırsınız:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | Teknik Detaylar
+
+`from starlette.requests import Request` ve `from starlette.responses import JSONResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olsun diye `starlette.responses` içeriğini `fastapi.responses` olarak da sunar. Ancak mevcut response’ların çoğu doğrudan Starlette’ten gelir. `Request` için de aynısı geçerlidir.
+
+///
+
+## Varsayılan Exception Handler’ları Override Etmek { #override-the-default-exception-handlers }
+
+**FastAPI** bazı varsayılan exception handler’lara sahiptir.
+
+Bu handler’lar, `HTTPException` `raise` ettiğinizde ve request geçersiz veri içerdiğinde varsayılan JSON response’ları döndürmekten sorumludur.
+
+Bu exception handler’ları kendi handler’larınızla override edebilirsiniz.
+
+### Request Validation Exception’larını Override Etmek { #override-request-validation-exceptions }
+
+Bir request geçersiz veri içerdiğinde, **FastAPI** içeride `RequestValidationError` raise eder.
+
+Ve bunun için varsayılan bir exception handler da içerir.
+
+Override etmek için `RequestValidationError`’ı import edin ve exception handler’ı `@app.exception_handler(RequestValidationError)` ile decorate edin.
+
+Exception handler, bir `Request` ve exception’ı alır.
+
+{* ../../docs_src/handling_errors/tutorial004_py39.py hl[2,14:19] *}
+
+Artık `/items/foo`’ya giderseniz, şu varsayılan JSON hatası yerine:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+şu şekilde bir metin (text) versiyonu alırsınız:
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### `HTTPException` Hata Handler’ını Override Etmek { #override-the-httpexception-error-handler }
+
+Benzer şekilde `HTTPException` handler’ını da override edebilirsiniz.
+
+Örneğin bu hatalar için JSON yerine plain text response döndürmek isteyebilirsiniz:
+
+{* ../../docs_src/handling_errors/tutorial004_py39.py hl[3:4,9:11,25] *}
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import PlainTextResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olsun diye `starlette.responses` içeriğini `fastapi.responses` olarak da sunar. Ancak mevcut response’ların çoğu doğrudan Starlette’ten gelir.
+
+///
+
+/// warning | Uyarı
+
+`RequestValidationError`, validation hatasının gerçekleştiği dosya adı ve satır bilgilerini içerir; isterseniz bunu log’larınıza ilgili bilgilerle birlikte yazdırabilirsiniz.
+
+Ancak bu, eğer sadece string’e çevirip bu bilgiyi doğrudan response olarak döndürürseniz sisteminiz hakkında bir miktar bilgi sızdırabileceğiniz anlamına gelir. Bu yüzden burada kod, her bir hatayı ayrı ayrı çıkarıp gösterir.
+
+///
+
+### `RequestValidationError` Body’sini Kullanmak { #use-the-requestvalidationerror-body }
+
+`RequestValidationError`, geçersiz veriyle aldığı `body`’yi içerir.
+
+Uygulamanızı geliştirirken body’yi log’lamak, debug etmek, kullanıcıya döndürmek vb. için bunu kullanabilirsiniz.
+
+{* ../../docs_src/handling_errors/tutorial005_py39.py hl[14] *}
+
+Şimdi şu gibi geçersiz bir item göndermeyi deneyin:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Aldığınız body’yi de içeren, verinin geçersiz olduğunu söyleyen bir response alırsınız:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### FastAPI’nin `HTTPException`’ı vs Starlette’in `HTTPException`’ı { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI**’nin kendi `HTTPException`’ı vardır.
+
+Ve **FastAPI**’nin `HTTPException` hata sınıfı, Starlette’in `HTTPException` hata sınıfından kalıtım alır (inherit).
+
+Tek fark şudur: **FastAPI**’nin `HTTPException`’ı `detail` alanı için JSON’a çevrilebilir herhangi bir veri kabul ederken, Starlette’in `HTTPException`’ı burada sadece string kabul eder.
+
+Bu yüzden kodunuzda her zamanki gibi **FastAPI**’nin `HTTPException`’ını raise etmeye devam edebilirsiniz.
+
+Ancak bir exception handler register ederken, bunu Starlette’in `HTTPException`’ı için register etmelisiniz.
+
+Böylece Starlette’in internal kodunun herhangi bir bölümü ya da bir Starlette extension/plug-in’i Starlette `HTTPException` raise ederse, handler’ınız bunu yakalayıp (catch) handle edebilir.
+
+Bu örnekte, iki `HTTPException`’ı da aynı kodda kullanabilmek için Starlette’in exception’ı `StarletteHTTPException` olarak yeniden adlandırılıyor:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### **FastAPI**’nin Exception Handler’larını Yeniden Kullanmak { #reuse-fastapis-exception-handlers }
+
+Exception’ı, **FastAPI**’nin aynı varsayılan exception handler’larıyla birlikte kullanmak isterseniz, varsayılan exception handler’ları `fastapi.exception_handlers` içinden import edip yeniden kullanabilirsiniz:
+
+{* ../../docs_src/handling_errors/tutorial006_py39.py hl[2:5,15,21] *}
+
+Bu örnekte sadece oldukça açıklayıcı bir mesajla hatayı yazdırıyorsunuz; ama fikir anlaşılıyor. Exception’ı kullanıp ardından varsayılan exception handler’ları olduğu gibi yeniden kullanabilirsiniz.
diff --git a/docs/tr/docs/tutorial/header-param-models.md b/docs/tr/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..9170515dc
--- /dev/null
+++ b/docs/tr/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Header Parametre Modelleri { #header-parameter-models }
+
+Birbiriyle ilişkili **header parametreleri**nden oluşan bir grubunuz varsa, bunları tanımlamak için bir **Pydantic model** oluşturabilirsiniz.
+
+Bu sayede modeli **birden fazla yerde yeniden kullanabilir**, ayrıca tüm parametreler için doğrulamaları ve metadata bilgilerini tek seferde tanımlayabilirsiniz. 😎
+
+/// note | Not
+
+Bu özellik FastAPI `0.115.0` sürümünden beri desteklenmektedir. 🤓
+
+///
+
+## Pydantic Model ile Header Parametreleri { #header-parameters-with-a-pydantic-model }
+
+İhtiyacınız olan **header parametreleri**ni bir **Pydantic model** içinde tanımlayın, ardından parametreyi `Header` olarak belirtin:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI**, request içindeki **headers** bölümünden **her alan** için veriyi **çıkarır** ve size tanımladığınız Pydantic model örneğini verir.
+
+## Dokümanları Kontrol Edin { #check-the-docs }
+
+Gerekli header'ları `/docs` altındaki doküman arayüzünde görebilirsiniz:
+
+
+contact alanlarıParametre Tip Açıklama namestrİletişim kişisi/kuruluşunu tanımlayan ad. urlstrİletişim bilgilerine işaret eden URL. URL formatında OLMALIDIR. emailstrİletişim kişisi/kuruluşunun e-posta adresi. E-posta adresi formatında OLMALIDIR. license_info alanlarıParametre Tip Açıklama namestrZORUNLU ( license_info ayarlanmışsa). API için kullanılan lisans adı.identifierstrAPI için bir SPDX lisans ifadesi. identifier alanı, url alanıyla karşılıklı olarak dışlayıcıdır (ikisi aynı anda kullanılamaz). OpenAPI 3.1.0, FastAPI 0.99.0 sürümünden itibaren mevcut.urlstrAPI için kullanılan lisansa ait URL. URL formatında OLMALIDIR.
+
+## License identifier { #license-identifier }
+
+OpenAPI 3.1.0 ve FastAPI 0.99.0 sürümünden itibaren, `license_info` içinde `url` yerine bir `identifier` da ayarlayabilirsiniz.
+
+Örneğin:
+
+{* ../../docs_src/metadata/tutorial001_1_py39.py hl[31] *}
+
+## Tag'ler için Metadata { #metadata-for-tags }
+
+`openapi_tags` parametresiyle, path operation'larınızı gruplamak için kullandığınız farklı tag'ler adına ek metadata da ekleyebilirsiniz.
+
+Bu parametre, her tag için bir sözlük (dictionary) içeren bir liste alır.
+
+Her sözlük şunları içerebilir:
+
+* `name` (**zorunlu**): *path operation*'larda ve `APIRouter`'larda `tags` parametresinde kullandığınız tag adıyla aynı olan bir `str`.
+* `description`: tag için kısa bir açıklama içeren `str`. Markdown içerebilir ve doküman arayüzünde gösterilir.
+* `externalDocs`: harici dokümanları tanımlayan bir `dict`:
+ * `description`: harici dokümanlar için kısa açıklama içeren `str`.
+ * `url` (**zorunlu**): harici dokümantasyonun URL'sini içeren `str`.
+
+### Tag'ler için metadata oluşturun { #create-metadata-for-tags }
+
+`users` ve `items` tag'lerini içeren bir örnekle deneyelim.
+
+Tag'leriniz için metadata oluşturup `openapi_tags` parametresine geçin:
+
+{* ../../docs_src/metadata/tutorial004_py39.py hl[3:16,18] *}
+
+Açıklamaların içinde Markdown kullanabileceğinizi unutmayın; örneğin "login" kalın (**login**) ve "fancy" italik (_fancy_) olarak gösterilecektir.
+
+/// tip | İpucu
+
+Kullandığınız tüm tag'ler için metadata eklemek zorunda değilsiniz.
+
+///
+
+### Tag'lerinizi kullanın { #use-your-tags }
+
+*path operation*'larınızı (ve `APIRouter`'ları) farklı tag'lere atamak için `tags` parametresini kullanın:
+
+{* ../../docs_src/metadata/tutorial004_py39.py hl[21,26] *}
+
+/// info | Bilgi
+
+Tag'ler hakkında daha fazlası için: [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank}.
+
+///
+
+### Dokümanları kontrol edin { #check-the-docs }
+
+Artık dokümanlara baktığınızda, eklediğiniz tüm metadata gösterilir:
+
+
+
+### Tag sırası { #order-of-tags }
+
+Her tag metadata sözlüğünün listedeki sırası, doküman arayüzünde gösterilecek sırayı da belirler.
+
+Örneğin alfabetik sıralamada `users`, `items`'tan sonra gelirdi; ancak listedeki ilk sözlük olarak `users` metadata'sını eklediğimiz için, dokümanlarda önce o görünür.
+
+## OpenAPI URL'si { #openapi-url }
+
+Varsayılan olarak OpenAPI şeması `/openapi.json` adresinden sunulur.
+
+Ancak bunu `openapi_url` parametresiyle yapılandırabilirsiniz.
+
+Örneğin `/api/v1/openapi.json` adresinden sunulacak şekilde ayarlamak için:
+
+{* ../../docs_src/metadata/tutorial002_py39.py hl[3] *}
+
+OpenAPI şemasını tamamen kapatmak isterseniz `openapi_url=None` ayarlayabilirsiniz; bu, onu kullanan dokümantasyon arayüzlerini de devre dışı bırakır.
+
+## Doküman URL'leri { #docs-urls }
+
+Dahil gelen iki dokümantasyon arayüzünü yapılandırabilirsiniz:
+
+* **Swagger UI**: `/docs` adresinden sunulur.
+ * URL'sini `docs_url` parametresiyle ayarlayabilirsiniz.
+ * `docs_url=None` ayarlayarak devre dışı bırakabilirsiniz.
+* **ReDoc**: `/redoc` adresinden sunulur.
+ * URL'sini `redoc_url` parametresiyle ayarlayabilirsiniz.
+ * `redoc_url=None` ayarlayarak devre dışı bırakabilirsiniz.
+
+Örneğin Swagger UI'yi `/documentation` adresinden sunup ReDoc'u kapatmak için:
+
+{* ../../docs_src/metadata/tutorial003_py39.py hl[3] *}
diff --git a/docs/tr/docs/tutorial/middleware.md b/docs/tr/docs/tutorial/middleware.md
new file mode 100644
index 000000000..68222265e
--- /dev/null
+++ b/docs/tr/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# Middleware { #middleware }
+
+**FastAPI** uygulamalarına middleware ekleyebilirsiniz.
+
+"Middleware", herhangi bir özel *path operation* tarafından işlenmeden önce her **request** ile çalışan bir fonksiyondur. Ayrıca geri döndürmeden önce her **response** ile de çalışır.
+
+* Uygulamanıza gelen her **request**'i alır.
+* Ardından o **request** üzerinde bir işlem yapabilir veya gerekli herhangi bir kodu çalıştırabilir.
+* Sonra **request**'i uygulamanın geri kalanı tarafından işlenmesi için iletir (bir *path operation* tarafından).
+* Ardından uygulama tarafından üretilen **response**'u alır (bir *path operation* tarafından).
+* Sonra o **response** üzerinde bir işlem yapabilir veya gerekli herhangi bir kodu çalıştırabilir.
+* Son olarak **response**'u döndürür.
+
+/// note | Teknik Detaylar
+
+`yield` ile dependency'leriniz varsa, çıkış (exit) kodu middleware'den *sonra* çalışır.
+
+Herhangi bir background task varsa ([Background Tasks](background-tasks.md){.internal-link target=_blank} bölümünde ele alınıyor, ileride göreceksiniz), bunlar tüm middleware'ler *tamamlandıktan sonra* çalışır.
+
+///
+
+## Middleware Oluşturma { #create-a-middleware }
+
+Bir middleware oluşturmak için bir fonksiyonun üzerine `@app.middleware("http")` decorator'ünü kullanırsınız.
+
+Middleware fonksiyonu şunları alır:
+
+* `request`.
+* Parametre olarak `request` alacak bir `call_next` fonksiyonu.
+ * Bu fonksiyon `request`'i ilgili *path operation*'a iletir.
+ * Ardından ilgili *path operation* tarafından üretilen `response`'u döndürür.
+* Sonrasında `response`'u döndürmeden önce ayrıca değiştirebilirsiniz.
+
+{* ../../docs_src/middleware/tutorial001_py39.py hl[8:9,11,14] *}
+
+/// tip | İpucu
+
+Özel (proprietary) header'lar `X-` prefix'i kullanılarak eklenebilir, bunu aklınızda tutun.
+
+Ancak tarayıcıdaki bir client'ın görebilmesini istediğiniz özel header'larınız varsa, bunları CORS konfigürasyonlarınıza ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) eklemeniz gerekir. Bunun için, Starlette'ın CORS dokümanlarında belgelenen `expose_headers` parametresini kullanın.
+
+///
+
+/// note | Teknik Detaylar
+
+`from starlette.requests import Request` da kullanabilirdiniz.
+
+**FastAPI** bunu geliştirici olarak size kolaylık olsun diye sunar. Ancak doğrudan Starlette'tan gelir.
+
+///
+
+### `response`'tan Önce ve Sonra { #before-and-after-the-response }
+
+Herhangi bir *path operation* `request`'i almadan önce, `request` ile birlikte çalışacak kod ekleyebilirsiniz.
+
+Ayrıca `response` üretildikten sonra, geri döndürmeden önce de kod çalıştırabilirsiniz.
+
+Örneğin, request'i işleyip response üretmenin kaç saniye sürdüğünü içeren `X-Process-Time` adlı özel bir header ekleyebilirsiniz:
+
+{* ../../docs_src/middleware/tutorial001_py39.py hl[10,12:13] *}
+
+/// tip | İpucu
+
+Burada `time.time()` yerine `time.perf_counter()` kullanıyoruz, çünkü bu kullanım senaryolarında daha hassas olabilir. 🤓
+
+///
+
+## Birden Fazla Middleware Çalıştırma Sırası { #multiple-middleware-execution-order }
+
+`@app.middleware()` decorator'ü veya `app.add_middleware()` metodu ile birden fazla middleware eklediğinizde, eklenen her yeni middleware uygulamayı sarar ve bir stack oluşturur. En son eklenen middleware en *dıştaki* (outermost), ilk eklenen ise en *içteki* (innermost) olur.
+
+Request tarafında önce en *dıştaki* middleware çalışır.
+
+Response tarafında ise en son o çalışır.
+
+Örneğin:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+Bu, aşağıdaki çalıştırma sırasını oluşturur:
+
+* **Request**: MiddlewareB → MiddlewareA → route
+
+* **Response**: route → MiddlewareA → MiddlewareB
+
+Bu stack davranışı, middleware'lerin öngörülebilir ve kontrol edilebilir bir sırayla çalıştırılmasını sağlar.
+
+## Diğer Middleware'ler { #other-middlewares }
+
+Diğer middleware'ler hakkında daha fazlasını daha sonra [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank} bölümünde okuyabilirsiniz.
+
+Bir sonraki bölümde, middleware ile CORS'un nasıl ele alınacağını göreceksiniz.
diff --git a/docs/tr/docs/tutorial/path-operation-configuration.md b/docs/tr/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 000000000..610b863a4
--- /dev/null
+++ b/docs/tr/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# Path Operation Yapılandırması { #path-operation-configuration }
+
+Onu yapılandırmak için *path operation decorator*’ınıza geçebileceğiniz çeşitli parametreler vardır.
+
+/// warning | Uyarı
+
+Bu parametrelerin *path operation function*’ınıza değil, doğrudan *path operation decorator*’ına verildiğine dikkat edin.
+
+///
+
+## Response Status Code { #response-status-code }
+
+*Path operation*’ınızın response’unda kullanılacak (HTTP) `status_code`’u tanımlayabilirsiniz.
+
+`404` gibi `int` kodu doğrudan verebilirsiniz.
+
+Ancak her sayısal kodun ne işe yaradığını hatırlamıyorsanız, `status` içindeki kısayol sabitlerini kullanabilirsiniz:
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+Bu status code response’da kullanılacak ve OpenAPI şemasına eklenecektir.
+
+/// note | Teknik Detaylar
+
+`from starlette import status` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak işinizi kolaylaştırmak için `starlette.status`’u `fastapi.status` olarak da sunar. Ancak kaynağı doğrudan Starlette’tir.
+
+///
+
+## Tags { #tags }
+
+*Path operation*’ınıza tag ekleyebilirsiniz; `tags` parametresine `str` öğelerinden oluşan bir `list` verin (genellikle tek bir `str`):
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+Bunlar OpenAPI şemasına eklenecek ve otomatik dokümantasyon arayüzleri tarafından kullanılacaktır:
+
+
+
+### Enum ile Tags { #tags-with-enums }
+
+Büyük bir uygulamanız varsa, zamanla **birden fazla tag** birikebilir ve ilişkili *path operation*’lar için her zaman **aynı tag**’i kullandığınızdan emin olmak isteyebilirsiniz.
+
+Bu durumlarda tag’leri bir `Enum` içinde tutmak mantıklı olabilir.
+
+**FastAPI** bunu düz string’lerde olduğu gibi aynı şekilde destekler:
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py39.py hl[1,8:10,13,18] *}
+
+## Özet ve açıklama { #summary-and-description }
+
+Bir `summary` ve `description` ekleyebilirsiniz:
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *}
+
+## Docstring’den Description { #description-from-docstring }
+
+Açıklamalar genelde uzun olur ve birden fazla satıra yayılır; bu yüzden *path operation* açıklamasını, fonksiyonun içinde docstring olarak tanımlayabilirsiniz; **FastAPI** de onu buradan okur.
+
+Docstring içinde Markdown yazabilirsiniz; doğru şekilde yorumlanır ve gösterilir (docstring girintisi dikkate alınarak).
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+Interactive docs’ta şöyle kullanılacaktır:
+
+
+
+## Response description { #response-description }
+
+`response_description` parametresi ile response açıklamasını belirtebilirsiniz:
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *}
+
+/// info | Bilgi
+
+`response_description` özellikle response’u ifade eder; `description` ise genel olarak *path operation*’ı ifade eder.
+
+///
+
+/// check | Ek bilgi
+
+OpenAPI, her *path operation* için bir response description zorunlu kılar.
+
+Bu yüzden siz sağlamazsanız, **FastAPI** otomatik olarak "Successful response" üretir.
+
+///
+
+
+
+## Bir *path operation*’ı Deprecate Etmek { #deprecate-a-path-operation }
+
+Bir *path operation*’ı kaldırmadan, deprecated olarak işaretlemeniz gerekiyorsa `deprecated` parametresini verin:
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
+
+Interactive docs’ta deprecated olduğu net şekilde işaretlenecektir:
+
+
+
+Deprecated olan ve olmayan *path operation*’ların nasıl göründüğüne bakın:
+
+
+
+## Özet { #recap }
+
+*Path operation*’larınızı, *path operation decorator*’larına parametre geçirerek kolayca yapılandırabilir ve metadata ekleyebilirsiniz.
diff --git a/docs/tr/docs/tutorial/path-params-numeric-validations.md b/docs/tr/docs/tutorial/path-params-numeric-validations.md
new file mode 100644
index 000000000..e0118d71d
--- /dev/null
+++ b/docs/tr/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,154 @@
+# Path Parametreleri ve Sayısal Doğrulamalar { #path-parameters-and-numeric-validations }
+
+`Query` ile query parametreleri için daha fazla doğrulama ve metadata tanımlayabildiğiniz gibi, `Path` ile de path parametreleri için aynı tür doğrulama ve metadata tanımlayabilirsiniz.
+
+## `Path`'i İçe Aktarın { #import-path }
+
+Önce `fastapi` içinden `Path`'i ve `Annotated`'ı içe aktarın:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
+
+/// info | Bilgi
+
+FastAPI, 0.95.0 sürümünde `Annotated` desteğini ekledi (ve bunu önermeye başladı).
+
+Daha eski bir sürüm kullanıyorsanız, `Annotated` kullanmaya çalıştığınızda hata alırsınız.
+
+`Annotated` kullanmadan önce mutlaka FastAPI sürümünü en az 0.95.1 olacak şekilde [FastAPI sürümünü yükseltin](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}.
+
+///
+
+## Metadata Tanımlayın { #declare-metadata }
+
+`Query` için geçerli olan parametrelerin aynısını tanımlayabilirsiniz.
+
+Örneğin, `item_id` path parametresi için bir `title` metadata değeri tanımlamak isterseniz şunu yazabilirsiniz:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
+
+/// note | Not
+
+Bir path parametresi her zaman zorunludur, çünkü path'in bir parçası olmak zorundadır. `None` ile tanımlasanız veya bir varsayılan değer verseniz bile bu hiçbir şeyi değiştirmez; yine her zaman zorunlu olur.
+
+///
+
+## Parametreleri İhtiyacınıza Göre Sıralayın { #order-the-parameters-as-you-need }
+
+/// tip | İpucu
+
+`Annotated` kullanıyorsanız, bu muhtemelen o kadar önemli ya da gerekli değildir.
+
+///
+
+Diyelim ki query parametresi `q`'yu zorunlu bir `str` olarak tanımlamak istiyorsunuz.
+
+Ayrıca bu parametre için başka bir şey tanımlamanız gerekmiyor; dolayısıyla `Query` kullanmanıza da aslında gerek yok.
+
+Ancak `item_id` path parametresi için yine de `Path` kullanmanız gerekiyor. Ve bir sebepten `Annotated` kullanmak istemiyorsunuz.
+
+Python, "default" değeri olan bir parametreyi, "default" değeri olmayan bir parametreden önce yazarsanız şikayet eder.
+
+Ama bunların sırasını değiştirebilir ve default değeri olmayan parametreyi (query parametresi `q`) en başa koyabilirsiniz.
+
+Bu **FastAPI** için önemli değildir. FastAPI parametreleri isimlerine, tiplerine ve default tanımlarına (`Query`, `Path`, vb.) göre tespit eder; sırayla ilgilenmez.
+
+Dolayısıyla fonksiyonunuzu şöyle tanımlayabilirsiniz:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
+
+Ancak şunu unutmayın: `Annotated` kullanırsanız bu problem olmaz; çünkü `Query()` veya `Path()` için fonksiyon parametresi default değerlerini kullanmıyorsunuz.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *}
+
+## Parametreleri İhtiyacınıza Göre Sıralayın: Küçük Hileler { #order-the-parameters-as-you-need-tricks }
+
+/// tip | İpucu
+
+`Annotated` kullanıyorsanız, bu muhtemelen o kadar önemli ya da gerekli değildir.
+
+///
+
+İşte bazen işe yarayan **küçük bir hile**; ama çok sık ihtiyacınız olmayacak.
+
+Şunları yapmak istiyorsanız:
+
+* `q` query parametresini `Query` kullanmadan ve herhangi bir default değer vermeden tanımlamak
+* `item_id` path parametresini `Path` kullanarak tanımlamak
+* bunları farklı bir sırada yazmak
+* `Annotated` kullanmamak
+
+...Python bunun için küçük, özel bir sözdizimi sunar.
+
+Fonksiyonun ilk parametresi olarak `*` geçin.
+
+Python bu `*` ile bir şey yapmaz; ama bundan sonraki tüm parametrelerin keyword argument (anahtar-değer çiftleri) olarak çağrılması gerektiğini bilir; buna kwargs da denir. Default değerleri olmasa bile.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+
+### `Annotated` ile Daha İyi { #better-with-annotated }
+
+Şunu da unutmayın: `Annotated` kullanırsanız, fonksiyon parametresi default değerlerini kullanmadığınız için bu sorun ortaya çıkmaz ve muhtemelen `*` kullanmanız da gerekmez.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+
+## Sayı Doğrulamaları: Büyük Eşit { #number-validations-greater-than-or-equal }
+
+`Query` ve `Path` (ve ileride göreceğiniz diğerleri) ile sayı kısıtları tanımlayabilirsiniz.
+
+Burada `ge=1` ile, `item_id` değerinin `1`'den "`g`reater than or `e`qual" olacak şekilde bir tam sayı olması gerekir.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## Sayı Doğrulamaları: Büyük ve Küçük Eşit { #number-validations-greater-than-and-less-than-or-equal }
+
+Aynısı şunlar için de geçerlidir:
+
+* `gt`: `g`reater `t`han
+* `le`: `l`ess than or `e`qual
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+
+## Sayı Doğrulamaları: `float` Değerler, Büyük ve Küçük { #number-validations-floats-greater-than-and-less-than }
+
+Sayı doğrulamaları `float` değerler için de çalışır.
+
+Burada gt tanımlayabilmek (sadece ge değil) önemli hale gelir. Çünkü örneğin bir değerin `0`'dan büyük olmasını isteyebilirsiniz; `1`'den küçük olsa bile.
+
+Bu durumda `0.5` geçerli bir değer olur. Ancak `0.0` veya `0` geçerli olmaz.
+
+Aynısı lt için de geçerlidir.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+
+## Özet { #recap }
+
+`Query`, `Path` (ve henüz görmedikleriniz) ile metadata ve string doğrulamalarını, [Query Parametreleri ve String Doğrulamalar](query-params-str-validations.md){.internal-link target=_blank} bölümündekiyle aynı şekilde tanımlayabilirsiniz.
+
+Ayrıca sayısal doğrulamalar da tanımlayabilirsiniz:
+
+* `gt`: `g`reater `t`han
+* `ge`: `g`reater than or `e`qual
+* `lt`: `l`ess `t`han
+* `le`: `l`ess than or `e`qual
+
+/// info | Bilgi
+
+`Query`, `Path` ve ileride göreceğiniz diğer class'lar ortak bir `Param` class'ının alt class'larıdır.
+
+Hepsi, gördüğünüz ek doğrulama ve metadata parametrelerini paylaşır.
+
+///
+
+/// note | Teknik Detaylar
+
+`Query`, `Path` ve diğerlerini `fastapi` içinden import ettiğinizde, bunlar aslında birer fonksiyondur.
+
+Çağrıldıklarında, aynı isme sahip class'ların instance'larını döndürürler.
+
+Yani `Query`'yi import edersiniz; bu bir fonksiyondur. Onu çağırdığınızda, yine `Query` adlı bir class'ın instance'ını döndürür.
+
+Bu fonksiyonlar (class'ları doğrudan kullanmak yerine) editörünüzün type'larıyla ilgili hata işaretlememesi için vardır.
+
+Bu sayede, bu hataları yok saymak üzere özel ayarlar eklemeden normal editörünüzü ve coding araçlarınızı kullanabilirsiniz.
+
+///
diff --git a/docs/tr/docs/tutorial/query-param-models.md b/docs/tr/docs/tutorial/query-param-models.md
new file mode 100644
index 000000000..75139a677
--- /dev/null
+++ b/docs/tr/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Query Parameter Modelleri { #query-parameter-models }
+
+Birbirleriyle ilişkili bir **query parameter** grubunuz varsa, bunları tanımlamak için bir **Pydantic model** oluşturabilirsiniz.
+
+Böylece **modeli yeniden kullanabilir**, **birden fazla yerde** tekrar tekrar kullanabilir ve tüm parametreler için validation (doğrulama) ile metadata’yı tek seferde tanımlayabilirsiniz. 😎
+
+/// note | Not
+
+Bu özellik FastAPI `0.115.0` sürümünden beri desteklenmektedir. 🤓
+
+///
+
+## Pydantic Model ile Query Parameters { #query-parameters-with-a-pydantic-model }
+
+İhtiyacınız olan **query parameter**’ları bir **Pydantic model** içinde tanımlayın, ardından parametreyi `Query` olarak belirtin:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI**, request’teki **query parameter**’lardan **her field** için veriyi **extract** eder ve tanımladığınız Pydantic model’i size verir.
+
+## Dokümanları Kontrol Edin { #check-the-docs }
+
+Query parameter’ları `/docs` altındaki dokümantasyon arayüzünde görebilirsiniz:
+
+
+
+
+### Varsayılanlarla query parametresi listesi / birden fazla değer { #query-parameter-list-multiple-values-with-defaults }
+
+Hiç değer verilmezse varsayılan bir `list` de tanımlayabilirsiniz:
+
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *}
+
+Şu adrese giderseniz:
+
+```
+http://localhost:8000/items/
+```
+
+`q`’nun varsayılanı `["foo", "bar"]` olur ve response şöyle olur:
+
+```JSON
+{
+ "q": [
+ "foo",
+ "bar"
+ ]
+}
+```
+
+#### Sadece `list` kullanmak { #using-just-list }
+
+`list[str]` yerine doğrudan `list` de kullanabilirsiniz:
+
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}
+
+/// note | Not
+
+Bu durumda FastAPI, listenin içeriğini kontrol etmez.
+
+Örneğin `list[int]`, listenin içeriğinin integer olduğunu kontrol eder (ve dokümante eder). Ancak tek başına `list` bunu yapmaz.
+
+///
+
+## Daha fazla metadata tanımlayın { #declare-more-metadata }
+
+Parametre hakkında daha fazla bilgi ekleyebilirsiniz.
+
+Bu bilgiler oluşturulan OpenAPI’a dahil edilir ve dokümantasyon arayüzleri ile harici araçlar tarafından kullanılır.
+
+/// note | Not
+
+Farklı araçların OpenAPI desteği farklı seviyelerde olabilir.
+
+Bazıları tanımladığınız ek bilgilerin hepsini göstermeyebilir; ancak çoğu durumda eksik özellik geliştirme planındadır.
+
+///
+
+Bir `title` ekleyebilirsiniz:
+
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
+
+Ve bir `description`:
+
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
+
+## Alias parametreleri { #alias-parameters }
+
+Parametrenin adının `item-query` olmasını istediğinizi düşünün.
+
+Örneğin:
+
+```
+http://127.0.0.1:8000/items/?item-query=foobaritems
+```
+
+Ancak `item-query` geçerli bir Python değişken adı değildir.
+
+En yakın seçenek `item_query` olur.
+
+Ama sizin hâlâ tam olarak `item-query` olmasına ihtiyacınız var...
+
+O zaman bir `alias` tanımlayabilirsiniz; bu alias, parametre değerini bulmak için kullanılacaktır:
+
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
+
+## Parametreleri deprecated yapmak { #deprecating-parameters }
+
+Diyelim ki artık bu parametreyi istemiyorsunuz.
+
+Bazı client’lar hâlâ kullandığı için bir süre tutmanız gerekiyor, ama dokümanların bunu açıkça deprecated olarak göstermesini istiyorsunuz.
+
+O zaman `Query`’ye `deprecated=True` parametresini geçin:
+
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
+
+Dokümanlarda şöyle görünür:
+
+
+
+## Parametreleri OpenAPI’dan hariç tutun { #exclude-parameters-from-openapi }
+
+Oluşturulan OpenAPI şemasından (dolayısıyla otomatik dokümantasyon sistemlerinden) bir query parametresini hariç tutmak için `Query`’nin `include_in_schema` parametresini `False` yapın:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## Özel Doğrulama { #custom-validation }
+
+Yukarıdaki parametrelerle yapılamayan bazı **özel doğrulama** ihtiyaçlarınız olabilir.
+
+Bu durumlarda, normal doğrulamadan sonra (ör. değerin `str` olduğunun doğrulanmasından sonra) uygulanacak bir **custom validator function** kullanabilirsiniz.
+
+Bunu, `Annotated` içinde Pydantic’in `AfterValidator`’ını kullanarak yapabilirsiniz.
+
+/// tip | İpucu
+
+Pydantic’te `BeforeValidator` ve başka validator’lar da vardır. 🤓
+
+///
+
+Örneğin bu custom validator, bir item ID’sinin ISBN kitap numarası için `isbn-` ile veya IMDB film URL ID’si için `imdb-` ile başladığını kontrol eder:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | Bilgi
+
+Bu özellik Pydantic 2 ve üzeri sürümlerde mevcuttur. 😎
+
+///
+
+/// tip | İpucu
+
+Veritabanı veya başka bir API gibi herhangi bir **harici bileşen** ile iletişim gerektiren bir doğrulama yapmanız gerekiyorsa, bunun yerine **FastAPI Dependencies** kullanmalısınız; onları ileride öğreneceksiniz.
+
+Bu custom validator’lar, request’te sağlanan **yalnızca** **aynı veri** ile kontrol edilebilen şeyler içindir.
+
+///
+
+### O Kodu Anlamak { #understand-that-code }
+
+Önemli nokta, **`Annotated` içinde bir fonksiyonla birlikte `AfterValidator` kullanmak**. İsterseniz bu kısmı atlayabilirsiniz. 🤸
+
+---
+
+Ama bu örnek kodun detaylarını merak ediyorsanız, birkaç ek bilgi:
+
+#### `value.startswith()` ile String { #string-with-value-startswith }
+
+Fark ettiniz mi? `value.startswith()` ile bir string, tuple alabilir ve tuple içindeki her değeri kontrol eder:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### Rastgele Bir Item { #a-random-item }
+
+`data.items()` ile, her dictionary öğesi için key ve value içeren tuple’lardan oluşan bir iterable object elde ederiz.
+
+Bu iterable object’i `list(data.items())` ile düzgün bir `list`’e çeviririz.
+
+Ardından `random.choice()` ile list’ten **rastgele bir değer** alırız; yani `(id, name)` içeren bir tuple elde ederiz. Şuna benzer: `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
+
+Sonra tuple içindeki bu **iki değeri** `id` ve `name` değişkenlerine **atarız**.
+
+Böylece kullanıcı bir item ID’si vermemiş olsa bile yine de rastgele bir öneri alır.
+
+...bütün bunları **tek bir basit satırda** yapıyoruz. 🤯 Python’u sevmemek elde mi? 🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## Özet { #recap }
+
+Parametreleriniz için ek doğrulamalar ve metadata tanımlayabilirsiniz.
+
+Genel doğrulamalar ve metadata:
+
+* `alias`
+* `title`
+* `description`
+* `deprecated`
+
+String’lere özel doğrulamalar:
+
+* `min_length`
+* `max_length`
+* `pattern`
+
+`AfterValidator` ile custom doğrulamalar.
+
+Bu örneklerde `str` değerleri için doğrulamanın nasıl tanımlanacağını gördünüz.
+
+Sayılar gibi diğer tipler için doğrulamaları nasıl tanımlayacağınızı öğrenmek için sonraki bölümlere geçin.
diff --git a/docs/tr/docs/tutorial/request-files.md b/docs/tr/docs/tutorial/request-files.md
new file mode 100644
index 000000000..0bbc557e0
--- /dev/null
+++ b/docs/tr/docs/tutorial/request-files.md
@@ -0,0 +1,176 @@
+# Request Dosyaları { #request-files }
+
+İstemcinin upload edeceği dosyaları `File` kullanarak tanımlayabilirsiniz.
+
+/// info | Bilgi
+
+Upload edilen dosyaları alabilmek için önce `python-multipart` yükleyin.
+
+Bir [virtual environment](../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan, aktive ettiğinizden ve ardından paketi yüklediğinizden emin olun. Örneğin:
+
+```console
+$ pip install python-multipart
+```
+
+Bunun nedeni, upload edilen dosyaların "form data" olarak gönderilmesidir.
+
+///
+
+## `File` Import Edin { #import-file }
+
+`fastapi` içinden `File` ve `UploadFile` import edin:
+
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *}
+
+## `File` Parametrelerini Tanımlayın { #define-file-parameters }
+
+`Body` veya `Form` için yaptığınız gibi dosya parametreleri oluşturun:
+
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *}
+
+/// info | Bilgi
+
+`File`, doğrudan `Form`’dan türeyen bir sınıftır.
+
+Ancak unutmayın: `fastapi` içinden `Query`, `Path`, `File` ve diğerlerini import ettiğinizde, bunlar aslında özel sınıflar döndüren fonksiyonlardır.
+
+///
+
+/// tip | İpucu
+
+File body’leri tanımlamak için `File` kullanmanız gerekir; aksi halde parametreler query parametreleri veya body (JSON) parametreleri olarak yorumlanır.
+
+///
+
+Dosyalar "form data" olarak upload edilir.
+
+*path operation function* parametrenizin tipini `bytes` olarak tanımlarsanız, **FastAPI** dosyayı sizin için okur ve içeriği `bytes` olarak alırsınız.
+
+Bunun, dosyanın tüm içeriğinin bellekte tutulacağı anlamına geldiğini unutmayın. Küçük dosyalar için iyi çalışır.
+
+Ancak bazı durumlarda `UploadFile` kullanmak size fayda sağlayabilir.
+
+## `UploadFile` ile Dosya Parametreleri { #file-parameters-with-uploadfile }
+
+Tipi `UploadFile` olan bir dosya parametresi tanımlayın:
+
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *}
+
+`UploadFile` kullanmanın `bytes`’a göre birkaç avantajı vardır:
+
+* Parametrenin varsayılan değerinde `File()` kullanmak zorunda değilsiniz.
+* "Spooled" bir dosya kullanır:
+ * Belirli bir maksimum boyuta kadar bellekte tutulan, bu limiti aşınca diske yazılan bir dosya.
+* Bu sayede görüntüler, videolar, büyük binary’ler vb. gibi büyük dosyalarda tüm belleği tüketmeden iyi çalışır.
+* Upload edilen dosyadan metadata alabilirsiniz.
+* file-like bir `async` arayüze sahiptir.
+* `SpooledTemporaryFile` nesnesini dışa açar; bunu, file-like nesne bekleyen diğer library’lere doğrudan geçebilirsiniz.
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` şu attribute’lara sahiptir:
+
+* `filename`: Upload edilen orijinal dosya adını içeren bir `str` (örn. `myimage.jpg`).
+* `content_type`: Content type’ı (MIME type / media type) içeren bir `str` (örn. `image/jpeg`).
+* `file`: Bir `SpooledTemporaryFile` (bir file-like nesne). Bu, "file-like" nesne bekleyen diğer fonksiyonlara veya library’lere doğrudan verebileceğiniz gerçek Python file nesnesidir.
+
+`UploadFile` şu `async` method’lara sahiptir. Bunların hepsi altta ilgili dosya method’larını çağırır (dahili `SpooledTemporaryFile` kullanarak).
+
+* `write(data)`: Dosyaya `data` (`str` veya `bytes`) yazar.
+* `read(size)`: Dosyadan `size` (`int`) kadar byte/karakter okur.
+* `seek(offset)`: Dosyada `offset` (`int`) byte pozisyonuna gider.
+ * Örn. `await myfile.seek(0)` dosyanın başına gider.
+ * Bu, özellikle bir kez `await myfile.read()` çalıştırdıysanız ve sonra içeriği yeniden okumaya ihtiyaç duyuyorsanız faydalıdır.
+* `close()`: Dosyayı kapatır.
+
+Bu method’ların hepsi `async` olduğundan, bunları "await" etmeniz gerekir.
+
+Örneğin, bir `async` *path operation function* içinde içeriği şöyle alabilirsiniz:
+
+```Python
+contents = await myfile.read()
+```
+
+Normal bir `def` *path operation function* içindeyseniz `UploadFile.file`’a doğrudan erişebilirsiniz, örneğin:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | `async` Teknik Detaylar
+
+`async` method’ları kullandığınızda, **FastAPI** dosya method’larını bir threadpool içinde çalıştırır ve bunları await eder.
+
+///
+
+/// note | Starlette Teknik Detaylar
+
+**FastAPI**’nin `UploadFile`’ı doğrudan **Starlette**’in `UploadFile`’ından türetilmiştir; ancak **Pydantic** ve FastAPI’nin diğer parçalarıyla uyumlu olması için bazı gerekli eklemeler yapar.
+
+///
+
+## "Form Data" Nedir { #what-is-form-data }
+
+HTML formları (``) veriyi server’a gönderirken normalde JSON’dan farklı, veri için "özel" bir encoding kullanır.
+
+**FastAPI**, JSON yerine bu veriyi doğru yerden okuyacağından emin olur.
+
+/// note | Teknik Detaylar
+
+Formlardan gelen veri, dosya içermiyorsa normalde "media type" olarak `application/x-www-form-urlencoded` ile encode edilir.
+
+Ancak form dosya içeriyorsa `multipart/form-data` olarak encode edilir. `File` kullanırsanız, **FastAPI** dosyaları body’nin doğru kısmından alması gerektiğini bilir.
+
+Bu encoding’ler ve form alanları hakkında daha fazla okumak isterseniz MDN web dokümanlarındaki POST sayfasına bakın.
+
+///
+
+/// warning | Uyarı
+
+Bir *path operation* içinde birden fazla `File` ve `Form` parametresi tanımlayabilirsiniz, ancak JSON olarak almayı beklediğiniz `Body` alanlarını ayrıca tanımlayamazsınız; çünkü request body `application/json` yerine `multipart/form-data` ile encode edilmiş olur.
+
+Bu, **FastAPI**’nin bir kısıtı değildir; HTTP protocol’ünün bir parçasıdır.
+
+///
+
+## Opsiyonel Dosya Upload { #optional-file-upload }
+
+Standart type annotation’ları kullanıp varsayılan değeri `None` yaparak bir dosyayı opsiyonel hale getirebilirsiniz:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## Ek Metadata ile `UploadFile` { #uploadfile-with-additional-metadata }
+
+Ek metadata ayarlamak için `UploadFile` ile birlikte `File()` da kullanabilirsiniz. Örneğin:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+
+## Birden Fazla Dosya Upload { #multiple-file-uploads }
+
+Aynı anda birden fazla dosya upload etmek mümkündür.
+
+Bu dosyalar, "form data" ile gönderilen aynı "form field" ile ilişkilendirilir.
+
+Bunu kullanmak için `bytes` veya `UploadFile` listesini tanımlayın:
+
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+
+Tanımladığınız gibi, `bytes` veya `UploadFile`’lardan oluşan bir `list` alırsınız.
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import HTMLResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştiriciye kolaylık olsun diye `starlette.responses` modülünü `fastapi.responses` olarak da sağlar. Ancak mevcut response’ların çoğu doğrudan Starlette’ten gelir.
+
+///
+
+### Ek Metadata ile Birden Fazla Dosya Upload { #multiple-file-uploads-with-additional-metadata }
+
+Daha önce olduğu gibi, `UploadFile` için bile ek parametreler ayarlamak amacıyla `File()` kullanabilirsiniz:
+
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+
+## Özet { #recap }
+
+Request’te (form data olarak gönderilen) upload edilecek dosyaları tanımlamak için `File`, `bytes` ve `UploadFile` kullanın.
diff --git a/docs/tr/docs/tutorial/request-form-models.md b/docs/tr/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..c35f956fc
--- /dev/null
+++ b/docs/tr/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Form Model'leri { #form-models }
+
+FastAPI'de **form field**'larını tanımlamak için **Pydantic model**'lerini kullanabilirsiniz.
+
+/// info | Bilgi
+
+Form'ları kullanmak için önce `python-multipart`'ı yükleyin.
+
+Bir [virtual environment](../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan, onu etkinleştirdiğinizden ve ardından paketi kurduğunuzdan emin olun. Örneğin:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Not
+
+Bu özellik FastAPI `0.113.0` sürümünden itibaren desteklenmektedir. 🤓
+
+///
+
+## Form'lar için Pydantic Model'leri { #pydantic-models-for-forms }
+
+Sadece, **form field** olarak almak istediğiniz alanlarla bir **Pydantic model** tanımlayın ve ardından parametreyi `Form` olarak bildirin:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI**, request içindeki **form data**'dan **her bir field** için veriyi **çıkarır** ve size tanımladığınız Pydantic model'ini verir.
+
+## Dokümanları Kontrol Edin { #check-the-docs }
+
+Bunu `/docs` altındaki doküman arayüzünde doğrulayabilirsiniz:
+
+
+
+
+Ve her iki model de etkileşimli API dokümantasyonunda kullanılır:
+
+
+
+## Diğer Return Type Annotation’ları { #other-return-type-annotations }
+
+Bazı durumlarda Pydantic field olarak geçerli olmayan bir şey döndürebilir ve bunu fonksiyonda annotate edebilirsiniz; amaç sadece araçların (editör, mypy vb.) sağladığı desteği almaktır.
+
+### Doğrudan Response Döndürmek { #return-a-response-directly }
+
+En yaygın durum, [ileri seviye dokümanlarda daha sonra anlatıldığı gibi doğrudan bir Response döndürmektir](../advanced/response-directly.md){.internal-link target=_blank}.
+
+{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
+
+Bu basit durum FastAPI tarafından otomatik olarak ele alınır; çünkü dönüş tipi annotation’ı `Response` class’ıdır (veya onun bir subclass’ı).
+
+Araçlar da memnun olur; çünkü hem `RedirectResponse` hem `JSONResponse`, `Response`’un subclass’ıdır. Yani type annotation doğrudur.
+
+### Bir Response Subclass’ını Annotate Etmek { #annotate-a-response-subclass }
+
+Type annotation içinde `Response`’un bir subclass’ını da kullanabilirsiniz:
+
+{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
+
+Bu da çalışır; çünkü `RedirectResponse`, `Response`’un subclass’ıdır ve FastAPI bu basit durumu otomatik olarak yönetir.
+
+### Geçersiz Return Type Annotation’ları { #invalid-return-type-annotations }
+
+Ancak geçerli bir Pydantic tipi olmayan başka rastgele bir obje (ör. bir veritabanı objesi) döndürür ve fonksiyonu da öyle annotate ederseniz, FastAPI bu type annotation’dan bir Pydantic response model oluşturmaya çalışır ve başarısız olur.
+
+Aynı şey, farklı tipler arasında bir union kullandığınızda ve bu tiplerden biri veya birkaçı geçerli bir Pydantic tipi değilse de olur; örneğin şu kullanım patlar 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+...bu, type annotation Pydantic tipi olmadığı ve tek bir `Response` class’ı (veya subclass’ı) olmadığı için başarısız olur; bu, bir `Response` ile bir `dict` arasında union’dır (ikiden herhangi biri).
+
+### Response Model’i Devre Dışı Bırakmak { #disable-response-model }
+
+Yukarıdaki örnekten devam edersek; FastAPI’nin varsayılan olarak yaptığı veri doğrulama, dokümantasyon, filtreleme vb. işlemleri istemiyor olabilirsiniz.
+
+Ancak yine de editörler ve type checker’lar (ör. mypy) gibi araçların desteğini almak için fonksiyonda dönüş tipi annotation’ını korumak isteyebilirsiniz.
+
+Bu durumda `response_model=None` ayarlayarak response model üretimini devre dışı bırakabilirsiniz:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+Bu, FastAPI’nin response model üretimini atlamasını sağlar; böylece FastAPI uygulamanızı etkilemeden ihtiyacınız olan herhangi bir return type annotation’ını kullanabilirsiniz. 🤓
+
+## Response Model encoding parametreleri { #response-model-encoding-parameters }
+
+Response model’inizde şu şekilde default değerler olabilir:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None` (veya Python 3.10’da `str | None = None`) için default `None`’dır.
+* `tax: float = 10.5` için default `10.5`’tir.
+* `tags: List[str] = []` için default, boş bir list’tir: `[]`.
+
+Ancak gerçekte kaydedilmedilerse, bunları sonuçtan çıkarmak isteyebilirsiniz.
+
+Örneğin NoSQL veritabanında çok sayıda optional attribute içeren modelleriniz varsa, default değerlerle dolu çok uzun JSON response’ları göndermek istemeyebilirsiniz.
+
+### `response_model_exclude_unset` parametresini kullanın { #use-the-response-model-exclude-unset-parameter }
+
+*Path operation decorator* parametresi olarak `response_model_exclude_unset=True` ayarlayabilirsiniz:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+böylece response’a default değerler dahil edilmez; yalnızca gerçekten set edilmiş değerler gelir.
+
+Dolayısıyla ID’si `foo` olan item için bu *path operation*’a request atarsanız, response (default değerler olmadan) şöyle olur:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | Bilgi
+
+Ayrıca şunları da kullanabilirsiniz:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+Bunlar, `exclude_defaults` ve `exclude_none` için Pydantic dokümanlarında anlatıldığı gibidir.
+
+///
+
+#### Default’u olan field’lar için değer içeren data { #data-with-values-for-fields-with-defaults }
+
+Ama data’nız modelde default değeri olan field’lar için değer içeriyorsa, örneğin ID’si `bar` olan item gibi:
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+bunlar response’a dahil edilir.
+
+#### Default değerlerle aynı değerlere sahip data { #data-with-the-same-values-as-the-defaults }
+
+Eğer data, default değerlerle aynı değerlere sahipse, örneğin ID’si `baz` olan item gibi:
+
+```Python hl_lines="3 5-6"
+{
+ "name": "Baz",
+ "description": None,
+ "price": 50.2,
+ "tax": 10.5,
+ "tags": []
+}
+```
+
+FastAPI yeterince akıllıdır (aslında Pydantic yeterince akıllıdır) ve `description`, `tax`, `tags` default ile aynı olsa bile bunların explicit olarak set edildiğini (default’tan alınmadığını) anlar.
+
+Bu yüzden JSON response içinde yer alırlar.
+
+/// tip | İpucu
+
+Default değerlerin yalnızca `None` olmak zorunda olmadığını unutmayın.
+
+Bir list (`[]`), `10.5` gibi bir `float` vb. olabilirler.
+
+///
+
+### `response_model_include` ve `response_model_exclude` { #response-model-include-and-response-model-exclude }
+
+Ayrıca *path operation decorator* parametreleri `response_model_include` ve `response_model_exclude`’u da kullanabilirsiniz.
+
+Bunlar; dahil edilecek attribute isimlerini (geri kalanını atlayarak) ya da hariç tutulacak attribute isimlerini (geri kalanını dahil ederek) belirten `str` değerlerinden oluşan bir `set` alır.
+
+Tek bir Pydantic model’iniz varsa ve output’tan bazı verileri hızlıca çıkarmak istiyorsanız, bu yöntem pratik bir kısayol olabilir.
+
+/// tip | İpucu
+
+Ancak yine de, bu parametreler yerine yukarıdaki yaklaşımı (birden fazla class kullanmayı) tercih etmeniz önerilir.
+
+Çünkü `response_model_include` veya `response_model_exclude` ile bazı attribute’ları atlıyor olsanız bile, uygulamanızın OpenAPI’sinde (ve dokümanlarda) üretilen JSON Schema hâlâ tam modelin JSON Schema’sı olacaktır.
+
+Bu durum, benzer şekilde çalışan `response_model_by_alias` için de geçerlidir.
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | İpucu
+
+`{"name", "description"}` sözdizimi, bu iki değere sahip bir `set` oluşturur.
+
+Bu, `set(["name", "description"])` ile eşdeğerdir.
+
+///
+
+#### `set` yerine `list` kullanmak { #using-lists-instead-of-sets }
+
+Yanlışlıkla `set` yerine `list` veya `tuple` kullanırsanız, FastAPI bunu yine `set`’e çevirir ve doğru şekilde çalışır:
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## Özet { #recap }
+
+Response model’leri tanımlamak ve özellikle private data’nın filtrelendiğinden emin olmak için *path operation decorator* parametresi `response_model`’i kullanın.
+
+Yalnızca explicit olarak set edilmiş değerleri döndürmek için `response_model_exclude_unset` kullanın.
diff --git a/docs/tr/docs/tutorial/response-status-code.md b/docs/tr/docs/tutorial/response-status-code.md
new file mode 100644
index 000000000..57ae7bde3
--- /dev/null
+++ b/docs/tr/docs/tutorial/response-status-code.md
@@ -0,0 +1,101 @@
+# Response Status Code { #response-status-code }
+
+Bir response model tanımlayabildiğiniz gibi, herhangi bir *path operation* içinde `status_code` parametresiyle response için kullanılacak HTTP status code'u da belirtebilirsiniz:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* vb.
+
+{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+
+/// note | Not
+
+`status_code`'un, "decorator" metodunun (`get`, `post`, vb.) bir parametresi olduğuna dikkat edin. Tüm parametreler ve body gibi, sizin *path operation function*'ınızın bir parametresi değildir.
+
+///
+
+`status_code` parametresi, HTTP status code'u içeren bir sayı alır.
+
+/// info | Bilgi
+
+Alternatif olarak `status_code`, Python'un `http.HTTPStatus`'ı gibi bir `IntEnum` da alabilir.
+
+///
+
+Bu sayede:
+
+* Response'da o status code döner.
+* OpenAPI şemasında (dolayısıyla kullanıcı arayüzlerinde de) bu şekilde dokümante edilir:
+
+
+
+/// note | Not
+
+Bazı response code'lar (bir sonraki bölümde göreceğiz) response'un bir body'ye sahip olmadığını belirtir.
+
+FastAPI bunu bilir ve response body olmadığını söyleyen OpenAPI dokümantasyonunu üretir.
+
+///
+
+## HTTP status code'lar hakkında { #about-http-status-codes }
+
+/// note | Not
+
+HTTP status code'ların ne olduğunu zaten biliyorsanız, bir sonraki bölüme geçin.
+
+///
+
+HTTP'de, response'un bir parçası olarak 3 basamaklı sayısal bir status code gönderirsiniz.
+
+Bu status code'ların tanınmalarını sağlayan bir isimleri de vardır; ancak önemli olan kısım sayıdır.
+
+Kısaca:
+
+* `100 - 199` "Information" içindir. Doğrudan nadiren kullanırsınız. Bu status code'lara sahip response'lar body içeremez.
+* **`200 - 299`** "Successful" response'lar içindir. En sık kullanacağınız aralık budur.
+ * `200`, varsayılan status code'dur ve her şeyin "OK" olduğunu ifade eder.
+ * Başka bir örnek `201` ("Created") olabilir. Genellikle veritabanında yeni bir kayıt oluşturduktan sonra kullanılır.
+ * Özel bir durum ise `204` ("No Content")'tür. Client'a döndürülecek içerik olmadığında kullanılır; bu nedenle response body olmamalıdır.
+* **`300 - 399`** "Redirection" içindir. Bu status code'lara sahip response'lar, `304` ("Not Modified") hariç, body içerebilir de içermeyebilir de; `304` kesinlikle body içermemelidir.
+* **`400 - 499`** "Client error" response'ları içindir. Muhtemelen en sık kullanacağınız ikinci aralık budur.
+ * Örneğin `404`, "Not Found" response'u içindir.
+ * Client kaynaklı genel hatalar için doğrudan `400` kullanabilirsiniz.
+* `500 - 599` server hataları içindir. Neredeyse hiç doğrudan kullanmazsınız. Uygulama kodunuzun bir bölümünde ya da server'da bir şeyler ters giderse, otomatik olarak bu status code'lardan biri döner.
+
+/// tip | İpucu
+
+Her bir status code hakkında daha fazla bilgi almak ve hangi kodun ne için kullanıldığını görmek için HTTP status code'lar hakkında MDN dokümantasyonuna göz atın.
+
+///
+
+## İsimleri hatırlamak için kısayol { #shortcut-to-remember-the-names }
+
+Önceki örneğe tekrar bakalım:
+
+{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+
+`201`, "Created" için kullanılan status code'dur.
+
+Ancak bu kodların her birinin ne anlama geldiğini ezberlemek zorunda değilsiniz.
+
+`fastapi.status` içindeki kolaylık değişkenlerini (convenience variables) kullanabilirsiniz.
+
+{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
+
+Bunlar sadece kolaylık sağlar; aynı sayıyı taşırlar. Ancak bu şekilde editörün autocomplete özelliğiyle kolayca bulabilirsiniz:
+
+
+
+/// note | Teknik Detaylar
+
+`from starlette import status` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olsun diye `starlette.status`'u `fastapi.status` olarak da sunar. Ancak bu aslında doğrudan Starlette'den gelir.
+
+///
+
+## Varsayılanı değiştirmek { #changing-the-default }
+
+Daha sonra, [İleri Düzey Kullanıcı Kılavuzu](../advanced/response-change-status-code.md){.internal-link target=_blank} içinde, burada tanımladığınız varsayılanın dışında farklı bir status code nasıl döndüreceğinizi göreceksiniz.
diff --git a/docs/tr/docs/tutorial/schema-extra-example.md b/docs/tr/docs/tutorial/schema-extra-example.md
new file mode 100644
index 000000000..a91dda892
--- /dev/null
+++ b/docs/tr/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# Request Örnek Verilerini Tanımlama { #declare-request-example-data }
+
+Uygulamanızın alabileceği veriler için örnekler (examples) tanımlayabilirsiniz.
+
+Bunu yapmanın birkaç yolu var.
+
+## Pydantic modellerinde ek JSON Schema verisi { #extra-json-schema-data-in-pydantic-models }
+
+Oluşturulan JSON Schema’ya eklenecek şekilde bir Pydantic model için `examples` tanımlayabilirsiniz.
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+Bu ek bilgi, o modelin çıktı **JSON Schema**’sına olduğu gibi eklenir ve API dokümanlarında kullanılır.
+
+Pydantic dokümanları: Configuration bölümünde anlatıldığı gibi, bir `dict` alan `model_config` niteliğini kullanabilirsiniz.
+
+Üretilen JSON Schema’da görünmesini istediğiniz (ör. `examples` dahil) her türlü ek veriyi içeren bir `dict` ile `"json_schema_extra"` ayarlayabilirsiniz.
+
+/// tip | İpucu
+
+Aynı tekniği JSON Schema’yı genişletmek ve kendi özel ek bilgilerinizi eklemek için de kullanabilirsiniz.
+
+Örneğin, bir frontend kullanıcı arayüzü için metadata eklemek vb. amaçlarla kullanılabilir.
+
+///
+
+/// info | Bilgi
+
+OpenAPI 3.1.0 (FastAPI 0.99.0’dan beri kullanılıyor), **JSON Schema** standardının bir parçası olan `examples` için destek ekledi.
+
+Bundan önce yalnızca tek bir örnek için `example` anahtar kelimesini destekliyordu. Bu hâlâ OpenAPI 3.1.0 tarafından desteklenir; ancak artık deprecated durumdadır ve JSON Schema standardının parçası değildir. Bu nedenle `example` kullanımını `examples`’a taşımanız önerilir. 🤓
+
+Daha fazlasını sayfanın sonunda okuyabilirsiniz.
+
+///
+
+## `Field` ek argümanları { #field-additional-arguments }
+
+Pydantic modelleriyle `Field()` kullanırken ek `examples` de tanımlayabilirsiniz:
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## JSON Schema - OpenAPI içinde `examples` { #examples-in-json-schema-openapi }
+
+Aşağıdakilerden herhangi birini kullanırken:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+OpenAPI içindeki **JSON Schema**’larına eklenecek ek bilgilerle birlikte bir `examples` grubu da tanımlayabilirsiniz.
+
+### `examples` ile `Body` { #body-with-examples }
+
+Burada `Body()` içinde beklenen veri için tek bir örnek içeren `examples` geçiriyoruz:
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### Doküman arayüzünde örnek { #example-in-the-docs-ui }
+
+Yukarıdaki yöntemlerden herhangi biriyle `/docs` içinde şöyle görünür:
+
+
+
+### Birden fazla `examples` ile `Body` { #body-with-multiple-examples }
+
+Elbette birden fazla `examples` da geçebilirsiniz:
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+Bunu yaptığınızda, örnekler bu body verisi için dahili **JSON Schema**’nın bir parçası olur.
+
+Buna rağmen, time of writing this, doküman arayüzünü gösteren araç olan Swagger UI, **JSON Schema** içindeki veriler için birden fazla örneği göstermeyi desteklemiyor. Ancak aşağıda bir çözüm yolu var.
+
+### OpenAPI’ye özel `examples` { #openapi-specific-examples }
+
+**JSON Schema** `examples`’ı desteklemeden önce OpenAPI, yine `examples` adlı farklı bir alanı destekliyordu.
+
+Bu **OpenAPI’ye özel** `examples`, OpenAPI spesifikasyonunda başka bir bölümde yer alır. Her bir JSON Schema’nın içinde değil, **her bir *path operation* detayları** içinde bulunur.
+
+Swagger UI da bu özel `examples` alanını bir süredir destekliyor. Dolayısıyla bunu, **doküman arayüzünde** farklı **örnekleri göstermek** için kullanabilirsiniz.
+
+OpenAPI’ye özel bu `examples` alanının şekli, (bir `list` yerine) **birden fazla örnek** içeren bir `dict`’tir; her örnek ayrıca **OpenAPI**’ye eklenecek ekstra bilgiler içerir.
+
+Bu, OpenAPI’nin içerdiği JSON Schema’ların içine girmez; bunun yerine doğrudan *path operation* üzerinde, dışarıda yer alır.
+
+### `openapi_examples` Parametresini Kullanma { #using-the-openapi-examples-parameter }
+
+FastAPI’de OpenAPI’ye özel `examples`’ı, şu araçlar için `openapi_examples` parametresiyle tanımlayabilirsiniz:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+`dict`’in anahtarları her bir örneği tanımlar; her bir değer ise başka bir `dict`’tir.
+
+`examples` içindeki her bir örnek `dict`’i şunları içerebilir:
+
+* `summary`: Örnek için kısa açıklama.
+* `description`: Markdown metni içerebilen uzun açıklama.
+* `value`: Gösterilecek gerçek örnek (ör. bir `dict`).
+* `externalValue`: `value`’a alternatif; örneğe işaret eden bir URL. Ancak bu, `value` kadar çok araç tarafından desteklenmiyor olabilir.
+
+Şöyle kullanabilirsiniz:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### Doküman Arayüzünde OpenAPI Örnekleri { #openapi-examples-in-the-docs-ui }
+
+`Body()`’ye `openapi_examples` eklendiğinde `/docs` şöyle görünür:
+
+
+
+## Teknik Detaylar { #technical-details }
+
+/// tip | İpucu
+
+Zaten **FastAPI** sürümü **0.99.0 veya üzerini** kullanıyorsanız, büyük olasılıkla bu detayları **atlanabilirsiniz**.
+
+Bunlar daha çok OpenAPI 3.1.0’ın henüz mevcut olmadığı eski sürümler için geçerlidir.
+
+Bunu kısa bir OpenAPI ve JSON Schema **tarih dersi** gibi düşünebilirsiniz. 🤓
+
+///
+
+/// warning | Uyarı
+
+Bunlar **JSON Schema** ve **OpenAPI** standartları hakkında oldukça teknik detaylardır.
+
+Yukarıdaki fikirler sizin için zaten çalışıyorsa bu kadarı yeterli olabilir; muhtemelen bu detaylara ihtiyacınız yoktur, gönül rahatlığıyla atlayabilirsiniz.
+
+///
+
+OpenAPI 3.1.0’dan önce OpenAPI, **JSON Schema**’nın daha eski ve değiştirilmiş bir sürümünü kullanıyordu.
+
+JSON Schema’da `examples` yoktu; bu yüzden OpenAPI, değiştirilmiş sürümüne kendi `example` alanını ekledi.
+
+OpenAPI ayrıca spesifikasyonun diğer bölümlerine de `example` ve `examples` alanlarını ekledi:
+
+* `Parameter Object` (spesifikasyonda) — FastAPI’de şunlar tarafından kullanılıyordu:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* `Request Body Object`; `content` alanında, `Media Type Object` üzerinde (spesifikasyonda) — FastAPI’de şunlar tarafından kullanılıyordu:
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info | Bilgi
+
+Bu eski OpenAPI’ye özel `examples` parametresi, FastAPI `0.103.0` sürümünden beri `openapi_examples` olarak kullanılıyor.
+
+///
+
+### JSON Schema’nın `examples` alanı { #json-schemas-examples-field }
+
+Sonrasında JSON Schema, spesifikasyonun yeni bir sürümüne `examples` alanını ekledi.
+
+Ardından yeni OpenAPI 3.1.0, bu yeni `examples` alanını içeren en güncel sürümü (JSON Schema 2020-12) temel aldı.
+
+Ve artık, deprecated olan eski tekil (ve özel) `example` alanına kıyasla bu yeni `examples` alanı önceliklidir.
+
+JSON Schema’daki bu yeni `examples` alanı, OpenAPI’de başka yerlerde kullanılan (yukarıda anlatılan) metadata’lı `dict` yapısından farklı olarak **sadece örneklerden oluşan bir `list`**’tir.
+
+/// info | Bilgi
+
+OpenAPI 3.1.0, JSON Schema ile bu yeni ve daha basit entegrasyonla yayımlandıktan sonra bile bir süre, otomatik dokümantasyonu sağlayan araç Swagger UI OpenAPI 3.1.0’ı desteklemiyordu (5.0.0 sürümünden beri destekliyor 🎉).
+
+Bu nedenle, FastAPI’nin 0.99.0 öncesi sürümleri OpenAPI 3.1.0’dan daha düşük sürümleri kullanmaya devam etti.
+
+///
+
+### Pydantic ve FastAPI `examples` { #pydantic-and-fastapi-examples }
+
+Bir Pydantic modelinin içine `schema_extra` ya da `Field(examples=["something"])` kullanarak `examples` eklediğinizde, bu örnek o Pydantic modelinin **JSON Schema**’sına eklenir.
+
+Ve Pydantic modelinin bu **JSON Schema**’sı, API’nizin **OpenAPI**’sine dahil edilir; ardından doküman arayüzünde kullanılır.
+
+FastAPI 0.99.0’dan önceki sürümlerde (0.99.0 ve üzeri daha yeni OpenAPI 3.1.0’ı kullanır) `Query()`, `Body()` vb. diğer araçlarla `example` veya `examples` kullandığınızda, bu örnekler o veriyi tanımlayan JSON Schema’ya (OpenAPI’nin kendi JSON Schema sürümüne bile) eklenmiyordu; bunun yerine doğrudan OpenAPI’deki *path operation* tanımına ekleniyordu (JSON Schema kullanan OpenAPI bölümlerinin dışında).
+
+Ancak artık FastAPI 0.99.0 ve üzeri OpenAPI 3.1.0 kullandığı (JSON Schema 2020-12) ve Swagger UI 5.0.0 ve üzeriyle birlikte, her şey daha tutarlı ve örnekler JSON Schema’ya dahil ediliyor.
+
+### Swagger UI ve OpenAPI’ye özel `examples` { #swagger-ui-and-openapi-specific-examples }
+
+Swagger UI (2023-08-26 itibarıyla) birden fazla JSON Schema örneğini desteklemediği için, kullanıcıların dokümanlarda birden fazla örnek göstermesi mümkün değildi.
+
+Bunu çözmek için FastAPI `0.103.0`, yeni `openapi_examples` parametresiyle aynı eski **OpenAPI’ye özel** `examples` alanını tanımlamayı **desteklemeye başladı**. 🤓
+
+### Özet { #summary }
+
+Eskiden tarihten pek hoşlanmadığımı söylerdim... şimdi bakın, "teknoloji tarihi" dersi anlatıyorum. 😅
+
+Kısacası, **FastAPI 0.99.0 veya üzerine yükseltin**; her şey çok daha **basit, tutarlı ve sezgisel** olur ve bu tarihsel detayların hiçbirini bilmeniz gerekmez. 😎
diff --git a/docs/tr/docs/tutorial/security/first-steps.md b/docs/tr/docs/tutorial/security/first-steps.md
new file mode 100644
index 000000000..7e0a70a02
--- /dev/null
+++ b/docs/tr/docs/tutorial/security/first-steps.md
@@ -0,0 +1,203 @@
+# Güvenlik - İlk Adımlar { #security-first-steps }
+
+**backend** API’nizin bir domain’de olduğunu düşünelim.
+
+Ve başka bir domain’de ya da aynı domain’in farklı bir path’inde (veya bir mobil uygulamada) bir **frontend**’iniz var.
+
+Ve frontend’in, **username** ve **password** kullanarak backend ile kimlik doğrulaması yapabilmesini istiyorsunuz.
+
+Bunu **FastAPI** ile **OAuth2** kullanarak oluşturabiliriz.
+
+Ama ihtiyacınız olan küçük bilgi parçalarını bulmak için uzun spesifikasyonun tamamını okuma zahmetine girmeyelim.
+
+Güvenliği yönetmek için **FastAPI**’nin sunduğu araçları kullanalım.
+
+## Nasıl Görünüyor { #how-it-looks }
+
+Önce kodu kullanıp nasıl çalıştığına bakalım, sonra neler olup bittiğini anlamak için geri döneriz.
+
+## `main.py` Oluşturun { #create-main-py }
+
+Örneği `main.py` adlı bir dosyaya kopyalayın:
+
+{* ../../docs_src/security/tutorial001_an_py39.py *}
+
+## Çalıştırın { #run-it }
+
+/// info | Bilgi
+
+`python-multipart` paketi, `pip install "fastapi[standard]"` komutunu çalıştırdığınızda **FastAPI** ile birlikte otomatik olarak kurulur.
+
+Ancak `pip install fastapi` komutunu kullanırsanız, `python-multipart` paketi varsayılan olarak dahil edilmez.
+
+Elle kurmak için bir [virtual environment](../../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan, onu aktive ettiğinizden emin olun ve ardından şununla kurun:
+
+```console
+$ pip install python-multipart
+```
+
+Bunun nedeni, **OAuth2**’nin `username` ve `password` göndermek için "form data" kullanmasıdır.
+
+///
+
+Örneği şu şekilde çalıştırın:
+
+
+
+/// check | Authorize butonu!
+
+Artık parıl parıl yeni bir "Authorize" butonunuz var.
+
+Ayrıca *path operation*’ınızın sağ üst köşesinde tıklayabileceğiniz küçük bir kilit simgesi de bulunuyor.
+
+///
+
+Ve ona tıklarsanız, `username` ve `password` (ve diğer opsiyonel alanları) girebileceğiniz küçük bir yetkilendirme formu görürsünüz:
+
+
+
+/// note | Not
+
+Formda ne yazdığınızın önemi yok; şimdilik çalışmayacak. Ama birazdan oraya da geleceğiz.
+
+///
+
+Bu, elbette son kullanıcılar için bir frontend değil; ancak tüm API’nizi etkileşimli şekilde belgelemek için harika bir otomatik araçtır.
+
+Frontend ekibi tarafından kullanılabilir (bu ekip siz de olabilirsiniz).
+
+Üçüncü taraf uygulamalar ve sistemler tarafından kullanılabilir.
+
+Ve aynı uygulamayı debug etmek, kontrol etmek ve test etmek için sizin tarafınızdan da kullanılabilir.
+
+## `password` Flow { #the-password-flow }
+
+Şimdi biraz geri dönüp bunların ne olduğuna bakalım.
+
+`password` "flow"u, OAuth2’de güvenlik ve authentication’ı yönetmek için tanımlanmış yöntemlerden ("flow"lardan) biridir.
+
+OAuth2, backend’in veya API’nin, kullanıcıyı authenticate eden server’dan bağımsız olabilmesi için tasarlanmıştır.
+
+Ancak bu örnekte, aynı **FastAPI** uygulaması hem API’yi hem de authentication’ı yönetecek.
+
+O yüzden basitleştirilmiş bu bakış açısından üzerinden geçelim:
+
+* Kullanıcı frontend’de `username` ve `password` yazar ve `Enter`’a basar.
+* Frontend (kullanıcının browser’ında çalışır), bu `username` ve `password` değerlerini API’mizdeki belirli bir URL’ye gönderir (`tokenUrl="token"` ile tanımlanan).
+* API, `username` ve `password` değerlerini kontrol eder ve bir "token" ile response döner (henüz bunların hiçbirini implement etmedik).
+ * "Token", daha sonra bu kullanıcıyı doğrulamak için kullanabileceğimiz içerik taşıyan bir string’dir.
+ * Normalde token’ın bir süre sonra süresi dolacak şekilde ayarlanması beklenir.
+ * Böylece kullanıcının bir noktada tekrar giriş yapması gerekir.
+ * Ayrıca token çalınırsa risk daha düşük olur. Çoğu durumda, sonsuza kadar çalışacak kalıcı bir anahtar gibi değildir.
+* Frontend bu token’ı geçici olarak bir yerde saklar.
+* Kullanıcı frontend’de tıklayarak web uygulamasının başka bir bölümüne gider.
+* Frontend’in API’den daha fazla veri alması gerekir.
+ * Ancak o endpoint için authentication gereklidir.
+ * Bu yüzden API’mizle authenticate olmak için `Authorization` header’ını, `Bearer ` + token değeriyle gönderir.
+ * Token `foobar` içeriyorsa `Authorization` header’ının içeriği `Bearer foobar` olur.
+
+## **FastAPI**’nin `OAuth2PasswordBearer`’ı { #fastapis-oauth2passwordbearer }
+
+**FastAPI**, bu güvenlik özelliklerini implement etmek için farklı soyutlama seviyelerinde çeşitli araçlar sağlar.
+
+Bu örnekte **OAuth2**’yi, **Password** flow ile, **Bearer** token kullanarak uygulayacağız. Bunu `OAuth2PasswordBearer` sınıfı ile yaparız.
+
+/// info | Bilgi
+
+"Bearer" token tek seçenek değildir.
+
+Ama bizim kullanım senaryomuz için en iyi seçenek odur.
+
+Ayrıca bir OAuth2 uzmanı değilseniz ve ihtiyaçlarınıza daha uygun başka bir seçeneğin neden gerekli olduğunu net olarak bilmiyorsanız, çoğu kullanım senaryosu için de en uygun seçenek olacaktır.
+
+Bu durumda bile **FastAPI**, onu oluşturabilmeniz için gereken araçları sunar.
+
+///
+
+`OAuth2PasswordBearer` sınıfının bir instance’ını oluştururken `tokenUrl` parametresini veririz. Bu parametre, client’ın (kullanıcının browser’ında çalışan frontend’in) token almak için `username` ve `password` göndereceği URL’yi içerir.
+
+{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *}
+
+/// tip | İpucu
+
+Burada `tokenUrl="token"`, henüz oluşturmadığımız göreli bir URL olan `token`’ı ifade eder. Göreli URL olduğu için `./token` ile eşdeğerdir.
+
+Göreli URL kullandığımız için, API’niz `https://example.com/` adresinde olsaydı `https://example.com/token` anlamına gelirdi. Ama API’niz `https://example.com/api/v1/` adresinde olsaydı, bu kez `https://example.com/api/v1/token` anlamına gelirdi.
+
+Göreli URL kullanmak, [Behind a Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank} gibi daha ileri kullanım senaryolarında bile uygulamanızın çalışmaya devam etmesini garanti etmek açısından önemlidir.
+
+///
+
+Bu parametre o endpoint’i / *path operation*’ı oluşturmaz; fakat `/token` URL’sinin client’ın token almak için kullanması gereken URL olduğunu bildirir. Bu bilgi OpenAPI’de, dolayısıyla etkileşimli API dokümantasyon sistemlerinde kullanılır.
+
+Birazdan gerçek path operation’ı da oluşturacağız.
+
+/// info | Teknik Detaylar
+
+Eğer çok katı bir "Pythonista" iseniz, `token_url` yerine `tokenUrl` şeklindeki parametre adlandırma stilini sevmeyebilirsiniz.
+
+Bunun nedeni, OpenAPI spesifikasyonundaki isimle aynı adın kullanılmasıdır. Böylece bu güvenlik şemalarından herhangi biri hakkında daha fazla araştırma yapmanız gerekirse, adı kopyalayıp yapıştırarak kolayca daha fazla bilgi bulabilirsiniz.
+
+///
+
+`oauth2_scheme` değişkeni, `OAuth2PasswordBearer`’ın bir instance’ıdır; ama aynı zamanda "callable"dır.
+
+Şu şekilde çağrılabilir:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+Dolayısıyla `Depends` ile kullanılabilir.
+
+### Kullanın { #use-it }
+
+Artık `Depends` ile bir dependency olarak `oauth2_scheme`’i geçebilirsiniz.
+
+{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+
+Bu dependency, *path operation function* içindeki `token` parametresine atanacak bir `str` sağlar.
+
+**FastAPI**, bu dependency’yi OpenAPI şemasında (ve otomatik API dokümanlarında) bir "security scheme" tanımlamak için kullanabileceğini bilir.
+
+/// info | Teknik Detaylar
+
+**FastAPI**, bir dependency içinde tanımlanan `OAuth2PasswordBearer` sınıfını OpenAPI’de security scheme tanımlamak için kullanabileceğini bilir; çünkü bu sınıf `fastapi.security.oauth2.OAuth2`’den kalıtım alır, o da `fastapi.security.base.SecurityBase`’den kalıtım alır.
+
+OpenAPI (ve otomatik API dokümanları) ile entegre olan tüm security araçları `SecurityBase`’den kalıtım alır; **FastAPI** bu sayede onları OpenAPI’ye nasıl entegre edeceğini anlayabilir.
+
+///
+
+## Ne Yapar { #what-it-does }
+
+Request içinde `Authorization` header’ını arar, değerin `Bearer ` + bir token olup olmadığını kontrol eder ve token’ı `str` olarak döndürür.
+
+Eğer `Authorization` header’ını görmezse ya da değer `Bearer ` token’ı içermiyorsa, doğrudan 401 status code hatasıyla (`UNAUTHORIZED`) response döner.
+
+Token’ın var olup olmadığını kontrol edip ayrıca hata döndürmenize bile gerek yoktur. Fonksiyonunuz çalışıyorsa, token içinde bir `str` olacağından emin olabilirsiniz.
+
+Bunu şimdiden etkileşimli dokümanlarda deneyebilirsiniz:
+
+
+
+Henüz token’ın geçerliliğini doğrulamıyoruz, ama başlangıç için bu bile yeterli.
+
+## Özet { #recap }
+
+Yani sadece 3 veya 4 ekstra satırla, şimdiden ilkel de olsa bir güvenlik katmanı elde etmiş oldunuz.
diff --git a/docs/tr/docs/tutorial/security/get-current-user.md b/docs/tr/docs/tutorial/security/get-current-user.md
new file mode 100644
index 000000000..9f56c7628
--- /dev/null
+++ b/docs/tr/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# Mevcut Kullanıcıyı Alma { #get-current-user }
+
+Önceki bölümde güvenlik sistemi (dependency injection sistemine dayanır) *path operation function*'a `str` olarak bir `token` veriyordu:
+
+{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+
+Ancak bu hâlâ pek kullanışlı değil.
+
+Bize mevcut kullanıcıyı verecek şekilde düzenleyelim.
+
+## Bir kullanıcı modeli oluşturun { #create-a-user-model }
+
+Önce bir Pydantic kullanıcı modeli oluşturalım.
+
+Body'leri bildirmek için Pydantic'i nasıl kullanıyorsak, aynı şekilde onu başka her yerde de kullanabiliriz:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## `get_current_user` dependency'si oluşturun { #create-a-get-current-user-dependency }
+
+Bir `get_current_user` dependency'si oluşturalım.
+
+Dependency'lerin alt dependency'leri olabileceğini hatırlıyor musunuz?
+
+`get_current_user`, daha önce oluşturduğumuz `oauth2_scheme` ile aynı dependency'yi kullanacak.
+
+Daha önce *path operation* içinde doğrudan yaptığımız gibi, yeni dependency'miz `get_current_user`, alt dependency olan `oauth2_scheme` üzerinden `str` olarak bir `token` alacak:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## Kullanıcıyı alın { #get-the-user }
+
+`get_current_user`, oluşturduğumuz (sahte) bir yardımcı (utility) fonksiyonu kullanacak; bu fonksiyon `str` olarak bir token alır ve Pydantic `User` modelimizi döndürür:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## Mevcut kullanıcıyı enjekte edin { #inject-the-current-user }
+
+Artık *path operation* içinde `get_current_user` ile aynı `Depends` yaklaşımını kullanabiliriz:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+`current_user` tipini Pydantic `User` modeli olarak belirttiğimize dikkat edin.
+
+Bu sayede fonksiyonun içinde otomatik tamamlama ve tip kontrollerinin tamamından faydalanırız.
+
+/// tip | İpucu
+
+Request body'lerinin de Pydantic modelleri ile bildirildiğini hatırlıyor olabilirsiniz.
+
+Burada `Depends` kullandığınız için **FastAPI** karışıklık yaşamaz.
+
+///
+
+/// check | Ek bilgi
+
+Bu dependency sisteminin tasarımı, hepsi `User` modeli döndüren farklı dependency'lere (farklı "dependable"lara) sahip olmamıza izin verir.
+
+Bu tipte veri döndürebilen yalnızca tek bir dependency ile sınırlı değiliz.
+
+///
+
+## Diğer modeller { #other-models }
+
+Artık *path operation function* içinde mevcut kullanıcıyı doğrudan alabilir ve güvenlik mekanizmalarını `Depends` kullanarak **Dependency Injection** seviyesinde yönetebilirsiniz.
+
+Ayrıca güvenlik gereksinimleri için herhangi bir model veya veri kullanabilirsiniz (bu örnekte bir Pydantic `User` modeli).
+
+Ancak belirli bir data model, class ya da type kullanmak zorunda değilsiniz.
+
+Modelinizde bir `id` ve `email` olsun, ama `username` olmasın mı istiyorsunuz? Elbette. Aynı araçları kullanabilirsiniz.
+
+Sadece bir `str` mı istiyorsunuz? Ya da sadece bir `dict`? Veya doğrudan bir veritabanı class model instance'ı? Hepsi aynı şekilde çalışır.
+
+Uygulamanıza giriş yapan kullanıcılar yok da robotlar, botlar veya yalnızca bir access token'a sahip başka sistemler mi var? Yine, her şey aynı şekilde çalışır.
+
+Uygulamanız için neye ihtiyacınız varsa o türden bir model, class ve veritabanı kullanın. **FastAPI**, dependency injection sistemiyle bunları destekler.
+
+## Kod boyutu { #code-size }
+
+Bu örnek biraz uzun görünebilir. Güvenlik, data model'ler, utility fonksiyonlar ve *path operation*'ları aynı dosyada bir araya getirdiğimizi unutmayın.
+
+Ama kritik nokta şu:
+
+Güvenlik ve dependency injection tarafını bir kez yazarsınız.
+
+İstediğiniz kadar karmaşık hâle getirebilirsiniz. Yine de hepsi tek bir yerde ve sadece bir kez yazılmış olur. Üstelik tüm esneklikle.
+
+Sonrasında aynı güvenlik sistemini kullanan binlerce endpoint (*path operation*) olabilir.
+
+Ve bunların hepsi (ya da istediğiniz bir kısmı) bu dependency'leri veya oluşturacağınız başka dependency'leri yeniden kullanmaktan faydalanabilir.
+
+Hatta bu binlerce *path operation* 3 satır kadar kısa olabilir:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## Özet { #recap }
+
+Artık *path operation function* içinde mevcut kullanıcıyı doğrudan alabilirsiniz.
+
+Yolun yarısına geldik.
+
+Kullanıcının/istemcinin gerçekten `username` ve `password` göndermesini sağlayacak bir *path operation* eklememiz gerekiyor.
+
+Sırada bu var.
diff --git a/docs/tr/docs/tutorial/security/index.md b/docs/tr/docs/tutorial/security/index.md
new file mode 100644
index 000000000..a592db6df
--- /dev/null
+++ b/docs/tr/docs/tutorial/security/index.md
@@ -0,0 +1,106 @@
+# Güvenlik { #security }
+
+Güvenlik, authentication ve authorization’ı ele almanın birçok yolu vardır.
+
+Ve bu konu genellikle karmaşık ve "zor"dur.
+
+Birçok framework ve sistemde yalnızca security ve authentication’ı yönetmek bile ciddi miktarda emek ve kod gerektirir (çoğu durumda yazılan toplam kodun %50’si veya daha fazlası olabilir).
+
+**FastAPI**, tüm security spesifikasyonlarını baştan sona inceleyip öğrenmek zorunda kalmadan **Security** konusunu kolay, hızlı ve standart bir şekilde ele almanıza yardımcı olacak çeşitli araçlar sunar.
+
+Ama önce, küçük birkaç kavrama bakalım.
+
+## Acelem var? { #in-a-hurry }
+
+Bu terimlerin hiçbirini umursamıyorsanız ve sadece kullanıcı adı ve parola tabanlı authentication ile security’yi *hemen şimdi* eklemeniz gerekiyorsa, bir sonraki bölümlere geçin.
+
+## OAuth2 { #oauth2 }
+
+OAuth2, authentication ve authorization’ı yönetmek için çeşitli yöntemleri tanımlayan bir spesifikasyondur.
+
+Oldukça kapsamlı bir spesifikasyondur ve birkaç karmaşık use case’i kapsar.
+
+"Üçüncü taraf" kullanarak authentication yapmanın yollarını da içerir.
+
+"Facebook, Google, X (Twitter), GitHub ile giriş yap" bulunan sistemlerin arka planda kullandığı şey de budur.
+
+### OAuth 1 { #oauth-1 }
+
+OAuth 1 de vardı; OAuth2’den çok farklıdır ve daha karmaşıktır, çünkü iletişimi nasıl şifreleyeceğinize dair doğrudan spesifikasyonlar içeriyordu.
+
+Günümüzde pek popüler değildir veya pek kullanılmaz.
+
+OAuth2 ise iletişimin nasıl şifreleneceğini belirtmez; uygulamanızın HTTPS ile sunulmasını bekler.
+
+/// tip | İpucu
+
+**deployment** bölümünde Traefik ve Let's Encrypt kullanarak ücretsiz şekilde HTTPS’i nasıl kuracağınızı göreceksiniz.
+
+///
+
+## OpenID Connect { #openid-connect }
+
+OpenID Connect, **OAuth2** tabanlı başka bir spesifikasyondur.
+
+OAuth2’de nispeten belirsiz kalan bazı noktaları tanımlayarak onu daha birlikte çalışabilir (interoperable) hâle getirmeye çalışır.
+
+Örneğin, Google ile giriş OpenID Connect kullanır (arka planda OAuth2 kullanır).
+
+Ancak Facebook ile giriş OpenID Connect’i desteklemez. Kendine özgü bir OAuth2 çeşidi vardır.
+
+### OpenID ("OpenID Connect" değil) { #openid-not-openid-connect }
+
+Bir de "OpenID" spesifikasyonu vardı. Bu da **OpenID Connect** ile aynı problemi çözmeye çalışıyordu ama OAuth2 tabanlı değildi.
+
+Dolayısıyla tamamen ayrı, ek bir sistemdi.
+
+Günümüzde pek popüler değildir veya pek kullanılmaz.
+
+## OpenAPI { #openapi }
+
+OpenAPI (önceden Swagger olarak biliniyordu), API’ler inşa etmek için açık spesifikasyondur (artık Linux Foundation’ın bir parçası).
+
+**FastAPI**, **OpenAPI** tabanlıdır.
+
+Bu sayede birden fazla otomatik etkileşimli dokümantasyon arayüzü, code generation vb. mümkün olur.
+
+OpenAPI, birden fazla security "scheme" tanımlamanın bir yolunu sunar.
+
+Bunları kullanarak, etkileşimli dokümantasyon sistemleri de dahil olmak üzere tüm bu standart tabanlı araçlardan faydalanabilirsiniz.
+
+OpenAPI şu security scheme’lerini tanımlar:
+
+* `apiKey`: uygulamaya özel bir anahtar; şuradan gelebilir:
+ * Bir query parameter.
+ * Bir header.
+ * Bir cookie.
+* `http`: standart HTTP authentication sistemleri, örneğin:
+ * `bearer`: `Authorization` header’ı; değeri `Bearer ` + bir token olacak şekilde. Bu, OAuth2’den gelir.
+ * HTTP Basic authentication.
+ * HTTP Digest, vb.
+* `oauth2`: OAuth2 ile security’yi yönetmenin tüm yolları ("flow" olarak adlandırılır).
+ * Bu flow’ların birçoğu, bir OAuth 2.0 authentication provider (Google, Facebook, X (Twitter), GitHub vb.) oluşturmak için uygundur:
+ * `implicit`
+ * `clientCredentials`
+ * `authorizationCode`
+ * Ancak, aynı uygulamanın içinde doğrudan authentication yönetmek için mükemmel şekilde kullanılabilecek özel bir "flow" vardır:
+ * `password`: sonraki bazı bölümlerde bunun örnekleri ele alınacak.
+* `openIdConnect`: OAuth2 authentication verisinin otomatik olarak nasıl keşfedileceğini tanımlamanın bir yolunu sunar.
+ * Bu otomatik keşif, OpenID Connect spesifikasyonunda tanımlanan şeydir.
+
+
+/// tip | İpucu
+
+Google, Facebook, X (Twitter), GitHub vb. gibi diğer authentication/authorization provider’larını entegre etmek de mümkündür ve nispeten kolaydır.
+
+En karmaşık kısım, bu tür bir authentication/authorization provider’ı inşa etmektir; ancak **FastAPI** ağır işleri sizin yerinize yaparken bunu kolayca yapabilmeniz için araçlar sunar.
+
+///
+
+## **FastAPI** yardımcı araçları { #fastapi-utilities }
+
+FastAPI, `fastapi.security` modülünde bu security scheme’lerinin her biri için, bu mekanizmaları kullanmayı kolaylaştıran çeşitli araçlar sağlar.
+
+Sonraki bölümlerde, **FastAPI**’nin sunduğu bu araçları kullanarak API’nize nasıl security ekleyeceğinizi göreceksiniz.
+
+Ayrıca bunun etkileşimli dokümantasyon sistemine nasıl otomatik olarak entegre edildiğini de göreceksiniz.
diff --git a/docs/tr/docs/tutorial/security/oauth2-jwt.md b/docs/tr/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 000000000..716761157
--- /dev/null
+++ b/docs/tr/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,273 @@
+# Password ile OAuth2 (ve hashing), JWT token'ları ile Bearer { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+Artık tüm security flow elimizde olduğuna göre, uygulamayı gerçekten güvenli hâle getirelim: JWT token'ları ve güvenli password hashing kullanacağız.
+
+Bu kodu uygulamanızda gerçekten kullanabilirsiniz; password hash'lerini veritabanınıza kaydedebilirsiniz, vb.
+
+Bir önceki bölümde bıraktığımız yerden başlayıp üzerine ekleyerek ilerleyeceğiz.
+
+## JWT Hakkında { #about-jwt }
+
+JWT, "JSON Web Tokens" anlamına gelir.
+
+Bir JSON nesnesini, boşluk içermeyen uzun ve yoğun bir string'e kodlamak için kullanılan bir standarttır. Şuna benzer:
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+Şifrelenmiş değildir; yani herkes içeriğindeki bilgiyi geri çıkarabilir.
+
+Ancak imzalanmıştır. Bu yüzden, sizin ürettiğiniz bir token'ı aldığınızda, gerçekten onu sizin ürettiğinizi doğrulayabilirsiniz.
+
+Bu şekilde, örneğin 1 haftalık süre sonu (expiration) olan bir token oluşturabilirsiniz. Sonra kullanıcı ertesi gün token ile geri geldiğinde, kullanıcının hâlâ sisteminizde oturum açmış olduğunu bilirsiniz.
+
+Bir hafta sonra token'ın süresi dolar; kullanıcı yetkilendirilmez ve yeni bir token almak için tekrar giriş yapmak zorunda kalır. Ayrıca kullanıcı (veya üçüncü bir taraf) token'ı değiştirip süre sonunu farklı göstermek isterse bunu tespit edebilirsiniz; çünkü imzalar eşleşmez.
+
+JWT token'larıyla oynayıp nasıl çalıştıklarını görmek isterseniz https://jwt.io adresine bakın.
+
+## `PyJWT` Kurulumu { #install-pyjwt }
+
+Python'da JWT token'larını üretmek ve doğrulamak için `PyJWT` kurmamız gerekiyor.
+
+Bir [virtual environment](../../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan emin olun, aktif edin ve ardından `pyjwt` kurun:
+
+
+
+Uygulamayı, öncekiyle aynı şekilde authorize edin.
+
+Şu kimlik bilgilerini kullanarak:
+
+Username: `johndoe`
+Password: `secret`
+
+/// check | Ek bilgi
+
+Kodun hiçbir yerinde düz metin password "`secret`" yok; sadece hash'lenmiş hâli var.
+
+///
+
+
+
+`/users/me/` endpoint'ini çağırın; response şöyle olacaktır:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+Developer tools'u açarsanız, gönderilen verinin sadece token'ı içerdiğini görebilirsiniz. Password sadece kullanıcıyı authenticate edip access token almak için yapılan ilk request'te gönderilir, sonrasında gönderilmez:
+
+
+
+/// note | Not
+
+`Authorization` header'ına dikkat edin; değeri `Bearer ` ile başlıyor.
+
+///
+
+## `scopes` ile İleri Seviye Kullanım { #advanced-usage-with-scopes }
+
+OAuth2'nin "scopes" kavramı vardır.
+
+Bunları kullanarak bir JWT token'a belirli bir izin seti ekleyebilirsiniz.
+
+Sonra bu token'ı bir kullanıcıya doğrudan veya bir üçüncü tarafa verip, API'nizle belirli kısıtlarla etkileşime girmesini sağlayabilirsiniz.
+
+Nasıl kullanıldıklarını ve **FastAPI** ile nasıl entegre olduklarını, ileride **Advanced User Guide** içinde öğreneceksiniz.
+
+## Özet { #recap }
+
+Şimdiye kadar gördüklerinizle, OAuth2 ve JWT gibi standartları kullanarak güvenli bir **FastAPI** uygulaması kurabilirsiniz.
+
+Neredeyse her framework'te security'yi ele almak oldukça hızlı bir şekilde karmaşık bir konu hâline gelir.
+
+Bunu çok basitleştiren birçok paket, veri modeli, veritabanı ve mevcut özelliklerle ilgili pek çok ödün vermek zorunda kalır. Hatta bazıları işi aşırı basitleştirirken arka planda güvenlik açıkları da barındırır.
+
+---
+
+**FastAPI**, hiçbir veritabanı, veri modeli veya araç konusunda ödün vermez.
+
+Projenize en uygun olanları seçebilmeniz için size tam esneklik sağlar.
+
+Ayrıca `pwdlib` ve `PyJWT` gibi iyi bakımı yapılan ve yaygın kullanılan paketleri doğrudan kullanabilirsiniz; çünkü **FastAPI**, haricî paketleri entegre etmek için karmaşık mekanizmalara ihtiyaç duymaz.
+
+Buna rağmen, esneklikten, sağlamlıktan veya güvenlikten ödün vermeden süreci mümkün olduğunca basitleştiren araçları sağlar.
+
+Ve OAuth2 gibi güvenli, standart protokolleri nispeten basit bir şekilde kullanabilir ve uygulayabilirsiniz.
+
+Aynı standartları izleyerek, daha ince taneli (fine-grained) bir izin sistemi için OAuth2 "scopes" kullanımını **Advanced User Guide** içinde daha detaylı öğrenebilirsiniz. Scopes'lu OAuth2; Facebook, Google, GitHub, Microsoft, X (Twitter) vb. pek çok büyük kimlik doğrulama sağlayıcısının, üçüncü taraf uygulamaların kullanıcıları adına API'leriyle etkileşebilmesine izin vermek için kullandığı mekanizmadır.
diff --git a/docs/tr/docs/tutorial/security/simple-oauth2.md b/docs/tr/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 000000000..88efd98e5
--- /dev/null
+++ b/docs/tr/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# Password ve Bearer ile Basit OAuth2 { #simple-oauth2-with-password-and-bearer }
+
+Şimdi önceki bölümün üzerine inşa edip, eksik parçaları ekleyerek tam bir güvenlik akışı oluşturalım.
+
+## `username` ve `password`’ü Alma { #get-the-username-and-password }
+
+`username` ve `password`’ü almak için **FastAPI** security yardımcı araçlarını kullanacağız.
+
+OAuth2, (bizim kullandığımız) "password flow" kullanılırken client/kullanıcının form verisi olarak `username` ve `password` alanlarını göndermesi gerektiğini belirtir.
+
+Ayrıca spesifikasyon, bu alanların adlarının tam olarak böyle olması gerektiğini söyler. Yani `user-name` veya `email` işe yaramaz.
+
+Ancak merak etmeyin, frontend’de son kullanıcılarınıza dilediğiniz gibi gösterebilirsiniz.
+
+Veritabanı model(ler)inizde de istediğiniz başka isimleri kullanabilirsiniz.
+
+Fakat login *path operation*’ı için, spesifikasyonla uyumlu olmak (ve örneğin entegre API dokümantasyon sistemini kullanabilmek) adına bu isimleri kullanmamız gerekiyor.
+
+Spesifikasyon ayrıca `username` ve `password`’ün form verisi olarak gönderilmesi gerektiğini de söyler (yani burada JSON yok).
+
+### `scope` { #scope }
+
+Spesifikasyon, client’ın "`scope`" adlı başka bir form alanı da gönderebileceğini söyler.
+
+Form alanının adı `scope`’tur (tekil), ama aslında boşluklarla ayrılmış "scope"’lardan oluşan uzun bir string’dir.
+
+Her bir "scope" sadece bir string’dir (boşluk içermez).
+
+Genelde belirli güvenlik izinlerini (permission) belirtmek için kullanılırlar, örneğin:
+
+* `users:read` veya `users:write` yaygın örneklerdir.
+* `instagram_basic` Facebook / Instagram tarafından kullanılır.
+* `https://www.googleapis.com/auth/drive` Google tarafından kullanılır.
+
+/// info | Bilgi
+
+OAuth2’de bir "scope", gerekli olan belirli bir izni ifade eden basit bir string’dir.
+
+`:` gibi başka karakterler içermesi veya URL olması önemli değildir.
+
+Bu detaylar implementasyon’a özeldir.
+
+OAuth2 açısından bunlar sadece string’lerdir.
+
+///
+
+## `username` ve `password`’ü Almak İçin Kod { #code-to-get-the-username-and-password }
+
+Şimdi bunu yönetmek için **FastAPI**’nin sağladığı araçları kullanalım.
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+Önce `OAuth2PasswordRequestForm`’u import edin ve `/token` için *path operation* içinde `Depends` ile dependency olarak kullanın:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm`, şu alanları içeren bir form body tanımlayan bir class dependency’sidir:
+
+* `username`.
+* `password`.
+* Boşlukla ayrılmış string’lerden oluşan büyük bir string olarak opsiyonel `scope` alanı.
+* Opsiyonel `grant_type`.
+
+/// tip | İpucu
+
+OAuth2 spesifikasyonu aslında `grant_type` alanını sabit bir `password` değeriyle *zorunlu kılar*, ancak `OAuth2PasswordRequestForm` bunu zorlamaz.
+
+Bunu zorlamak istiyorsanız, `OAuth2PasswordRequestForm` yerine `OAuth2PasswordRequestFormStrict` kullanın.
+
+///
+
+* Opsiyonel `client_id` (bu örnekte ihtiyacımız yok).
+* Opsiyonel `client_secret` (bu örnekte ihtiyacımız yok).
+
+/// info | Bilgi
+
+`OAuth2PasswordRequestForm`, `OAuth2PasswordBearer` gibi **FastAPI**’ye özel “özel bir sınıf” değildir.
+
+`OAuth2PasswordBearer`, bunun bir security scheme olduğunu **FastAPI**’ye bildirir. Bu yüzden OpenAPI’ye o şekilde eklenir.
+
+Ama `OAuth2PasswordRequestForm` sadece bir class dependency’dir; bunu kendiniz de yazabilirdiniz ya da doğrudan `Form` parametreleri tanımlayabilirdiniz.
+
+Fakat çok yaygın bir kullanım olduğu için **FastAPI** bunu işleri kolaylaştırmak adına doğrudan sağlar.
+
+///
+
+### Form Verisini Kullanma { #use-the-form-data }
+
+/// tip | İpucu
+
+`OAuth2PasswordRequestForm` dependency class’ının instance’ında boşluklarla ayrılmış uzun string olarak bir `scope` attribute’u olmaz; bunun yerine gönderilen her scope için gerçek string listesini içeren `scopes` attribute’u olur.
+
+Bu örnekte `scopes` kullanmıyoruz, ama ihtiyacınız olursa bu özellik hazır.
+
+///
+
+Şimdi form alanındaki `username`’i kullanarak (sahte) veritabanından kullanıcı verisini alın.
+
+Böyle bir kullanıcı yoksa, "Incorrect username or password" diyerek bir hata döndürelim.
+
+Hata için `HTTPException` exception’ını kullanıyoruz:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### Password’ü Kontrol Etme { #check-the-password }
+
+Bu noktada veritabanından kullanıcı verisine sahibiz, ancak password’ü henüz kontrol etmedik.
+
+Önce bu veriyi Pydantic `UserInDB` modeline koyalım.
+
+Asla düz metin (plaintext) password kaydetmemelisiniz; bu yüzden (sahte) password hashing sistemini kullanacağız.
+
+Password’ler eşleşmezse, aynı hatayı döndürürüz.
+
+#### Password hashing { #password-hashing }
+
+"Hashing" şudur: bir içeriği (bu örnekte password) anlaşılmaz görünen bayt dizisine (yani bir string’e) dönüştürmek.
+
+Aynı içeriği (aynı password’ü) her verdiğinizde, birebir aynı anlamsız görünen çıktıyı elde edersiniz.
+
+Ama bu anlamsız çıktıyı tekrar password’e geri çeviremezsiniz.
+
+##### Neden password hashing kullanılır { #why-use-password-hashing }
+
+Veritabanınız çalınırsa, hırsız kullanıcılarınızın düz metin password’lerine değil, sadece hash’lere sahip olur.
+
+Dolayısıyla hırsız, aynı password’leri başka bir sistemde denemeye çalışamaz (birçok kullanıcı her yerde aynı password’ü kullandığı için bu tehlikeli olurdu).
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### `**user_dict` Hakkında { #about-user-dict }
+
+`UserInDB(**user_dict)` şu anlama gelir:
+
+*`user_dict` içindeki key ve value’ları doğrudan key-value argümanları olarak geçir; şu ifadeyle eşdeğerdir:*
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info | Bilgi
+
+`**user_dict` için daha kapsamlı bir açıklama için [**Extra Models** dokümantasyonundaki ilgili bölüme](../extra-models.md#about-user-in-dict){.internal-link target=_blank} geri dönüp bakın.
+
+///
+
+## Token’ı Döndürme { #return-the-token }
+
+`token` endpoint’inin response’u bir JSON object olmalıdır.
+
+Bir `token_type` içermelidir. Biz "Bearer" token’ları kullandığımız için token type "`bearer`" olmalıdır.
+
+Ayrıca `access_token` içermelidir; bunun değeri access token’ımızı içeren bir string olmalıdır.
+
+Bu basit örnekte tamamen güvensiz davranıp token olarak aynı `username`’i döndüreceğiz.
+
+/// tip | İpucu
+
+Bir sonraki bölümde, password hashing ve JWT token’ları ile gerçekten güvenli bir implementasyon göreceksiniz.
+
+Ama şimdilik ihtiyacımız olan spesifik detaylara odaklanalım.
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | İpucu
+
+Spesifikasyona göre, bu örnekteki gibi `access_token` ve `token_type` içeren bir JSON döndürmelisiniz.
+
+Bunu kendi kodunuzda kendiniz yapmalı ve bu JSON key’lerini kullandığınızdan emin olmalısınız.
+
+Spesifikasyonlara uyum için, doğru yapmanız gereken neredeyse tek şey budur.
+
+Geri kalanını **FastAPI** sizin yerinize yönetir.
+
+///
+
+## Dependency’leri Güncelleme { #update-the-dependencies }
+
+Şimdi dependency’lerimizi güncelleyeceğiz.
+
+`current_user`’ı *sadece* kullanıcı aktifse almak istiyoruz.
+
+Bu yüzden, `get_current_user`’ı dependency olarak kullanan ek bir dependency olan `get_current_active_user`’ı oluşturuyoruz.
+
+Bu iki dependency de kullanıcı yoksa veya pasifse sadece HTTP hatası döndürecek.
+
+Dolayısıyla endpoint’imizde kullanıcıyı ancak kullanıcı varsa, doğru şekilde authenticate edildiyse ve aktifse alacağız:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | Bilgi
+
+Burada `Bearer` değerine sahip ek `WWW-Authenticate` header’ını döndürmemiz de spesifikasyonun bir parçasıdır.
+
+Herhangi bir HTTP (hata) durum kodu 401 "UNAUTHORIZED", ayrıca `WWW-Authenticate` header’ı da döndürmelidir.
+
+Bearer token’lar (bizim durumumuz) için bu header’ın değeri `Bearer` olmalıdır.
+
+Aslında bu ekstra header’ı atlayabilirsiniz, yine de çalışır.
+
+Ama spesifikasyonlara uyumlu olması için burada eklenmiştir.
+
+Ayrıca, bunu bekleyen ve kullanan araçlar olabilir (şimdi veya ileride) ve bu da sizin ya da kullanıcılarınız için faydalı olabilir.
+
+Standartların faydası da bu...
+
+///
+
+## Çalışır Halini Görün { #see-it-in-action }
+
+Etkileşimli dokümanları açın: http://127.0.0.1:8000/docs.
+
+### Authenticate Olma { #authenticate }
+
+"Authorize" butonuna tıklayın.
+
+Şu bilgileri kullanın:
+
+User: `johndoe`
+
+Password: `secret`
+
+
+
+Sistemde authenticate olduktan sonra şöyle görürsünüz:
+
+
+
+### Kendi Kullanıcı Verinizi Alma { #get-your-own-user-data }
+
+Şimdi `/users/me` path’inde `GET` operasyonunu kullanın.
+
+Kullanıcınızın verisini şöyle alırsınız:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+Kilit ikonuna tıklayıp logout olursanız ve sonra aynı operasyonu tekrar denerseniz, şu şekilde bir HTTP 401 hatası alırsınız:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### Pasif Kullanıcı { #inactive-user }
+
+Şimdi pasif bir kullanıcıyla deneyin; şu bilgilerle authenticate olun:
+
+User: `alice`
+
+Password: `secret2`
+
+Ve `/users/me` path’inde `GET` operasyonunu kullanmayı deneyin.
+
+Şöyle bir "Inactive user" hatası alırsınız:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## Özet { #recap }
+
+Artık API’niz için `username` ve `password` tabanlı, eksiksiz bir güvenlik sistemi implement etmek için gerekli araçlara sahipsiniz.
+
+Bu araçlarla güvenlik sistemini herhangi bir veritabanıyla ve herhangi bir user veya veri modeliyle uyumlu hale getirebilirsiniz.
+
+Eksik kalan tek detay, bunun henüz gerçekten "güvenli" olmamasıdır.
+
+Bir sonraki bölümde güvenli bir password hashing kütüphanesini ve JWT token’larını nasıl kullanacağınızı göreceksiniz.
diff --git a/docs/tr/docs/tutorial/sql-databases.md b/docs/tr/docs/tutorial/sql-databases.md
new file mode 100644
index 000000000..e1638cb04
--- /dev/null
+++ b/docs/tr/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# SQL (İlişkisel) Veritabanları { #sql-relational-databases }
+
+**FastAPI**, SQL (ilişkisel) bir veritabanı kullanmanızı zorunlu kılmaz. Ancak isterseniz **istediğiniz herhangi bir veritabanını** kullanabilirsiniz.
+
+Burada SQLModel kullanarak bir örnek göreceğiz.
+
+**SQLModel**, SQLAlchemy ve Pydantic’in üzerine inşa edilmiştir. **FastAPI**’nin yazarı tarafından, **SQL veritabanları** kullanması gereken FastAPI uygulamalarıyla mükemmel uyum sağlaması için geliştirilmiştir.
+
+/// tip | İpucu
+
+İstediğiniz başka bir SQL veya NoSQL veritabanı kütüphanesini kullanabilirsiniz (bazı durumlarda "ORMs" olarak adlandırılır). FastAPI sizi hiçbir şeye zorlamaz.
+
+///
+
+SQLModel, SQLAlchemy tabanlı olduğu için SQLAlchemy’nin **desteklediği herhangi bir veritabanını** kolayca kullanabilirsiniz (bu da SQLModel tarafından da desteklendikleri anlamına gelir), örneğin:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server, vb.
+
+Bu örnekte **SQLite** kullanacağız; çünkü tek bir dosya kullanır ve Python’da yerleşik desteği vardır. Yani bu örneği kopyalayıp olduğu gibi çalıştırabilirsiniz.
+
+Daha sonra, production uygulamanız için **PostgreSQL** gibi bir veritabanı sunucusu kullanmak isteyebilirsiniz.
+
+/// tip | İpucu
+
+Frontend ve daha fazla araçla birlikte **FastAPI** + **PostgreSQL** içeren resmi bir proje oluşturucu (project generator) var: https://github.com/fastapi/full-stack-fastapi-template
+
+///
+
+Bu çok basit ve kısa bir eğitimdir. Veritabanları genelinde, SQL hakkında veya daha ileri özellikler hakkında öğrenmek isterseniz SQLModel dokümantasyonuna gidin.
+
+## `SQLModel` Kurulumu { #install-sqlmodel }
+
+Önce [virtual environment](../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan emin olun, aktive edin ve ardından `sqlmodel`’i yükleyin:
+
+
+
+harry v1]
+ style harry-1 fill:#ccc,stroke-dasharray: 5 5
+ harry-3[harry v3]
+ end
+ subgraph stone-project[philosophers-stone project]
+ stone(philosophers-stone) -.-x|⛔️| harry-1
+ end
+ subgraph azkaban-project[prisoner-of-azkaban project]
+ azkaban(prisoner-of-azkaban) --> |requires| harry-3
+ end
+```
+
+/// tip | İpucu
+
+Python package'lerinde **yeni versiyonlarda** **breaking change**'lerden kaçınmak oldukça yaygındır; ancak yine de daha güvenlisi, yeni versiyonları bilinçli şekilde kurmak ve mümkünse test'leri çalıştırıp her şeyin doğru çalıştığını doğrulamaktır.
+
+///
+
+Şimdi bunu, **projelerinizin bağımlı olduğu** daha **birçok** başka **package** ile birlikte düşünün. Yönetmesi epey zorlaşır. Sonunda bazı projeleri package'lerin **uyumsuz versiyonlarıyla** çalıştırıp, bir şeylerin neden çalışmadığını anlamamak gibi durumlara düşebilirsiniz.
+
+Ayrıca işletim sisteminize (örn. Linux, Windows, macOS) bağlı olarak Python zaten kurulu gelmiş olabilir. Bu durumda, sisteminizin **ihtiyaç duyduğu** bazı package'ler belirli versiyonlarla önceden kurulu olabilir. Global Python environment'a package kurarsanız, işletim sistemiyle gelen bazı programları **bozma** ihtimaliniz olabilir.
+
+## Package'ler Nereye Kuruluyor { #where-are-packages-installed }
+
+Python'ı kurduğunuzda, bilgisayarınızda bazı dosyalar içeren klasörler oluşturulur.
+
+Bu klasörlerin bir kısmı, kurduğunuz tüm package'leri barındırmaktan sorumludur.
+
+Şunu çalıştırdığınızda:
+
+
-웹 API 대신 터미널에서 사용할 CLI 앱을 만들고 있다면, **Typer**를 확인해 보십시오.
+웹 API 대신 터미널에서 사용할 CLI 앱을 만들고 있다면, **Typer**를 확인해 보십시오.
**Typer**는 FastAPI의 동생입니다. 그리고 **CLI를 위한 FastAPI**가 되기 위해 생겼습니다. ⌨️ 🚀
@@ -161,8 +161,6 @@ $ pip install "fastapi[standard]"
다음 내용으로 `main.py` 파일을 만드십시오:
```Python
-from typing import Union
-
from fastapi import FastAPI
app = FastAPI()
@@ -174,7 +172,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Union[str, None] = None):
+def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
```
@@ -183,9 +181,7 @@ def read_item(item_id: int, q: Union[str, None] = None):
여러분의 코드가 `async` / `await`을 사용한다면, `async def`를 사용하십시오:
-```Python hl_lines="9 14"
-from typing import Union
-
+```Python hl_lines="7 12"
from fastapi import FastAPI
app = FastAPI()
@@ -197,7 +193,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Union[str, None] = None):
+async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
```
@@ -288,9 +284,7 @@ INFO: Application startup complete.
Pydantic 덕분에 표준 Python 타입을 사용해 본문을 선언합니다.
-```Python hl_lines="4 9-12 25-27"
-from typing import Union
-
+```Python hl_lines="2 7-10 23-25"
from fastapi import FastAPI
from pydantic import BaseModel
@@ -300,7 +294,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Union[bool, None] = None
+ is_offer: bool | None = None
@app.get("/")
@@ -309,7 +303,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Union[str, None] = None):
+def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
@@ -374,7 +368,7 @@ item: Item
* 데이터 검증:
* 데이터가 유효하지 않을 때 자동으로 생성하는 명확한 에러.
* 깊이 중첩된 JSON 객체에 대한 유효성 검사.
-* 입력 데이터 변환: 네트워크에서 파이썬 데이터 및 타입으로 전송. 읽을 수 있는 것들:
+* 입력 데이터 변환: 네트워크에서 파이썬 데이터 및 타입으로 전송. 읽을 수 있는 것들:
* JSON.
* 경로 매개변수.
* 쿼리 매개변수.
@@ -382,7 +376,7 @@ item: Item
* 헤더.
* 폼(Forms).
* 파일.
-* 출력 데이터 변환: 파이썬 데이터 및 타입을 네트워크 데이터로 전환(JSON 형식으로):
+* 출력 데이터 변환: 파이썬 데이터 및 타입을 네트워크 데이터로 전환(JSON 형식으로):
* 파이썬 타입 변환 (`str`, `int`, `float`, `bool`, `list`, 등).
* `datetime` 객체.
* `UUID` 객체.
@@ -445,7 +439,7 @@ item: Item
* 서로 다른 장소에서 **매개변수** 선언: **헤더**, **쿠키**, **폼 필드** 그리고 **파일**.
* `maximum_length` 또는 `regex`처럼 **유효성 제약**하는 방법.
-* 강력하고 사용하기 쉬운 **의존성 주입** 시스템.
+* 강력하고 사용하기 쉬운 **의존성 주입** 시스템.
* **OAuth2** 지원을 포함한 **JWT tokens** 및 **HTTP Basic**을 갖는 보안과 인증.
* (Pydantic 덕분에) **깊은 중첩 JSON 모델**을 선언하는데 더 진보한 (하지만 마찬가지로 쉬운) 기술.
* Strawberry 및 기타 라이브러리와의 **GraphQL** 통합.
diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md
index 701351e63..bebdffed8 100644
--- a/docs/ko/docs/tutorial/body-multiple-params.md
+++ b/docs/ko/docs/tutorial/body-multiple-params.md
@@ -102,15 +102,16 @@
기본적으로 단일 값은 쿼리 매개변수로 해석되므로, 명시적으로 `Query`를 추가할 필요 없이 이렇게 하면 됩니다:
+```Python
+q: str | None = None
+```
+
+또는 Python 3.9에서는:
+
```Python
q: Union[str, None] = None
```
-또는 Python 3.10 이상에서는:
-
-```Python
-q: str | None = None
-```
예를 들어:
diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md
index b8a87667a..baef3fb40 100644
--- a/docs/ko/docs/tutorial/path-operation-configuration.md
+++ b/docs/ko/docs/tutorial/path-operation-configuration.md
@@ -52,11 +52,11 @@
`summary`와 `description`을 추가할 수 있습니다:
-{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *}
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
## 독스트링으로 만든 설명 { #description-from-docstring }
-설명은 보통 길어지고 여러 줄에 걸쳐있기 때문에, *경로 처리* 설명을 함수 docstring에 선언할 수 있으며, **FastAPI**는 그곳에서 이를 읽습니다.
+설명은 보통 길어지고 여러 줄에 걸쳐있기 때문에, *경로 처리* 설명을 함수 docstring에 선언할 수 있으며, **FastAPI**는 그곳에서 이를 읽습니다.
독스트링에는 Markdown을 작성할 수 있으며, (독스트링의 들여쓰기를 고려하여) 올바르게 해석되고 표시됩니다.
@@ -70,7 +70,7 @@
`response_description` 매개변수로 응답에 관한 설명을 명시할 수 있습니다:
-{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *}
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
/// info | 정보
@@ -90,7 +90,7 @@ OpenAPI는 각 *경로 처리*가 응답에 관한 설명을 요구할 것을
## *경로 처리* 지원중단하기 { #deprecate-a-path-operation }
-*경로 처리*를 제거하지 않고 deprecated로 표시해야 한다면, `deprecated` 매개변수를 전달하면 됩니다:
+*경로 처리*를 제거하지 않고 deprecated로 표시해야 한다면, `deprecated` 매개변수를 전달하면 됩니다:
{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
From 2224b4e63b13a97a3132c7c1ff0cc2476d02527b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?=
httpx - Obrigatório caso você queira utilizar o `TestClient`.
* jinja2 - Obrigatório se você quer utilizar a configuração padrão de templates.
-* python-multipart - Obrigatório se você deseja suporte a "parsing" de formulário, com `request.form()`.
+* python-multipart - Obrigatório se você deseja suporte a "parsing" de formulário, com `request.form()`.
Utilizado pelo FastAPI:
diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md
index 3cba04912..24f35b210 100644
--- a/docs/pt/docs/tutorial/body-multiple-params.md
+++ b/docs/pt/docs/tutorial/body-multiple-params.md
@@ -101,13 +101,13 @@ Obviamente, você também pode declarar parâmetros de consulta assim que você
Dado que, por padrão, valores singulares são interpretados como parâmetros de consulta, você não precisa explicitamente adicionar uma `Query`, você pode somente:
```Python
-q: Union[str, None] = None
+q: str | None = None
```
-Ou como em Python 3.10 e versões superiores:
+Ou em Python 3.9:
```Python
-q: str | None = None
+q: Union[str, None] = None
```
Por exemplo:
diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md
index 84eebc128..2527c2892 100644
--- a/docs/pt/docs/tutorial/path-operation-configuration.md
+++ b/docs/pt/docs/tutorial/path-operation-configuration.md
@@ -52,7 +52,7 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`.
Você pode adicionar um `summary` e uma `description`:
-{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *}
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
## Descrição do docstring { #description-from-docstring }
@@ -70,7 +70,7 @@ Ela será usada nas documentações interativas:
Você pode especificar a descrição da resposta com o parâmetro `response_description`:
-{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *}
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
/// info | Informação
From 3578270af481d006bac53e1659640ce0bf257dba Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
+
+## 组合预定义响应和自定义响应 { #combine-predefined-responses-and-custom-ones }
+
+你可能希望有一些适用于许多*路径操作*的预定义响应,但同时又想把它们与每个*路径操作*所需的自定义响应组合在一起。
+
+在这些情况下,你可以使用 Python 的“解包”`dict` 的技巧 `**dict_to_unpack`:
-您可能希望有一些应用于许多路径操作的预定义响应,但是你想将不同的路径和自定义的相应组合在一块。
-对于这些情况,你可以使用Python的技术,将 `dict` 与 `**dict_to_unpack` 解包:
```Python
old_dict = {
"old key": "old value",
@@ -203,19 +223,25 @@ old_dict = {
new_dict = {**old_dict, "new key": "new value"}
```
-这里, new_dict 将包含来自 old_dict 的所有键值对加上新的键值对:
-```python
+这里,`new_dict` 将包含来自 `old_dict` 的所有键值对,再加上新的键值对:
+
+```Python
{
"old key": "old value",
"second old key": "second old value",
"new key": "new value",
}
```
-您可以使用该技术在路径操作中重用一些预定义的响应,并将它们与其他自定义响应相结合。
-**例如:**
-{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *}
-## 有关OpenAPI响应的更多信息
-要了解您可以在响应中包含哪些内容,您可以查看OpenAPI规范中的以下部分:
- + [OpenAPI响应对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responsesObject),它包括 Response Object 。
- + [OpenAPI响应对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responseObject),您可以直接在 `responses` 参数中的每个响应中包含任何内容。包括 `description` 、 `headers` 、 `content` (其中是声明不同的媒体类型和JSON Schemas)和 `links` 。
+你可以使用该技巧在*路径操作*中重用一些预定义响应,并把它们与额外的自定义响应组合在一起。
+
+例如:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## 关于 OpenAPI 响应的更多信息 { #more-information-about-openapi-responses }
+
+要查看响应中究竟可以包含什么,你可以查看 OpenAPI 规范中的以下部分:
+
+* OpenAPI Responses 对象,它包含 `Response Object`。
+* OpenAPI Response 对象,你可以把这里的任何内容直接包含到 `responses` 参数中的每个响应里。包括 `description`、`headers`、`content`(在这里声明不同的媒体类型和 JSON Schemas),以及 `links`。
diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md
index b048a2a17..23ceab4e8 100644
--- a/docs/zh/docs/advanced/additional-status-codes.md
+++ b/docs/zh/docs/advanced/additional-status-codes.md
@@ -1,10 +1,10 @@
-# 额外的状态码
+# 额外的状态码 { #additional-status-codes }
**FastAPI** 默认使用 `JSONResponse` 返回一个响应,将你的 *路径操作* 中的返回内容放到该 `JSONResponse` 中。
**FastAPI** 会自动使用默认的状态码或者使用你在 *路径操作* 中设置的状态码。
-## 额外的状态码
+## 额外的状态码 { #additional-status-codes_1 }
如果你想要返回主要状态码之外的状态码,你可以通过直接返回一个 `Response` 来实现,比如 `JSONResponse`,然后直接设置额外的状态码。
@@ -12,15 +12,15 @@
但是你也希望它能够接受新的条目。并且当这些条目不存在时,会自动创建并返回 201 「创建」的 HTTP 状态码。
-要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为为你要的值。
+要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为你要的值。
-{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *}
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
-/// warning | 警告
+/// warning
当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。
-FastAPI 不会用模型等对该响应进行序列化。
+它不会用模型等进行序列化。
确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。
@@ -34,7 +34,7 @@ FastAPI 不会用模型等对该响应进行序列化。
///
-## OpenAPI 和 API 文档
+## OpenAPI 和 API 文档 { #openapi-and-api-docs }
如果你直接返回额外的状态码和响应,它们不会包含在 OpenAPI 方案(API 文档)中,因为 FastAPI 没办法预先知道你要返回什么。
diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md
index 8375bd48e..3efca8944 100644
--- a/docs/zh/docs/advanced/advanced-dependencies.md
+++ b/docs/zh/docs/advanced/advanced-dependencies.md
@@ -1,65 +1,163 @@
-# 高级依赖项
+# 高级依赖项 { #advanced-dependencies }
-## 参数化的依赖项
+## 参数化的依赖项 { #parameterized-dependencies }
-我们之前看到的所有依赖项都是写死的函数或类。
+目前我们看到的依赖项都是固定的函数或类。
-但也可以为依赖项设置参数,避免声明多个不同的函数或类。
+但有时你可能希望为依赖项设置参数,而不必声明许多不同的函数或类。
-假设要创建校验查询参数 `q` 是否包含固定内容的依赖项。
+假设我们要有一个依赖项,用来检查查询参数 `q` 是否包含某个固定内容。
-但此处要把待检验的固定内容定义为参数。
+但我们希望能够把这个固定内容参数化。
-## **可调用**实例
+## “可调用”的实例 { #a-callable-instance }
-Python 可以把类实例变为**可调用项**。
+在 Python 中,可以让某个类的实例变成“可调用对象”(callable)。
-这里说的不是类本身(类本就是可调用项),而是类实例。
+这里指的是类的实例(类本身已经是可调用的),而不是类本身。
-为此,需要声明 `__call__` 方法:
+为此,声明一个 `__call__` 方法:
-{* ../../docs_src/dependencies/tutorial011.py hl[10] *}
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *}
-本例中,**FastAPI** 使用 `__call__` 检查附加参数及子依赖项,稍后,还要调用它向*路径操作函数*传递值。
+在这种情况下,**FastAPI** 会使用这个 `__call__` 来检查附加参数和子依赖,并且稍后会调用它,把返回值传递给你的*路径操作函数*中的参数。
-## 参数化实例
+## 参数化实例 { #parameterize-the-instance }
-接下来,使用 `__init__` 声明用于**参数化**依赖项的实例参数:
+现在,我们可以用 `__init__` 声明实例的参数,用来“参数化”这个依赖项:
-{* ../../docs_src/dependencies/tutorial011.py hl[7] *}
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *}
-本例中,**FastAPI** 不使用 `__init__`,我们要直接在代码中使用。
+在本例中,**FastAPI** 不会接触或关心 `__init__`,我们会在自己的代码中直接使用它。
-## 创建实例
+## 创建实例 { #create-an-instance }
-使用以下代码创建类实例:
+我们可以这样创建该类的实例:
-{* ../../docs_src/dependencies/tutorial011.py hl[16] *}
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *}
-这样就可以**参数化**依赖项,它包含 `checker.fixed_content` 的属性 - `"bar"`。
+这样就把依赖项“参数化”了,现在它内部带有属性 `checker.fixed_content` 的值 `"bar"`。
-## 把实例作为依赖项
+## 把实例作为依赖项 { #use-the-instance-as-a-dependency }
-然后,不要再在 `Depends(checker)` 中使用 `Depends(FixedContentQueryChecker)`, 而是要使用 `checker`,因为依赖项是类实例 - `checker`,不是类。
+然后,我们可以在 `Depends(checker)` 中使用这个 `checker`,而不是 `Depends(FixedContentQueryChecker)`,因为依赖项是实例 `checker`,不是类本身。
-处理依赖项时,**FastAPI** 以如下方式调用 `checker`:
+解析依赖项时,**FastAPI** 会像这样调用 `checker`:
```Python
checker(q="somequery")
```
-……并用*路径操作函数*的参数 `fixed_content_included` 返回依赖项的值:
+...并将其返回值作为依赖项的值,传给我们的*路径操作函数*中的参数 `fixed_content_included`:
-{* ../../docs_src/dependencies/tutorial011.py hl[20] *}
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *}
/// tip | 提示
-本章示例有些刻意,也看不出有什么用处。
+这些看起来可能有些牵强,目前它的用处也许还不太明显。
-这个简例只是为了说明高级依赖项的运作机制。
+这些示例刻意保持简单,但展示了整体的工作方式。
-在有关安全的章节中,工具函数将以这种方式实现。
+在安全相关的章节里,有一些工具函数就是以相同的方式实现的。
-只要能理解本章内容,就能理解安全工具背后的运行机制。
+如果你理解了这里的内容,你就已经知道那些安全工具在底层是如何工作的。
///
+
+## 带 `yield` 的依赖项、`HTTPException`、`except` 与后台任务 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | 警告
+
+你很可能不需要了解这些技术细节。
+
+这些细节主要在你的 FastAPI 应用版本低于 0.121.0 且你正遇到带 `yield` 的依赖项问题时才有用。
+
+///
+
+带 `yield` 的依赖项随着时间演进以覆盖不同用例并修复一些问题,下面是变更摘要。
+
+### 带 `yield` 的依赖项与 `scope` { #dependencies-with-yield-and-scope }
+
+在 0.121.0 版本中,FastAPI 为带 `yield` 的依赖项新增了 `Depends(scope="function")` 的支持。
+
+使用 `Depends(scope="function")` 时,`yield` 之后的退出代码会在*路径操作函数*结束后、响应发送给客户端之前立即执行。
+
+而当使用默认的 `Depends(scope="request")` 时,`yield` 之后的退出代码会在响应发送之后执行。
+
+你可以在文档 [带 `yield` 的依赖项 - 提前退出与 `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope) 中了解更多。
+
+### 带 `yield` 的依赖项与 `StreamingResponse`(技术细节) { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+在 FastAPI 0.118.0 之前,如果你使用带 `yield` 的依赖项,它会在*路径操作函数*返回后、发送响应之前运行 `yield` 之后的退出代码。
+
+这样做的目的是避免在等待响应通过网络传输期间不必要地占用资源。
+
+这也意味着,如果你返回的是 `StreamingResponse`,那么该带 `yield` 的依赖项的退出代码会在开始发送响应前就已经执行完毕。
+
+例如,如果你在带 `yield` 的依赖项中持有一个数据库会话,那么 `StreamingResponse` 在流式发送数据时将无法使用该会话,因为会话已经在 `yield` 之后的退出代码里被关闭了。
+
+在 0.118.0 中,这一行为被回退为:让 `yield` 之后的退出代码在响应发送之后再执行。
+
+/// info | 信息
+
+如你在下文所见,这与 0.106.0 之前的行为非常相似,但对若干边界情况做了改进和修复。
+
+///
+
+#### 需要提前执行退出代码的用例 { #use-cases-with-early-exit-code }
+
+在某些特定条件下,旧的行为(在发送响应之前执行带 `yield` 依赖项的退出代码)会更有利。
+
+例如,设想你在带 `yield` 的依赖项中仅用数据库会话来校验用户,而在*路径操作函数*中并不会再次使用该会话;同时,响应需要很长时间才能发送完,比如一个缓慢发送数据的 `StreamingResponse`,且它出于某种原因并不使用数据库。
+
+这种情况下,会一直持有数据库会话直到响应发送完毕;但如果并不再使用它,就没有必要一直占用。
+
+代码可能如下:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+退出代码(自动关闭 `Session`)位于:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...会在响应把慢速数据发送完之后才运行:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+但由于 `generate_stream()` 并不使用数据库会话,因此在发送响应期间保持会话打开并非必要。
+
+如果你使用的是 SQLModel(或 SQLAlchemy)并碰到这种特定用例,你可以在不再需要时显式关闭会话:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+这样会话会释放数据库连接,让其他请求可以使用。
+
+如果你还有其他需要在 `yield` 依赖项中提前退出的用例,请创建一个 GitHub 讨论问题,说明你的具体用例以及为何提前关闭会对你有帮助。
+
+如果确有有力的用例需要提前关闭,我会考虑新增一种选择性启用提前关闭的方式。
+
+### 带 `yield` 的依赖项与 `except`(技术细节) { #dependencies-with-yield-and-except-technical-details }
+
+在 FastAPI 0.110.0 之前,如果你在带 `yield` 的依赖项中用 `except` 捕获了一个异常,并且没有再次抛出它,那么该异常会被自动抛出/转发给任意异常处理器或内部服务器错误处理器。
+
+在 0.110.0 中对此作出了变更,以修复将异常转发为未处理(内部服务器错误)时造成的内存消耗问题,并使其与常规 Python 代码的行为保持一致。
+
+### 后台任务与带 `yield` 的依赖项(技术细节) { #background-tasks-and-dependencies-with-yield-technical-details }
+
+在 FastAPI 0.106.0 之前,`yield` 之后抛出异常是不可行的,因为带 `yield` 的依赖项中的退出代码会在响应发送之后才执行,此时[异常处理器](../tutorial/handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}已经运行完毕。
+
+之所以这样设计,主要是为了允许在后台任务中继续使用依赖项通过 `yield`“产出”的对象,因为退出代码会在后台任务完成之后才执行。
+
+在 FastAPI 0.106.0 中,这一行为被修改,目的是避免在等待响应通过网络传输时一直占用资源。
+
+/// tip | 提示
+
+另外,后台任务通常是一段独立的逻辑,应该单独处理,并使用它自己的资源(例如它自己的数据库连接)。
+
+因此,这样做你的代码通常会更清晰。
+
+///
+
+如果你过去依赖于旧行为,现在应在后台任务内部自行创建所需资源,并且只在内部使用不依赖于带 `yield` 依赖项资源的数据。
+
+例如,不要复用相同的数据库会话,而是在后台任务内部创建一个新的会话,并用这个新会话从数据库获取对象。然后,不是把数据库对象本身作为参数传给后台任务函数,而是传递该对象的 ID,并在后台任务函数内部再次获取该对象。
diff --git a/docs/zh/docs/advanced/async-tests.md b/docs/zh/docs/advanced/async-tests.md
index b5ac15b5b..6803358d2 100644
--- a/docs/zh/docs/advanced/async-tests.md
+++ b/docs/zh/docs/advanced/async-tests.md
@@ -1,4 +1,4 @@
-# 异步测试
+# 异步测试 { #async-tests }
您已经了解了如何使用 `TestClient` 测试 **FastAPI** 应用程序。但是到目前为止,您只了解了如何编写同步测试,而没有使用 `async` 异步函数。
@@ -6,11 +6,11 @@
让我们看看如何才能实现这一点。
-## pytest.mark.anyio
+## pytest.mark.anyio { #pytest-mark-anyio }
如果我们想在测试中调用异步函数,那么我们的测试函数必须是异步的。 AnyIO 为此提供了一个简洁的插件,它允许我们指定一些测试函数要异步调用。
-## HTTPX
+## HTTPX { #httpx }
即使您的 **FastAPI** 应用程序使用普通的 `def` 函数而不是 `async def` ,它本质上仍是一个 `async` 异步应用程序。
@@ -18,7 +18,7 @@
`TestClient` 是基于 HTTPX 的。幸运的是,我们可以直接使用它来测试API。
-## 示例
+## 示例 { #example }
举个简单的例子,让我们来看一个[更大的应用](../tutorial/bigger-applications.md){.internal-link target=_blank}和[测试](../tutorial/testing.md){.internal-link target=_blank}中描述的类似文件结构:
@@ -32,13 +32,13 @@
文件 `main.py` 将包含:
-{* ../../docs_src/async_tests/main.py *}
+{* ../../docs_src/async_tests/app_a_py39/main.py *}
文件 `test_main.py` 将包含针对 `main.py` 的测试,现在它可能看起来如下:
-{* ../../docs_src/async_tests/test_main.py *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py *}
-## 运行测试
+## 运行测试 { #run-it }
您可以通过以下方式照常运行测试:
@@ -52,13 +52,13 @@ $ pytest
-## 详细说明
+## 详细说明 { #in-detail }
这个标记 `@pytest.mark.anyio` 会告诉 pytest 该测试函数应该被异步调用:
-{* ../../docs_src/async_tests/test_main.py hl[7] *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[7] *}
-/// tip
+/// tip | 提示
请注意,测试函数现在用的是 `async def`,而不是像以前使用 `TestClient` 时那样只是 `def` 。
@@ -66,7 +66,7 @@ $ pytest
我们现在可以使用应用程序创建一个 `AsyncClient` ,并使用 `await` 向其发送异步请求。
-{* ../../docs_src/async_tests/test_main.py hl[9:12] *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[9:12] *}
这相当于:
@@ -76,24 +76,24 @@ response = client.get('/')
我们曾经通过它向 `TestClient` 发出请求。
-/// tip
+/// tip | 提示
请注意,我们正在将 async/await 与新的 `AsyncClient` 一起使用——请求是异步的。
///
-/// warning
+/// warning | 警告
如果您的应用程序依赖于生命周期事件, `AsyncClient` 将不会触发这些事件。为了确保它们被触发,请使用 florimondmanca/asgi-lifespan 中的 `LifespanManager` 。
///
-## 其他异步函数调用
+## 其他异步函数调用 { #other-asynchronous-function-calls }
由于测试函数现在是异步的,因此除了在测试中向 FastAPI 应用程序发送请求之外,您现在还可以调用(和使用 `await` 等待)其他 `async` 异步函数,就和您在代码中的其他任何地方调用它们的方法一样。
-/// tip
+/// tip | 提示
-如果您在测试程序中集成异步函数调用的时候遇到一个 `RuntimeError: Task attached to a different loop` 的报错(例如,使用 MongoDB 的 MotorClient 时),请记住,只能在异步函数中实例化需要事件循环的对象,例如通过 `'@app.on_event("startup")` 回调函数进行初始化。
+如果您在测试程序中集成异步函数调用的时候遇到一个 `RuntimeError: Task attached to a different loop` 的报错(例如,使用 MongoDB 的 MotorClient 时),请记住,只能在异步函数中实例化需要事件循环的对象,例如在 `@app.on_event("startup")` 回调中初始化。
///
diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md
index f8f61c8a3..b44b0b5ac 100644
--- a/docs/zh/docs/advanced/behind-a-proxy.md
+++ b/docs/zh/docs/advanced/behind-a-proxy.md
@@ -1,30 +1,131 @@
-# 使用代理
+# 使用代理 { #behind-a-proxy }
-有些情况下,您可能要使用 Traefik 或 Nginx 等**代理**服务器,并添加应用不能识别的附加路径前缀配置。
+在很多情况下,你会在 FastAPI 应用前面使用像 Traefik 或 Nginx 这样的**代理**。
-此时,要使用 `root_path` 配置应用。
+这些代理可以处理 HTTPS 证书等事项。
-`root_path` 是 ASGI 规范提供的机制,FastAPI 就是基于此规范开发的(通过 Starlette)。
+## 代理转发的请求头 { #proxy-forwarded-headers }
+
+在你的应用前面的**代理**通常会在把请求转发给你的**服务器**之前,临时设置一些请求头,让服务器知道该请求是由代理**转发**的,并告知原始(公网)URL,包括域名、是否使用 HTTPS 等。
+
+**服务器**程序(例如通过 **FastAPI CLI** 运行的 **Uvicorn**)能够解析这些请求头,然后把这些信息传递给你的应用。
+
+但出于安全考虑,由于服务器并不知道自己处在受信任的代理之后,它默认不会解析这些请求头。
+
+/// note | 技术细节
+
+这些代理相关的请求头包括:
+
+- X-Forwarded-For
+- X-Forwarded-Proto
+- X-Forwarded-Host
+
+///
+
+### 启用代理转发的请求头 { #enable-proxy-forwarded-headers }
+
+你可以用 *CLI 选项* `--forwarded-allow-ips` 启动 FastAPI CLI,并传入应该被信任、允许读取这些转发请求头的 IP 地址列表。
+
+如果设置为 `--forwarded-allow-ips="*"`,就会信任所有来源 IP。
+
+如果你的**服务器**位于受信任的**代理**之后,并且只有代理会与它通信,这将使其接受该**代理**的任何 IP。
+
+
Host: mysuperapp.com
Path: /items
+
+ Note over Proxy: Proxy adds forwarded headers
+
+ Proxy->>Server: HTTP Request
X-Forwarded-For: [client IP]
X-Forwarded-Proto: https
X-Forwarded-Host: mysuperapp.com
Path: /items
+
+ Note over Server: Server interprets headers
(if --forwarded-allow-ips is set)
+
+ Server->>Proxy: HTTP Response
with correct HTTPS URLs
+
+ Proxy->>Client: HTTPS Response
+```
+
+**代理**会拦截原始客户端请求,并在将请求传递给**应用服务器**之前,添加特殊的*转发*请求头(`X-Forwarded-*`)。
+
+这些请求头保留了原始请求中否则会丢失的信息:
+
+- X-Forwarded-For:原始客户端的 IP 地址
+- X-Forwarded-Proto:原始协议(`https`)
+- X-Forwarded-Host:原始主机(`mysuperapp.com`)
+
+当 **FastAPI CLI** 配置了 `--forwarded-allow-ips` 后,它会信任并使用这些请求头,例如用于在重定向中生成正确的 URL。
+
+## 移除路径前缀的代理 { #proxy-with-a-stripped-path-prefix }
+
+你可能会有一个代理,为你的应用添加一个路径前缀。
+
+在这些情况下,你可以使用 `root_path` 来配置你的应用。
+
+`root_path` 是 ASGI 规范(FastAPI 基于该规范,通过 Starlette 构建)提供的机制。
`root_path` 用于处理这些特定情况。
-在挂载子应用时,也可以在内部使用。
+在挂载子应用时,它也会在内部使用。
-## 移除路径前缀的代理
+“移除路径前缀的代理”在这里的意思是:你可以在代码中声明一个路径 `/app`,然后在顶层添加一层(代理),把你的 **FastAPI** 应用放在类似 `/api/v1` 的路径下。
-本例中,移除路径前缀的代理是指在代码中声明路径 `/app`,然后在应用顶层添加代理,把 **FastAPI** 应用放在 `/api/v1` 路径下。
+在这种情况下,原始路径 `/app` 实际上会在 `/api/v1/app` 提供服务。
-本例的原始路径 `/app` 实际上是在 `/api/v1/app` 提供服务。
+即使你的所有代码都假设只有 `/app`。
-哪怕所有代码都假设只有 `/app`。
+{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[6] *}
-代理只在把请求传送给 Uvicorn 之前才会**移除路径前缀**,让应用以为它是在 `/app` 提供服务,因此不必在代码中加入前缀 `/api/v1`。
+代理会在将请求传递给应用服务器(可能是通过 FastAPI CLI 运行的 Uvicorn)之前,实时**“移除”**这个**路径前缀**,让你的应用认为它是在 `/app` 被服务,这样你就不需要更新所有代码去包含 `/api/v1` 前缀。
-但之后,在(前端)打开 API 文档时,代理会要求在 `/openapi.json`,而不是 `/api/v1/openapi.json` 中提取 OpenAPI 概图。
+到这里,一切都会像往常一样工作。
-因此, (运行在浏览器中的)前端会尝试访问 `/openapi.json`,但没有办法获取 OpenAPI 概图。
+但是,当你打开集成的文档界面(前端)时,它会期望在 `/openapi.json` 获取 OpenAPI 模式,而不是在 `/api/v1/openapi.json`。
-这是因为应用使用了以 `/api/v1` 为路径前缀的代理,前端要从 `/api/v1/openapi.json` 中提取 OpenAPI 概图。
+因此,(在浏览器中运行的)前端会尝试访问 `/openapi.json`,但无法获取 OpenAPI 模式。
+
+因为我们的应用使用了路径前缀为 `/api/v1` 的代理,前端需要从 `/api/v1/openapi.json` 获取 OpenAPI 模式。
```mermaid
graph LR
@@ -39,15 +140,15 @@ proxy --> server
/// tip | 提示
-IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。
+IP `0.0.0.0` 通常表示程序监听该机器/服务器上的所有可用 IP。
///
-API 文档还需要 OpenAPI 概图声明 API `server` 位于 `/api/v1`(使用代理时的 URL)。例如:
+文档界面还需要 OpenAPI 模式声明该 API 的 `server` 位于 `/api/v1`(代理后面)。例如:
```JSON hl_lines="4-8"
{
- "openapi": "3.0.2",
+ "openapi": "3.1.0",
// More stuff here
"servers": [
{
@@ -60,53 +161,53 @@ API 文档还需要 OpenAPI 概图声明 API `server` 位于 `/api/v1`(使用
}
```
-本例中的 `Proxy` 是 **Traefik**,`server` 是运行 FastAPI 应用的 **Uvicorn**。
+在此示例中,“Proxy” 可以是 **Traefik** 之类的。服务器可以是用 **Uvicorn** 的 **FastAPI CLI** 运行你的 FastAPI 应用。
-### 提供 `root_path`
+### 提供 `root_path` { #providing-the-root-path }
-为此,要以如下方式使用命令行选项 `--root-path`:
+为此,你可以像下面这样使用命令行选项 `--root-path`:
-但输入**官方**链接 `/api/v1/docs`,并使用端口 `9999` 访问 API 文档,就能正常运行了!🎉
+但如果我们在“官方”URL(代理端口为 `9999`)的 `/api/v1/docs` 访问文档界面,它就能正常工作!🎉
-输入 http://127.0.0.1:9999/api/v1/docs 查看文档:
+你可以在 http://127.0.0.1:9999/api/v1/docs 查看:
-一切正常。 ✔️
+完全符合我们的预期。✔️
-这是因为 FastAPI 在 OpenAPI 里使用 `root_path` 提供的 URL 创建默认 `server`。
+这是因为 FastAPI 使用该 `root_path` 在 OpenAPI 中创建默认的 `server`,其 URL 来自 `root_path`。
-## 附加的服务器
+## 附加的服务器 { #additional-servers }
/// warning | 警告
-此用例较难,可以跳过。
+这是一个更高级的用例,可以跳过。
///
-默认情况下,**FastAPI** 使用 `root_path` 的链接在 OpenAPI 概图中创建 `server`。
+默认情况下,**FastAPI** 会在 OpenAPI 模式中使用 `root_path` 的 URL 创建一个 `server`。
-但也可以使用其它备选 `servers`,例如,需要同一个 API 文档与 staging 和生产环境交互。
+但你也可以提供其他备选的 `servers`,例如你希望让“同一个”文档界面同时与预发布环境和生产环境交互。
-如果传递自定义 `servers` 列表,并有 `root_path`( 因为 API 使用了代理),**FastAPI** 会在列表开头使用这个 `root_path` 插入**服务器**。
+如果你传入了自定义的 `servers` 列表,并且存在 `root_path`(因为你的 API 位于代理后面),**FastAPI** 会在列表开头插入一个使用该 `root_path` 的“server”。
例如:
-{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *}
+{* ../../docs_src/behind_a_proxy/tutorial003_py39.py hl[4:7] *}
-这段代码生产如下 OpenAPI 概图:
+会生成如下的 OpenAPI 模式:
```JSON hl_lines="5-7"
{
- "openapi": "3.0.2",
+ "openapi": "3.1.0",
// More stuff here
"servers": [
{
@@ -328,30 +429,38 @@ $ uvicorn main:app --root-path /api/v1
/// tip | 提示
-注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。
+注意这个自动生成的服务器,`url` 的值为 `/api/v1`,取自 `root_path`。
///
-http://127.0.0.1:9999/api/v1/docs 的 API 文档所示如下:
+在 http://127.0.0.1:9999/api/v1/docs 的文档界面中,它看起来是这样的:
/// tip | 提示
-API 文档与所选的服务器进行交互。
+文档界面会与你所选择的服务器交互。
///
-### 从 `root_path` 禁用自动服务器
+/// note | 技术细节
-如果不想让 **FastAPI** 包含使用 `root_path` 的自动服务器,则要使用参数 `root_path_in_servers=False`:
+OpenAPI 规范中的 `servers` 属性是可选的。
-{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *}
+如果你没有指定 `servers` 参数,并且 `root_path` 等于 `/`,则默认情况下,生成的 OpenAPI 模式中会完全省略 `servers` 属性,这等价于只有一个 `url` 值为 `/` 的服务器。
-这样,就不会在 OpenAPI 概图中包含服务器了。
+///
-## 挂载子应用
+### 从 `root_path` 禁用自动服务器 { #disable-automatic-server-from-root-path }
-如需挂载子应用(详见 [子应用 - 挂载](sub-applications.md){.internal-link target=_blank}),也要通过 `root_path` 使用代理,这与正常应用一样,别无二致。
+如果你不希望 **FastAPI** 包含一个使用 `root_path` 的自动服务器,可以使用参数 `root_path_in_servers=False`:
-FastAPI 在内部使用 `root_path`,因此子应用也可以正常运行。✨
+{* ../../docs_src/behind_a_proxy/tutorial004_py39.py hl[9] *}
+
+这样它就不会被包含到 OpenAPI 模式中。
+
+## 挂载子应用 { #mounting-a-sub-application }
+
+如果你需要在使用带有 `root_path` 的代理时挂载一个子应用(参见 [子应用 - 挂载](sub-applications.md){.internal-link target=_blank}),你可以像预期的那样正常操作。
+
+FastAPI 会在内部智能地使用 `root_path`,因此它可以直接正常工作。✨
diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md
index 22a9b4b51..f5bec5fdc 100644
--- a/docs/zh/docs/advanced/custom-response.md
+++ b/docs/zh/docs/advanced/custom-response.md
@@ -1,32 +1,38 @@
-# 自定义响应 - HTML,流,文件和其他
+# 自定义响应 - HTML、流、文件等 { #custom-response-html-stream-file-others }
**FastAPI** 默认会使用 `JSONResponse` 返回响应。
你可以通过直接返回 `Response` 来重载它,参见 [直接返回响应](response-directly.md){.internal-link target=_blank}。
-但如果你直接返回 `Response`,返回数据不会自动转换,也不会自动生成文档(例如,在 HTTP 头 `Content-Type` 中包含特定的「媒体类型」作为生成的 OpenAPI 的一部分)。
+但如果你直接返回一个 `Response`(或其任意子类,比如 `JSONResponse`),返回数据不会自动转换(即使你声明了 `response_model`),也不会自动生成文档(例如,在生成的 OpenAPI 中,HTTP 头 `Content-Type` 里的特定「媒体类型」不会被包含)。
-你还可以在 *路径操作装饰器* 中声明你想用的 `Response`。
+你还可以在 *路径操作装饰器* 中通过 `response_class` 参数声明要使用的 `Response`(例如任意 `Response` 子类)。
你从 *路径操作函数* 中返回的内容将被放在该 `Response` 中。
-并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或者 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。
+并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。
-/// note | 说明
+/// note | 注意
-如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。
+如果你使用不带有任何媒体类型的响应类,FastAPI 会认为你的响应没有任何内容,所以不会在生成的 OpenAPI 文档中记录响应格式。
///
-## 使用 `ORJSONResponse`
+## 使用 `ORJSONResponse` { #use-orjsonresponse }
例如,如果你需要压榨性能,你可以安装并使用 `orjson` 并将响应设置为 `ORJSONResponse`。
导入你想要使用的 `Response` 类(子类)然后在 *路径操作装饰器* 中声明它。
-{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *}
+对于较大的响应,直接返回一个 `Response` 会比返回一个字典快得多。
-/// info | 提示
+这是因为默认情况下,FastAPI 会检查其中的每一项并确保它可以被序列化为 JSON,使用教程中解释的相同 [JSON 兼容编码器](../tutorial/encoder.md){.internal-link target=_blank}。这正是它允许你返回「任意对象」的原因,例如数据库模型。
+
+但如果你确定你返回的内容是「可以用 JSON 序列化」的,你可以将它直接传给响应类,从而避免在传给响应类之前先通过 `jsonable_encoder` 带来的额外开销。
+
+{* ../../docs_src/custom_response/tutorial001b_py39.py hl[2,7] *}
+
+/// info | 信息
参数 `response_class` 也会用来定义响应的「媒体类型」。
@@ -36,22 +42,22 @@
///
-/// tip | 小贴士
+/// tip | 提示
`ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。
///
-## HTML 响应
+## HTML 响应 { #html-response }
使用 `HTMLResponse` 来从 **FastAPI** 中直接返回一个 HTML 响应。
* 导入 `HTMLResponse`。
* 将 `HTMLResponse` 作为你的 *路径操作* 的 `response_class` 参数传入。
-{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial002_py39.py hl[2,7] *}
-/// info | 提示
+/// info | 信息
参数 `response_class` 也会用来定义响应的「媒体类型」。
@@ -61,13 +67,13 @@
///
-### 返回一个 `Response`
+### 返回一个 `Response` { #return-a-response }
正如你在 [直接返回响应](response-directly.md){.internal-link target=_blank} 中了解到的,你也可以通过直接返回响应在 *路径操作* 中直接重载响应。
和上面一样的例子,返回一个 `HTMLResponse` 看起来可能是这样:
-{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *}
+{* ../../docs_src/custom_response/tutorial003_py39.py hl[2,7,19] *}
/// warning | 警告
@@ -75,33 +81,33 @@
///
-/// info | 提示
+/// info | 信息
-当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。
+当然,实际的 `Content-Type` 头、状态码等等,将来自于你返回的 `Response` 对象。
///
-### OpenAPI 中的文档和重载 `Response`
+### 在 OpenAPI 中文档化并重载 `Response` { #document-in-openapi-and-override-response }
如果你想要在函数内重载响应,但是同时在 OpenAPI 中文档化「媒体类型」,你可以使用 `response_class` 参数并返回一个 `Response` 对象。
接着 `response_class` 参数只会被用来文档化 OpenAPI 的 *路径操作*,你的 `Response` 用来返回响应。
-### 直接返回 `HTMLResponse`
+#### 直接返回 `HTMLResponse` { #return-an-htmlresponse-directly }
比如像这样:
-{* ../../docs_src/custom_response/tutorial004.py hl[7,23,21] *}
+{* ../../docs_src/custom_response/tutorial004_py39.py hl[7,21,23] *}
在这个例子中,函数 `generate_html_response()` 已经生成并返回 `Response` 对象而不是在 `str` 中返回 HTML。
-通过返回函数 `generate_html_response()` 的调用结果,你已经返回一个重载 **FastAPI** 默认行为的 `Response` 对象,
+通过返回函数 `generate_html_response()` 的调用结果,你已经返回一个重载 **FastAPI** 默认行为的 `Response` 对象。
-但如果你在 `response_class` 中也传入了 `HTMLResponse`,**FastAPI** 会知道如何在 OpenAPI 和交互式文档中使用 `text/html` 将其文档化为 HTML。
+但如果你在 `response_class` 中也传入了 `HTMLResponse`,**FastAPI** 会知道如何在 OpenAPI 和交互式文档中使用 `text/html` 将其文档化为 HTML:
-## 可用响应
+## 可用响应 { #available-responses }
这里有一些可用的响应。
@@ -115,7 +121,7 @@
///
-### `Response`
+### `Response` { #response }
其他全部的响应都继承自主类 `Response`。
@@ -128,77 +134,115 @@
* `headers` - 一个由字符串组成的 `dict`。
* `media_type` - 一个给出媒体类型的 `str`,比如 `"text/html"`。
-FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它还将包含一个基于 media_type 的 Content-Type 头,并为文本类型附加一个字符集。
+FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它还将包含一个基于 `media_type` 的 Content-Type 头,并为文本类型附加一个字符集。
+{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
-{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
-
-### `HTMLResponse`
+### `HTMLResponse` { #htmlresponse }
如上文所述,接受文本或字节并返回 HTML 响应。
-### `PlainTextResponse`
+### `PlainTextResponse` { #plaintextresponse }
接受文本或字节并返回纯文本响应。
-{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial005_py39.py hl[2,7,9] *}
-### `JSONResponse`
+### `JSONResponse` { #jsonresponse }
接受数据并返回一个 `application/json` 编码的响应。
如上文所述,这是 **FastAPI** 中使用的默认响应。
-### `ORJSONResponse`
+### `ORJSONResponse` { #orjsonresponse }
如上文所述,`ORJSONResponse` 是一个使用 `orjson` 的快速的可选 JSON 响应。
+/// info | 信息
-### `UJSONResponse`
+这需要先安装 `orjson`,例如使用 `pip install orjson`。
+
+///
+
+### `UJSONResponse` { #ujsonresponse }
`UJSONResponse` 是一个使用 `ujson` 的可选 JSON 响应。
+/// info | 信息
+
+这需要先安装 `ujson`,例如使用 `pip install ujson`。
+
+///
+
/// warning | 警告
在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。
///
-{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001_py39.py hl[2,7] *}
-/// tip | 小贴士
+/// tip | 提示
`ORJSONResponse` 可能是一个更快的选择。
///
-### `RedirectResponse`
+### `RedirectResponse` { #redirectresponse }
-返回 HTTP 重定向。默认情况下使用 307 状态代码(临时重定向)。
+返回 HTTP 重定向。默认情况下使用 307 状态码(临时重定向)。
-{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *}
+你可以直接返回一个 `RedirectResponse`:
-### `StreamingResponse`
+{* ../../docs_src/custom_response/tutorial006_py39.py hl[2,9] *}
+
+---
+
+或者你可以把它用于 `response_class` 参数:
+
+{* ../../docs_src/custom_response/tutorial006b_py39.py hl[2,7,9] *}
+
+如果你这么做,那么你可以在 *路径操作* 函数中直接返回 URL。
+
+在这种情况下,将使用 `RedirectResponse` 的默认 `status_code`,即 `307`。
+
+---
+
+你也可以将 `status_code` 参数和 `response_class` 参数结合使用:
+
+{* ../../docs_src/custom_response/tutorial006c_py39.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
采用异步生成器或普通生成器/迭代器,然后流式传输响应主体。
-{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *}
+{* ../../docs_src/custom_response/tutorial007_py39.py hl[2,14] *}
-#### 对类似文件的对象使用 `StreamingResponse`
+#### 对类似文件的对象使用 `StreamingResponse` { #using-streamingresponse-with-file-like-objects }
-如果您有类似文件的对象(例如,由 `open()` 返回的对象),则可以在 `StreamingResponse` 中将其返回。
+如果您有一个类文件对象(例如由 `open()` 返回的对象),你可以创建一个生成器函数来迭代该类文件对象。
-包括许多与云存储,视频处理等交互的库。
+这样,你就不必先把它全部读入内存,可以将该生成器函数传给 `StreamingResponse` 并返回它。
-{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *}
+这也包括许多与云存储、视频处理等交互的库。
-/// tip | 小贴士
+{* ../../docs_src/custom_response/tutorial008_py39.py hl[2,10:12,14] *}
+
+1. 这是生成器函数。之所以是「生成器函数」,是因为它内部包含 `yield` 语句。
+2. 通过使用 `with` 代码块,我们可以确保在生成器函数完成后关闭类文件对象。因此,在它完成发送响应之后会被关闭。
+3. 这个 `yield from` 告诉函数去迭代名为 `file_like` 的那个对象。然后,对于每个被迭代出来的部分,都把该部分作为来自这个生成器函数(`iterfile`)的值再 `yield` 出去。
+
+ 因此,它是一个把「生成」工作内部转交给其他东西的生成器函数。
+
+ 通过这种方式,我们可以把它放在 `with` 代码块中,从而确保类文件对象在结束后被关闭。
+
+/// tip | 提示
注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。
///
-### `FileResponse`
+### `FileResponse` { #fileresponse }
异步传输文件作为响应。
@@ -209,10 +253,60 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
* `media_type` - 给出媒体类型的字符串。如果未设置,则文件名或路径将用于推断媒体类型。
* `filename` - 如果给出,它将包含在响应的 `Content-Disposition` 中。
-文件响应将包含适当的 `Content-Length`,`Last-Modified` 和 `ETag` 的响应头。
+文件响应将包含适当的 `Content-Length`、`Last-Modified` 和 `ETag` 响应头。
-{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *}
+{* ../../docs_src/custom_response/tutorial009_py39.py hl[2,10] *}
-## 额外文档
+你也可以使用 `response_class` 参数:
-您还可以使用 `response` 在 OpenAPI 中声明媒体类型和许多其他详细信息:[OpenAPI 中的额外文档](additional-responses.md){.internal-link target=_blank}。
+{* ../../docs_src/custom_response/tutorial009b_py39.py hl[2,8,10] *}
+
+在这种情况下,你可以在 *路径操作* 函数中直接返回文件路径。
+
+## 自定义响应类 { #custom-response-class }
+
+你可以创建你自己的自定义响应类,继承自 `Response` 并使用它。
+
+例如,假设你想使用 `orjson`,但要使用内置 `ORJSONResponse` 类没有启用的一些自定义设置。
+
+假设你想让它返回带缩进、格式化的 JSON,因此你想使用 orjson 选项 `orjson.OPT_INDENT_2`。
+
+你可以创建一个 `CustomORJSONResponse`。你需要做的主要事情是实现一个返回 `bytes` 的 `Response.render(content)` 方法:
+
+{* ../../docs_src/custom_response/tutorial009c_py39.py hl[9:14,17] *}
+
+现在,不再是返回:
+
+```json
+{"message": "Hello World"}
+```
+
+…这个响应将返回:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+当然,你很可能会找到比格式化 JSON 更好的方式来利用这一点。😉
+
+## 默认响应类 { #default-response-class }
+
+在创建 **FastAPI** 类实例或 `APIRouter` 时,你可以指定默认要使用的响应类。
+
+用于定义它的参数是 `default_response_class`。
+
+在下面的示例中,**FastAPI** 会在所有 *路径操作* 中默认使用 `ORJSONResponse`,而不是 `JSONResponse`。
+
+{* ../../docs_src/custom_response/tutorial010_py39.py hl[2,4] *}
+
+/// tip | 提示
+
+你仍然可以像之前一样在 *路径操作* 中重载 `response_class`。
+
+///
+
+## 额外文档 { #additional-documentation }
+
+你还可以使用 `responses` 在 OpenAPI 中声明媒体类型和许多其他详细信息:[OpenAPI 中的额外文档](additional-responses.md){.internal-link target=_blank}。
diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md
index 4e8e77d2a..d62aef8f3 100644
--- a/docs/zh/docs/advanced/dataclasses.md
+++ b/docs/zh/docs/advanced/dataclasses.md
@@ -1,97 +1,87 @@
-# 使用数据类
+# 使用数据类 { #using-dataclasses }
-FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 模型声明请求与响应。
+FastAPI 基于 **Pydantic** 构建,我已经向你展示过如何使用 Pydantic 模型声明请求与响应。
-但 FastAPI 还可以使用数据类(`dataclasses`):
+但 FastAPI 也支持以相同方式使用 `dataclasses`:
-{* ../../docs_src/dataclasses_/tutorial001.py hl[1,7:12,19:20] *}
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
-这还是借助于 **Pydantic** 及其内置的 `dataclasses`。
+这仍然得益于 **Pydantic**,因为它对 `dataclasses` 的内置支持。
-因此,即便上述代码没有显式使用 Pydantic,FastAPI 仍会使用 Pydantic 把标准数据类转换为 Pydantic 数据类(`dataclasses`)。
+因此,即便上面的代码没有显式使用 Pydantic,FastAPI 也会使用 Pydantic 将那些标准数据类转换为 Pydantic 风格的 dataclasses。
并且,它仍然支持以下功能:
* 数据验证
* 数据序列化
-* 数据存档等
+* 数据文档等
-数据类的和运作方式与 Pydantic 模型相同。实际上,它的底层使用的也是 Pydantic。
+这与使用 Pydantic 模型时的工作方式相同。而且底层实际上也是借助 Pydantic 实现的。
-/// info | 说明
+/// info | 信息
-注意,数据类不支持 Pydantic 模型的所有功能。
+请注意,数据类不能完成 Pydantic 模型能做的所有事情。
-因此,开发时仍需要使用 Pydantic 模型。
+因此,你可能仍然需要使用 Pydantic 模型。
-但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓
+但如果你已有一堆数据类,这个技巧可以让它们很好地为使用 FastAPI 的 Web API 所用。🤓
///
-## `response_model` 使用数据类
+## 在 `response_model` 中使用数据类 { #dataclasses-in-response-model }
-在 `response_model` 参数中使用 `dataclasses`:
+你也可以在 `response_model` 参数中使用 `dataclasses`:
-{* ../../docs_src/dataclasses_/tutorial002.py hl[1,7:13,19] *}
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
-本例把数据类自动转换为 Pydantic 数据类。
+该数据类会被自动转换为 Pydantic 的数据类。
-API 文档中也会显示相关概图:
+这样,它的模式会显示在 API 文档界面中:
-## 在嵌套数据结构中使用数据类
+## 在嵌套数据结构中使用数据类 { #dataclasses-in-nested-data-structures }
-您还可以把 `dataclasses` 与其它类型注解组合在一起,创建嵌套数据结构。
+你也可以把 `dataclasses` 与其它类型注解组合在一起,创建嵌套数据结构。
-还有一些情况也可以使用 Pydantic 的 `dataclasses`。例如,在 API 文档中显示错误。
+在某些情况下,你可能仍然需要使用 Pydantic 的 `dataclasses` 版本。例如,如果自动生成的 API 文档出现错误。
-本例把标准的 `dataclasses` 直接替换为 `pydantic.dataclasses`:
+在这种情况下,你可以直接把标准的 `dataclasses` 替换为 `pydantic.dataclasses`,它是一个可直接替换的实现:
-```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" }
-{!../../docs_src/dataclasses_/tutorial003.py!}
-```
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
-1. 本例依然要从标准的 `dataclasses` 中导入 `field`;
+1. 我们仍然从标准库的 `dataclasses` 导入 `field`。
+2. `pydantic.dataclasses` 是 `dataclasses` 的可直接替换版本。
+3. `Author` 数据类包含一个由 `Item` 数据类组成的列表。
+4. `Author` 数据类被用作 `response_model` 参数。
+5. 你可以将其它标准类型注解与数据类一起用作请求体。
-2. 使用 `pydantic.dataclasses` 直接替换 `dataclasses`;
+ 在本例中,它是一个 `Item` 数据类列表。
+6. 这里我们返回一个字典,里面的 `items` 是一个数据类列表。
-3. `Author` 数据类包含 `Item` 数据类列表;
+ FastAPI 仍然能够将数据序列化为 JSON。
+7. 这里的 `response_model` 使用了 “`Author` 数据类列表” 的类型注解。
-4. `Author` 数据类用于 `response_model` 参数;
+ 同样,你可以将 `dataclasses` 与标准类型注解组合使用。
+8. 注意,这个 *路径操作函数* 使用的是常规的 `def` 而不是 `async def`。
-5. 其它带有数据类的标准类型注解也可以作为请求体;
+ 一如既往,在 FastAPI 中你可以按需组合 `def` 和 `async def`。
- 本例使用的是 `Item` 数据类列表;
+ 如果需要回顾何时用哪一个,请查看关于 [`async` 和 `await`](../async.md#in-a-hurry){.internal-link target=_blank} 的文档中的 _“急不可待?”_ 一节。
+9. 这个 *路径操作函数* 返回的不是数据类(当然也可以返回数据类),而是包含内部数据的字典列表。
-6. 这行代码返回的是包含 `items` 的字典,`items` 是数据类列表;
+ FastAPI 会使用(包含数据类的)`response_model` 参数来转换响应。
- FastAPI 仍能把数据序列化为 JSON;
+你可以将 `dataclasses` 与其它类型注解以多种不同方式组合,来构建复杂的数据结构。
-7. 这行代码中,`response_model` 的类型注解是 `Author` 数据类列表;
+更多细节请参考上面代码中的内联注释提示。
- 再一次,可以把 `dataclasses` 与标准类型注解一起使用;
+## 深入学习 { #learn-more }
-8. 注意,*路径操作函数*使用的是普通函数,不是异步函数;
+你还可以把 `dataclasses` 与其它 Pydantic 模型组合、从它们继承、把它们包含到你自己的模型中等。
- 与往常一样,在 FastAPI 中,可以按需组合普通函数与异步函数;
+想了解更多,请查看 Pydantic 关于 dataclasses 的文档。
- 如果不清楚何时使用异步函数或普通函数,请参阅**急不可待?**一节中对 `async` 与 `await` 的说明;
+## 版本 { #version }
-9. *路径操作函数*返回的不是数据类(虽然它可以返回数据类),而是返回内含数据的字典列表;
-
- FastAPI 使用(包含数据类的) `response_model` 参数转换响应。
-
-把 `dataclasses` 与其它类型注解组合在一起,可以组成不同形式的复杂数据结构。
-
-更多内容详见上述代码内的注释。
-
-## 深入学习
-
-您还可以把 `dataclasses` 与其它 Pydantic 模型组合在一起,继承合并的模型,把它们包含在您自己的模型里。
-
-详见 Pydantic 官档 - 数据类。
-
-## 版本
-
-本章内容自 FastAPI `0.67.0` 版起生效。🔖
+自 FastAPI 版本 `0.67.0` 起可用。🔖
diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md
index 1ef6cdd3c..7b49931a4 100644
--- a/docs/zh/docs/advanced/events.md
+++ b/docs/zh/docs/advanced/events.md
@@ -1,18 +1,18 @@
-# 生命周期事件
+# 生命周期事件 { #lifespan-events }
你可以定义在应用**启动**前执行的逻辑(代码)。这意味着在应用**开始接收请求**之前,这些代码只会被执行**一次**。
同样地,你可以定义在应用**关闭**时应执行的逻辑。在这种情况下,这段代码将在**处理可能的多次请求后**执行**一次**。
-因为这段代码在应用开始接收请求**之前**执行,也会在处理可能的若干请求**之后**执行,它覆盖了整个应用程序的**生命周期**("生命周期"这个词很重要😉)。
+因为这段代码在应用开始接收请求**之前**执行,也会在处理可能的若干请求**之后**执行,它覆盖了整个应用程序的**生命周期**(“生命周期”这个词很重要😉)。
这对于设置你需要在整个应用中使用的**资源**非常有用,这些资源在请求之间**共享**,你可能需要在之后进行**释放**。例如,数据库连接池,或加载一个共享的机器学习模型。
-## 用例
+## 用例 { #use-case }
-让我们从一个示例用例开始,看看如何解决它。
+让我们从一个示例**用例**开始,看看如何用它来解决问题。
-假设你有几个**机器学习的模型**,你想要用它们来处理请求。
+假设你有几个**机器学习的模型**,你想要用它们来处理请求。🤖
相同的模型在请求之间是共享的,因此并非每个请求或每个用户各自拥有一个模型。
@@ -20,19 +20,17 @@
你可以在模块/文件的顶部加载它,但这也意味着即使你只是在运行一个简单的自动化测试,它也会**加载模型**,这样测试将**变慢**,因为它必须在能够独立运行代码的其他部分之前等待模型加载完成。
-这就是我们要解决的问题——在处理请求前加载模型,但只是在应用开始接收请求前,而不是代码执行时。
+这就是我们要解决的问题——在处理请求前加载模型,但只是在应用开始接收请求前,而不是在代码被加载时。
-## 生命周期 lifespan
+## Lifespan { #lifespan }
-你可以使用`FastAPI()`应用的`lifespan`参数和一个上下文管理器(稍后我将为你展示)来定义**启动**和**关闭**的逻辑。
+你可以使用 `FastAPI` 应用的 `lifespan` 参数和一个“上下文管理器”(稍后我将为你展示)来定义**启动**和**关闭**的逻辑。
让我们从一个例子开始,然后详细介绍。
-我们使用`yield`创建了一个异步函数`lifespan()`像这样:
+我们使用 `yield` 创建了一个异步函数 `lifespan()` 像这样:
-```Python hl_lines="16 19"
-{!../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003_py39.py hl[16,19] *}
在这里,我们在 `yield` 之前将(虚拟的)模型函数放入机器学习模型的字典中,以此模拟加载模型的耗时**启动**操作。这段代码将在应用程序**开始处理请求之前**执行,即**启动**期间。
@@ -40,35 +38,31 @@
/// tip | 提示
-**关闭**事件只会在你停止应用时触发。
+**关闭**事件会在你**停止**应用时发生。
-可能你需要启动一个新版本,或者你只是你厌倦了运行它。 🤷
+可能你需要启动一个新版本,或者你只是厌倦了运行它。 🤷
///
-## 生命周期函数
+### 生命周期函数 { #lifespan-function }
首先要注意的是,我们定义了一个带有 `yield` 的异步函数。这与带有 `yield` 的依赖项非常相似。
-```Python hl_lines="14-19"
-{!../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003_py39.py hl[14:19] *}
-这个函数在 `yield`之前的部分,会在应用启动前执行。
+这个函数在 `yield` 之前的部分,会在应用启动前执行。
剩下的部分在 `yield` 之后,会在应用完成后执行。
-## 异步上下文管理器
+### 异步上下文管理器 { #async-context-manager }
-如你所见,这个函数有一个装饰器 `@asynccontextmanager` 。
+如你所见,这个函数有一个装饰器 `@asynccontextmanager`。
它将函数转化为所谓的“**异步上下文管理器**”。
-```Python hl_lines="1 13"
-{!../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003_py39.py hl[1,13] *}
-在 Python 中, **上下文管理器**是一个你可以在 `with` 语句中使用的东西,例如,`open()` 可以作为上下文管理器使用。
+在 Python 中,**上下文管理器**是一个你可以在 `with` 语句中使用的东西,例如,`open()` 可以作为上下文管理器使用。
```Python
with open("file.txt") as file:
@@ -82,21 +76,19 @@ async with lifespan(app):
await do_stuff()
```
-你可以像上面一样创建了一个上下文管理器或者异步上下文管理器,它的作用是在进入 `with` 块时,执行 `yield` 之前的代码,并且在离开 `with` 块时,执行 `yield` 后面的代码。
+你可以像上面一样创建一个上下文管理器或者异步上下文管理器,它的作用是在进入 `with` 块时,执行 `yield` 之前的代码,并且在离开 `with` 块时,执行 `yield` 后面的代码。
但在我们上面的例子里,我们并不是直接使用,而是传递给 FastAPI 来供其使用。
-`FastAPI()` 的 `lifespan` 参数接受一个**异步上下文管理器**,所以我们可以把我们新定义的上下文管理器 `lifespan` 传给它。
+`FastAPI` 的 `lifespan` 参数接受一个**异步上下文管理器**,所以我们可以把我们新定义的异步上下文管理器 `lifespan` 传给它。
-```Python hl_lines="22"
-{!../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003_py39.py hl[22] *}
-## 替代事件(弃用)
+## 替代事件(弃用) { #alternative-events-deprecated }
/// warning | 警告
-配置**启动**和**关闭**事件的推荐方法是使用 `FastAPI()` 应用的 `lifespan` 参数,如前所示。如果你提供了一个 `lifespan` 参数,启动(`startup`)和关闭(`shutdown`)事件处理器将不再生效。要么使用 `lifespan`,要么配置所有事件,两者不能共用。
+配置**启动**和**关闭**的推荐方法是使用 `FastAPI` 应用的 `lifespan` 参数,如前所示。如果你提供了一个 `lifespan` 参数,启动(`startup`)和关闭(`shutdown`)事件处理器将不再生效。要么使用 `lifespan`,要么配置所有事件,两者不能共用。
你可以跳过这一部分。
@@ -104,70 +96,70 @@ async with lifespan(app):
有一种替代方法可以定义在**启动**和**关闭**期间执行的逻辑。
-**FastAPI** 支持定义在应用启动前,或应用关闭时执行的事件处理器(函数)。
+你可以定义在应用启动前或应用关闭时需要执行的事件处理器(函数)。
事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。
-### `startup` 事件
+### `startup` 事件 { #startup-event }
-使用 `startup` 事件声明 `app` 启动前运行的函数:
+使用事件 `"startup"` 声明一个在应用启动前运行的函数:
-{* ../../docs_src/events/tutorial001.py hl[8] *}
+{* ../../docs_src/events/tutorial001_py39.py hl[8] *}
-本例中,`startup` 事件处理器函数为项目数据库(只是**字典**)提供了一些初始值。
+本例中,`startup` 事件处理器函数为项目“数据库”(只是一个 `dict`)提供了一些初始值。
**FastAPI** 支持多个事件处理器函数。
只有所有 `startup` 事件处理器运行完毕,**FastAPI** 应用才开始接收请求。
-### `shutdown` 事件
+### `shutdown` 事件 { #shutdown-event }
-使用 `shutdown` 事件声明 `app` 关闭时运行的函数:
+使用事件 `"shutdown"` 声明一个在应用关闭时运行的函数:
-{* ../../docs_src/events/tutorial002.py hl[6] *}
+{* ../../docs_src/events/tutorial002_py39.py hl[6] *}
-此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。
+此处,`shutdown` 事件处理器函数会向文件 `log.txt` 写入一行文本 `"Application shutdown"`。
-/// info | 说明
+/// info | 信息
-`open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。
+在 `open()` 函数中,`mode="a"` 指的是“追加”。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。
///
/// tip | 提示
-注意,本例使用 Python `open()` 标准函数与文件交互。
+注意,本例使用 Python 标准的 `open()` 函数与文件交互。
-这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。
+这个函数执行 I/O(输入/输出)操作,需要“等待”内容写进磁盘。
-但 `open()` 函数不支持使用 `async` 与 `await`。
+但 `open()` 不使用 `async` 和 `await`。
-因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。
+因此,声明事件处理函数要使用 `def`,而不是 `async def`。
///
-### `startup` 和 `shutdown` 一起使用
+### `startup` 和 `shutdown` 一起使用 { #startup-and-shutdown-together }
启动和关闭的逻辑很可能是连接在一起的,你可能希望启动某个东西然后结束它,获取一个资源然后释放它等等。
在不共享逻辑或变量的不同函数中处理这些逻辑比较困难,因为你需要在全局变量中存储值或使用类似的方式。
-因此,推荐使用 `lifespan` 。
+因此,推荐使用上面所述的 `lifespan`。
-## 技术细节
+## 技术细节 { #technical-details }
只是为好奇者提供的技术细节。🤓
-在底层,这部分是生命周期协议的一部分,参见 ASGI 技术规范,定义了称为启动(`startup`)和关闭(`shutdown`)的事件。
+在底层,这部分是 ASGI 技术规范中的 Lifespan 协议的一部分,定义了称为 `startup` 和 `shutdown` 的事件。
-/// info | 说明
+/// info | 信息
-有关事件处理器的详情,请参阅 Starlette 官档 - 事件。
+你可以在 Starlette 的 Lifespan 文档 中阅读更多关于 `lifespan` 处理器的内容。
-包括如何处理生命周期状态,这可以用于程序的其他部分。
+包括如何处理生命周期状态,以便在代码的其他部分使用。
///
-## 子应用
+## 子应用 { #sub-applications }
-🚨 **FastAPI** 只会触发主应用中的生命周期事件,不包括[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的。
+🚨 请注意,这些生命周期事件(startup 和 shutdown)只会在主应用上执行,不会在[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}上执行。
diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md
index bcb9ba2bf..48a4ba07a 100644
--- a/docs/zh/docs/advanced/generate-clients.md
+++ b/docs/zh/docs/advanced/generate-clients.md
@@ -1,237 +1,208 @@
-# 生成客户端
+# 生成 SDK { #generating-sdks }
-因为 **FastAPI** 是基于OpenAPI规范的,自然您可以使用许多相匹配的工具,包括自动生成API文档 (由 Swagger UI 提供)。
+因为 **FastAPI** 基于 **OpenAPI** 规范,它的 API 可以用许多工具都能理解的标准格式来描述。
-一个不太明显而又特别的优势是,你可以为你的API针对不同的**编程语言**来**生成客户端**(有时候被叫做 **SDKs** )。
+这让你可以轻松生成最新的**文档**、多语言的客户端库(**SDKs**),以及与代码保持同步的**测试**或**自动化工作流**。
-## OpenAPI 客户端生成
+本指南将带你为 FastAPI 后端生成一个 **TypeScript SDK**。
-有许多工具可以从**OpenAPI**生成客户端。
+## 开源 SDK 生成器 { #open-source-sdk-generators }
-一个常见的工具是 OpenAPI Generator。
+一个功能多样的选择是 OpenAPI Generator,它支持**多种编程语言**,可以根据你的 OpenAPI 规范生成 SDK。
-如果您正在开发**前端**,一个非常有趣的替代方案是 openapi-ts。
+对于 **TypeScript 客户端**,Hey API 是为 TypeScript 生态打造的专用方案,提供优化的使用体验。
-## 生成一个 TypeScript 前端客户端
+你还可以在 OpenAPI.Tools 上发现更多 SDK 生成器。
-让我们从一个简单的 FastAPI 应用开始:
+/// tip | 提示
-{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *}
-
-请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。
-
-### API 文档
-
-如果您访问API文档,您将看到它具有在请求中发送和在响应中接收数据的**模式(schemas)**:
-
-
-
-您可以看到这些模式,因为它们是用程序中的模型声明的。
-
-那些信息可以在应用的 **OpenAPI模式** 被找到,然后显示在API文档中(通过Swagger UI)。
-
-OpenAPI中所包含的模型里有相同的信息可以用于 **生成客户端代码**。
-
-### 生成一个TypeScript 客户端
-
-现在我们有了带有模型的应用,我们可以为前端生成客户端代码。
-
-#### 安装 `openapi-ts`
-
-您可以使用以下工具在前端代码中安装 `openapi-ts`:
-
-
-
-您还将自动补全要发送的数据:
-
-
-
-/// tip
-
-请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。
+FastAPI 会自动生成 **OpenAPI 3.1** 规范,因此你使用的任何工具都必须支持该版本。
///
-如果发送的数据字段不符,你也会看到编辑器的错误提示:
+## 来自 FastAPI 赞助商的 SDK 生成器 { #sdk-generators-from-fastapi-sponsors }
+
+本节介绍的是由赞助 FastAPI 的公司提供的、具备**风险投资背景**或**公司支持**的方案。这些产品在高质量生成的 SDK 之上,提供了**更多特性**和**集成**。
+
+通过 ✨ [**赞助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,这些公司帮助确保框架及其**生态**保持健康并且**可持续**。
+
+他们的赞助也体现了对 FastAPI **社区**(也就是你)的高度承诺,不仅关注提供**优秀的服务**,也支持一个**健壮且繁荣的框架**——FastAPI。🙇
+
+例如,你可以尝试:
+
+* Speakeasy
+* Stainless
+* liblab
+
+其中一些方案也可能是开源的或提供免费层级,你可以不花钱就先试用。其他商业 SDK 生成器也可在网上找到。🤓
+
+## 创建一个 TypeScript SDK { #create-a-typescript-sdk }
+
+先从一个简单的 FastAPI 应用开始:
+
+{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *}
+
+请注意,这些*路径操作*使用 `Item` 和 `ResponseMessage` 模型来定义它们的请求载荷和响应载荷。
+
+### API 文档 { #api-docs }
+
+访问 `/docs` 时,你会看到有用于请求发送和响应接收数据的**模式**:
+
+
+
+之所以能看到这些模式,是因为它们在应用中用模型声明了。
+
+这些信息会包含在应用的 **OpenAPI 模式** 中,并显示在 API 文档里。
+
+OpenAPI 中包含的这些模型信息就是用于**生成客户端代码**的基础。
+
+### Hey API { #hey-api }
+
+当我们有了带模型的 FastAPI 应用后,可以使用 Hey API 来生成 TypeScript 客户端。最快的方式是通过 npx:
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+这会在 `./src/client` 生成一个 TypeScript SDK。
+
+你可以在其官网了解如何安装 `@hey-api/openapi-ts`,以及阅读生成结果的说明。
+
+### 使用 SDK { #using-the-sdk }
+
+现在你可以导入并使用客户端代码了。它可能是这样,并且你会发现方法有自动补全:
+
+
+
+要发送的载荷也会有自动补全:
+
+
+
+/// tip | 提示
+
+请注意 `name` 和 `price` 的自动补全,它们是在 FastAPI 应用中的 `Item` 模型里定义的。
+
+///
+
+你发送的数据如果不符合要求,会在编辑器中显示内联错误:
-响应(response)对象也拥有自动补全:
+响应对象同样有自动补全:
-## 带有标签的 FastAPI 应用
+## 带有标签的 FastAPI 应用 { #fastapi-app-with-tags }
-在许多情况下,你的FastAPI应用程序会更复杂,你可能会使用标签来分隔不同组的*路径操作(path operations)*。
+很多情况下,你的 FastAPI 应用会更大,你可能会用标签来划分不同组的*路径操作*。
-例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔:
+例如,你可以有一个 **items** 相关的部分和另一个 **users** 相关的部分,它们可以用标签来分隔:
{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *}
-### 生成带有标签的 TypeScript 客户端
+### 生成带标签的 TypeScript 客户端 { #generate-a-typescript-client-with-tags }
-如果您使用标签为FastAPI应用生成客户端,它通常也会根据标签分割客户端代码。
+如果你为使用了标签的 FastAPI 应用生成客户端,通常也会根据标签来拆分客户端代码。
-通过这种方式,您将能够为客户端代码进行正确地排序和分组:
+这样你就可以在客户端代码中把内容正确地组织和分组:
-在这个案例中,您有:
+在这个例子中,你会有:
* `ItemsService`
* `UsersService`
-### 客户端方法名称
+### 客户端方法名 { #client-method-names }
-现在生成的方法名像 `createItemItemsPost` 看起来不太简洁:
+现在,像 `createItemItemsPost` 这样的生成方法名看起来不太简洁:
```TypeScript
ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
```
-...这是因为客户端生成器为每个 *路径操作* 使用OpenAPI的内部 **操作 ID(operation ID)**。
+……这是因为客户端生成器会把每个*路径操作*的 OpenAPI 内部**操作 ID(operation ID)**用作方法名的一部分。
-OpenAPI要求每个操作 ID 在所有 *路径操作* 中都是唯一的,因此 FastAPI 使用**函数名**、**路径**和**HTTP方法/操作**来生成此操作ID,因为这样可以确保这些操作 ID 是唯一的。
+OpenAPI 要求每个操作 ID 在所有*路径操作*中都是唯一的,因此 FastAPI 会使用**函数名**、**路径**和**HTTP 方法/操作**来生成操作 ID,以确保其唯一性。
-但接下来我会告诉你如何改进。 🤓
+接下来我会告诉你如何改进。🤓
-## 自定义操作ID和更好的方法名
+## 自定义操作 ID 与更好的方法名 { #custom-operation-ids-and-better-method-names }
-您可以**修改**这些操作ID的**生成**方式,以使其更简洁,并在客户端中具有**更简洁的方法名称**。
+你可以**修改**这些操作 ID 的**生成**方式,使之更简单,从而在客户端中得到**更简洁的方法名**。
-在这种情况下,您必须确保每个操作ID在其他方面是**唯一**的。
+在这种情况下,你需要用其他方式确保每个操作 ID 依然是**唯一**的。
-例如,您可以确保每个*路径操作*都有一个标签,然后根据**标签**和*路径操作***名称**(函数名)来生成操作ID。
+例如,你可以确保每个*路径操作*都有一个标签,然后基于**标签**和*路径操作***名称**(函数名)来生成操作 ID。
-### 自定义生成唯一ID函数
+### 自定义唯一 ID 生成函数 { #custom-generate-unique-id-function }
-FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID**,也用于任何所需自定义模型的名称,用于请求或响应。
+FastAPI 为每个*路径操作*使用一个**唯一 ID**,它既用于**操作 ID**,也用于请求或响应里任何需要的自定义模型名称。
-你可以自定义该函数。它接受一个 `APIRoute` 对象作为输入,并输出一个字符串。
+你可以自定义这个函数。它接收一个 `APIRoute` 并返回一个字符串。
-例如,以下是一个示例,它使用第一个标签(你可能只有一个标签)和*路径操作*名称(函数名)。
+例如,这里使用第一个标签(你很可能只有一个标签)和*路径操作*名称(函数名)。
-然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**:
+然后你可以把这个自定义函数通过 `generate_unique_id_function` 参数传给 **FastAPI**:
{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *}
-### 使用自定义操作ID生成TypeScript客户端
+### 使用自定义操作 ID 生成 TypeScript 客户端 { #generate-a-typescript-client-with-custom-operation-ids }
-现在,如果你再次生成客户端,你会发现它具有改善的方法名称:
+现在再次生成客户端,你会看到方法名已经改进:
-正如你所见,现在方法名称中只包含标签和函数名,不再包含URL路径和HTTP操作的信息。
+如你所见,方法名现在由标签和函数名组成,不再包含 URL 路径和 HTTP 操作的信息。
-### 预处理用于客户端生成器的OpenAPI规范
+### 为客户端生成器预处理 OpenAPI 规范 { #preprocess-the-openapi-specification-for-the-client-generator }
-生成的代码仍然存在一些**重复的信息**。
+生成的代码中仍有一些**重复信息**。
-我们已经知道该方法与 **items** 相关,因为它在 `ItemsService` 中(从标签中获取),但方法名中仍然有标签名作为前缀。😕
+我们已经知道这个方法与 **items** 有关,因为它位于 `ItemsService`(来自标签),但方法名里仍然带有标签名前缀。😕
-一般情况下对于OpenAPI,我们可能仍然希望保留它,因为这将确保操作ID是**唯一的**。
+通常我们仍然希望在 OpenAPI 中保留它,以确保操作 ID 的**唯一性**。
-但对于生成的客户端,我们可以在生成客户端之前**修改** OpenAPI 操作ID,以使方法名称更加美观和**简洁**。
+但对于生成的客户端,我们可以在生成之前**修改** OpenAPI 的操作 ID,只是为了让方法名更美观、更**简洁**。
-我们可以将 OpenAPI JSON 下载到一个名为`openapi.json`的文件中,然后使用以下脚本**删除此前缀的标签**:
+我们可以把 OpenAPI JSON 下载到 `openapi.json` 文件中,然后用如下脚本**移除这个标签前缀**:
-{* ../../docs_src/generate_clients/tutorial004.py *}
+{* ../../docs_src/generate_clients/tutorial004_py39.py *}
-通过这样做,操作ID将从类似于 `items-get_items` 的名称重命名为 `get_items` ,这样客户端生成器就可以生成更简洁的方法名称。
+//// tab | Node.js
-### 使用预处理的OpenAPI生成TypeScript客户端
-
-现在,由于最终结果保存在文件openapi.json中,你可以修改 package.json 文件以使用此本地文件,例如:
-
-```JSON hl_lines="7"
-{
- "name": "frontend-app",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios"
- },
- "author": "",
- "license": "",
- "devDependencies": {
- "@hey-api/openapi-ts": "^0.27.38",
- "typescript": "^4.6.2"
- }
-}
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
```
-生成新的客户端之后,你现在将拥有**清晰的方法名称**,具备**自动补全**、**错误提示**等功能:
+////
+
+这样,操作 ID 会从 `items-get_items` 之类的名字重命名为 `get_items`,从而让客户端生成器生成更简洁的方法名。
+
+### 使用预处理后的 OpenAPI 生成 TypeScript 客户端 { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+因为最终结果现在保存在 `openapi.json` 中,你需要更新输入位置:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+生成新客户端后,你将拥有**简洁的方法名**,并具备**自动补全**、**内联错误**等功能:
-## 优点
+## 优点 { #benefits }
-当使用自动生成的客户端时,你将获得以下的自动补全功能:
+使用自动生成的客户端时,你会获得以下内容的**自动补全**:
-* 方法。
-* 请求体中的数据、查询参数等。
-* 响应数据。
+* 方法
+* 请求体中的数据、查询参数等
+* 响应数据
-你还将获得针对所有内容的错误提示。
+你还会为所有内容获得**内联错误**。
-每当你更新后端代码并**重新生成**前端代码时,新的*路径操作*将作为方法可用,旧的方法将被删除,并且其他任何更改将反映在生成的代码中。 🤓
+每当你更新后端代码并**重新生成**前端时,新的*路径操作*会作为方法可用,旧的方法会被移除,其他任何更改都会反映到生成的代码中。🤓
-这也意味着如果有任何更改,它将自动**反映**在客户端代码中。如果你**构建**客户端,在使用的数据上存在**不匹配**时,它将报错。
+这也意味着如果有任何变更,它会自动**反映**到客户端代码中。而当你**构建**客户端时,如果所用数据存在任何**不匹配**,它会直接报错。
-因此,你将在开发周期的早期**检测到许多错误**,而不必等待错误在生产环境中向最终用户展示,然后尝试调试问题所在。 ✨
+因此,你可以在开发周期的早期就**发现许多错误**,而不必等到错误在生产环境中暴露给最终用户后再去调试问题所在。✨
diff --git a/docs/zh/docs/advanced/index.md b/docs/zh/docs/advanced/index.md
index 6525802fc..610c18713 100644
--- a/docs/zh/docs/advanced/index.md
+++ b/docs/zh/docs/advanced/index.md
@@ -1,21 +1,21 @@
-# 高级用户指南
+# 高级用户指南 { #advanced-user-guide }
-## 额外特性
+## 附加功能 { #additional-features }
-主要的教程 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 应该足以让你了解 **FastAPI** 的所有主要特性。
+主要的[教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank}足以带你了解 **FastAPI** 的所有主要特性。
-你会在接下来的章节中了解到其他的选项、配置以及额外的特性。
+在接下来的章节中,你将看到其他选项、配置和附加功能。
-/// tip
+/// tip | 提示
-接下来的章节**并不一定是**「高级的」。
+接下来的章节不一定是“高级”的。
-而且对于你的使用场景来说,解决方案很可能就在其中。
+对于你的用例,解决方案很可能就在其中之一。
///
-## 先阅读教程
+## 先阅读教程 { #read-the-tutorial-first }
-你可能仍会用到 **FastAPI** 主教程 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 中的大多数特性。
+仅凭主要[教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank}中的知识,你已经可以使用 **FastAPI** 的大多数功能。
-接下来的章节我们认为你已经读过 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank},并且假设你已经知晓其中主要思想。
+接下来的章节默认你已经读过它,并理解其中的核心概念。
diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md
index 65e8c183f..108bbbb5c 100644
--- a/docs/zh/docs/advanced/middleware.md
+++ b/docs/zh/docs/advanced/middleware.md
@@ -1,4 +1,4 @@
-# 高级中间件
+# 高级中间件 { #advanced-middleware }
用户指南介绍了如何为应用添加[自定义中间件](../tutorial/middleware.md){.internal-link target=_blank} 。
@@ -6,9 +6,9 @@
本章学习如何使用其它中间件。
-## 添加 ASGI 中间件
+## 添加 ASGI 中间件 { #adding-asgi-middlewares }
-因为 **FastAPI** 基于 Starlette,且执行 ASGI 规范,所以可以使用任意 ASGI 中间件。
+因为 **FastAPI** 基于 Starlette,且执行 ASGI 规范,所以可以使用任意 ASGI 中间件。
中间件不必是专为 FastAPI 或 Starlette 定制的,只要遵循 ASGI 规范即可。
@@ -39,11 +39,11 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
`app.add_middleware()` 的第一个参数是中间件的类,其它参数则是要传递给中间件的参数。
-## 集成中间件
+## 集成中间件 { #integrated-middlewares }
**FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。
-/// note | 技术细节
+/// note | 注意
以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。
@@ -51,45 +51,47 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
///
-## `HTTPSRedirectMiddleware`
+## `HTTPSRedirectMiddleware` { #httpsredirectmiddleware }
强制所有传入请求必须是 `https` 或 `wss`。
任何传向 `http` 或 `ws` 的请求都会被重定向至安全方案。
-{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial001_py39.py hl[2,6] *}
-## `TrustedHostMiddleware`
+## `TrustedHostMiddleware` { #trustedhostmiddleware }
强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。
-{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *}
+{* ../../docs_src/advanced_middleware/tutorial002_py39.py hl[2,6:8] *}
支持以下参数:
-* `allowed_hosts` - 允许的域名(主机名)列表。`*.example.com` 等通配符域名可以匹配子域名,或使用 `allowed_hosts=["*"]` 允许任意主机名,或省略中间件。
+* `allowed_hosts` - 允许的域名(主机名)列表。`*.example.com` 等通配符域名可以匹配子域名。若要允许任意主机名,可使用 `allowed_hosts=["*"]` 或省略此中间件。
+* `www_redirect` - 若设置为 `True`,对允许主机的非 www 版本的请求将被重定向到其 www 版本。默认为 `True`。
如果传入的请求没有通过验证,则发送 `400` 响应。
-## `GZipMiddleware`
+## `GZipMiddleware` { #gzipmiddleware }
-处理 `Accept-Encoding` 请求头中包含 `gzip` 请求的 GZip 响应。
+处理 `Accept-Encoding` 请求头中包含 `"gzip"` 请求的 GZip 响应。
中间件会处理标准响应与流响应。
-{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial003_py39.py hl[2,6] *}
支持以下参数:
-* `minimum_size` - 小于最小字节的响应不使用 GZip。 默认值是 `500`。
+* `minimum_size` - 小于该最小字节数的响应不使用 GZip。默认值是 `500`。
+* `compresslevel` - GZip 压缩使用的级别,为 1 到 9 的整数。默认为 `9`。值越低压缩越快但文件更大,值越高压缩越慢但文件更小。
-## 其它中间件
+## 其它中间件 { #other-middlewares }
除了上述中间件外,FastAPI 还支持其它ASGI 中间件。
例如:
-* Uvicorn 的 `ProxyHeadersMiddleware`
+* Uvicorn 的 `ProxyHeadersMiddleware`
* MessagePack
-其它可用中间件详见 Starlette 官档 - 中间件 及 ASGI Awesome 列表。
+其它可用中间件详见 Starlette 官档 - 中间件 及 ASGI Awesome 列表。
diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md
index f021eb10a..6e8df68ae 100644
--- a/docs/zh/docs/advanced/openapi-callbacks.md
+++ b/docs/zh/docs/advanced/openapi-callbacks.md
@@ -1,12 +1,12 @@
-# OpenAPI 回调
+# OpenAPI 回调 { #openapi-callbacks }
-您可以创建触发外部 API 请求的*路径操作* API,这个外部 API 可以是别人创建的,也可以是由您自己创建的。
+您可以创建一个包含*路径操作*的 API,它会触发对别人创建的*外部 API*的请求(很可能就是那个会“使用”您 API 的同一个开发者)。
-API 应用调用外部 API 时的流程叫做**回调**。因为外部开发者编写的软件发送请求至您的 API,然后您的 API 要进行回调,并把请求发送至外部 API。
+当您的 API 应用调用*外部 API*时,这个过程被称为“回调”。因为外部开发者编写的软件会先向您的 API 发送请求,然后您的 API 再进行*回调*,向*外部 API*发送请求(很可能也是该开发者创建的)。
-此时,我们需要存档外部 API 的*信息*,比如应该有哪些*路径操作*,返回什么样的请求体,应该返回哪种响应等。
+此时,我们需要存档外部 API 的*信息*,比如应该有哪些*路径操作*,请求体应该是什么,应该返回什么响应等。
-## 使用回调的应用
+## 使用回调的应用 { #an-app-with-callbacks }
示例如下。
@@ -14,16 +14,16 @@ API 应用调用外部 API 时的流程叫做**回调**。因为外部开发者
发票包括 `id`、`title`(可选)、`customer`、`total` 等属性。
-API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建一条发票记录。
+API 的用户(外部开发者)要在您的 API 内使用 POST 请求创建一条发票记录。
(假设)您的 API 将:
* 把发票发送至外部开发者的消费者
* 归集现金
* 把通知发送至 API 的用户(外部开发者)
- * 通过(从您的 API)发送 POST 请求至外部 API (即**回调**)来完成
+ * 通过(从您的 API)发送 POST 请求至外部 API(即**回调**)来完成
-## 常规 **FastAPI** 应用
+## 常规 **FastAPI** 应用 { #the-normal-fastapi-app }
添加回调前,首先看下常规 API 应用是什么样子。
@@ -31,17 +31,17 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建
这部分代码很常规,您对绝大多数代码应该都比较熟悉了:
-{* ../../docs_src/openapi_callbacks/tutorial001.py hl[10:14,37:54] *}
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[7:11,34:51] *}
/// tip | 提示
-`callback_url` 查询参数使用 Pydantic 的 URL 类型。
+`callback_url` 查询参数使用 Pydantic 的 Url 类型。
///
此处唯一比较新的内容是*路径操作装饰器*中的 `callbacks=invoices_callback_router.routes` 参数,下文介绍。
-## 存档回调
+## 存档回调 { #documenting-the-callback }
实际的回调代码高度依赖于您自己的 API 应用。
@@ -51,14 +51,14 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建
```Python
callback_url = "https://example.com/api/v1/invoices/events/"
-requests.post(callback_url, json={"description": "Invoice paid", "paid": True})
+httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
```
但回调最重要的部分可能是,根据 API 要发送给回调请求体的数据等内容,确保您的 API 用户(外部开发者)正确地实现*外部 API*。
因此,我们下一步要做的就是添加代码,为从 API 接收回调的*外部 API*存档。
-这部分文档在 `/docs` 下的 Swagger API 文档中显示,并且会告诉外部开发者如何构建*外部 API*。
+这部分文档在 `/docs` 下的 Swagger UI 中显示,并且会告诉外部开发者如何构建*外部 API*。
本例没有实现回调本身(只是一行代码),只有文档部分。
@@ -66,17 +66,17 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True})
实际的回调只是 HTTP 请求。
-实现回调时,要使用 HTTPX 或 Requests。
+实现回调时,要使用 HTTPX 或 Requests。
///
-## 编写回调文档代码
+## 编写回调文档代码 { #write-the-callback-documentation-code }
应用不执行这部分代码,只是用它来*记录 外部 API* 。
但,您已经知道用 **FastAPI** 创建自动 API 文档有多简单了。
-我们要使用与存档*外部 API* 相同的知识……通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。
+我们要使用与存档*外部 API* 相同的知识...通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。
/// tip | 提示
@@ -86,13 +86,13 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True})
///
-### 创建回调的 `APIRouter`
+### 创建回调的 `APIRouter` { #create-a-callback-apirouter }
首先,新建包含一些用于回调的 `APIRouter`。
-{* ../../docs_src/openapi_callbacks/tutorial001.py hl[5,26] *}
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[1,23] *}
-### 创建回调*路径操作*
+### 创建回调*路径操作* { #create-the-callback-path-operation }
创建回调*路径操作*也使用之前创建的 `APIRouter`。
@@ -101,16 +101,16 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True})
* 声明要接收的请求体,例如,`body: InvoiceEvent`
* 还要声明要返回的响应,例如,`response_model=InvoiceEventReceived`
-{* ../../docs_src/openapi_callbacks/tutorial001.py hl[17:19,22:23,29:33] *}
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[14:16,19:20,26:30] *}
回调*路径操作*与常规*路径操作*有两点主要区别:
* 它不需要任何实际的代码,因为应用不会调用这段代码。它只是用于存档*外部 API*。因此,函数的内容只需要 `pass` 就可以了
-* *路径*可以包含 OpenAPI 3 表达式(详见下文),可以使用带参数的变量,以及发送至您的 API 的原始请求的部分
+* *路径*可以包含 OpenAPI 3 表达式(详见下文),可以使用带参数的变量,以及发送至您的 API 的原始请求的部分
-### 回调路径表达式
+### 回调路径表达式 { #the-callback-path-expression }
-回调*路径*支持包含发送给您的 API 的原始请求的部分的 OpenAPI 3 表达式。
+回调*路径*支持包含发送给您的 API 的原始请求的部分的 OpenAPI 3 表达式。
本例中是**字符串**:
@@ -159,17 +159,17 @@ JSON 请求体包含如下内容:
/// tip | 提示
-注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。
+注意,回调 URL 包含 `callback_url`(`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。
///
-### 添加回调路由
+### 添加回调路由 { #add-the-callback-router }
至此,在上文创建的回调路由里就包含了*回调路径操作*(外部开发者要在外部 API 中实现)。
现在使用 API *路径操作装饰器*的参数 `callbacks`,从回调路由传递属性 `.routes`(实际上只是路由/路径操作的**列表**):
-{* ../../docs_src/openapi_callbacks/tutorial001.py hl[36] *}
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *}
/// tip | 提示
@@ -177,9 +177,9 @@ JSON 请求体包含如下内容:
///
-### 查看文档
+### 查看文档 { #check-the-docs }
-现在,使用 Uvicorn 启动应用,打开 http://127.0.0.1:8000/docs。
+现在,使用 Uvicorn 启动应用,打开 http://127.0.0.1:8000/docs。
就能看到文档的*路径操作*已经包含了**回调**的内容以及*外部 API*:
diff --git a/docs/zh/docs/advanced/openapi-webhooks.md b/docs/zh/docs/advanced/openapi-webhooks.md
index 92ae8db15..9e64ed4e3 100644
--- a/docs/zh/docs/advanced/openapi-webhooks.md
+++ b/docs/zh/docs/advanced/openapi-webhooks.md
@@ -1,4 +1,4 @@
-# OpenAPI 网络钩子
+# OpenAPI 网络钩子 { #openapi-webhooks }
有些情况下,您可能想告诉您的 API **用户**,您的应用程序可以携带一些数据调用*他们的*应用程序(给它们发送请求),通常是为了**通知**某种**事件**。
@@ -6,7 +6,7 @@
这通常被称为**网络钩子**(Webhook)。
-## 使用网络钩子的步骤
+## 使用网络钩子的步骤 { #webhooks-steps }
通常的过程是**您**在代码中**定义**要发送的消息,即**请求的主体**。
@@ -16,27 +16,27 @@
所有关于注册网络钩子的 URL 的**逻辑**以及发送这些请求的实际代码都由您决定。您可以在**自己的代码**中以任何想要的方式来编写它。
-## 使用 `FastAPI` 和 OpenAPI 文档化网络钩子
+## 使用 `FastAPI` 和 OpenAPI 文档化网络钩子 { #documenting-webhooks-with-fastapi-and-openapi }
使用 **FastAPI**,您可以利用 OpenAPI 来自定义这些网络钩子的名称、您的应用可以发送的 HTTP 操作类型(例如 `POST`、`PUT` 等)以及您的应用将发送的**请求体**。
这能让您的用户更轻松地**实现他们的 API** 来接收您的**网络钩子**请求,他们甚至可能能够自动生成一些自己的 API 代码。
-/// info
+/// info | 信息
网络钩子在 OpenAPI 3.1.0 及以上版本中可用,FastAPI `0.99.0` 及以上版本支持。
///
-## 带有网络钩子的应用程序
+## 带有网络钩子的应用程序 { #an-app-with-webhooks }
当您创建一个 **FastAPI** 应用程序时,有一个 `webhooks` 属性可以用来定义网络钩子,方式与您定义*路径操作*的时候相同,例如使用 `@app.webhooks.post()` 。
-{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *}
+{* ../../docs_src/openapi_webhooks/tutorial001_py39.py hl[9:13,36:53] *}
您定义的网络钩子将被包含在 `OpenAPI` 的架构中,并出现在自动生成的**文档 UI** 中。
-/// info
+/// info | 信息
`app.webhooks` 对象实际上只是一个 `APIRouter` ,与您在使用多个文件来构建应用程序时所使用的类型相同。
@@ -46,7 +46,7 @@
这是因为我们预计**您的用户**会以其他方式(例如通过网页仪表板)来定义他们希望接收网络钩子的请求的实际 **URL 路径**。
-### 查看文档
+### 查看文档 { #check-the-docs }
现在您可以启动您的应用程序并访问 http://127.0.0.1:8000/docs.
diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md
index 12600eddb..6c9928ffc 100644
--- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md
@@ -1,26 +1,26 @@
-# 路径操作的高级配置
+# 路径操作的高级配置 { #path-operation-advanced-configuration }
-## OpenAPI 的 operationId
+## OpenAPI 的 operationId { #openapi-operationid }
/// warning
-如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。
+如果你并非 OpenAPI 的“专家”,你可能不需要这部分内容。
///
-你可以在路径操作中通过参数 `operation_id` 设置要使用的 OpenAPI `operationId`。
+你可以在 *路径操作* 中通过参数 `operation_id` 设置要使用的 OpenAPI `operationId`。
-务必确保每个操作路径的 `operation_id` 都是唯一的。
+务必确保每个操作的 `operation_id` 都是唯一的。
-{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}
-### 使用 *路径操作函数* 的函数名作为 operationId
+### 使用 *路径操作函数* 的函数名作为 operationId { #using-the-path-operation-function-name-as-the-operationid }
-如果你想用你的 API 的函数名作为 `operationId` 的名字,你可以遍历一遍 API 的函数名,然后使用他们的 `APIRoute.name` 重写每个 *路径操作* 的 `operation_id`。
+如果你想用 API 的函数名作为 `operationId`,你可以遍历所有路径操作,并使用它们的 `APIRoute.name` 重写每个 *路径操作* 的 `operation_id`。
你应该在添加了所有 *路径操作* 之后执行此操作。
-{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12,13,14,15,16,17,18,19,20,21,24] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py39.py hl[2, 12:21, 24] *}
/// tip
@@ -36,19 +36,137 @@
///
-## 从 OpenAPI 中排除
+## 从 OpenAPI 中排除 { #exclude-from-openapi }
-使用参数 `include_in_schema` 并将其设置为 `False` ,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了)。
+使用参数 `include_in_schema` 并将其设置为 `False`,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了):
-{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}
-## docstring 的高级描述
+## 来自 docstring 的高级描述 { #advanced-description-from-docstring }
你可以限制 *路径操作函数* 的 `docstring` 中用于 OpenAPI 的行数。
-添加一个 `\f` (一个「换页」的转义字符)可以使 **FastAPI** 在那一位置截断用于 OpenAPI 的输出。
+添加一个 `\f`(一个“换页”的转义字符)可以使 **FastAPI** 在那一位置截断用于 OpenAPI 的输出。
剩余部分不会出现在文档中,但是其他工具(比如 Sphinx)可以使用剩余部分。
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
-{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19,20,21,22,23,24,25,26,27,28,29] *}
+## 附加响应 { #additional-responses }
+
+你可能已经见过如何为一个 *路径操作* 声明 `response_model` 和 `status_code`。
+
+这定义了该 *路径操作* 主响应的元数据。
+
+你也可以为它声明带有各自模型、状态码等的附加响应。
+
+文档中有一个完整章节,你可以阅读这里的[OpenAPI 中的附加响应](additional-responses.md){.internal-link target=_blank}。
+
+## OpenAPI Extra { #openapi-extra }
+
+当你在应用中声明一个 *路径操作* 时,**FastAPI** 会自动生成与该 *路径操作* 相关的元数据,以包含到 OpenAPI 方案中。
+
+/// note | 技术细节
+
+在 OpenAPI 规范中,这被称为 Operation 对象。
+
+///
+
+它包含关于该 *路径操作* 的所有信息,并用于生成自动文档。
+
+它包括 `tags`、`parameters`、`requestBody`、`responses` 等。
+
+这个特定于 *路径操作* 的 OpenAPI 方案通常由 **FastAPI** 自动生成,但你也可以扩展它。
+
+/// tip
+
+这是一个较低层级的扩展点。
+
+如果你只需要声明附加响应,更方便的方式是使用[OpenAPI 中的附加响应](additional-responses.md){.internal-link target=_blank}。
+
+///
+
+你可以使用参数 `openapi_extra` 扩展某个 *路径操作* 的 OpenAPI 方案。
+
+### OpenAPI 扩展 { #openapi-extensions }
+
+例如,这个 `openapi_extra` 可用于声明 [OpenAPI 扩展](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py39.py hl[6] *}
+
+当你打开自动 API 文档时,你的扩展会显示在该 *路径操作* 的底部。
+
+
+
+如果你查看最终生成的 OpenAPI(在你的 API 的 `/openapi.json`),你也会看到你的扩展作为该 *路径操作* 的一部分:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### 自定义 OpenAPI 路径操作方案 { #custom-openapi-path-operation-schema }
+
+`openapi_extra` 中的字典会与该 *路径操作* 自动生成的 OpenAPI 方案进行深度合并。
+
+因此,你可以在自动生成的方案上添加额外数据。
+
+例如,你可以决定用自己的代码读取并验证请求,而不使用 FastAPI 与 Pydantic 的自动功能,但你仍然希望在 OpenAPI 方案中定义该请求。
+
+你可以用 `openapi_extra` 来做到:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py39.py hl[19:36, 39:40] *}
+
+在这个示例中,我们没有声明任何 Pydantic 模型。事实上,请求体甚至没有被 解析 为 JSON,而是直接以 `bytes` 读取,并由函数 `magic_data_reader()` 以某种方式负责解析。
+
+尽管如此,我们仍然可以声明请求体的预期方案。
+
+### 自定义 OpenAPI 内容类型 { #custom-openapi-content-type }
+
+使用同样的技巧,你可以用一个 Pydantic 模型来定义 JSON Schema,然后把它包含到该 *路径操作* 的自定义 OpenAPI 方案部分中。
+
+即使请求中的数据类型不是 JSON,你也可以这样做。
+
+例如,在这个应用中我们不使用 FastAPI 集成的从 Pydantic 模型提取 JSON Schema 的功能,也不使用对 JSON 的自动校验。实际上,我们将请求的内容类型声明为 YAML,而不是 JSON:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[15:20, 22] *}
+
+尽管我们没有使用默认的集成功能,我们仍然使用 Pydantic 模型手动生成我们想以 YAML 接收的数据的 JSON Schema。
+
+然后我们直接使用请求并将请求体提取为 `bytes`。这意味着 FastAPI 甚至不会尝试将请求负载解析为 JSON。
+
+接着在我们的代码中,我们直接解析该 YAML 内容,然后再次使用同一个 Pydantic 模型来验证该 YAML 内容:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[24:31] *}
+
+/// tip
+
+这里我们复用了同一个 Pydantic 模型。
+
+但同样地,我们也可以用其他方式对其进行验证。
+
+///
diff --git a/docs/zh/docs/advanced/response-change-status-code.md b/docs/zh/docs/advanced/response-change-status-code.md
index cc1f2a73e..cdcd39f50 100644
--- a/docs/zh/docs/advanced/response-change-status-code.md
+++ b/docs/zh/docs/advanced/response-change-status-code.md
@@ -1,10 +1,10 @@
-# 响应 - 更改状态码
+# 响应 - 更改状态码 { #response-change-status-code }
你可能之前已经了解到,你可以设置默认的[响应状态码](../tutorial/response-status-code.md){.internal-link target=_blank}。
但在某些情况下,你需要返回一个不同于默认值的状态码。
-## 使用场景
+## 使用场景 { #use-case }
例如,假设你想默认返回一个HTTP状态码为“OK”`200`。
@@ -14,16 +14,16 @@
对于这些情况,你可以使用一个`Response`参数。
-## 使用 `Response` 参数
+## 使用 `Response` 参数 { #use-a-response-parameter }
你可以在你的*路径操作函数*中声明一个`Response`类型的参数(就像你可以为cookies和头部做的那样)。
然后你可以在这个*临时*响应对象中设置`status_code`。
-{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *}
+{* ../../docs_src/response_change_status_code/tutorial001_py39.py hl[1,9,12] *}
然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。
-**FastAPI**将使用这个临时响应来提取状态码(也包括cookies和头部),并将它们放入包含你返回的值的最终响应中,该响应由任何`response_model`过滤。
+**FastAPI**将使用这个*临时*响应来提取状态码(也包括cookies和头部),并将它们放入包含你返回的值的最终响应中,该响应由任何`response_model`过滤。
你也可以在依赖项中声明`Response`参数,并在其中设置状态码。但请注意,最后设置的状态码将会生效。
diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md
index d5f2fe6fc..cc311a270 100644
--- a/docs/zh/docs/advanced/response-cookies.md
+++ b/docs/zh/docs/advanced/response-cookies.md
@@ -1,10 +1,10 @@
-# 响应Cookies
+# 响应Cookies { #response-cookies }
-## 使用 `Response` 参数
+## 使用 `Response` 参数 { #use-a-response-parameter }
-你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。
+你可以在 *路径操作函数* 中定义一个类型为 `Response` 的参数,这样你就可以在这个临时响应对象中设置cookie了。
-{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *}
+{* ../../docs_src/response_cookies/tutorial002_py39.py hl[1, 8:9] *}
而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。
@@ -12,17 +12,17 @@
**FastAPI** 会使用这个 *临时* 响应对象去装在这些cookies信息 (同样还有headers和状态码等信息), 最终会将这些信息和通过`response_model`转化过的数据合并到最终的响应里。
-你也可以在depend中定义`Response`参数,并设置cookie和header。
+你也可以在依赖中定义`Response`参数,并设置cookie和header。
-## 直接响应 `Response`
+## 直接响应 `Response` { #return-a-response-directly }
你还可以在直接响应`Response`时直接创建cookies。
-你可以参考[Return a Response Directly](response-directly.md){.internal-link target=_blank}来创建response
+你可以参考[直接返回 Response](response-directly.md){.internal-link target=_blank}来创建response
然后设置Cookies,并返回:
-{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *}
+{* ../../docs_src/response_cookies/tutorial001_py39.py hl[10:12] *}
/// tip
@@ -34,7 +34,7 @@
///
-### 更多信息
+### 更多信息 { #more-info }
/// note | 技术细节
diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md
index 4d9cd53f2..8a9cf6ab8 100644
--- a/docs/zh/docs/advanced/response-directly.md
+++ b/docs/zh/docs/advanced/response-directly.md
@@ -1,4 +1,4 @@
-# 直接返回响应
+# 直接返回响应 { #return-a-response-directly }
当你创建一个 **FastAPI** *路径操作* 时,你可以正常返回以下任意一种数据:`dict`,`list`,Pydantic 模型,数据库模型等等。
@@ -10,11 +10,11 @@
直接返回响应可能会有用处,比如返回自定义的响应头和 cookies。
-## 返回 `Response`
+## 返回 `Response` { #return-a-response }
事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。
-/// tip | 小贴士
+/// tip | 提示
`JSONResponse` 本身是一个 `Response` 的子类。
@@ -26,18 +26,17 @@
这种特性给你极大的可扩展性。你可以返回任何数据类型,重写任何数据声明或者校验,等等。
-## 在 `Response` 中使用 `jsonable_encoder`
+## 在 `Response` 中使用 `jsonable_encoder` { #using-the-jsonable-encoder-in-a-response }
由于 **FastAPI** 并未对你返回的 `Response` 做任何改变,你必须确保你已经准备好响应内容。
-例如,如果不首先将 Pydantic 模型转换为 `dict`,并将所有数据类型(如 `datetime`、`UUID` 等)转换为兼容 JSON 的类型,则不能将其放入JSONResponse中。
+例如,如果不首先将 Pydantic 模型转换为 `dict`,并将所有数据类型(如 `datetime`、`UUID` 等)转换为兼容 JSON 的类型,则不能将其放入 `JSONResponse` 中。
-对于这些情况,在将数据传递给响应之前,你可以使用 `jsonable_encoder` 来转换你的数据。
+对于这些情况,在将数据传递给响应之前,你可以使用 `jsonable_encoder` 来转换你的数据:
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
-{* ../../docs_src/response_directly/tutorial001.py hl[4,6,20,21] *}
-
-/// note | 技术细节
+/// note | 注意
你也可以使用 `from starlette.responses import JSONResponse`。
@@ -45,22 +44,22 @@
///
-## 返回自定义 `Response`
+## 返回自定义 `Response` { #returning-a-custom-response }
-上面的例子展示了需要的所有部分,但还不够实用,因为你本可以只是直接返回 `item`,而**FastAPI** 默认帮你把这个 `item` 放到 `JSONResponse` 中,又默认将其转换成了 `dict`等等。
+上面的例子展示了需要的所有部分,但还不够实用,因为你本可以只是直接返回 `item`,而 **FastAPI** 默认帮你把这个 `item` 放到 `JSONResponse` 中,又默认将其转换成了 `dict` 等等。
现在,让我们看看你如何才能返回一个自定义的响应。
假设你想要返回一个 XML 响应。
-你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回。
+你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回:
-{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
+{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
-## 说明
+## 说明 { #notes }
当你直接返回 `Response` 时,它的数据既没有校验,又不会进行转换(序列化),也不会自动生成文档。
-但是你仍可以参考 [OpenApI 中的额外响应](additional-responses.md){.internal-link target=_blank} 给响应编写文档。
+但是你仍可以参考 [OpenAPI 中的额外响应](additional-responses.md){.internal-link target=_blank} 给响应编写文档。
在后续的章节中你可以了解到如何使用/声明这些自定义的 `Response` 的同时还保留自动化的数据转换和文档等。
diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md
index 5c6a62e93..fa02f53be 100644
--- a/docs/zh/docs/advanced/response-headers.md
+++ b/docs/zh/docs/advanced/response-headers.md
@@ -1,39 +1,41 @@
-# 响应头
+# 响应头 { #response-headers }
-## 使用 `Response` 参数
+## 使用 `Response` 参数 { #use-a-response-parameter }
-你可以在你的*路径操作函数*中声明一个`Response`类型的参数(就像你可以为cookies做的那样)。
+你可以在你的*路径操作函数*中声明一个 `Response` 类型的参数(就像你可以为 cookies 做的那样)。
然后你可以在这个*临时*响应对象中设置头部。
-{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *}
-然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。
+{* ../../docs_src/response_headers/tutorial002_py39.py hl[1, 7:8] *}
-**FastAPI**将使用这个临时响应来提取头部(也包括cookies和状态码),并将它们放入包含你返回的值的最终响应中,该响应由任何`response_model`过滤。
+然后你可以像平常一样返回任何你需要的对象(例如一个 `dict` 或者一个数据库模型)。
-你也可以在依赖项中声明`Response`参数,并在其中设置头部(和cookies)。
+如果你声明了一个 `response_model`,它仍然会被用来过滤和转换你返回的对象。
-## 直接返回 `Response`
+**FastAPI** 将使用这个临时响应来提取头部(也包括 cookies 和状态码),并将它们放入包含你返回的值的最终响应中,该响应由任何 `response_model` 过滤。
-你也可以在直接返回`Response`时添加头部。
+你也可以在依赖项中声明 `Response` 参数,并在其中设置头部(和 cookies)。
+
+## 直接返回 `Response` { #return-a-response-directly }
+
+你也可以在直接返回 `Response` 时添加头部。
按照[直接返回响应](response-directly.md){.internal-link target=_blank}中所述创建响应,并将头部作为附加参数传递:
-{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *}
-
+{* ../../docs_src/response_headers/tutorial001_py39.py hl[10:12] *}
/// note | 技术细节
-你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。
+你也可以使用 `from starlette.responses import Response` 或 `from starlette.responses import JSONResponse`。
-**FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。
+**FastAPI** 提供了与 `fastapi.responses` 相同的 `starlette.responses`,只是为了方便你(开发者)。但是,大多数可用的响应都直接来自 Starlette。
-由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。
+由于 `Response` 经常用于设置头部和 cookies,**FastAPI** 还在 `fastapi.Response` 中提供了它。
///
-## 自定义头部
+## 自定义头部 { #custom-headers }
-请注意,可以使用'X-'前缀添加自定义专有头部。
+请注意,可以通过使用 `X-` 前缀添加自定义专有头部。
-但是,如果你有自定义头部,你希望浏览器中的客户端能够看到它们,你需要将它们添加到你的CORS配置中(在[CORS(跨源资源共享)](../tutorial/cors.md){.internal-link target=_blank}中阅读更多),使用在Starlette的CORS文档中记录的`expose_headers`参数。
+但是,如果你有自定义头部,并希望浏览器中的客户端能够看到它们,你需要将它们添加到你的 CORS 配置中(在 [CORS(跨源资源共享)](../tutorial/cors.md){.internal-link target=_blank} 中阅读更多),使用在 Starlette 的 CORS 文档中记录的 `expose_headers` 参数。
diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md
index 599429f9d..55479d8e3 100644
--- a/docs/zh/docs/advanced/security/http-basic-auth.md
+++ b/docs/zh/docs/advanced/security/http-basic-auth.md
@@ -1,4 +1,4 @@
-# HTTP 基础授权
+# HTTP 基础授权 { #http-basic-auth }
最简单的用例是使用 HTTP 基础授权(HTTP Basic Auth)。
@@ -6,16 +6,16 @@
如果没有接收到 HTTP 基础授权,就返回 HTTP 401 `"Unauthorized"` 错误。
-并返回含 `Basic` 值的请求头 `WWW-Authenticate`以及可选的 `realm` 参数。
+并返回响应头 `WWW-Authenticate`,其值为 `Basic`,以及可选的 `realm` 参数。
HTTP 基础授权让浏览器显示内置的用户名与密码提示。
输入用户名与密码后,浏览器会把它们自动发送至请求头。
-## 简单的 HTTP 基础授权
+## 简单的 HTTP 基础授权 { #simple-http-basic-auth }
* 导入 `HTTPBasic` 与 `HTTPBasicCredentials`
-* 使用 `HTTPBasic` 创建**安全概图**
+* 使用 `HTTPBasic` 创建**安全方案**
* 在*路径操作*的依赖项中使用 `security`
* 返回类型为 `HTTPBasicCredentials` 的对象:
* 包含发送的 `username` 与 `password`
@@ -26,7 +26,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。
-## 检查用户名
+## 检查用户名 { #check-the-username }
以下是更完整的示例。
@@ -52,13 +52,13 @@ if not (credentials.username == "stanleyjobson") or not (credentials.password ==
但使用 `secrets.compare_digest()`,可以防御**时差攻击**,更加安全。
-### 时差攻击
+### 时差攻击 { #timing-attacks }
什么是**时差攻击**?
假设攻击者试图猜出用户名与密码。
-他们发送用户名为 `johndoe`,密码为 `love123` 的请求。
+他们发送用户名为 `johndoe`,密码为 `love123` 的请求。
然后,Python 代码执行如下操作:
@@ -80,28 +80,28 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
此时,Python 要对比 `stanleyjobsox` 与 `stanleyjobson` 中的 `stanleyjobso`,才能知道这两个字符串不一样。因此会多花费几微秒来返回**错误的用户或密码**。
-#### 反应时间对攻击者的帮助
+#### 反应时间对攻击者的帮助 { #the-time-to-answer-helps-the-attackers }
通过服务器花费了更多微秒才发送**错误的用户或密码**响应,攻击者会知道猜对了一些内容,起码开头字母是正确的。
然后,他们就可以放弃 `johndoe`,再用类似 `stanleyjobsox` 的内容进行尝试。
-#### **专业**攻击
+#### **专业**攻击 { #a-professional-attack }
当然,攻击者不用手动操作,而是编写每秒能执行成千上万次测试的攻击程序,每次都会找到更多正确字符。
但是,在您的应用的**帮助**下,攻击者利用时间差,就能在几分钟或几小时内,以这种方式猜出正确的用户名和密码。
-#### 使用 `secrets.compare_digest()` 修补
+#### 使用 `secrets.compare_digest()` 修补 { #fix-it-with-secrets-compare-digest }
在此,代码中使用了 `secrets.compare_digest()`。
简单的说,它使用相同的时间对比 `stanleyjobsox` 和 `stanleyjobson`,还有 `johndoe` 和 `stanleyjobson`。对比密码时也一样。
-在代码中使用 `secrets.compare_digest()` ,就可以安全地防御全面攻击了。
+在代码中使用 `secrets.compare_digest()` ,就可以安全地防御这整类安全攻击。
-### 返回错误
+### 返回错误 { #return-the-error }
-检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示:
+检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加响应头 `WWW-Authenticate`,让浏览器再次显示登录提示:
{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *}
diff --git a/docs/zh/docs/advanced/security/index.md b/docs/zh/docs/advanced/security/index.md
index 267e7ced7..84fec7aab 100644
--- a/docs/zh/docs/advanced/security/index.md
+++ b/docs/zh/docs/advanced/security/index.md
@@ -1,19 +1,19 @@
-# 高级安全
+# 高级安全 { #advanced-security }
-## 附加特性
+## 附加特性 { #additional-features }
-除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性.
+除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性。
-/// tip | 小贴士
+/// tip | 提示
-接下来的章节 **并不一定是 "高级的"**.
+接下来的章节**并不一定是 "高级的"**。
而且对于你的使用场景来说,解决方案很可能就在其中。
///
-## 先阅读教程
+## 先阅读教程 { #read-the-tutorial-first }
-接下来的部分假设你已经阅读了主要的 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank}.
+接下来的部分假设你已经阅读了主要的 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank}。
-它们都基于相同的概念,但支持一些额外的功能.
+它们都基于相同的概念,但支持一些额外的功能。
diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md
index 784c38490..ce7facf4b 100644
--- a/docs/zh/docs/advanced/security/oauth2-scopes.md
+++ b/docs/zh/docs/advanced/security/oauth2-scopes.md
@@ -1,274 +1,274 @@
-# OAuth2 作用域
+# OAuth2 作用域 { #oauth2-scopes }
-**FastAPI** 无缝集成 OAuth2 作用域(`Scopes`),可以直接使用。
+你可以在 **FastAPI** 中直接使用 OAuth2 作用域(Scopes),它们已无缝集成。
-作用域是更精密的权限系统,遵循 OAuth2 标准,与 OpenAPI 应用(和 API 自动文档)集成。
+这样你就可以按照 OAuth2 标准,构建更精细的权限系统,并将其集成进你的 OpenAPI 应用(以及 API 文档)中。
-OAuth2 也是脸书、谷歌、GitHub、微软、推特等第三方身份验证应用使用的机制。这些身份验证应用在用户登录应用时使用 OAuth2 提供指定权限。
+带作用域的 OAuth2 是很多大型身份验证提供商使用的机制,例如 Facebook、Google、GitHub、Microsoft、X (Twitter) 等。它们用它来为用户和应用授予特定权限。
-脸书、谷歌、GitHub、微软、推特就是 OAuth2 作用域登录。
+每次你“使用” Facebook、Google、GitHub、Microsoft、X (Twitter) “登录”时,该应用就在使用带作用域的 OAuth2。
-本章介绍如何在 **FastAPI** 应用中使用 OAuth2 作用域管理验证与授权。
+本节将介绍如何在你的 **FastAPI** 应用中,使用相同的带作用域的 OAuth2 管理认证与授权。
/// warning | 警告
-本章内容较难,刚接触 FastAPI 的新手可以跳过。
+本节内容相对进阶,如果你刚开始,可以先跳过。
-OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。
+你并不一定需要 OAuth2 作用域,你也可以用你自己的方式处理认证与授权。
-但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。
+但带作用域的 OAuth2 能很好地集成进你的 API(通过 OpenAPI)和 API 文档。
-不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。
+不过,无论如何,你都可以在代码中按需强制这些作用域,或任何其它安全/授权需求。
-很多情况下,OAuth2 作用域就像一把牛刀。
+很多情况下,带作用域的 OAuth2 可能有点“大材小用”。
-但如果您确定要使用作用域,或对它有兴趣,请继续阅读。
+但如果你确实需要它,或者只是好奇,请继续阅读。
///
-## OAuth2 作用域与 OpenAPI
+## OAuth2 作用域与 OpenAPI { #oauth2-scopes-and-openapi }
-OAuth2 规范的**作用域**是由空格分割的字符串组成的列表。
+OAuth2 规范将“作用域”定义为由空格分隔的字符串列表。
-这些字符串支持任何格式,但不能包含空格。
+这些字符串的内容可以是任意格式,但不应包含空格。
-作用域表示的是**权限**。
+这些作用域表示“权限”。
-OpenAPI 中(例如 API 文档)可以定义**安全方案**。
+在 OpenAPI(例如 API 文档)中,你可以定义“安全方案”(security schemes)。
-这些安全方案在使用 OAuth2 时,还可以声明和使用作用域。
+当这些安全方案使用 OAuth2 时,你还可以声明并使用作用域。
-**作用域**只是(不带空格的)字符串。
+每个“作用域”只是一个(不带空格的)字符串。
-常用于声明特定安全权限,例如:
+它们通常用于声明特定的安全权限,例如:
-* 常见用例为,`users:read` 或 `users:write`
-* 脸书和 Instagram 使用 `instagram_basic`
-* 谷歌使用 `https://www.googleapis.com/auth/drive`
+* 常见示例:`users:read` 或 `users:write`
+* Facebook / Instagram 使用 `instagram_basic`
+* Google 使用 `https://www.googleapis.com/auth/drive`
-/// info | 说明
+/// info | 信息
-OAuth2 中,**作用域**只是声明特定权限的字符串。
+在 OAuth2 中,“作用域”只是一个声明所需特定权限的字符串。
-是否使用冒号 `:` 等符号,或是不是 URL 并不重要。
+是否包含像 `:` 这样的字符,或者是不是一个 URL,并不重要。
-这些细节只是特定的实现方式。
+这些细节取决于具体实现。
-对 OAuth2 来说,它们都只是字符串而已。
+对 OAuth2 而言,它们都只是字符串。
///
-## 全局纵览
+## 全局纵览 { #global-view }
-首先,快速浏览一下以下代码与**用户指南**中 [OAuth2 实现密码哈希与 Bearer JWT 令牌验证](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}一章中代码的区别。以下代码使用 OAuth2 作用域:
+首先,让我们快速看看与**用户指南**中 [OAuth2 实现密码(含哈希)、Bearer + JWT 令牌](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank} 示例相比有哪些变化。现在开始使用 OAuth2 作用域:
-{* ../../docs_src/security/tutorial005.py hl[2,4,8,12,46,64,105,107:115,121:124,128:134,139,153] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
-下面,我们逐步说明修改的代码内容。
+下面我们逐步回顾这些更改。
-## OAuth2 安全方案
+## OAuth2 安全方案 { #oauth2-security-scheme }
-第一个修改的地方是,使用两个作用域 `me` 和 `items ` 声明 OAuth2 安全方案。
+第一个变化是:我们在声明 OAuth2 安全方案时,添加了两个可用的作用域 `me` 和 `items`。
-`scopes` 参数接收**字典**,键是作用域、值是作用域的描述:
+参数 `scopes` 接收一个 `dict`,以作用域为键、描述为值:
-{* ../../docs_src/security/tutorial005.py hl[62:65] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
-因为声明了作用域,所以登录或授权时会在 API 文档中显示。
+因为我们现在声明了这些作用域,所以当你登录/授权时,它们会显示在 API 文档里。
-此处,选择给予访问权限的作用域: `me` 和 `items`。
+你可以选择要授予访问权限的作用域:`me` 和 `items`。
-这也是使用脸书、谷歌、GitHub 登录时的授权机制。
+这与使用 Facebook、Google、GitHub 等登录时授予权限的机制相同:
-## JWT 令牌作用域
+## 带作用域的 JWT 令牌 { #jwt-token-with-scopes }
-现在,修改令牌*路径操作*,返回请求的作用域。
+现在,修改令牌的*路径操作*以返回请求的作用域。
-此处仍然使用 `OAuth2PasswordRequestForm`。它包含类型为**字符串列表**的 `scopes` 属性,且`scopes` 属性中包含要在请求里接收的每个作用域。
+我们仍然使用 `OAuth2PasswordRequestForm`。它包含 `scopes` 属性,其值是 `list[str]`,包含请求中接收到的每个作用域。
-这样,返回的 JWT 令牌中就包含了作用域。
+我们把这些作用域作为 JWT 令牌的一部分返回。
/// danger | 危险
-为了简明起见,本例把接收的作用域直接添加到了令牌里。
+为简单起见,此处我们只是把接收到的作用域直接添加到了令牌中。
-但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。
+但在你的应用里,为了安全起见,你应该只添加该用户实际能够拥有的作用域,或你预先定义的作用域。
///
-{* ../../docs_src/security/tutorial005.py hl[153] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
-## 在*路径操作*与依赖项中声明作用域
+## 在*路径操作*与依赖项中声明作用域 { #declare-scopes-in-path-operations-and-dependencies }
-接下来,为*路径操作* `/users/me/items/` 声明作用域 `items`。
+现在我们声明,路径操作 `/users/me/items/` 需要作用域 `items`。
-为此,要从 `fastapi` 中导入并使用 `Security` 。
+为此,从 `fastapi` 导入并使用 `Security`。
-`Security` 声明依赖项的方式和 `Depends` 一样,但 `Security` 还能接收作用域(字符串)列表类型的参数 `scopes`。
+你可以用 `Security` 来声明依赖(就像 `Depends` 一样),但 `Security` 还接收一个 `scopes` 参数,其值是作用域(字符串)列表。
-此处使用与 `Depends` 相同的方式,把依赖项函数 `get_current_active_user` 传递给 `Security`。
+在这里,我们把依赖函数 `get_current_active_user` 传给 `Security`(就像用 `Depends` 一样)。
-同时,还传递了作用域**列表**,本例中只传递了一个作用域:`items`(此处支持传递更多作用域)。
+同时还传入一个作用域 `list`,此处仅包含一个作用域:`items`(也可以包含更多)。
-依赖项函数 `get_current_active_user` 还能声明子依赖项,不仅可以使用 `Depends`,也可以使用 `Security`。声明子依赖项函数(`get_current_user`)及更多作用域。
+依赖函数 `get_current_active_user` 也可以声明子依赖,不仅可以用 `Depends`,也可以用 `Security`。它声明了自己的子依赖函数(`get_current_user`),并添加了更多的作用域需求。
-本例要求使用作用域 `me`(还可以使用更多作用域)。
+在这个例子里,它需要作用域 `me`(也可以需要多个作用域)。
-/// note | 笔记
+/// note | 注意
不必在不同位置添加不同的作用域。
-本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。
+这里这样做,是为了演示 **FastAPI** 如何处理在不同层级声明的作用域。
///
-{* ../../docs_src/security/tutorial005.py hl[4,139,166] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
/// info | 技术细节
-`Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。
+`Security` 实际上是 `Depends` 的子类,它只多了一个我们稍后会看到的参数。
-但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。
+但当你使用 `Security` 而不是 `Depends` 时,**FastAPI** 会知道它可以声明安全作用域,在内部使用它们,并用 OpenAPI 文档化 API。
-但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。
+另外,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等,实际上都是返回特殊类的函数。
///
-## 使用 `SecurityScopes`
+## 使用 `SecurityScopes` { #use-securityscopes }
-修改依赖项 `get_current_user`。
+现在更新依赖项 `get_current_user`。
-这是上面的依赖项使用的依赖项。
+上面那些依赖会用到它。
-这里使用的也是之前创建的 OAuth2 方案,并把它声明为依赖项:`oauth2_scheme`。
+这里我们使用之前创建的同一个 OAuth2 方案,并把它声明为依赖:`oauth2_scheme`。
-该依赖项函数本身不需要作用域,因此,可以使用 `Depends` 和 `oauth2_scheme`。不需要指定安全作用域时,不必使用 `Security`。
+因为这个依赖函数本身没有任何作用域需求,所以我们可以用 `Depends(oauth2_scheme)`,当不需要指定安全作用域时,不必使用 `Security`。
-此处还声明了从 `fastapi.security` 导入的 `SecurityScopes` 类型的特殊参数。
+我们还声明了一个从 `fastapi.security` 导入的特殊参数 `SecurityScopes` 类型。
-`SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。
+这个 `SecurityScopes` 类类似于 `Request`(`Request` 用来直接获取请求对象)。
-{* ../../docs_src/security/tutorial005.py hl[8,105] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
-## 使用 `scopes`
+## 使用 `scopes` { #use-the-scopes }
参数 `security_scopes` 的类型是 `SecurityScopes`。
-它的属性 `scopes` 是作用域列表,所有依赖项都把它作为子依赖项。也就是说所有**依赖**……这听起来有些绕,后文会有解释。
+它会有一个 `scopes` 属性,包含一个列表,里面是它自身以及所有把它作为子依赖的依赖项所需要的所有作用域。也就是说,所有“依赖者”……这可能有点绕,下面会再次解释。
-(类 `SecurityScopes` 的)`security_scopes` 对象还提供了单字符串类型的属性 `scope_str`,该属性是(要在本例中使用的)用空格分割的作用域。
+`security_scopes` 对象(类型为 `SecurityScopes`)还提供了一个 `scope_str` 属性,它是一个用空格分隔这些作用域的单个字符串(我们将会用到它)。
-此处还创建了后续代码中要复用(`raise`)的 `HTTPException` 。
+我们创建一个 `HTTPException`,后面可以在多个位置复用(`raise`)它。
-该异常包含了作用域所需的(如有),以空格分割的字符串(使用 `scope_str`)。该字符串要放到包含作用域的 `WWW-Authenticate` 请求头中(这也是规范的要求)。
+在这个异常中,我们包含所需的作用域(如果有的话),以空格分隔的字符串(使用 `scope_str`)。我们把这个包含作用域的字符串放在 `WWW-Authenticate` 响应头中(这是规范要求的一部分)。
-{* ../../docs_src/security/tutorial005.py hl[105,107:115] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
-## 校验 `username` 与数据形状
+## 校验 `username` 与数据形状 { #verify-the-username-and-data-shape }
-我们可以校验是否获取了 `username`,并抽取作用域。
+我们校验是否获取到了 `username`,并提取作用域。
-然后,使用 Pydantic 模型校验数据(捕获 `ValidationError` 异常),如果读取 JWT 令牌或使用 Pydantic 模型验证数据时出错,就会触发之前创建的 `HTTPException` 异常。
+然后使用 Pydantic 模型验证这些数据(捕获 `ValidationError` 异常),如果读取 JWT 令牌或用 Pydantic 验证数据时出错,就抛出我们之前创建的 `HTTPException`。
-对此,要使用新的属性 `scopes` 更新 Pydantic 模型 `TokenData`。
+为此,我们给 Pydantic 模型 `TokenData` 添加了一个新属性 `scopes`。
-使用 Pydantic 验证数据可以确保数据中含有由作用域组成的**字符串列表**,以及 `username` 字符串等内容。
+通过用 Pydantic 验证数据,我们可以确保确实得到了例如一个由作用域组成的 `list[str]`,以及一个 `str` 类型的 `username`。
-反之,如果使用**字典**或其它数据结构,就有可能在后面某些位置破坏应用,形成安全隐患。
+而不是,例如得到一个 `dict` 或其它什么,这可能会在后续某个时刻破坏应用,形成安全风险。
-还可以使用用户名验证用户,如果没有用户,也会触发之前创建的异常。
+我们还验证是否存在该用户名的用户,如果没有,就抛出前面创建的同一个异常。
-{* ../../docs_src/security/tutorial005.py hl[46,116:127] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
-## 校验 `scopes`
+## 校验 `scopes` { #verify-the-scopes }
-接下来,校验所有依赖项和依赖要素(包括*路径操作*)所需的作用域。这些作用域包含在令牌的 `scopes` 里,如果不在其中就会触发 `HTTPException` 异常。
+现在我们要验证,这个依赖以及所有依赖者(包括*路径操作*)所需的所有作用域,是否都包含在接收到的令牌里的作用域中,否则就抛出 `HTTPException`。
-为此,要使用包含所有作用域**字符串列表**的 `security_scopes.scopes`, 。
+为此,我们使用 `security_scopes.scopes`,它包含一个由这些作用域组成的 `list[str]`。
-{* ../../docs_src/security/tutorial005.py hl[128:134] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
-## 依赖项树与作用域
+## 依赖树与作用域 { #dependency-tree-and-scopes }
-再次查看这个依赖项树与作用域。
+再次回顾这个依赖树与作用域。
-`get_current_active_user` 依赖项包含子依赖项 `get_current_user`,并在 `get_current_active_user`中声明了作用域 `"me"` 包含所需作用域列表 ,在 `security_scopes.scopes` 中传递给 `get_current_user`。
+由于 `get_current_active_user` 依赖把 `get_current_user` 作为子依赖,因此在 `get_current_active_user` 中声明的作用域 `"me"` 会被包含在传给 `get_current_user` 的 `security_scopes.scopes` 所需作用域列表中。
-*路径操作*自身也声明了作用域,`"items"`,这也是 `security_scopes.scopes` 列表传递给 `get_current_user` 的。
+*路径操作*本身也声明了一个作用域 `"items"`,它也会包含在传给 `get_current_user` 的 `security_scopes.scopes` 列表中。
-依赖项与作用域的层级架构如下:
+依赖与作用域的层级结构如下:
* *路径操作* `read_own_items` 包含:
- * 依赖项所需的作用域 `["items"]`:
- * `get_current_active_user`:
- * 依赖项函数 `get_current_active_user` 包含:
- * 所需的作用域 `"me"` 包含依赖项:
- * `get_current_user`:
- * 依赖项函数 `get_current_user` 包含:
- * 没有作用域需求其自身
- * 依赖项使用 `oauth2_scheme`
- * `security_scopes` 参数的类型是 `SecurityScopes`:
- * `security_scopes` 参数的属性 `scopes` 是包含上述声明的所有作用域的**列表**,因此:
- * `security_scopes.scopes` 包含用于*路径操作*的 `["me", "items"]`
- * `security_scopes.scopes` 包含*路径操作* `read_users_me` 的 `["me"]`,因为它在依赖项里被声明
- * `security_scopes.scopes` 包含用于*路径操作* `read_system_status` 的 `[]`(空列表),并且它的依赖项 `get_current_user` 也没有声明任何 `scope`
+ * 带有依赖的必需作用域 `["items"]`:
+ * `get_current_active_user`:
+ * 依赖函数 `get_current_active_user` 包含:
+ * 带有依赖的必需作用域 `["me"]`:
+ * `get_current_user`:
+ * 依赖函数 `get_current_user` 包含:
+ * 自身不需要任何作用域。
+ * 一个使用 `oauth2_scheme` 的依赖。
+ * 一个类型为 `SecurityScopes` 的 `security_scopes` 参数:
+ * 该 `security_scopes` 参数有一个 `scopes` 属性,它是一个包含上面所有已声明作用域的 `list`,因此:
+ * 对于*路径操作* `read_own_items`,`security_scopes.scopes` 将包含 `["me", "items"]`。
+ * 对于*路径操作* `read_users_me`,`security_scopes.scopes` 将包含 `["me"]`,因为它在依赖 `get_current_active_user` 中被声明。
+ * 对于*路径操作* `read_system_status`,`security_scopes.scopes` 将包含 `[]`(空列表),因为它既没有声明任何带 `scopes` 的 `Security`,其依赖 `get_current_user` 也没有声明任何 `scopes`。
/// tip | 提示
-此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。
+这里重要且“神奇”的地方是,`get_current_user` 在检查每个*路径操作*时会得到不同的 `scopes` 列表。
-所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。
+这一切都取决于为该特定*路径操作*在其自身以及依赖树中的每个依赖里声明的 `scopes`。
///
-## `SecurityScopes` 的更多细节
+## 关于 `SecurityScopes` 的更多细节 { #more-details-about-securityscopes }
-您可以任何位置或多个位置使用 `SecurityScopes`,不一定非得在**根**依赖项中使用。
+你可以在任意位置、多个位置使用 `SecurityScopes`,不一定非得在“根”依赖里。
-它总是在当前 `Security` 依赖项中和所有依赖因子对于**特定** *路径操作*和**特定**依赖树中安全作用域
+它总会包含当前 `Security` 依赖中以及所有依赖者在“该特定”*路径操作*和“该特定”依赖树里声明的安全作用域。
-因为 `SecurityScopes` 包含所有由依赖项声明的作用域,可以在核心依赖函数中用它验证所需作用域的令牌,然后再在不同的*路径操作*中声明不同作用域需求。
+因为 `SecurityScopes` 会包含依赖者声明的所有作用域,你可以在一个核心依赖函数里用它验证令牌是否具有所需作用域,然后在不同的*路径操作*里声明不同的作用域需求。
-它们会为每个*路径操作*进行单独检查。
+它们会针对每个*路径操作*分别检查。
-## 查看文档
+## 查看文档 { #check-it }
-打开 API 文档,进行身份验证,并指定要授权的作用域。
+打开 API 文档,你可以进行身份验证,并指定要授权的作用域。
-没有选择任何作用域,也可以进行**身份验证**,但访问 `/uses/me` 或 `/users/me/items` 时,会显示没有足够的权限。但仍可以访问 `/status/`。
+如果你不选择任何作用域,你依然会“通过认证”,但当你访问 `/users/me/` 或 `/users/me/items/` 时,会收到一个错误,提示你没有足够的权限。你仍然可以访问 `/status/`。
-如果选择了作用域 `me`,但没有选择作用域 `items`,则可以访问 `/users/me/`,但不能访问 `/users/me/items`。
+如果你选择了作用域 `me`,但没有选择作用域 `items`,你可以访问 `/users/me/`,但不能访问 `/users/me/items/`。
-这就是通过用户提供的令牌使用第三方应用访问这些*路径操作*时会发生的情况,具体怎样取决于用户授予第三方应用的权限。
+当第三方应用使用用户提供的令牌访问这些*路径操作*时,也会发生同样的情况,取决于用户授予该应用了多少权限。
-## 关于第三方集成
+## 关于第三方集成 { #about-third-party-integrations }
-本例使用 OAuth2 **密码**流。
+在这个示例中我们使用的是 OAuth2 的“password”流。
-这种方式适用于登录我们自己的应用,最好使用我们自己的前端。
+当我们登录自己的应用(很可能还有我们自己的前端)时,这是合适的。
-因为我们能控制自己的前端应用,可以信任它接收 `username` 与 `password`。
+因为我们可以信任它来接收 `username` 和 `password`,毕竟我们掌控它。
-但如果构建的是连接其它应用的 OAuth2 应用,比如具有与脸书、谷歌、GitHub 相同功能的第三方身份验证应用。那您就应该使用其它安全流。
+但如果你在构建一个 OAuth2 应用,让其它应用来连接(也就是说,你在构建等同于 Facebook、Google、GitHub 等的身份验证提供商),你应该使用其它的流。
-最常用的是隐式流。
+最常见的是隐式流(implicit flow)。
-最安全的是代码流,但实现起来更复杂,而且需要更多步骤。因为它更复杂,很多第三方身份验证应用最终建议使用隐式流。
+最安全的是代码流(authorization code flow),但实现更复杂,需要更多步骤。也因为更复杂,很多提供商最终会建议使用隐式流。
-/// note | 笔记
+/// note | 注意
-每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。
+每个身份验证提供商常常会用不同的方式给它们的流命名,以融入自己的品牌。
-但归根结底,它们使用的都是 OAuth2 标准。
+但归根结底,它们实现的都是同一个 OAuth2 标准。
///
-**FastAPI** 的 `fastapi.security.oauth2` 里包含了所有 OAuth2 身份验证流工具。
+**FastAPI** 在 `fastapi.security.oauth2` 中为所有这些 OAuth2 身份验证流提供了工具。
-## 装饰器 `dependencies` 中的 `Security`
+## 装饰器 `dependencies` 中的 `Security` { #security-in-decorator-dependencies }
-同样,您可以在装饰器的 `dependencies` 参数中定义 `Depends` 列表,(详见[路径操作装饰器依赖项](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank})),也可以把 `scopes` 与 `Security` 一起使用。
+就像你可以在装饰器的 `dependencies` 参数中定义 `Depends` 的 `list`(详见[路径操作装饰器依赖项](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}),你也可以在那儿配合 `Security` 使用 `scopes`。
diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md
index e33da136f..adf264491 100644
--- a/docs/zh/docs/advanced/settings.md
+++ b/docs/zh/docs/advanced/settings.md
@@ -1,190 +1,94 @@
-# 设置和环境变量
+# 设置和环境变量 { #settings-and-environment-variables }
-在许多情况下,您的应用程序可能需要一些外部设置或配置,例如密钥、数据库凭据、电子邮件服务的凭据等等。
+在许多情况下,你的应用可能需要一些外部设置或配置,例如密钥、数据库凭据、电子邮件服务的凭据等。
-这些设置中的大多数是可变的(可以更改的),比如数据库的 URL。而且许多设置可能是敏感的,比如密钥。
+这些设置中的大多数是可变的(可能会改变),例如数据库 URL。并且很多可能是敏感的,比如密钥。
因此,通常会将它们提供为由应用程序读取的环境变量。
-## 环境变量
+/// tip | 提示
-/// tip
-
-如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。
+要理解环境变量,你可以阅读[环境变量](../environment-variables.md){.internal-link target=_blank}。
///
-环境变量(也称为"env var")是一种存在于 Python 代码之外、存在于操作系统中的变量,可以被您的 Python 代码(或其他程序)读取。
+## 类型和验证 { #types-and-validation }
-您可以在 shell 中创建和使用环境变量,而无需使用 Python:
+这些环境变量只能处理文本字符串,因为它们在 Python 之外,并且必须与其他程序及系统的其余部分兼容(甚至与不同的操作系统,如 Linux、Windows、macOS)。
-//// tab | Linux、macOS、Windows Bash
+这意味着,在 Python 中从环境变量读取的任何值都是 `str` 类型,任何到不同类型的转换或任何验证都必须在代码中完成。
+
+## Pydantic 的 `Settings` { #pydantic-settings }
+
+幸运的是,Pydantic 提供了一个很好的工具来处理来自环境变量的这些设置:Pydantic: Settings management。
+
+### 安装 `pydantic-settings` { #install-pydantic-settings }
+
+首先,确保你创建并激活了[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后安装 `pydantic-settings` 包:
-然后查看子应用文档 http://127.0.0.1:8000/subapi/docs。
+然后查看子应用文档 http://127.0.0.1:8000/subapi/docs。
下图显示的是子应用的 API 文档,也是只包括其自有的*路径操作*,所有这些路径操作都在 `/subapi` 子路径前缀下。
@@ -56,7 +56,7 @@ $ uvicorn main:app --reload
两个用户界面都可以正常运行,因为浏览器能够与每个指定的应用或子应用会话。
-### 技术细节:`root_path`
+### 技术细节:`root_path` { #technical-details-root-path }
以上述方式挂载子应用时,FastAPI 使用 ASGI 规范中的 `root_path` 机制处理挂载子应用路径之间的通信。
diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md
index e627eed98..f2e5c21cf 100644
--- a/docs/zh/docs/advanced/templates.md
+++ b/docs/zh/docs/advanced/templates.md
@@ -1,4 +1,4 @@
-# 模板
+# 模板 { #templates }
**FastAPI** 支持多种模板引擎。
@@ -6,9 +6,9 @@ Flask 等工具使用的 Jinja2 是最用的模板引擎。
在 Starlette 的支持下,**FastAPI** 应用可以直接使用工具轻易地配置 Jinja2。
-## 安装依赖项
+## 安装依赖项 { #install-dependencies }
-安装 `jinja2`:
+确保你创建一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank},激活它,并安装 `jinja2`:
-所有这些消息都将使用同一个 WebSocket 连
+所有这些消息都将使用同一个 WebSocket 连接。
-接。
-
-## 使用 `Depends` 和其他依赖项
+## 使用 `Depends` 和其他依赖项 { #using-depends-and-others }
在 WebSocket 端点中,您可以从 `fastapi` 导入并使用以下内容:
@@ -101,7 +107,7 @@ $ uvicorn main:app --reload
* `Path`
* `Query`
-它们的工作方式与其他 FastAPI 端点/ *路径操作* 相同:
+它们的工作方式与其他 FastAPI 端点/*路径操作* 相同:
{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *}
@@ -113,16 +119,20 @@ $ uvicorn main:app --reload
///
-### 尝试带有依赖项的 WebSockets
+### 尝试带有依赖项的 WebSockets { #try-the-websockets-with-dependencies }
如果您的文件名为 `main.py`,请使用以下命令运行应用程序:
+
-## 处理断开连接和多个客户端
+## 处理断开连接和多个客户端 { #handling-disconnections-and-multiple-clients }
当 WebSocket 连接关闭时,`await websocket.receive_text()` 将引发 `WebSocketDisconnect` 异常,您可以捕获并处理该异常,就像本示例中的示例一样。
@@ -164,13 +174,13 @@ Client #1596980209979 left the chat
但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。
-如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。
+如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 encode/broadcaster。
///
-## 更多信息
+## 更多信息 { #more-info }
要了解更多选项,请查看 Starlette 的文档:
-* [WebSocket 类](https://www.starlette.dev/websockets/)
-* [基于类的 WebSocket 处理](https://www.starlette.dev/endpoints/#websocketendpoint)。
+* `WebSocket` 类。
+* 基于类的 WebSocket 处理。
diff --git a/docs/zh/docs/advanced/wsgi.md b/docs/zh/docs/advanced/wsgi.md
index 363025a34..73fcb3219 100644
--- a/docs/zh/docs/advanced/wsgi.md
+++ b/docs/zh/docs/advanced/wsgi.md
@@ -1,32 +1,48 @@
-# 包含 WSGI - Flask,Django,其它
+# 包含 WSGI - Flask,Django,其它 { #including-wsgi-flask-django-others }
-您可以挂载多个 WSGI 应用,正如您在 [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank} 中所看到的那样。
+您可以挂载 WSGI 应用,正如您在 [子应用 - 挂载](sub-applications.md){.internal-link target=_blank}、[在代理之后](behind-a-proxy.md){.internal-link target=_blank} 中所看到的那样。
为此, 您可以使用 `WSGIMiddleware` 来包装你的 WSGI 应用,如:Flask,Django,等等。
-## 使用 `WSGIMiddleware`
+## 使用 `WSGIMiddleware` { #using-wsgimiddleware }
-您需要导入 `WSGIMiddleware`。
+/// info | 信息
+
+需要安装 `a2wsgi`,例如使用 `pip install a2wsgi`。
+
+///
+
+您需要从 `a2wsgi` 导入 `WSGIMiddleware`。
然后使用该中间件包装 WSGI 应用(例如 Flask)。
之后将其挂载到某一个路径下。
-{* ../../docs_src/wsgi/tutorial001.py hl[2:3,22] *}
+{* ../../docs_src/wsgi/tutorial001_py39.py hl[1,3,23] *}
-## 检查
+/// note | 注意
+
+之前推荐使用 `fastapi.middleware.wsgi` 中的 `WSGIMiddleware`,但它现在已被弃用。
+
+建议改用 `a2wsgi` 包,使用方式保持不变。
+
+只要确保已安装 `a2wsgi` 包,并且从 `a2wsgi` 正确导入 `WSGIMiddleware` 即可。
+
+///
+
+## 检查 { #check-it }
现在,所有定义在 `/v1/` 路径下的请求将会被 Flask 应用处理。
其余的请求则会被 **FastAPI** 处理。
-如果您使用 Uvicorn 运行应用实例并且访问 http://localhost:8000/v1/,您将会看到由 Flask 返回的响应:
+如果你运行它并访问 http://localhost:8000/v1/,你将会看到由 Flask 返回的响应:
```txt
Hello, World from Flask!
```
-并且如果您访问 http://localhost:8000/v2,您将会看到由 FastAPI 返回的响应:
+如果你访问 http://localhost:8000/v2,你将会看到由 FastAPI 返回的响应:
```JSON
{
diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md
index 4028ed51a..c94c90787 100644
--- a/docs/zh/docs/async.md
+++ b/docs/zh/docs/async.md
@@ -1,10 +1,10 @@
-# 并发 async / await
+# 并发 async / await { #concurrency-and-async-await }
有关路径操作函数的 `async def` 语法以及异步代码、并发和并行的一些背景知识。
-## 赶时间吗?
+## 赶时间吗? { #in-a-hurry }
-TL;DR:
+TL;DR:
如果你正在使用第三方库,它们会告诉你使用 `await` 关键字来调用它们,就像这样:
@@ -21,7 +21,7 @@ async def read_results():
return results
```
-/// note
+/// note | 注意
你只能在被 `async def` 创建的函数内使用 `await`
@@ -40,7 +40,7 @@ def results():
---
-如果你的应用程序不需要与其他任何东西通信而等待其响应,请使用 `async def`。
+如果你的应用程序不需要与其他任何东西通信而等待其响应,请使用 `async def`,即使函数内部不需要使用 `await`。
---
@@ -54,7 +54,7 @@ def results():
但是,通过遵循上述步骤,它将能够进行一些性能优化。
-## 技术细节
+## 技术细节 { #technical-details }
Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 `await` 语法的东西来写**”异步代码“**。
@@ -64,7 +64,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
* **`async` 和 `await`**
* **协程**
-## 异步代码
+## 异步代码 { #asynchronous-code }
异步代码仅仅意味着编程语言 💬 有办法告诉计算机/程序 🤖 在代码中的某个点,它 🤖 将不得不等待在某些地方完成一些事情。让我们假设一些事情被称为 "慢文件"📝.
@@ -74,7 +74,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
接下来,它 🤖 完成第一个任务(比如是我们的"慢文件"📝) 并继续与之相关的一切。
-这个"等待其他事情"通常指的是一些相对较慢(与处理器和 RAM 存储器的速度相比)的 I/O 操作,比如说:
+这个"等待其他事情"通常指的是一些相对较慢(与处理器和 RAM 存储器的速度相比)的 I/O 操作,比如说:
* 通过网络发送来自客户端的数据
* 客户端接收来自网络中的数据
@@ -85,7 +85,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
* 一个数据库查询,直到返回结果
* 等等.
-这个执行的时间大多是在等待 I/O 操作,因此它们被叫做 "I/O 密集型" 操作。
+这个执行的时间大多是在等待 I/O 操作,因此它们被叫做 "I/O 密集型" 操作。
它被称为"异步"的原因是因为计算机/程序不必与慢任务"同步",去等待任务完成的确切时刻,而在此期间不做任何事情直到能够获取任务结果才继续工作。
@@ -93,7 +93,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
对于"同步"(与"异步"相反),他们通常也使用"顺序"一词,因为计算机程序在切换到另一个任务之前是按顺序执行所有步骤,即使这些步骤涉及到等待。
-### 并发与汉堡
+### 并发与汉堡 { #concurrency-and-burgers }
上述异步代码的思想有时也被称为“并发”,它不同于“并行”。
@@ -103,7 +103,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
要了解差异,请想象以下关于汉堡的故事:
-### 并发汉堡
+### 并发汉堡 { #concurrent-burgers }
你和你的恋人一起去快餐店,你排队在后面,收银员从你前面的人接单。😍
@@ -139,7 +139,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
-/// info
+/// info | 信息
漂亮的插画来自 Ketrina Thompson. 🎨
@@ -163,7 +163,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
然后你去柜台🔀, 到现在初始任务已经完成⏯, 拿起汉堡,说声谢谢,然后把它们送到桌上。这就完成了与计数器交互的步骤/任务⏹. 这反过来又产生了一项新任务,即"吃汉堡"🔀 ⏯, 上一个"拿汉堡"的任务已经结束了⏹.
-### 并行汉堡
+### 并行汉堡 { #parallel-burgers }
现在让我们假设不是"并发汉堡",而是"并行汉堡"。
@@ -205,7 +205,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
没有太多的交谈或调情,因为大部分时间 🕙 都在柜台前等待😞。
-/// info
+/// info | 信息
漂亮的插画来自 Ketrina Thompson. 🎨
@@ -233,7 +233,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
你可不会想带你的恋人 😍 和你一起去银行办事🏦.
-### 汉堡结论
+### 汉堡结论 { #burger-conclusion }
在"你与恋人一起吃汉堡"的这个场景中,因为有很多人在等待🕙, 使用并发系统更有意义⏸🔀⏯.
@@ -253,7 +253,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
你可以同时拥有并行性和异步性,你可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言(全部归功于 Starlette)。
-### 并发比并行好吗?
+### 并发比并行好吗? { #is-concurrency-better-than-parallelism }
不!这不是故事的本意。
@@ -277,7 +277,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
在这个场景中,每个清洁工(包括你)都将是一个处理器,完成这个工作的一部分。
-由于大多数执行时间是由实际工作(而不是等待)占用的,并且计算机中的工作是由 CPU 完成的,所以他们称这些问题为"CPU 密集型"。
+由于大多数执行时间是由实际工作(而不是等待)占用的,并且计算机中的工作是由 CPU 完成的,所以他们称这些问题为"CPU 密集型"。
---
@@ -290,7 +290,7 @@ CPU 密集型操作的常见示例是需要复杂的数学处理。
* **机器学习**: 它通常需要大量的"矩阵"和"向量"乘法。想象一个包含数字的巨大电子表格,并同时将所有数字相乘;
* **深度学习**: 这是机器学习的一个子领域,同样适用。只是没有一个数字的电子表格可以相乘,而是一个庞大的数字集合,在很多情况下,你需要使用一个特殊的处理器来构建和使用这些模型。
-### 并发 + 并行: Web + 机器学习
+### 并发 + 并行: Web + 机器学习 { #concurrency-parallelism-web-machine-learning }
使用 **FastAPI**,你可以利用 Web 开发中常见的并发机制的优势(NodeJS 的主要吸引力)。
@@ -300,7 +300,7 @@ CPU 密集型操作的常见示例是需要复杂的数学处理。
了解如何在生产环境中实现这种并行性,可查看此文 [Deployment](deployment/index.md){.internal-link target=_blank}。
-## `async` 和 `await`
+## `async` 和 `await` { #async-and-await }
现代版本的 Python 有一种非常直观的方式来定义异步代码。这使它看起来就像正常的"顺序"代码,并在适当的时候"等待"。
@@ -316,16 +316,16 @@ burgers = await get_burgers(2)
```Python hl_lines="1"
async def get_burgers(number: int):
- # Do some asynchronous stuff to create the burgers
+ # 执行一些异步操作来制作汉堡
return burgers
```
...而不是 `def`:
```Python hl_lines="2"
-# This is not asynchronous
+# 这不是异步的
def get_sequential_burgers(number: int):
- # Do some sequential stuff to create the burgers
+ # 执行一些顺序操作来制作汉堡
return burgers
```
@@ -334,7 +334,7 @@ def get_sequential_burgers(number: int):
当你想调用一个 `async def` 函数时,你必须"等待"它。因此,这不会起作用:
```Python
-# This won't work, because get_burgers was defined with: async def
+# 这样不行,因为 get_burgers 是用 async def 定义的
burgers = get_burgers(2)
```
@@ -349,7 +349,7 @@ async def read_burgers():
return burgers
```
-### 更多技术细节
+### 更多技术细节 { #more-technical-details }
你可能已经注意到,`await` 只能在 `async def` 定义的函数内部使用。
@@ -361,7 +361,7 @@ async def read_burgers():
但如果你想在没有 FastAPI 的情况下使用 `async` / `await`,则可以这样做。
-### 编写自己的异步代码
+### 编写自己的异步代码 { #write-your-own-async-code }
Starlette (和 **FastAPI**) 是基于 AnyIO 实现的,这使得它们可以兼容 Python 的标准库 asyncio 和 Trio。
@@ -371,7 +371,7 @@ Starlette (和 **FastAPI**) 是基于 Asyncer。如果你有**结合使用异步代码和常规**(阻塞/同步)代码的需求,这个库会特别有用。
-### 其他形式的异步代码
+### 其他形式的异步代码 { #other-forms-of-asynchronous-code }
这种使用 `async` 和 `await` 的风格在语言中相对较新。
@@ -385,13 +385,13 @@ Starlette (和 **FastAPI**) 是基于 I/O 的代码。
+如果你使用过另一个不以上述方式工作的异步框架,并且你习惯于用普通的 `def` 定义普通的仅计算路径操作函数,以获得微小的性能增益(大约100纳秒),请注意,在 FastAPI 中,效果将完全相反。在这些情况下,最好使用 `async def`,除非路径操作函数内使用执行阻塞 I/O 的代码。
-在这两种情况下,与你之前的框架相比,**FastAPI** 可能[仍然很快](index.md#_11){.internal-link target=_blank}。
+在这两种情况下,与你之前的框架相比,**FastAPI** 可能[仍然很快](index.md#performance){.internal-link target=_blank}。
-### 依赖
+### 依赖 { #dependencies }
这同样适用于[依赖](tutorial/dependencies/index.md){.internal-link target=_blank}。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。
-### 子依赖
+### 子依赖 { #sub-dependencies }
你可以拥有多个相互依赖的依赖以及[子依赖](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。
-### 其他函数
+### 其他函数 { #other-utility-functions }
你可直接调用通过 `def` 或 `async def` 创建的任何其他函数,FastAPI 不会影响你调用它们的方式。
@@ -441,4 +441,4 @@ Starlette (和 **FastAPI**) 是基于 赶时间吗?.
+否则,你最好应该遵守的指导原则赶时间吗?.
diff --git a/docs/zh/docs/benchmarks.md b/docs/zh/docs/benchmarks.md
index 71e8d4838..1a4b4a3de 100644
--- a/docs/zh/docs/benchmarks.md
+++ b/docs/zh/docs/benchmarks.md
@@ -1,10 +1,10 @@
-# 基准测试
+# 基准测试 { #benchmarks }
-第三方机构 TechEmpower 的基准测试表明在 Uvicorn 下运行的 **FastAPI** 应用程序是 可用的最快的 Python 框架之一,仅次于 Starlette 和 Uvicorn 本身 (由 FastAPI 内部使用)。(*)
+第三方机构 TechEmpower 的基准测试表明在 Uvicorn 下运行的 **FastAPI** 应用程序是 可用的最快的 Python 框架之一,仅次于 Starlette 和 Uvicorn 本身(由 FastAPI 内部使用)。
但是在查看基准得分和对比时,请注意以下几点。
-## 基准测试和速度
+## 基准测试和速度 { #benchmarks-and-speed }
当你查看基准测试时,几个不同类型的工具被等效地做比较是很常见的情况。
@@ -20,15 +20,15 @@
* **Uvicorn**:
* 具有最佳性能,因为除了服务器本身外,它没有太多额外的代码。
- * 您不会直接在 Uvicorn 中编写应用程序。这意味着您的代码至少必须包含 Starlette(或 **FastAPI**)提供的代码。如果您这样做了(即直接在 Uvicorn 中编写应用程序),最终的应用程序会和使用了框架并且最小化了应用代码和 bug 的情况具有相同的性能损耗。
- * 如果要对比与 Uvicorn 对标的服务器,请将其与 Daphne,Hypercorn,uWSGI等应用服务器进行比较。
+ * 你不会直接在 Uvicorn 中编写应用程序。这意味着你的代码至少必须包含 Starlette(或 **FastAPI**)提供的代码。如果你这样做了(即直接在 Uvicorn 中编写应用程序),最终的应用程序会和使用了框架并且最小化了应用代码和 bug 的情况具有相同的性能损耗。
+ * 如果你要对比 Uvicorn,请将其与 Daphne,Hypercorn,uWSGI 等应用服务器进行比较。
* **Starlette**:
- * 在 Uvicorn 后使用 Starlette,性能会略有下降。实际上,Starlette 使用 Uvicorn运行。因此,由于必须执行更多的代码,它只会比 Uvicorn 更慢。
- * 但它为您提供了构建简单的网络程序的工具,并具有基于路径的路由等功能。
+ * 在 Uvicorn 后使用 Starlette,性能会略有下降。实际上,Starlette 使用 Uvicorn 运行。因此,由于必须执行更多的代码,它只会比 Uvicorn 更慢。
+ * 但它为你提供了构建简单的网络程序的工具,并具有基于路径的路由等功能。
* 如果想对比与 Starlette 对标的开发框架,请将其与 Sanic,Flask,Django 等网络框架(或微框架)进行比较。
* **FastAPI**:
* 与 Starlette 使用 Uvicorn 一样,由于 **FastAPI** 使用 Starlette,因此 FastAPI 不能比 Starlette 更快。
- * FastAPI 在 Starlette 基础上提供了更多功能。例如在开发 API 时,所需的数据验证和序列化功能。FastAPI 可以帮助您自动生成 API文档,(文档在应用程序启动时自动生成,所以不会增加应用程序运行时的开销)。
- * 如果您不使用 FastAPI 而直接使用 Starlette(或诸如 Sanic,Flask,Responder 等其它工具),您则要自己实现所有的数据验证和序列化。那么最终您的应用程序会和使用 FastAPI 构建的程序有相同的开销。一般这种数据验证和序列化的操作在您应用程序的代码中会占很大比重。
- * 因此,通过使用 FastAPI 意味着您可以节省开发时间,减少编码错误,用更少的编码实现其功能,并且相比不使用 FastAPI 您很大可能会获得相同或更好的性能(因为那样您必须在代码中实现所有相同的功能)。
- * 如果您想对比与 FastAPI 对标的开发框架,请与能够提供数据验证,序列化和带有自动文档生成的网络应用程序框架(或工具集)进行对比,例如具有集成自动数据验证,序列化和自动化文档的 Flask-apispec,NestJS,Molten 等。
+ * FastAPI 在 Starlette 基础上提供了更多功能。例如在开发 API 时,所需的数据验证和序列化功能。FastAPI 可以帮助你自动生成 API文档,(文档在应用程序启动时自动生成,所以不会增加应用程序运行时的开销)。
+ * 如果你不使用 FastAPI 而直接使用 Starlette(或诸如 Sanic,Flask,Responder 等其它工具),你则要自己实现所有的数据验证和序列化。那么最终你的应用程序会和使用 FastAPI 构建的程序有相同的开销。一般这种数据验证和序列化的操作在你应用程序的代码中会占很大比重。
+ * 因此,通过使用 FastAPI 意味着你可以节省开发时间,减少编码错误,用更少的编码实现其功能,并且相比不使用 FastAPI 你很大可能会获得相同或更好的性能(因为那样你必须在代码中实现所有相同的功能)。
+ * 如果你想对比 FastAPI,请与能够提供数据验证、序列化和文档的网络应用程序框架(或工具集)进行对比,例如具有集成自动数据验证、序列化和自动化文档的 Flask-apispec,NestJS,Molten 等。
diff --git a/docs/zh/docs/deployment/cloud.md b/docs/zh/docs/deployment/cloud.md
index 8a892a560..96883bd6b 100644
--- a/docs/zh/docs/deployment/cloud.md
+++ b/docs/zh/docs/deployment/cloud.md
@@ -1,13 +1,24 @@
-# 在云上部署 FastAPI
+# 在云服务商上部署 FastAPI { #deploy-fastapi-on-cloud-providers }
-您几乎可以使用**任何云服务商**来部署 FastAPI 应用程序。
+你几乎可以使用**任何云服务商**来部署你的 FastAPI 应用。
-在大多数情况下,主要的云服务商都有部署 FastAPI 的指南。
+在大多数情况下,主流云服务商都有部署 FastAPI 的指南。
-## 云服务商 - 赞助商
+## FastAPI Cloud { #fastapi-cloud }
-一些云服务商 ✨ [**赞助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,这确保了FastAPI 及其**生态系统**持续健康地**发展**。
+**FastAPI Cloud** 由 **FastAPI** 背后的同一作者与团队打造。
-这表明了他们对 FastAPI 及其**社区**(您)的真正承诺,因为他们不仅想为您提供**良好的服务**,而且还想确保您拥有一个**良好且健康的框架**:FastAPI。 🙇
+它简化了**构建**、**部署**和**访问** API 的流程,几乎不费力。
-您可能想尝试他们的服务并阅读他们的指南.
+它把使用 FastAPI 构建应用时相同的**开发者体验**带到了将应用**部署**到云上的过程。🎉
+
+FastAPI Cloud 是 *FastAPI and friends* 开源项目的主要赞助方和资金提供者。✨
+
+## 云服务商 - 赞助商 { #cloud-providers-sponsors }
+
+还有一些云服务商也会 ✨ [**赞助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨。🙇
+
+你也可以考虑按照他们的指南尝试他们的服务:
+
+* Render
+* Railway
diff --git a/docs/zh/docs/deployment/concepts.md b/docs/zh/docs/deployment/concepts.md
index f7208da7c..66d32629c 100644
--- a/docs/zh/docs/deployment/concepts.md
+++ b/docs/zh/docs/deployment/concepts.md
@@ -1,4 +1,4 @@
-# 部署概念
+# 部署概念 { #deployments-concepts }
在部署 **FastAPI** 应用程序或任何类型的 Web API 时,有几个概念值得了解,通过掌握这些概念您可以找到**最合适的**方法来**部署您的应用程序**。
@@ -13,7 +13,7 @@
我们接下来了解它们将如何影响**部署**。
-我们的最终目标是能够以**安全**的方式**为您的 API 客户端**提供服务,同时要**避免中断**,并且尽可能高效地利用**计算资源**( 例如服务器CPU资源)。 🚀
+我们的最终目标是能够以**安全**的方式**为您的 API 客户端**提供服务,同时要**避免中断**,并且尽可能高效地利用**计算资源**(例如远程服务器/虚拟机)。 🚀
我将在这里告诉您更多关于这些**概念**的信息,希望能给您提供**直觉**来决定如何在非常不同的环境中部署 API,甚至在是尚不存在的**未来**的环境里。
@@ -23,7 +23,7 @@
但现在,让我们仔细看一下这些重要的**概念**。 这些概念也适用于任何其他类型的 Web API。 💡
-## 安全性 - HTTPS
+## 安全性 - HTTPS { #security-https }
在[上一章有关 HTTPS](https.md){.internal-link target=_blank} 中,我们了解了 HTTPS 如何为您的 API 提供加密。
@@ -31,21 +31,20 @@
并且必须有某个东西负责**更新 HTTPS 证书**,它可以是相同的组件,也可以是不同的组件。
-
-### HTTPS 示例工具
+### HTTPS 示例工具 { #example-tools-for-https }
您可以用作 TLS 终止代理的一些工具包括:
* Traefik
- * 自动处理证书更新 ✨
+ * 自动处理证书更新 ✨
* Caddy
- * 自动处理证书更新 ✨
+ * 自动处理证书更新 ✨
* Nginx
- * 使用 Certbot 等外部组件进行证书更新
+ * 使用 Certbot 等外部组件进行证书更新
* HAProxy
- * 使用 Certbot 等外部组件进行证书更新
-* 带有 Ingress Controller(如Nginx) 的 Kubernetes
- * 使用诸如 cert-manager 之类的外部组件来进行证书更新
+ * 使用 Certbot 等外部组件进行证书更新
+* 带有 Ingress Controller(如 Nginx) 的 Kubernetes
+ * 使用诸如 cert-manager 之类的外部组件来进行证书更新
* 由云服务商内部处理,作为其服务的一部分(请阅读下文👇)
另一种选择是您可以使用**云服务**来完成更多工作,包括设置 HTTPS。 它可能有一些限制或向您收取更多费用等。但在这种情况下,您不必自己设置 TLS 终止代理。
@@ -56,11 +55,11 @@
接下来要考虑的概念都是关于运行实际 API 的程序(例如 Uvicorn)。
-## 程序和进程
+## 程序和进程 { #program-and-process }
我们将讨论很多关于正在运行的“**进程**”的内容,因此弄清楚它的含义以及与“**程序**”这个词有什么区别是很有用的。
-### 什么是程序
+### 什么是程序 { #what-is-a-program }
**程序**这个词通常用来描述很多东西:
@@ -68,12 +67,12 @@
* 操作系统可以**执行**的**文件**,例如:`python`、`python.exe`或`uvicorn`。
* 在操作系统上**运行**、使用CPU 并将内容存储在内存上的特定程序。 这也被称为**进程**。
-### 什么是进程
+### 什么是进程 { #what-is-a-process }
**进程** 这个词通常以更具体的方式使用,仅指在操作系统中运行的东西(如上面的最后一点):
* 在操作系统上**运行**的特定程序。
- * 这不是指文件,也不是指代码,它**具体**指的是操作系统正在**执行**和管理的东西。
+ * 这不是指文件,也不是指代码,它**具体**指的是操作系统正在**执行**和管理的东西。
* 任何程序,任何代码,**只有在执行时才能做事**。 因此,是当有**进程正在运行**时。
* 该进程可以由您或操作系统**终止**(或“杀死”)。 那时,它停止运行/被执行,并且它可以**不再做事情**。
* 您计算机上运行的每个应用程序背后都有一些进程,每个正在运行的程序,每个窗口等。并且通常在计算机打开时**同时**运行许多进程。
@@ -89,13 +88,13 @@
现在我们知道了术语“进程”和“程序”之间的区别,让我们继续讨论部署。
-## 启动时运行
+## 启动时运行 { #running-on-startup }
在大多数情况下,当您创建 Web API 时,您希望它**始终运行**、不间断,以便您的客户端始终可以访问它。 这是当然的,除非您有特定原因希望它仅在某些情况下运行,但大多数时候您希望它不断运行并且**可用**。
-### 在远程服务器中
+### 在远程服务器中 { #in-a-remote-server }
-当您设置远程服务器(云服务器、虚拟机等)时,您可以做的最简单的事情就是手动运行 Uvicorn(或类似的),就像本地开发时一样。
+当您设置远程服务器(云服务器、虚拟机等)时,您可以做的最简单的事情就是使用 `fastapi run`(它使用 Uvicorn)或类似方式,手动运行,就像本地开发时一样。
它将会在**开发过程中**发挥作用并发挥作用。
@@ -103,16 +102,15 @@
如果服务器重新启动(例如更新后或从云提供商迁移后),您可能**不会注意到它**。 因此,您甚至不知道必须手动重新启动该进程。 所以,你的 API 将一直处于挂掉的状态。 😱
-
-### 启动时自动运行
+### 启动时自动运行 { #run-automatically-on-startup }
一般来说,您可能希望服务器程序(例如 Uvicorn)在服务器启动时自动启动,并且不需要任何**人为干预**,让进程始终与您的 API 一起运行(例如 Uvicorn 运行您的 FastAPI 应用程序) 。
-### 单独的程序
+### 单独的程序 { #separate-program }
为了实现这一点,您通常会有一个**单独的程序**来确保您的应用程序在启动时运行。 在许多情况下,它还可以确保其他组件或应用程序也运行,例如数据库。
-### 启动时运行的示例工具
+### 启动时运行的示例工具 { #example-tools-to-run-at-startup }
可以完成这项工作的工具的一些示例是:
@@ -127,44 +125,43 @@
我将在接下来的章节中为您提供更具体的示例。
-
-## 重新启动
+## 重新启动 { #restarts }
与确保应用程序在启动时运行类似,您可能还想确保它在挂掉后**重新启动**。
-### 我们会犯错误
+### 我们会犯错误 { #we-make-mistakes }
作为人类,我们总是会犯**错误**。 软件几乎*总是*在不同的地方隐藏着**bug**。 🐛
作为开发人员,当我们发现这些bug并实现新功能(也可能添加新bug😅)时,我们会不断改进代码。
-### 自动处理小错误
+### 自动处理小错误 { #small-errors-automatically-handled }
使用 FastAPI 构建 Web API 时,如果我们的代码中存在错误,FastAPI 通常会将其包含到触发错误的单个请求中。 🛡
对于该请求,客户端将收到 **500 内部服务器错误**,但应用程序将继续处理下一个请求,而不是完全崩溃。
-### 更大的错误 - 崩溃
+### 更大的错误 - 崩溃 { #bigger-errors-crashes }
尽管如此,在某些情况下,我们编写的一些代码可能会导致整个应用程序崩溃,从而导致 Uvicorn 和 Python 崩溃。 💥
尽管如此,您可能不希望应用程序因为某个地方出现错误而保持死机状态,您可能希望它**继续运行**,至少对于未破坏的*路径操作*。
-### 崩溃后重新启动
+### 崩溃后重新启动 { #restart-after-crash }
但在那些严重错误导致正在运行的**进程**崩溃的情况下,您需要一个外部组件来负责**重新启动**进程,至少尝试几次......
-/// tip
+/// tip | 提示
...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。
- 因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。
+因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。
///
您可能希望让这个东西作为 **外部组件** 负责重新启动您的应用程序,因为到那时,使用 Uvicorn 和 Python 的同一应用程序已经崩溃了,因此同一应用程序的相同代码中没有东西可以对此做出什么。
-### 自动重新启动的示例工具
+### 自动重新启动的示例工具 { #example-tools-to-restart-automatically }
在大多数情况下,用于**启动时运行程序**的同一工具也用于处理自动**重新启动**。
@@ -173,25 +170,25 @@
* Docker
* Kubernetes
* Docker Compose
-* Docker in Swarm mode
+* Docker in Swarm Mode
* Systemd
* Supervisor
* 作为其服务的一部分由云提供商内部处理
* 其他的...
-## 复制 - 进程和内存
+## 复制 - 进程和内存 { #replication-processes-and-memory }
-对于 FastAPI 应用程序,使用像 Uvicorn 这样的服务器程序,在**一个进程**中运行一次就可以同时为多个客户端提供服务。
+对于 FastAPI 应用程序,使用像 `fastapi` 命令(运行 Uvicorn)这样的服务器程序,在**一个进程**中运行一次就可以同时为多个客户端提供服务。
但在许多情况下,您会希望同时运行多个工作进程。
-### 多进程 - Workers
+### 多进程 - Workers { #multiple-processes-workers }
-如果您的客户端数量多于单个进程可以处理的数量(例如,如果虚拟机不是太大),并且服务器的 CPU 中有 **多个核心**,那么您可以让 **多个进程** 运行 同时处理同一个应用程序,并在它们之间分发所有请求。
+如果您的客户端数量多于单个进程可以处理的数量(例如,如果虚拟机不是太大),并且服务器的 CPU 中有 **多个核心**,那么您可以让 **多个进程** 同时运行同一个应用程序,并在它们之间分发所有请求。
当您运行同一 API 程序的**多个进程**时,它们通常称为 **workers**。
-### 工作进程和端口
+### 工作进程和端口 { #worker-processes-and-ports }
还记得文档 [About HTTPS](https.md){.internal-link target=_blank} 中只有一个进程可以侦听服务器中的端口和 IP 地址的一种组合吗?
@@ -199,20 +196,19 @@
因此,为了能够同时拥有**多个进程**,必须有一个**单个进程侦听端口**,然后以某种方式将通信传输到每个工作进程。
-### 每个进程的内存
+### 每个进程的内存 { #memory-per-process }
现在,当程序将内容加载到内存中时,例如,将机器学习模型加载到变量中,或者将大文件的内容加载到变量中,所有这些都会消耗服务器的一点内存 (RAM) 。
多个进程通常**不共享任何内存**。 这意味着每个正在运行的进程都有自己的东西、变量和内存。 如果您的代码消耗了大量内存,**每个进程**将消耗等量的内存。
-### 服务器内存
+### 服务器内存 { #server-memory }
例如,如果您的代码加载 **1 GB 大小**的机器学习模型,则当您使用 API 运行一个进程时,它将至少消耗 1 GB RAM。 如果您启动 **4 个进程**(4 个工作进程),每个进程将消耗 1 GB RAM。 因此,您的 API 总共将消耗 **4 GB RAM**。
如果您的远程服务器或虚拟机只有 3 GB RAM,尝试加载超过 4 GB RAM 将导致问题。 🚨
-
-### 多进程 - 一个例子
+### 多进程 - 一个例子 { #multiple-processes-an-example }
在此示例中,有一个 **Manager Process** 启动并控制两个 **Worker Processes**。
@@ -224,11 +220,11 @@
当然,除了您的应用程序之外,同一台机器可能还运行**其他进程**。
-一个有趣的细节是,随着时间的推移,每个进程使用的 **CPU 百分比可能会发生很大变化,但内存 (RAM) 通常会或多或少保持稳定**。
+一个有趣的细节是,随着时间的推移,每个进程使用的 **CPU 百分比**可能会发生很大变化,但**内存 (RAM)** 通常会或多或少保持**稳定**。
如果您有一个每次执行相当数量的计算的 API,并且您有很多客户端,那么 **CPU 利用率** 可能也会保持稳定(而不是不断快速上升和下降)。
-### 复制工具和策略示例
+### 复制工具和策略示例 { #examples-of-replication-tools-and-strategies }
可以通过多种方法来实现这一目标,我将在接下来的章节中向您详细介绍具体策略,例如在谈论 Docker 和容器时。
@@ -236,26 +232,22 @@
以下是一些可能的组合和策略:
-* **Gunicorn** 管理 **Uvicorn workers**
- * Gunicorn 将是监听 **IP** 和 **端口** 的 **进程管理器**,复制将通过 **多个 Uvicorn 工作进程** 进行
-* **Uvicorn** 管理 **Uvicorn workers**
- * 一个 Uvicorn **进程管理器** 将监听 **IP** 和 **端口**,并且它将启动 **多个 Uvicorn 工作进程**
+* 带有 `--workers` 的 **Uvicorn**
+ * 一个 Uvicorn **进程管理器** 将监听 **IP** 和 **端口**,并且它将启动 **多个 Uvicorn 工作进程**。
* **Kubernetes** 和其他分布式 **容器系统**
- * **Kubernetes** 层中的某些东西将侦听 **IP** 和 **端口**。 复制将通过拥有**多个容器**,每个容器运行**一个 Uvicorn 进程**
+ * **Kubernetes** 层中的某些东西将侦听 **IP** 和 **端口**。 复制将通过拥有**多个容器**,每个容器运行**一个 Uvicorn 进程**。
* **云服务** 为您处理此问题
- * 云服务可能**为您处理复制**。 它可能会让您定义 **要运行的进程**,或要使用的 **容器映像**,在任何情况下,它很可能是 **单个 Uvicorn 进程**,并且云服务将负责复制它。
+ * 云服务可能**为您处理复制**。 它可能会让您定义 **要运行的进程**,或要使用的 **容器映像**,在任何情况下,它很可能是 **单个 Uvicorn 进程**,并且云服务将负责复制它。
-
-
-/// tip
+/// tip | 提示
如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。
- 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
+我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
///
-## 启动之前的步骤
+## 启动之前的步骤 { #previous-steps-before-starting }
在很多情况下,您希望在**启动**应用程序之前执行一些步骤。
@@ -269,15 +261,15 @@
当然,也有一些情况,多次运行前面的步骤也没有问题,这样的话就好办多了。
-/// tip
+/// tip | 提示
另外,请记住,根据您的设置,在某些情况下,您在开始应用程序之前**可能甚至不需要任何先前的步骤**。
- 在这种情况下,您就不必担心这些。 🤷
+在这种情况下,您就不必担心这些。 🤷
///
-### 前面步骤策略的示例
+### 前面步骤策略的示例 { #examples-of-previous-steps-strategies }
这将在**很大程度上取决于您部署系统的方式**,并且可能与您启动程序、处理重启等的方式有关。
@@ -285,15 +277,15 @@
* Kubernetes 中的“Init Container”在应用程序容器之前运行
* 一个 bash 脚本,运行前面的步骤,然后启动您的应用程序
- * 您仍然需要一种方法来启动/重新启动 bash 脚本、检测错误等。
+ * 您仍然需要一种方法来启动/重新启动 bash 脚本、检测错误等。
-/// tip
+/// tip | 提示
我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
///
-## 资源利用率
+## 资源利用率 { #resource-utilization }
您的服务器是一个**资源**,您可以通过您的程序消耗或**利用**CPU 上的计算时间以及可用的 RAM 内存。
@@ -313,8 +305,7 @@
您可以使用“htop”等简单工具来查看服务器中使用的 CPU 和 RAM 或每个进程使用的数量。 或者您可以使用更复杂的监控工具,这些工具可能分布在服务器等上。
-
-## 回顾
+## 回顾 { #recap }
您在这里阅读了一些在决定如何部署应用程序时可能需要牢记的主要概念:
diff --git a/docs/zh/docs/deployment/docker.md b/docs/zh/docs/deployment/docker.md
index f120ebfb8..3d0c19903 100644
--- a/docs/zh/docs/deployment/docker.md
+++ b/docs/zh/docs/deployment/docker.md
@@ -1,17 +1,17 @@
-# 容器中的 FastAPI - Docker
+# 容器中的 FastAPI - Docker { #fastapi-in-containers-docker }
-部署 FastAPI 应用程序时,常见的方法是构建 **Linux 容器镜像**。 通常使用 **Docker** 完成。 然后,你可以通过几种可能的方式之一部署该容器镜像。
+部署 FastAPI 应用时,常见做法是构建一个**Linux 容器镜像**。通常使用 **Docker** 实现。然后你可以用几种方式之一部署该镜像。
-使用 Linux 容器有几个优点,包括**安全性**、**可复制性**、**简单性**等。
+使用 Linux 容器有多种优势,包括**安全性**、**可复制性**、**简单性**等。
-/// tip
+/// tip | 提示
-赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#fastapi-docker_1)。
+赶时间并且已经了解这些?直接跳到下面的 [`Dockerfile` 👇](#build-a-docker-image-for-fastapi)。
///
Dockerfile Preview 👀
+Dockerfile 预览 👀
```Dockerfile
FROM python:3.9
@@ -24,140 +24,127 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./app /code/app
-CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
+CMD ["fastapi", "run", "app/main.py", "--port", "80"]
# If running behind a proxy like Nginx or Traefik add --proxy-headers
-# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"]
+# CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"]
```
-### TLS 握手开始
+### TLS 握手开始 { #tls-handshake-start }
然后,浏览器将在**端口 443**(HTTPS 端口)上与该 IP 地址进行通信。
@@ -98,7 +97,7 @@ DNS 服务器会告诉浏览器使用某个特定的 **IP 地址**。 这将是
客户端和服务器之间建立 TLS 连接的过程称为 **TLS 握手**。
-### 带有 SNI 扩展的 TLS
+### 带有 SNI 扩展的 TLS { #tls-with-sni-extension }
**服务器中只有一个进程**可以侦听特定 **IP 地址**的特定 **端口**。 可能有其他进程在同一 IP 地址的其他端口上侦听,但每个 IP 地址和端口组合只有一个进程。
@@ -128,7 +127,7 @@ TLS 终止代理可以访问一个或多个 **TLS 证书**(HTTPS 证书)。
///
-### HTTPS 请求
+### HTTPS 请求 { #https-request }
现在客户端和服务器(特别是浏览器和 TLS 终止代理)具有 **加密的 TCP 连接**,它们可以开始 **HTTP 通信**。
@@ -136,19 +135,19 @@ TLS 终止代理可以访问一个或多个 **TLS 证书**(HTTPS 证书)。
-### 解密请求
+### 解密请求 { #decrypt-the-request }
TLS 终止代理将使用协商好的加密算法**解密请求**,并将**(解密的)HTTP 请求**传输到运行应用程序的进程(例如运行 FastAPI 应用的 Uvicorn 进程)。
-### HTTP 响应
+### HTTP 响应 { #http-response }
应用程序将处理请求并向 TLS 终止代理发送**(未加密)HTTP 响应**。
-### HTTPS 响应
+### HTTPS 响应 { #https-response }
然后,TLS 终止代理将使用之前协商的加密算法(以`someapp.example.com`的证书开头)对响应进行加密,并将其发送回浏览器。
@@ -158,7 +157,7 @@ TLS 终止代理将使用协商好的加密算法**解密请求**,并将**(
客户端(浏览器)将知道响应来自正确的服务器,因为它使用了他们之前使用 **HTTPS 证书** 协商出的加密算法。
-### 多个应用程序
+### 多个应用程序 { #multiple-applications }
在同一台(或多台)服务器中,可能存在**多个应用程序**,例如其他 API 程序或数据库。
@@ -168,7 +167,7 @@ TLS 终止代理将使用协商好的加密算法**解密请求**,并将**(
这样,TLS 终止代理就可以为多个应用程序处理**多个域名**的 HTTPS 和证书,然后在每种情况下将请求传输到正确的应用程序。
-### 证书更新
+### 证书更新 { #certificate-renewal }
在未来的某个时候,每个证书都会**过期**(大约在获得证书后 3 个月)。
@@ -183,16 +182,48 @@ TLS 终止代理将使用协商好的加密算法**解密请求**,并将**(
有多种方法可以做到这一点。 一些流行的方式是:
* **修改一些DNS记录**。
- * 为此,续订程序需要支持 DNS 提供商的 API,因此,要看你使用的 DNS 提供商是否提供这一功能。
+ * 为此,续订程序需要支持 DNS 提供商的 API,因此,要看你使用的 DNS 提供商是否提供这一功能。
* **在与域名关联的公共 IP 地址上作为服务器运行**(至少在证书获取过程中)。
- * 正如我们上面所说,只有一个进程可以监听特定的 IP 和端口。
- * 这就是当同一个 TLS 终止代理还负责证书续订过程时它非常有用的原因之一。
- * 否则,你可能需要暂时停止 TLS 终止代理,启动续订程序以获取证书,然后使用 TLS 终止代理配置它们,然后重新启动 TLS 终止代理。 这并不理想,因为你的应用程序在 TLS 终止代理关闭期间将不可用。
+ * 正如我们上面所说,只有一个进程可以监听特定的 IP 和端口。
+ * 这就是当同一个 TLS 终止代理还负责证书续订过程时它非常有用的原因之一。
+ * 否则,你可能需要暂时停止 TLS 终止代理,启动续订程序以获取证书,然后使用 TLS 终止代理配置它们,然后重新启动 TLS 终止代理。 这并不理想,因为你的应用程序在 TLS 终止代理关闭期间将不可用。
通过拥有一个**单独的系统来使用 TLS 终止代理来处理 HTTPS**, 而不是直接将 TLS 证书与应用程序服务器一起使用 (例如 Uvicorn),你可以在
更新证书的过程中同时保持提供服务。
-## 回顾
+## 代理转发请求头 { #proxy-forwarded-headers }
+
+当使用代理来处理 HTTPS 时,你的**应用服务器**(例如通过 FastAPI CLI 运行的 Uvicorn)对 HTTPS 过程并不了解,它只通过纯 HTTP 与 **TLS 终止代理**通信。
+
+这个**代理**通常会在将请求转发给**应用服务器**之前,临时设置一些 HTTP 请求头,以便让应用服务器知道该请求是由代理**转发**过来的。
+
+/// note | 技术细节
+
+这些代理请求头包括:
+
+* X-Forwarded-For
+* X-Forwarded-Proto
+* X-Forwarded-Host
+
+///
+
+不过,由于**应用服务器**并不知道自己位于受信任的**代理**之后,默认情况下,它不会信任这些请求头。
+
+但你可以配置**应用服务器**去信任由**代理**发送的这些“转发”请求头。如果你在使用 FastAPI CLI,可以使用命令行选项 `--forwarded-allow-ips` 指定它应该信任哪些 IP 发来的这些“转发”请求头。
+
+例如,如果**应用服务器**只接收来自受信任**代理**的通信,你可以设置 `--forwarded-allow-ips="*"`,让它信任所有传入的 IP,因为它只会接收来自**代理**所使用 IP 的请求。
+
+这样,应用就能知道自己的公共 URL、是否使用 HTTPS、域名等信息。
+
+这在需要正确处理重定向等场景时很有用。
+
+/// tip
+
+你可以在文档中了解更多:[在代理之后 - 启用代理转发请求头](../advanced/behind-a-proxy.md#enable-proxy-forwarded-headers){.internal-link target=_blank}
+
+///
+
+## 回顾 { #recap }
拥有**HTTPS** 非常重要,并且在大多数情况下相当**关键**。 作为开发人员,你围绕 HTTPS 所做的大部分努力就是**理解这些概念**以及它们的工作原理。
diff --git a/docs/zh/docs/deployment/index.md b/docs/zh/docs/deployment/index.md
index 1ec0c5c5b..47dcede65 100644
--- a/docs/zh/docs/deployment/index.md
+++ b/docs/zh/docs/deployment/index.md
@@ -1,21 +1,23 @@
-# 部署
+# 部署 { #deployment }
部署 **FastAPI** 应用程序相对容易。
-## 部署是什么意思
+## 部署是什么意思 { #what-does-deployment-mean }
**部署**应用程序意味着执行必要的步骤以使其**可供用户使用**。
-对于**Web API**来说,通常涉及将上传到**云服务器**中,搭配一个性能和稳定性都不错的**服务器程序**,以便你的**用户**可以高效地**访问**你的应用程序,而不会出现中断或其他问题。
+对于**Web API**来说,通常涉及将其放到一台**远程机器**中,搭配一个性能和稳定性都不错的**服务器程序**,以便你的**用户**可以高效地**访问**你的应用程序,而不会出现中断或其他问题。
-这与**开发**阶段形成鲜明对比,在**开发**阶段,你不断更改代码、破坏代码、修复代码, 来回停止和重启服务器等。
+这与**开发**阶段形成鲜明对比,在**开发**阶段,你不断更改代码、破坏代码、修复代码,来回停止和重启开发服务器等。
-## 部署策略
+## 部署策略 { #deployment-strategies }
根据你的使用场景和使用的工具,有多种方法可以实现此目的。
你可以使用一些工具自行**部署服务器**,你也可以使用能为你完成部分工作的**云服务**,或其他可能的选项。
+例如,我们(FastAPI 团队)构建了 **FastAPI Cloud**,让将 FastAPI 应用部署到云端尽可能流畅,并且保持与使用 FastAPI 开发时相同的开发者体验。
+
我将向你展示在部署 **FastAPI** 应用程序时你可能应该记住的一些主要概念(尽管其中大部分适用于任何其他类型的 Web 应用程序)。
在接下来的部分中,你将看到更多需要记住的细节以及一些技巧。 ✨
diff --git a/docs/zh/docs/deployment/manually.md b/docs/zh/docs/deployment/manually.md
index 2c2784a64..6f2ad27b2 100644
--- a/docs/zh/docs/deployment/manually.md
+++ b/docs/zh/docs/deployment/manually.md
@@ -1,6 +1,6 @@
-# 手动运行服务器
+# 手动运行服务器 { #run-a-server-manually }
-## 使用 `fastapi run` 命令
+## 使用 `fastapi run` 命令 { #use-the-fastapi-run-command }
简而言之,使用 `fastapi run` 来运行您的 FastAPI 应用程序:
@@ -42,11 +42,11 @@ $ fastapi run ASGI。FastAPI 本质上是一个 ASGI Web 框架。
+FastAPI 使用了一种用于构建 Python Web 框架和服务器的标准,称为 ASGI。FastAPI 本质上是一个 ASGI Web 框架。
要在远程服务器上运行 **FastAPI** 应用(或任何其他 ASGI 应用),您需要一个 ASGI 服务器程序,例如 **Uvicorn**。它是 `fastapi` 命令默认使用的 ASGI 服务器。
@@ -58,7 +58,7 @@ FastAPI 使用了一种用于构建 Python Web 框架和服务器的标准,称
* Granian:基于 Rust 的 HTTP 服务器,专为 Python 应用设计。
* NGINX Unit:NGINX Unit 是一个轻量级且灵活的 Web 应用运行时环境。
-## 服务器主机和服务器程序
+## 服务器主机和服务器程序 { #server-machine-and-server-program }
关于名称,有一个小细节需要记住。 💡
@@ -68,8 +68,7 @@ FastAPI 使用了一种用于构建 Python Web 框架和服务器的标准,称
当提到远程主机时,通常将其称为**服务器**,但也称为**机器**(machine)、**VM**(虚拟机)、**节点**。 这些都是指某种类型的远程计算机,通常运行 Linux,您可以在其中运行程序。
-
-## 安装服务器程序
+## 安装服务器程序 { #install-the-server-program }
当您安装 FastAPI 时,它自带一个生产环境服务器——Uvicorn,并且您可以使用 `fastapi run` 命令来启动它。
@@ -101,7 +100,7 @@ $ pip install "uvicorn[standard]"
///
-## 运行服务器程序
+## 运行服务器程序 { #run-the-server-program }
如果您手动安装了 ASGI 服务器,通常需要以特定格式传递一个导入字符串,以便服务器能够正确导入您的 FastAPI 应用:
@@ -142,7 +141,7 @@ Uvicorn 和其他服务器支持 `--reload` 选项,该选项在开发过程中
///
-## 部署概念
+## 部署概念 { #deployment-concepts }
这些示例运行服务器程序(例如 Uvicorn),启动**单个进程**,在所有 IP(`0.0.0.0`)上监听预定义端口(例如`80`)。
diff --git a/docs/zh/docs/deployment/server-workers.md b/docs/zh/docs/deployment/server-workers.md
index e46ba7a09..2bbd5d9b6 100644
--- a/docs/zh/docs/deployment/server-workers.md
+++ b/docs/zh/docs/deployment/server-workers.md
@@ -1,4 +1,4 @@
-# 服务器工作进程(Workers) - 使用 Uvicorn 的多工作进程模式
+# 服务器工作进程(Workers) - 使用 Uvicorn 的多工作进程模式 { #server-workers-uvicorn-with-workers }
让我们回顾一下之前的部署概念:
@@ -17,7 +17,7 @@
在本章节中,我将向您展示如何使用 `fastapi` 命令或直接使用 `uvicorn` 命令以**多工作进程模式**运行 **Uvicorn**。
-/// info
+/// info | 信息
如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
@@ -25,7 +25,7 @@
///
-## 多个工作进程
+## 多个工作进程 { #multiple-workers }
您可以使用 `--workers` 命令行选项来启动多个工作进程:
@@ -111,7 +111,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
您还可以看到它显示了每个进程的 **PID**,父进程(这是**进程管理器**)的 PID 为`27365`,每个工作进程的 PID 为:`27368`、`27369`, `27370`和`27367`。
-## 部署概念
+## 部署概念 { #deployment-concepts }
在这里,您学习了如何使用多个**工作进程(workers)**来让应用程序的执行**并行化**,充分利用 CPU 的**多核性能**,并能够处理**更多的请求**。
@@ -124,13 +124,13 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
* **内存**
* **启动之前的先前步骤**
-## 容器和 Docker
+## 容器和 Docker { #containers-and-docker }
在关于 [容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank} 的下一章中,我将介绍一些可用于处理其他**部署概念**的策略。
我将向您展示如何**从零开始构建自己的镜像**,以运行一个单独的 Uvicorn 进程。这个过程相对简单,并且在使用 **Kubernetes** 等分布式容器管理系统时,这通常是您需要采取的方法。
-## 回顾
+## 回顾 { #recap }
您可以在使用 `fastapi` 或 `uvicorn` 命令时,通过 `--workers` CLI 选项启用多个工作进程(workers),以充分利用**多核 CPU**,以**并行运行多个进程**。
diff --git a/docs/zh/docs/deployment/versions.md b/docs/zh/docs/deployment/versions.md
index 228bb0765..23c37f3b5 100644
--- a/docs/zh/docs/deployment/versions.md
+++ b/docs/zh/docs/deployment/versions.md
@@ -1,4 +1,4 @@
-# 关于 FastAPI 版本
+# 关于 FastAPI 版本 { #about-fastapi-versions }
**FastAPI** 已在许多应用程序和系统的生产环境中使用。 并且测试覆盖率保持在100%。 但其开发进度仍在快速推进。
@@ -8,41 +8,41 @@
你现在就可以使用 **FastAPI** 创建生产环境应用程序(你可能已经这样做了一段时间),你只需确保使用的版本可以与其余代码正确配合即可。
-## 固定你的 `fastapi` 版本
+## 固定你的 `fastapi` 版本 { #pin-your-fastapi-version }
你应该做的第一件事是将你正在使用的 **FastAPI** 版本“固定”到你知道适用于你的应用程序的特定最新版本。
-例如,假设你在应用程序中使用版本`0.45.0`。
+例如,假设你在应用程序中使用版本`0.112.0`。
如果你使用`requirements.txt`文件,你可以使用以下命令指定版本:
-````txt
-fastapi==0.45.0
-````
+```txt
+fastapi[standard]==0.112.0
+```
-这意味着你将使用版本`0.45.0`。
+这意味着你将使用版本`0.112.0`。
或者你也可以将其固定为:
-````txt
-fastapi>=0.45.0,<0.46.0
-````
+```txt
+fastapi[standard]>=0.112.0,<0.113.0
+```
-这意味着你将使用`0.45.0`或更高版本,但低于`0.46.0`,例如,版本`0.45.2`仍会被接受。
+这意味着你将使用`0.112.0`或更高版本,但低于`0.113.0`,例如,版本`0.112.2`仍会被接受。
-如果你使用任何其他工具来管理你的安装,例如 Poetry、Pipenv 或其他工具,它们都有一种定义包的特定版本的方法。
+如果你使用任何其他工具来管理你的安装,例如 `uv`、Poetry、Pipenv 或其他工具,它们都有一种定义包的特定版本的方法。
-## 可用版本
+## 可用版本 { #available-versions }
你可以在[发行说明](../release-notes.md){.internal-link target=_blank}中查看可用版本(例如查看当前最新版本)。
-## 关于版本
+## 关于版本 { #about-versions }
遵循语义版本控制约定,任何低于`1.0.0`的版本都可能会添加 breaking changes。
-FastAPI 还遵循这样的约定:任何`PATCH`版本更改都是为了bug修复和non-breaking changes。
+FastAPI 还遵循这样的约定:任何"PATCH"版本更改都是为了bug修复和non-breaking changes。
-/// tip
+/// tip | 提示
"PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。
@@ -56,13 +56,13 @@ fastapi>=0.45.0,<0.46.0
"MINOR"版本中会添加breaking changes和新功能。
-/// tip
+/// tip | 提示
"MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。
///
-## 升级FastAPI版本
+## 升级FastAPI版本 { #upgrading-the-fastapi-versions }
你应该为你的应用程序添加测试。
@@ -72,7 +72,7 @@ fastapi>=0.45.0,<0.46.0
如果一切正常,或者在进行必要的更改之后,并且所有测试都通过了,那么你可以将`fastapi`固定到新的版本。
-## 关于Starlette
+## 关于Starlette { #about-starlette }
你不应该固定`starlette`的版本。
@@ -80,14 +80,14 @@ fastapi>=0.45.0,<0.46.0
因此,**FastAPI** 自己可以使用正确的 Starlette 版本。
-## 关于 Pydantic
+## 关于 Pydantic { #about-pydantic }
Pydantic 包含针对 **FastAPI** 的测试及其自己的测试,因此 Pydantic 的新版本(`1.0.0`以上)始终与 FastAPI 兼容。
-你可以将 Pydantic 固定到适合你的`1.0.0`以上和`2.0.0`以下的任何版本。
+你可以将 Pydantic 固定到任何高于 `1.0.0` 且适合你的版本。
例如:
-````txt
-pydantic>=1.2.0,<2.0.0
-````
+```txt
+pydantic>=2.7.0,<3.0.0
+```
diff --git a/docs/zh/docs/environment-variables.md b/docs/zh/docs/environment-variables.md
index 812278051..8729a6306 100644
--- a/docs/zh/docs/environment-variables.md
+++ b/docs/zh/docs/environment-variables.md
@@ -1,6 +1,6 @@
-# 环境变量
+# 环境变量 { #environment-variables }
-/// tip
+/// tip | 提示
如果你已经知道什么是“环境变量”并且知道如何使用它们,你可以放心跳过这一部分。
@@ -10,7 +10,7 @@
环境变量对于处理应用程序**设置**、作为 Python **安装**的一部分等方面非常有用。
-## 创建和使用环境变量
+## 创建和使用环境变量 { #create-and-use-env-vars }
你在 **shell(终端)**中就可以**创建**和使用环境变量,并不需要用到 Python:
@@ -50,7 +50,7 @@ Hello Wade Wilson
////
-## 在 Python 中读取环境变量
+## 在 Python 中读取环境变量 { #read-env-vars-in-python }
你也可以在 Python **之外**的终端中创建环境变量(或使用任何其他方法),然后在 Python 中**读取**它们。
@@ -63,9 +63,9 @@ name = os.getenv("MY_NAME", "World")
print(f"Hello {name} from Python")
```
-/// tip
+/// tip | 提示
-第二个参数是 `os.getenv()` 的默认返回值。
+第二个参数是 `os.getenv()` 的默认返回值。
如果没有提供,默认值为 `None`,这里我们提供 `"World"` 作为默认值。
@@ -151,21 +151,21 @@ Hello World from Python
-/// tip
+/// tip | 提示
-你可以在 The Twelve-Factor App: 配置中了解更多信息。
+你可以在 The Twelve-Factor App: 配置中了解更多信息。
///
-## 类型和验证
+## 类型和验证 { #types-and-validation }
这些环境变量只能处理**文本字符串**,因为它们是处于 Python 范畴之外的,必须与其他程序和操作系统的其余部分兼容(甚至与不同的操作系统兼容,如 Linux、Windows、macOS)。
这意味着从环境变量中读取的**任何值**在 Python 中都将是一个 `str`,任何类型转换或验证都必须在代码中完成。
-你将在[高级用户指南 - 设置和环境变量](./advanced/settings.md)中了解更多关于使用环境变量处理**应用程序设置**的信息。
+你将在[高级用户指南 - 设置和环境变量](./advanced/settings.md){.internal-link target=_blank}中了解更多关于使用环境变量处理**应用程序设置**的信息。
-## `PATH` 环境变量
+## `PATH` 环境变量 { #path-environment-variable }
有一个**特殊的**环境变量称为 **`PATH`**,操作系统(Linux、macOS、Windows)用它来查找要运行的程序。
@@ -209,7 +209,7 @@ C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System3
如果找到了,那么操作系统将**使用它**;否则,操作系统会继续在**其他目录**中查找。
-### 安装 Python 和更新 `PATH`
+### 安装 Python 和更新 `PATH` { #installing-python-and-updating-the-path }
安装 Python 时,可能会询问你是否要更新 `PATH` 环境变量。
@@ -233,7 +233,7 @@ C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System3
假设你安装 Python 并最终将其安装在了目录 `C:\opt\custompython\bin` 中。
-如果你同意更新 `PATH` 环境变量 (在 Python 安装程序中,这个操作是名为 `Add Python x.xx to PATH` 的复选框 —— 译者注),那么安装程序将会将 `C:\opt\custompython\bin` 添加到 `PATH` 环境变量中。
+如果你同意更新 `PATH` 环境变量,那么安装程序将会将 `C:\opt\custompython\bin` 添加到 `PATH` 环境变量中。
```plaintext
C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin
@@ -285,13 +285,13 @@ $ C:\opt\custompython\bin\python
////
-当学习[虚拟环境](virtual-environments.md)时,这些信息将会很有用。
+当学习[虚拟环境](virtual-environments.md){.internal-link target=_blank}时,这些信息将会很有用。
-## 结论
+## 结论 { #conclusion }
通过这个教程,你应该对**环境变量**是什么以及如何在 Python 中使用它们有了基本的了解。
-你也可以在环境变量 - 维基百科 (Wikipedia for Environment Variable) 中了解更多关于它们的信息。
+你也可以在环境变量 - 维基百科中了解更多关于它们的信息。
在许多情况下,环境变量的用途和适用性并不是很明显。但是在开发过程中,它们会在许多不同的场景中出现,因此了解它们是很有必要的。
diff --git a/docs/zh/docs/fastapi-cli.md b/docs/zh/docs/fastapi-cli.md
index 3b67eb664..4d3b51a57 100644
--- a/docs/zh/docs/fastapi-cli.md
+++ b/docs/zh/docs/fastapi-cli.md
@@ -1,8 +1,8 @@
-# FastAPI CLI
+# FastAPI CLI { #fastapi-cli }
**FastAPI CLI** 是一个命令行程序,你可以用它来部署和运行你的 FastAPI 应用程序,管理你的 FastAPI 项目,等等。
-当你安装 FastAPI 时(例如使用 `pip install FastAPI` 命令),会包含一个名为 `fastapi-cli` 的软件包,该软件包在终端中提供 `fastapi` 命令。
+当你安装 FastAPI 时(例如使用 `pip install "fastapi[standard]"`),会包含一个名为 `fastapi-cli` 的软件包,该软件包在终端中提供 `fastapi` 命令。
要在开发环境中运行你的 FastAPI 应用,你可以使用 `fastapi dev` 命令:
@@ -48,32 +48,28 @@ $ fastapi dev Uvicorn
-## 改变主题
+## 改变主题 { #change-the-theme }
同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点):
-{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial002_py39.py hl[3] *}
这个配置会改变语法高亮主题:
-## 改变默认 Swagger UI 参数
+## 改变默认 Swagger UI 参数 { #change-default-swagger-ui-parameters }
FastAPI 包含了一些默认配置参数,适用于大多数用例。
其包括这些默认配置参数:
-{* ../../fastapi/openapi/docs.py ln[7:23] *}
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
你可以通过在 `swagger_ui_parameters` 中设置不同的值来覆盖它们。
比如,如果要禁用 `deepLinking`,你可以像这样传递设置到 `swagger_ui_parameters` 中:
-{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial003_py39.py hl[3] *}
-## 其他 Swagger UI 参数
+## 其他 Swagger UI 参数 { #other-swagger-ui-parameters }
-查看其他 Swagger UI 参数,请阅读 docs for Swagger UI parameters。
+查看所有其他可用的配置,请阅读 Swagger UI 参数文档。
-## JavaScript-only 配置
+## JavaScript-only 配置 { #javascript-only-settings }
Swagger UI 同样允许使用 **JavaScript-only** 配置对象(例如,JavaScript 函数)。
@@ -67,4 +67,4 @@ presets: [
这些是 **JavaScript** 对象,而不是字符串,所以你不能直接从 Python 代码中传递它们。
-如果你需要像这样使用 JavaScript-only 配置,你可以使用上述方法之一。覆盖所有 Swagger UI *path operation* 并手动编写任何你需要的 JavaScript。
+如果你需要像这样使用 JavaScript-only 配置,你可以使用上述方法之一。覆盖所有 Swagger UI *路径操作* 并手动编写任何你需要的 JavaScript。
diff --git a/docs/zh/docs/how-to/general.md b/docs/zh/docs/how-to/general.md
index e8b6dd3b2..e75ad6c79 100644
--- a/docs/zh/docs/how-to/general.md
+++ b/docs/zh/docs/how-to/general.md
@@ -1,39 +1,39 @@
-# 通用 - 如何操作 - 诀窍
+# 通用 - 如何操作 - 诀窍 { #general-how-to-recipes }
这里是一些指向文档中其他部分的链接,用于解答一般性或常见问题。
-## 数据过滤 - 安全性
+## 数据过滤 - 安全性 { #filter-data-security }
为确保不返回超过需要的数据,请阅读 [教程 - 响应模型 - 返回类型](../tutorial/response-model.md){.internal-link target=_blank} 文档。
-## 文档的标签 - OpenAPI
+## 文档的标签 - OpenAPI { #documentation-tags-openapi }
在文档界面中添加**路径操作**的标签和进行分组,请阅读 [教程 - 路径操作配置 - Tags 参数](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank} 文档。
-## 文档的概要和描述 - OpenAPI
+## 文档的概要和描述 - OpenAPI { #documentation-summary-and-description-openapi }
-在文档界面中添加**路径操作**的概要和描述,请阅读 [教程 - 路径操作配置 - Summary 和 Description 参数](../tutorial/path-operation-configuration.md#summary-description){.internal-link target=_blank} 文档。
+在文档界面中添加**路径操作**的概要和描述,请阅读 [教程 - 路径操作配置 - Summary 和 Description 参数](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank} 文档。
-## 文档的响应描述 - OpenAPI
+## 文档的响应描述 - OpenAPI { #documentation-response-description-openapi }
在文档界面中定义并显示响应描述,请阅读 [教程 - 路径操作配置 - 响应描述](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank} 文档。
-## 文档弃用**路径操作** - OpenAPI
+## 文档弃用**路径操作** - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
在文档界面中显示弃用的**路径操作**,请阅读 [教程 - 路径操作配置 - 弃用](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank} 文档。
-## 将任何数据转换为 JSON 兼容格式
+## 将任何数据转换为 JSON 兼容格式 { #convert-any-data-to-json-compatible }
要将任何数据转换为 JSON 兼容格式,请阅读 [教程 - JSON 兼容编码器](../tutorial/encoder.md){.internal-link target=_blank} 文档。
-## OpenAPI 元数据 - 文档
+## OpenAPI 元数据 - 文档 { #openapi-metadata-docs }
要添加 OpenAPI 的元数据,包括许可证、版本、联系方式等,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md){.internal-link target=_blank} 文档。
-## OpenAPI 自定义 URL
+## OpenAPI 自定义 URL { #openapi-custom-url }
要自定义 OpenAPI 的 URL(或删除它),请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#openapi-url){.internal-link target=_blank} 文档。
-## OpenAPI 文档 URL
+## OpenAPI 文档 URL { #openapi-docs-urls }
-要更改用于自动生成文档的 URL,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}.
+要更改用于自动生成文档的 URL,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}。
diff --git a/docs/zh/docs/how-to/index.md b/docs/zh/docs/how-to/index.md
index ac097618b..980dcd1a6 100644
--- a/docs/zh/docs/how-to/index.md
+++ b/docs/zh/docs/how-to/index.md
@@ -1,4 +1,4 @@
-# 如何操作 - 诀窍
+# 如何操作 - 诀窍 { #how-to-recipes }
在这里,你将看到关于**多个主题**的不同诀窍或“如何操作”指南。
@@ -6,7 +6,7 @@
如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。
-/// tip | 小技巧
+/// tip | 提示
如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。
diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md
index 9f4b6d3d5..1c2aea328 100644
--- a/docs/zh/docs/index.md
+++ b/docs/zh/docs/index.md
@@ -1,11 +1,11 @@
-# FastAPI
+# FastAPI { #fastapi }
+{% endfor -%}
+
+### 金牌和银牌赞助商 { #gold-and-silver-sponsors }
+
{% for sponsor in sponsors.gold -%}
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
{% endfor %}
-{% endif %}
-Other sponsors
+其他赞助商
-## 评价
+## 评价 { #opinions }
-「_[...] 最近我一直在使用 **FastAPI**。[...] 实际上我正在计划将其用于我所在的**微软**团队的所有**机器学习服务**。其中一些服务正被集成进核心 **Windows** 产品和一些 **Office** 产品。_」
+「_[...] 最近我大量使用 **FastAPI**。[...] 我实际上计划把它用于我团队在 **微软** 的所有 **机器学习服务**。其中一些正在集成进核心 **Windows** 产品以及一些 **Office** 产品。_」
-
+
+## **Typer**,命令行中的 FastAPI { #typer-the-fastapi-of-clis }
-如果你正在开发一个在终端中运行的命令行应用而不是 web API,不妨试下 **Typer**。
+如果你要开发一个用于终端的 命令行应用而不是 Web API,看看 **Typer**。
-**Typer** 是 FastAPI 的小同胞。它想要成为**命令行中的 FastAPI**。 ⌨️ 🚀
+**Typer** 是 FastAPI 的小同胞。它的目标是成为**命令行中的 FastAPI**。⌨️ 🚀
-## 依赖
+## 依赖 { #requirements }
-Python 及更高版本
+FastAPI 站在巨人的肩膀之上:
-FastAPI 站在以下巨人的肩膀之上:
-
-* Starlette 负责 web 部分。
+* Starlette 负责 Web 部分。
* Pydantic 负责数据部分。
-## 安装
+## 安装 { #installation }
+
+创建并激活一个虚拟环境,然后安装 FastAPI:
或者使用
-如果你的代码里会出现 `async` / `await`,请使用 `async def`:
-
-```Python hl_lines="9 14"
-from typing import Union
+如果你的代码里会用到 `async` / `await`,请使用 `async def`:
+```Python hl_lines="7 12"
from fastapi import FastAPI
app = FastAPI()
@@ -190,28 +193,41 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Union[str, None] = None):
+async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
```
**Note**:
-如果你不知道是否会用到,可以查看文档的 _"In a hurry?"_ 章节中 关于 `async` 和 `await` 的部分。
+如果你不确定,请查看文档中 _"In a hurry?"_ 章节的`async` 和 `await`部分。
async def...关于
+uvicorn main:app --reload 命令......关于命令
- `uvicorn main:app` 命令含义如下:
+`fastapi dev` 命令会读取你的 `main.py` 文件,检测其中的 **FastAPI** 应用,并使用 Uvicorn 启动服务器。
-* `main`:`main.py` 文件(一个 Python "模块")。
-* `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。
-* `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。
+默认情况下,`fastapi dev` 会在本地开发时启用自动重载。
+
+你可以在 FastAPI CLI 文档中了解更多。
fastapi dev main.py...email-validator - 用于 email 校验。
-用于 Starlette:
+Starlette 使用:
-* httpx - 使用 `TestClient` 时安装。
-* jinja2 - 使用默认模板配置时安装。
-* python-multipart - 需要通过 `request.form()` 对表单进行「解析」时安装。
-* itsdangerous - 需要 `SessionMiddleware` 支持时安装。
-* pyyaml - 使用 Starlette 提供的 `SchemaGenerator` 时安装(有 FastAPI 你可能并不需要它)。
-* graphene - 需要 `GraphQLApp` 支持时安装。
+* httpx - 使用 `TestClient` 时需要。
+* jinja2 - 使用默认模板配置时需要。
+* python-multipart - 使用 `request.form()` 支持表单「解析」时需要。
-用于 FastAPI / Starlette:
+FastAPI 使用:
-* uvicorn - 用于加载和运行你的应用程序的服务器。
-* orjson - 使用 `ORJSONResponse` 时安装。
-* ujson - 使用 `UJSONResponse` 时安装。
+* uvicorn - 加载并提供你的应用的服务器。包含 `uvicorn[standard]`,其中包含高性能服务所需的一些依赖(例如 `uvloop`)。
+* `fastapi-cli[standard]` - 提供 `fastapi` 命令。
+ * 其中包含 `fastapi-cloud-cli`,它允许你将 FastAPI 应用部署到 FastAPI Cloud。
-你可以通过 `pip install "fastapi[all]"` 命令来安装以上所有依赖。
+### 不包含 `standard` 依赖 { #without-standard-dependencies }
-## 许可协议
+如果你不想包含这些 `standard` 可选依赖,可以使用 `pip install fastapi`,而不是 `pip install "fastapi[standard]"`。
+
+### 不包含 `fastapi-cloud-cli` { #without-fastapi-cloud-cli }
+
+如果你想安装带有 standard 依赖但不包含 `fastapi-cloud-cli` 的 FastAPI,可以使用 `pip install "fastapi[standard-no-fastapi-cloud-cli]"`。
+
+### 其他可选依赖 { #additional-optional-dependencies }
+
+还有一些你可能想安装的可选依赖。
+
+额外的 Pydantic 可选依赖:
+
+* pydantic-settings - 用于配置管理。
+* pydantic-extra-types - 用于在 Pydantic 中使用的额外类型。
+
+额外的 FastAPI 可选依赖:
+
+* orjson - 使用 `ORJSONResponse` 时需要。
+* ujson - 使用 `UJSONResponse` 时需要。
+
+## 许可协议 { #license }
该项目遵循 MIT 许可协议。
diff --git a/docs/zh/docs/learn/index.md b/docs/zh/docs/learn/index.md
index 38696f6fe..144d5b2a9 100644
--- a/docs/zh/docs/learn/index.md
+++ b/docs/zh/docs/learn/index.md
@@ -1,4 +1,4 @@
-# 学习
+# 学习 { #learn }
以下是学习 **FastAPI** 的介绍部分和教程。
diff --git a/docs/zh/docs/project-generation.md b/docs/zh/docs/project-generation.md
index 48eb990df..a6ad9f94a 100644
--- a/docs/zh/docs/project-generation.md
+++ b/docs/zh/docs/project-generation.md
@@ -1,28 +1,28 @@
-# FastAPI全栈模板
+# FastAPI全栈模板 { #full-stack-fastapi-template }
-模板通常带有特定的设置,而且被设计为灵活和可定制的。这允许您根据项目的需求修改和调整它们,使它们成为一个很好的起点。🏁
+模板通常带有特定的设置,但它们被设计为灵活且可定制。这样你可以根据项目需求进行修改和调整,使其成为很好的起点。🏁
-您可以使用此模板开始,因为它包含了许多已经为您完成的初始设置、安全性、数据库和一些API端点。
+你可以使用此模板开始,它已经为你完成了大量的初始设置、安全性、数据库以及一些 API 端点。
-代码仓: Full Stack FastAPI Template
+GitHub 仓库: Full Stack FastAPI Template
-## FastAPI全栈模板 - 技术栈和特性
+## FastAPI全栈模板 - 技术栈和特性 { #full-stack-fastapi-template-technology-stack-and-features }
-- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) 用于Python后端API.
- - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) 用于Python和SQL数据库的集成(ORM)。
- - 🔍 [Pydantic](https://docs.pydantic.dev) FastAPI的依赖项之一,用于数据验证和配置管理。
- - 💾 [PostgreSQL](https://www.postgresql.org) 作为SQL数据库。
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com/zh) 用于 Python 后端 API。
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) 用于 Python 与 SQL 数据库的交互(ORM)。
+ - 🔍 [Pydantic](https://docs.pydantic.dev),FastAPI 使用,用于数据验证与配置管理。
+ - 💾 [PostgreSQL](https://www.postgresql.org) 作为 SQL 数据库。
- 🚀 [React](https://react.dev) 用于前端。
- - 💃 使用了TypeScript、hooks、[Vite](https://vitejs.dev)和其他一些现代化的前端技术栈。
- - 🎨 [Chakra UI](https://chakra-ui.com) 用于前端组件。
- - 🤖 一个自动化生成的前端客户端。
- - 🧪 [Playwright](https://playwright.dev)用于端到端测试。
- - 🦇 支持暗黑主题(Dark mode)。
-- 🐋 [Docker Compose](https://www.docker.com) 用于开发环境和生产环境。
-- 🔒 默认使用密码哈希来保证安全。
-- 🔑 JWT令牌用于权限验证。
-- 📫 使用邮箱来进行密码恢复。
-- ✅ 单元测试用了[Pytest](https://pytest.org).
-- 📞 [Traefik](https://traefik.io) 用于反向代理和负载均衡。
-- 🚢 部署指南(Docker Compose)包含了如何起一个Traefik前端代理来自动化HTTPS认证。
-- 🏭 CI(持续集成)和 CD(持续部署)基于GitHub Actions。
+ - 💃 使用 TypeScript、hooks、Vite 以及现代前端技术栈的其他部分。
+ - 🎨 [Tailwind CSS](https://tailwindcss.com) 与 [shadcn/ui](https://ui.shadcn.com) 用于前端组件。
+ - 🤖 自动生成的前端客户端。
+ - 🧪 [Playwright](https://playwright.dev) 用于端到端测试。
+ - 🦇 支持暗黑模式。
+- 🐋 [Docker Compose](https://www.docker.com) 用于开发与生产。
+- 🔒 默认启用安全的密码哈希。
+- 🔑 JWT(JSON Web Token)认证。
+- 📫 基于邮箱的密码找回。
+- ✅ 使用 [Pytest](https://pytest.org) 进行测试。
+- 📞 [Traefik](https://traefik.io) 用作反向代理/负载均衡。
+- 🚢 使用 Docker Compose 的部署指南,包括如何设置前端 Traefik 代理以自动处理 HTTPS 证书。
+- 🏭 基于 GitHub Actions 的 CI(持续集成)与 CD(持续部署)。
diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md
index a7f76d97f..3e1c593c1 100644
--- a/docs/zh/docs/python-types.md
+++ b/docs/zh/docs/python-types.md
@@ -1,31 +1,30 @@
-# Python 类型提示简介
+# Python 类型提示简介 { #python-types-intro }
-**Python 3.6+ 版本**加入了对"类型提示"的支持。
+Python 支持可选的“类型提示”(也叫“类型注解”)。
-这些**"类型提示"**是一种新的语法(在 Python 3.6 版本加入)用来声明一个变量的类型。
+这些“类型提示”或注解是一种特殊语法,用来声明变量的类型。
-通过声明变量的类型,编辑器和一些工具能给你提供更好的支持。
+通过为变量声明类型,编辑器和工具可以为你提供更好的支持。
-这只是一个关于 Python 类型提示的**快速入门 / 复习**。它仅涵盖与 **FastAPI** 一起使用所需的最少部分...实际上只有很少一点。
+这只是一个关于 Python 类型提示的快速入门/复习。它只涵盖与 **FastAPI** 一起使用所需的最少部分……实际上非常少。
-整个 **FastAPI** 都基于这些类型提示构建,它们带来了许多优点和好处。
+**FastAPI** 完全基于这些类型提示构建,它们带来了许多优势和好处。
-但即使你不会用到 **FastAPI**,了解一下类型提示也会让你从中受益。
+但即使你从不使用 **FastAPI**,了解一些类型提示也会让你受益。
-/// note
+/// note | 注意
-如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。
+如果你已经是 Python 专家,并且对类型提示了如指掌,可以跳到下一章。
///
-## 动机
+## 动机 { #motivation }
让我们从一个简单的例子开始:
-{* ../../docs_src/python_types/tutorial001.py *}
+{* ../../docs_src/python_types/tutorial001_py39.py *}
-
-运行这段程序将输出:
+运行这个程序会输出:
```
John Doe
@@ -33,38 +32,37 @@ John Doe
这个函数做了下面这些事情:
-* 接收 `first_name` 和 `last_name` 参数。
-* 通过 `title()` 将每个参数的第一个字母转换为大写形式。
-* 中间用一个空格来拼接它们。
+* 接收 `first_name` 和 `last_name`。
+* 通过 `title()` 将每个参数的第一个字母转换为大写。
+* 用一个空格将它们拼接起来。
-{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
-
-### 修改示例
+### 修改它 { #edit-it }
这是一个非常简单的程序。
-现在假设你将从头开始编写这段程序。
+但现在想象你要从零开始写它。
-在某一时刻,你开始定义函数,并且准备好了参数...。
+在某个时刻你开始定义函数,并且准备好了参数……
-现在你需要调用一个"将第一个字母转换为大写形式的方法"。
+接下来你需要调用“那个把首字母变大写的方法”。
-等等,那个方法是什么来着?`upper`?还是 `uppercase`?`first_uppercase`?`capitalize`?
+是 `upper`?是 `uppercase`?`first_uppercase`?还是 `capitalize`?
-然后你尝试向程序员老手的朋友——编辑器自动补全寻求帮助。
+然后,你试试程序员的老朋友——编辑器的自动补全。
-输入函数的第一个参数 `first_name`,输入点号(`.`)然后敲下 `Ctrl+Space` 来触发代码补全。
+你输入函数的第一个参数 `first_name`,再输入一个点(`.`),然后按下 `Ctrl+Space` 触发补全。
-但遗憾的是并没有起什么作用:
+但很遗憾,没有什么有用的提示:
-
+
-### 添加类型
+### 添加类型 { #add-types }
-让我们来修改上面例子的一行代码。
+我们来改前一个版本的一行代码。
-我们将把下面这段代码中的函数参数从:
+把函数参数从:
```Python
first_name, last_name
@@ -78,227 +76,389 @@ John Doe
就是这样。
-这些就是"类型提示":
+这些就是“类型提示”:
-{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
-
-这和声明默认值是不同的,例如:
+这和声明默认值不同,比如:
```Python
first_name="john", last_name="doe"
```
-这两者不一样。
+这是两码事。
我们用的是冒号(`:`),不是等号(`=`)。
-而且添加类型提示一般不会改变原来的运行结果。
+而且添加类型提示通常不会改变代码本来的行为。
-现在假设我们又一次正在创建这个函数,这次添加了类型提示。
+现在,再想象你又在编写这个函数了,不过这次加上了类型提示。
-在同样的地方,通过 `Ctrl+Space` 触发自动补全,你会发现:
+在同样的位置,你用 `Ctrl+Space` 触发自动补全,就能看到:
-
+
-这样,你可以滚动查看选项,直到你找到看起来眼熟的那个:
+这样,你可以滚动查看选项,直到找到那个“看着眼熟”的:
-
+
-## 更多动机
+## 更多动机 { #more-motivation }
-下面是一个已经有类型提示的函数:
+看这个已经带有类型提示的函数:
-{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
+因为编辑器知道变量的类型,你不仅能得到补全,还能获得错误检查:
-因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误:
+
-
+现在你知道需要修复它,用 `str(age)` 把 `age` 转成字符串:
-现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串:
+{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
-{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+## 声明类型 { #declaring-types }
+你刚刚看到的是声明类型提示的主要位置:函数参数。
-## 声明类型
+这也是你在 **FastAPI** 中使用它们的主要场景。
-你刚刚看到的就是声明类型提示的主要场景。用于函数的参数。
+### 简单类型 { #simple-types }
-这也是你将在 **FastAPI** 中使用它们的主要场景。
+你不仅可以声明 `str`,还可以声明所有标准的 Python 类型。
-### 简单类型
-
-不只是 `str`,你能够声明所有的标准 Python 类型。
-
-比如以下类型:
+例如:
* `int`
* `float`
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
+### 带类型参数的泛型类型 { #generic-types-with-type-parameters }
-### 嵌套类型
+有些数据结构可以包含其他值,比如 `dict`、`list`、`set` 和 `tuple`。而内部的值也会有自己的类型。
-有些容器数据结构可以包含其他的值,比如 `dict`、`list`、`set` 和 `tuple`。它们内部的值也会拥有自己的类型。
+这些带有内部类型的类型称为“泛型”(generic)类型。可以把它们连同内部类型一起声明出来。
-你可以使用 Python 的 `typing` 标准库来声明这些类型以及子类型。
+要声明这些类型以及内部类型,你可以使用 Python 标准库模块 `typing`。它就是为支持这些类型提示而存在的。
-它专门用来支持这些类型提示。
+#### 更新的 Python 版本 { #newer-versions-of-python }
-#### 列表
+使用 `typing` 的语法与所有版本兼容,从 Python 3.6 到最新版本(包括 Python 3.9、Python 3.10 等)。
-例如,让我们来定义一个由 `str` 组成的 `list` 变量。
+随着 Python 的发展,更新的版本对这些类型注解的支持更好,在很多情况下你甚至不需要导入和使用 `typing` 模块来声明类型注解。
-从 `typing` 模块导入 `List`(注意是大写的 `L`):
+如果你可以为项目选择更高版本的 Python,你将能享受到这种额外的简化。
-{* ../../docs_src/python_types/tutorial006.py hl[1] *}
+在整个文档中,会根据不同 Python 版本提供相应的示例(当存在差异时)。
+比如“Python 3.6+”表示兼容 Python 3.6 及以上(包括 3.7、3.8、3.9、3.10 等)。而“Python 3.9+”表示兼容 Python 3.9 及以上(包括 3.10 等)。
-同样以冒号(`:`)来声明这个变量。
+如果你可以使用最新的 Python 版本,请使用最新版本的示例,它们将拥有最简洁的语法,例如“Python 3.10+”。
-输入 `List` 作为类型。
+#### 列表 { #list }
-由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中:
+例如,我们来定义一个由 `str` 组成的 `list` 变量。
-{* ../../docs_src/python_types/tutorial006.py hl[4] *}
+用同样的冒号(`:`)语法声明变量。
+类型写 `list`。
-这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。
+因为 list 是一种包含内部类型的类型,把内部类型写在方括号里:
-这样,即使在处理列表中的元素时,你的编辑器也可以提供支持。
+{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
-没有类型,几乎是不可能实现下面这样:
+/// info | 信息
-
+方括号中的这些内部类型称为“类型参数”(type parameters)。
-注意,变量 `item` 是列表 `items` 中的元素之一。
+在这个例子中,`str` 是传给 `list` 的类型参数。
-而且,编辑器仍然知道它是一个 `str`,并为此提供了支持。
+///
-#### 元组和集合
+这表示:“变量 `items` 是一个 `list`,并且列表中的每一个元素都是 `str`”。
-声明 `tuple` 和 `set` 的方法也是一样的:
+这样,即使是在处理列表中的元素时,编辑器也能给你提供支持:
-{* ../../docs_src/python_types/tutorial007.py hl[1,4] *}
+
+没有类型的话,这几乎是不可能做到的。
+
+注意,变量 `item` 是列表 `items` 中的一个元素。
+
+即便如此,编辑器仍然知道它是 `str`,并为此提供支持。
+
+#### 元组和集合 { #tuple-and-set }
+
+声明 `tuple` 和 `set` 的方式类似:
+
+{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
这表示:
-* 变量 `items_t` 是一个 `tuple`,其中的前两个元素都是 `int` 类型, 最后一个元素是 `str` 类型。
-* 变量 `items_s` 是一个 `set`,其中的每个元素都是 `bytes` 类型。
+* 变量 `items_t` 是一个含有 3 个元素的 `tuple`,分别是一个 `int`、另一个 `int`,以及一个 `str`。
+* 变量 `items_s` 是一个 `set`,其中每个元素的类型是 `bytes`。
-#### 字典
+#### 字典 { #dict }
-定义 `dict` 时,需要传入两个子类型,用逗号进行分隔。
+定义 `dict` 时,需要传入 2 个类型参数,用逗号分隔。
-第一个子类型声明 `dict` 的所有键。
+第一个类型参数用于字典的键。
-第二个子类型声明 `dict` 的所有值:
-
-{* ../../docs_src/python_types/tutorial008.py hl[1,4] *}
+第二个类型参数用于字典的值:
+{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
这表示:
* 变量 `prices` 是一个 `dict`:
- * 这个 `dict` 的所有键为 `str` 类型(可以看作是字典内每个元素的名称)。
- * 这个 `dict` 的所有值为 `float` 类型(可以看作是字典内每个元素的价格)。
+ * 这个 `dict` 的键是 `str` 类型(比如,每个条目的名称)。
+ * 这个 `dict` 的值是 `float` 类型(比如,每个条目的价格)。
-### 类作为类型
+#### Union { #union }
-你也可以将类声明为变量的类型。
+你可以声明一个变量可以是若干种类型中的任意一种,比如既可以是 `int` 也可以是 `str`。
-假设你有一个名为 `Person` 的类,拥有 name 属性:
+在 Python 3.6 及以上(包括 Python 3.10),你可以使用 `typing` 中的 `Union`,把可能的类型放到方括号里。
-{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
-
-
-接下来,你可以将一个变量声明为 `Person` 类型:
-
-{* ../../docs_src/python_types/tutorial010.py hl[6] *}
-
-
-然后,你将再次获得所有的编辑器支持:
-
-
-
-## Pydantic 模型
-
-Pydantic 是一个用来执行数据校验的 Python 库。
-
-你可以将数据的"结构"声明为具有属性的类。
-
-每个属性都拥有类型。
-
-接着你用一些值来创建这个类的实例,这些值会被校验,并被转换为适当的类型(在需要的情况下),返回一个包含所有数据的对象。
-
-然后,你将获得这个对象的所有编辑器支持。
-
-下面的例子来自 Pydantic 官方文档:
+在 Python 3.10 中还有一种新的语法,可以用竖线(`|`)把可能的类型分隔开。
//// tab | Python 3.10+
-```Python
-{!> ../../docs_src/python_types/tutorial011_py310.py!}
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
////
//// tab | Python 3.9+
-```Python
-{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b_py39.py!}
```
////
-//// tab | Python 3.8+
+两种方式的含义一致:`item` 可以是 `int` 或 `str`。
-```Python
-{!> ../../docs_src/python_types/tutorial011.py!}
+#### 可能为 `None` { #possibly-none }
+
+你可以声明一个值的类型是某种类型(比如 `str`),但它也可能是 `None`。
+
+在 Python 3.6 及以上(包括 Python 3.10),你可以通过从 `typing` 模块导入并使用 `Optional` 来声明:
+
+```Python hl_lines="1 4"
+{!../../docs_src/python_types/tutorial009_py39.py!}
+```
+
+使用 `Optional[str]` 而不是仅仅 `str`,可以让编辑器帮助你发现把值当成总是 `str` 的错误(实际上它也可能是 `None`)。
+
+`Optional[Something]` 实际上是 `Union[Something, None]` 的简写,它们等价。
+
+这也意味着在 Python 3.10 中,你可以使用 `Something | None`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
```
////
+//// tab | Python 3.9+
-/// info
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009_py39.py!}
+```
-想进一步了解 Pydantic,请阅读其文档.
+////
+
+//// tab | Python 3.9+ 另一种写法
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b_py39.py!}
+```
+
+////
+
+#### 使用 `Union` 或 `Optional` { #using-union-or-optional }
+
+如果你使用的是 3.10 以下的 Python 版本,这里有个来自我非常主观的建议:
+
+* 🚨 避免使用 `Optional[SomeType]`
+* 改用 ✨**`Union[SomeType, None]`**✨
+
+两者等价,底层相同,但我更推荐 `Union` 而不是 `Optional`,因为“optional(可选)”这个词看起来像是在说“参数可选”,而它实际上表示“它可以是 `None`”,即使它并不是可选的,仍然是必填的。
+
+我认为 `Union[SomeType, None]` 更明确地表达了它的意思。
+
+这只是关于词语和名字。但这些词会影响你和你的队友如何理解代码。
+
+例如,看下面这个函数:
+
+{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
+
+参数 `name` 被定义为 `Optional[str]`,但它并不是“可选”的,你不能不传这个参数就调用函数:
+
+```Python
+say_hi() # 哦不,这会抛错!😱
+```
+
+参数 `name` 仍然是必填的(不是“可选”),因为它没有默认值。不过,`name` 接受 `None` 作为值:
+
+```Python
+say_hi(name=None) # 这样可以,None 是有效值 🎉
+```
+
+好消息是,一旦你使用 Python 3.10,就无需再为此操心,因为你可以直接用 `|` 来定义类型联合:
+
+{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
+
+这样你就不必再考虑 `Optional` 和 `Union` 这些名字了。😎
+
+#### 泛型类型 { #generic-types }
+
+这些在方括号中接收类型参数的类型称为“泛型类型”(Generic types)或“泛型”(Generics),例如:
+
+//// tab | Python 3.10+
+
+你可以把同样的内建类型作为泛型使用(带方括号和内部类型):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+以及与之前的 Python 版本一样,来自 `typing` 模块的:
+
+* `Union`
+* `Optional`
+* ……以及其他。
+
+在 Python 3.10 中,作为使用泛型 `Union` 和 `Optional` 的替代,你可以使用竖线(`|`)来声明类型联合,这更好也更简单。
+
+////
+
+//// tab | Python 3.9+
+
+你可以把同样的内建类型作为泛型使用(带方括号和内部类型):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+以及来自 `typing` 模块的泛型:
+
+* `Union`
+* `Optional`
+* ……以及其他。
+
+////
+
+### 类作为类型 { #classes-as-types }
+
+你也可以把类声明为变量的类型。
+
+假设你有一个名为 `Person` 的类,带有 name:
+
+{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
+
+然后你可以声明一个变量是 `Person` 类型:
+
+{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
+
+接着,你会再次获得所有的编辑器支持:
+
+
+
+注意,这表示“`one_person` 是类 `Person` 的一个实例(instance)”。
+
+它并不表示“`one_person` 是名为 `Person` 的类本身(class)”。
+
+## Pydantic 模型 { #pydantic-models }
+
+Pydantic 是一个用于执行数据校验的 Python 库。
+
+你将数据的“结构”声明为带有属性的类。
+
+每个属性都有一个类型。
+
+然后你用一些值创建这个类的实例,它会校验这些值,并在需要时把它们转换为合适的类型,返回一个包含所有数据的对象。
+
+你还能对这个结果对象获得完整的编辑器支持。
+
+下面是来自 Pydantic 官方文档的一个示例:
+
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info | 信息
+
+想了解更多关于 Pydantic 的信息,请查看其文档。
///
-整个 **FastAPI** 建立在 Pydantic 的基础之上。
+**FastAPI** 完全建立在 Pydantic 之上。
-实际上你将在 [教程 - 用户指南](tutorial/index.md){.internal-link target=_blank} 看到很多这种情况。
+你会在[教程 - 用户指南](tutorial/index.md){.internal-link target=_blank}中看到更多的实战示例。
-## **FastAPI** 中的类型提示
+/// tip | 提示
-**FastAPI** 利用这些类型提示来做下面几件事。
-
-使用 **FastAPI** 时用类型提示声明参数可以获得:
-
-* **编辑器支持**。
-* **类型检查**。
-
-...并且 **FastAPI** 还会用这些类型声明来:
-
-* **定义参数要求**:声明对请求路径参数、查询参数、请求头、请求体、依赖等的要求。
-* **转换数据**:将来自请求的数据转换为需要的类型。
-* **校验数据**: 对于每一个请求:
- * 当数据校验失败时自动生成**错误信息**返回给客户端。
-* 使用 OpenAPI **记录** API:
- * 然后用于自动生成交互式文档的用户界面。
-
-听上去有点抽象。不过不用担心。你将在 [教程 - 用户指南](tutorial/index.md){.internal-link target=_blank} 中看到所有的实战。
-
-最重要的是,通过使用标准的 Python 类型,只需要在一个地方声明(而不是添加更多的类、装饰器等),**FastAPI** 会为你完成很多的工作。
-
-/// info
-
-如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。
+当你在没有默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,Pydantic 有一个特殊行为,你可以在 Pydantic 文档的 必填的 Optional 字段 中了解更多。
+
+///
+
+## 带元数据注解的类型提示 { #type-hints-with-metadata-annotations }
+
+Python 还提供了一个特性,可以使用 `Annotated` 在这些类型提示中放入额外的元数据。
+
+从 Python 3.9 起,`Annotated` 是标准库的一部分,因此可以从 `typing` 导入。
+
+{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+
+Python 本身不会对这个 `Annotated` 做任何处理。对于编辑器和其他工具,类型仍然是 `str`。
+
+但你可以在 `Annotated` 中为 **FastAPI** 提供额外的元数据,来描述你希望应用如何行为。
+
+重要的是要记住:传给 `Annotated` 的第一个类型参数才是实际类型。其余的只是给其他工具用的元数据。
+
+现在你只需要知道 `Annotated` 的存在,并且它是标准 Python。😎
+
+稍后你会看到它有多么强大。
+
+/// tip | 提示
+
+这是标准 Python,这意味着你仍然可以在编辑器里获得尽可能好的开发体验,并能和你用来分析、重构代码的工具良好协作等。✨
+
+同时你的代码也能与许多其他 Python 工具和库高度兼容。🚀
+
+///
+
+## **FastAPI** 中的类型提示 { #type-hints-in-fastapi }
+
+**FastAPI** 利用这些类型提示来完成多件事情。
+
+在 **FastAPI** 中,用类型提示来声明参数,你将获得:
+
+* 编辑器支持。
+* 类型检查。
+
+……并且 **FastAPI** 会使用相同的声明来:
+
+* 定义要求:从请求路径参数、查询参数、请求头、请求体、依赖等。
+* 转换数据:把请求中的数据转换为所需类型。
+* 校验数据:对于每个请求:
+ * 当数据无效时,自动生成错误信息返回给客户端。
+* 使用 OpenAPI 记录 API:
+ * 然后用于自动生成交互式文档界面。
+
+这些听起来可能有点抽象。别担心。你会在[教程 - 用户指南](tutorial/index.md){.internal-link target=_blank}中看到所有这些的实际效果。
+
+重要的是,通过使用标准的 Python 类型,而且只在一个地方声明(而不是添加更多类、装饰器等),**FastAPI** 会为你完成大量工作。
+
+/// info | 信息
+
+如果你已经读完所有教程,又回来想进一步了解类型,一个不错的资源是 `mypy` 的“速查表”。
///
diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md
index b9becd8bf..8398472c3 100644
--- a/docs/zh/docs/tutorial/background-tasks.md
+++ b/docs/zh/docs/tutorial/background-tasks.md
@@ -1,4 +1,4 @@
-# 后台任务
+# 后台任务 { #background-tasks }
你可以定义在返回响应后运行的后台任务。
@@ -11,15 +11,15 @@
* 处理数据:
* 例如,假设您收到的文件必须经过一个缓慢的过程,您可以返回一个"Accepted"(HTTP 202)响应并在后台处理它。
-## 使用 `BackgroundTasks`
+## 使用 `BackgroundTasks` { #using-backgroundtasks }
首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数:
-{* ../../docs_src/background_tasks/tutorial001.py hl[1, 13] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
**FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。
-## 创建一个任务函数
+## 创建一个任务函数 { #create-a-task-function }
创建要作为后台任务运行的函数。
@@ -31,13 +31,13 @@
由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数:
-{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
-## 添加后台任务
+## 添加后台任务 { #add-the-background-task }
在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中:
-{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
`.add_task()` 接收以下参数:
@@ -45,53 +45,13 @@
* 应按顺序传递给任务函数的任意参数序列(`email`)。
* 应传递给任务函数的任意关键字参数(`message="some notification"`)。
-## 依赖注入
+## 依赖注入 { #dependency-injection }
使用 `BackgroundTasks` 也适用于依赖注入系统,你可以在多个级别声明 `BackgroundTasks` 类型的参数:在 *路径操作函数* 里,在依赖中(可依赖),在子依赖中,等等。
**FastAPI** 知道在每种情况下该做什么以及如何复用同一对象,因此所有后台任务被合并在一起并且随后在后台运行:
-//// tab | Python 3.10+
-
-{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13, 15, 22, 25] *}
-
-////
-
-//// tab | Python 3.9+
-
-{* ../../docs_src/background_tasks/tutorial002_an_py39.py hl[13, 15, 22, 25] *}
-
-////
-
-//// tab | Python 3.8+
-
-{* ../../docs_src/background_tasks/tutorial002_an.py hl[14, 16, 23, 26] *}
-
-////
-
-//// tab | Python 3.10+ 没Annotated
-
-/// tip
-
-尽可能选择使用 `Annotated` 的版本。
-
-///
-
-{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11, 13, 20, 23] *}
-
-////
-
-//// tab | Python 3.8+ 没Annotated
-
-/// tip
-
-尽可能选择使用 `Annotated` 的版本。
-
-///
-
-{* ../../docs_src/background_tasks/tutorial002.py hl[13, 15, 22, 25] *}
-
-////
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
该示例中,信息会在响应发出 *之后* 被写到 `log.txt` 文件。
@@ -99,7 +59,7 @@
然后另一个在 *路径操作函数* 生成的后台任务会使用路径参数 `email` 写入一条信息。
-## 技术细节
+## 技术细节 { #technical-details }
`BackgroundTasks` 类直接来自 `starlette.background`。
@@ -111,7 +71,7 @@
更多细节查看 Starlette's official docs for Background Tasks.
-## 告诫
+## 告诫 { #caveat }
如果您需要执行繁重的后台计算,并且不一定需要由同一进程运行(例如,您不需要共享内存、变量等),那么使用其他更大的工具(如 Celery)可能更好。
@@ -119,6 +79,6 @@
但是,如果您需要从同一个**FastAPI**应用程序访问变量和对象,或者您需要执行小型后台任务(如发送电子邮件通知),您只需使用 `BackgroundTasks` 即可。
-## 回顾
+## 回顾 { #recap }
导入并使用 `BackgroundTasks` 通过 *路径操作函数* 中的参数和依赖项来添加后台任务。
diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md
index 554bc654f..1ced002dc 100644
--- a/docs/zh/docs/tutorial/bigger-applications.md
+++ b/docs/zh/docs/tutorial/bigger-applications.md
@@ -1,16 +1,16 @@
-# 更大的应用 - 多个文件
+# 更大的应用 - 多个文件 { #bigger-applications-multiple-files }
如果你正在开发一个应用程序或 Web API,很少会将所有的内容都放在一个文件中。
**FastAPI** 提供了一个方便的工具,可以在保持所有灵活性的同时构建你的应用程序。
-/// info
+/// info | 信息
如果你来自 Flask,那这将相当于 Flask 的 Blueprints。
///
-## 一个文件结构示例
+## 一个文件结构示例 { #an-example-file-structure }
假设你的文件结构如下:
@@ -29,7 +29,7 @@
│ └── admin.py
```
-/// tip
+/// tip | 提示
上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。
@@ -52,11 +52,11 @@ from app.routers import items
* 还有一个子目录 `app/internal/` 包含另一个 `__init__.py` 文件,因此它是又一个「Python 子包」:`app.internal`。
* `app/internal/admin.py` 是另一个子模块:`app.internal.admin`。
-
+
带有注释的同一文件结构:
-```
+```bash
.
├── app # 「app」是一个 Python 包
│ ├── __init__.py # 这个文件使「app」成为一个 Python 包
@@ -71,7 +71,7 @@ from app.routers import items
│ └── admin.py # 「admin」子模块,例如 import app.internal.admin
```
-## `APIRouter`
+## `APIRouter` { #apirouter }
假设专门用于处理用户逻辑的文件是位于 `/app/routers/users.py` 的子模块。
@@ -81,23 +81,19 @@ from app.routers import items
你可以使用 `APIRouter` 为该模块创建*路径操作*。
-### 导入 `APIRouter`
+### 导入 `APIRouter` { #import-apirouter }
你可以导入它并通过与 `FastAPI` 类相同的方式创建一个「实例」:
-```Python hl_lines="1 3" title="app/routers/users.py"
-{!../../docs_src/bigger_applications/app/routers/users.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
-### 使用 `APIRouter` 的*路径操作*
+### 使用 `APIRouter` 的*路径操作* { #path-operations-with-apirouter }
然后你可以使用它来声明*路径操作*。
使用方式与 `FastAPI` 类相同:
-```Python hl_lines="6 11 16" title="app/routers/users.py"
-{!../../docs_src/bigger_applications/app/routers/users.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
你可以将 `APIRouter` 视为一个「迷你 `FastAPI`」类。
@@ -105,7 +101,7 @@ from app.routers import items
所有相同的 `parameters`、`responses`、`dependencies`、`tags` 等等。
-/// tip
+/// tip | 提示
在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。
@@ -113,7 +109,7 @@ from app.routers import items
我们将在主 `FastAPI` 应用中包含该 `APIRouter`,但首先,让我们来看看依赖项和另一个 `APIRouter`。
-## 依赖项
+## 依赖项 { #dependencies }
我们了解到我们将需要一些在应用程序的好几个地方所使用的依赖项。
@@ -121,11 +117,9 @@ from app.routers import items
现在我们将使用一个简单的依赖项来读取一个自定义的 `X-Token` 请求首部:
-```Python hl_lines="1 4-6" title="app/dependencies.py"
-{!../../docs_src/bigger_applications/app/dependencies.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
-/// tip
+/// tip | 提示
我们正在使用虚构的请求首部来简化此示例。
@@ -133,7 +127,7 @@ from app.routers import items
///
-## 其他使用 `APIRouter` 的模块
+## 其他使用 `APIRouter` 的模块 { #another-module-with-apirouter }
假设你在位于 `app/routers/items.py` 的模块中还有专门用于处理应用程序中「项目」的端点。
@@ -155,9 +149,7 @@ from app.routers import items
因此,我们可以将其添加到 `APIRouter` 中,而不是将其添加到每个路径操作中。
-```Python hl_lines="5-10 16 21" title="app/routers/items.py"
-{!../../docs_src/bigger_applications/app/routers/items.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
由于每个*路径操作*的路径都必须以 `/` 开头,例如:
@@ -175,7 +167,7 @@ async def read_item(item_id: str):
我们可以添加一个 `dependencies` 列表,这些依赖项将被添加到路由器中的所有*路径操作*中,并将针对向它们发起的每个请求执行/解决。
-/// tip
+/// tip | 提示
请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。
@@ -196,19 +188,19 @@ async def read_item(item_id: str):
* 路由器的依赖项最先执行,然后是[装饰器中的 `dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank},再然后是普通的参数依赖项。
* 你还可以添加[具有 `scopes` 的 `Security` 依赖项](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}。
-/// tip
+/// tip | 提示
在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。
///
-/// check
+/// check | 检查
`prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。
///
-### 导入依赖项
+### 导入依赖项 { #import-the-dependencies }
这些代码位于 `app.routers.items` 模块,`app/routers/items.py` 文件中。
@@ -216,13 +208,11 @@ async def read_item(item_id: str):
因此,我们通过 `..` 对依赖项使用了相对导入:
-```Python hl_lines="3" title="app/routers/items.py"
-{!../../docs_src/bigger_applications/app/routers/items.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[3] title["app/routers/items.py"] *}
-#### 相对导入如何工作
+#### 相对导入如何工作 { #how-relative-imports-work }
-/// tip
+/// tip | 提示
如果你完全了解导入的工作原理,请从下面的下一部分继续。
@@ -244,7 +234,7 @@ from .dependencies import get_token_header
请记住我们的程序/文件结构是怎样的:
-
+
---
@@ -276,24 +266,22 @@ from ...dependencies import get_token_header
* 从该模块(`app/routers/items.py` 文件)所在的同一个包(`app/routers/` 目录)开始...
* 跳转到其父包(`app/` 目录)...
* 然后跳转到该包的父包(该父包并不存在,`app` 已经是最顶层的包 😱)...
-* 在该父包中,找到 `dependencies` 模块(位于 `app/` 更上一级目录中的 `dependencies.py` 文件)...
+* 在该父包中,找到 `dependencies` 模块(位于 `app/dependencies.py` 的文件)...
* 然后从中导入函数 `get_token_header`。
这将引用 `app/` 的往上一级,带有其自己的 `__init __.py` 等文件的某个包。但是我们并没有这个包。因此,这将在我们的示例中引发错误。🚨
但是现在你知道了它的工作原理,因此无论它们多么复杂,你都可以在自己的应用程序中使用相对导入。🤓
-### 添加一些自定义的 `tags`、`responses` 和 `dependencies`
+### 添加一些自定义的 `tags`、`responses` 和 `dependencies` { #add-some-custom-tags-responses-and-dependencies }
我们不打算在每个*路径操作*中添加前缀 `/items` 或 `tags =["items"]`,因为我们将它们添加到了 `APIRouter` 中。
但是我们仍然可以添加*更多*将会应用于特定的*路径操作*的 `tags`,以及一些特定于该*路径操作*的额外 `responses`:
-```Python hl_lines="30-31" title="app/routers/items.py"
-{!../../docs_src/bigger_applications/app/routers/items.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[30:31] title["app/routers/items.py"] *}
-/// tip
+/// tip | 提示
最后的这个路径操作将包含标签的组合:`["items","custom"]`。
@@ -301,7 +289,7 @@ from ...dependencies import get_token_header
///
-## `FastAPI` 主体
+## `FastAPI` 主体 { #the-main-fastapi }
现在,让我们来看看位于 `app/main.py` 的模块。
@@ -311,27 +299,23 @@ from ...dependencies import get_token_header
并且由于你的大部分逻辑现在都存在于其自己的特定模块中,因此主文件的内容将非常简单。
-### 导入 `FastAPI`
+### 导入 `FastAPI` { #import-fastapi }
你可以像平常一样导入并创建一个 `FastAPI` 类。
我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起:
-```Python hl_lines="1 3 7" title="app/main.py"
-{!../../docs_src/bigger_applications/app/main.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[1,3,7] title["app/main.py"] *}
-### 导入 `APIRouter`
+### 导入 `APIRouter` { #import-the-apirouter }
现在,我们导入具有 `APIRouter` 的其他子模块:
-```Python hl_lines="5" title="app/main.py"
-{!../../docs_src/bigger_applications/app/main.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[4:5] title["app/main.py"] *}
由于文件 `app/routers/users.py` 和 `app/routers/items.py` 是同一 Python 包 `app` 一个部分的子模块,因此我们可以使用单个点 ` .` 通过「相对导入」来导入它们。
-### 导入是如何工作的
+### 导入是如何工作的 { #how-the-importing-works }
这段代码:
@@ -355,7 +339,7 @@ from .routers import items, users
from app.routers import items, users
```
-/// info
+/// info | 信息
第一个版本是「相对导入」:
@@ -373,7 +357,7 @@ from app.routers import items, users
///
-### 避免名称冲突
+### 避免名称冲突 { #avoid-name-collisions }
我们将直接导入 `items` 子模块,而不是仅导入其 `router` 变量。
@@ -390,19 +374,15 @@ from .routers.users import router
因此,为了能够在同一个文件中使用它们,我们直接导入子模块:
-```Python hl_lines="5" title="app/main.py"
-{!../../docs_src/bigger_applications/app/main.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[5] title["app/main.py"] *}
-### 包含 `users` 和 `items` 的 `APIRouter`
+### 包含 `users` 和 `items` 的 `APIRouter` { #include-the-apirouters-for-users-and-items }
现在,让我们来包含来自 `users` 和 `items` 子模块的 `router`。
-```Python hl_lines="10-11" title="app/main.py"
-{!../../docs_src/bigger_applications/app/main.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[10:11] title["app/main.py"] *}
-/// info
+/// info | 信息
`users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。
@@ -422,7 +402,7 @@ from .routers.users import router
///
-/// check
+/// check | 检查
包含路由器时,你不必担心性能问题。
@@ -432,7 +412,7 @@ from .routers.users import router
///
-### 包含一个有自定义 `prefix`、`tags`、`responses` 和 `dependencies` 的 `APIRouter`
+### 包含一个有自定义 `prefix`、`tags`、`responses` 和 `dependencies` 的 `APIRouter` { #include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies }
现在,假设你的组织为你提供了 `app/internal/admin.py` 文件。
@@ -440,17 +420,13 @@ from .routers.users import router
对于此示例,它将非常简单。但是假设由于它是与组织中的其他项目所共享的,因此我们无法对其进行修改,以及直接在 `APIRouter` 中添加 `prefix`、`dependencies`、`tags` 等:
-```Python hl_lines="3" title="app/internal/admin.py"
-{!../../docs_src/bigger_applications/app/internal/admin.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
但是我们仍然希望在包含 `APIRouter` 时设置一个自定义的 `prefix`,以便其所有*路径操作*以 `/admin` 开头,我们希望使用本项目已经有的 `dependencies` 保护它,并且我们希望它包含自定义的 `tags` 和 `responses`。
我们可以通过将这些参数传递给 `app.include_router()` 来完成所有的声明,而不必修改原始的 `APIRouter`:
-```Python hl_lines="14-17" title="app/main.py"
-{!../../docs_src/bigger_applications/app/main.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[14:17] title["app/main.py"] *}
这样,原始的 `APIRouter` 将保持不变,因此我们仍然可以与组织中的其他项目共享相同的 `app/internal/admin.py` 文件。
@@ -465,15 +441,13 @@ from .routers.users import router
因此,举例来说,其他项目能够以不同的身份认证方法使用相同的 `APIRouter`。
-### 包含一个*路径操作*
+### 包含一个*路径操作* { #include-a-path-operation }
我们还可以直接将*路径操作*添加到 `FastAPI` 应用中。
这里我们这样做了...只是为了表明我们可以做到🤷:
-```Python hl_lines="21-23" title="app/main.py"
-{!../../docs_src/bigger_applications/app/main.py!}
-```
+{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[21:23] title["app/main.py"] *}
它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。
@@ -491,14 +465,14 @@ from .routers.users import router
///
-## 查看自动化的 API 文档
+## 查看自动化的 API 文档 { #check-the-automatic-api-docs }
-现在,使用 `app.main` 模块和 `app` 变量运行 `uvicorn`:
+现在,运行你的应用:
+
-## 多次使用不同的 `prefix` 包含同一个路由器
+## 多次使用不同的 `prefix` 包含同一个路由器 { #include-the-same-router-multiple-times-with-different-prefix }
你也可以在*同一*路由器上使用不同的前缀来多次使用 `.include_router()`。
@@ -519,7 +493,7 @@ $ uvicorn app.main:app --reload
这是一个你可能并不真正需要的高级用法,但万一你有需要了就能够用上。
-## 在另一个 `APIRouter` 中包含一个 `APIRouter`
+## 在另一个 `APIRouter` 中包含一个 `APIRouter` { #include-an-apirouter-in-another }
与在 `FastAPI` 应用程序中包含 `APIRouter` 的方式相同,你也可以在另一个 `APIRouter` 中包含 `APIRouter`,通过:
@@ -527,4 +501,4 @@ $ uvicorn app.main:app --reload
router.include_router(other_router)
```
-请确保在你将 `router` 包含到 `FastAPI` 应用程序之前进行此操作,以便 `other_router` 中的`路径操作`也能被包含进来。
+请确保在你将 `router` 包含到 `FastAPI` 应用程序之前进行此操作,以便 `other_router` 中的*路径操作*也能被包含进来。
diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md
index 4cff58bfc..36be7c419 100644
--- a/docs/zh/docs/tutorial/body-fields.md
+++ b/docs/zh/docs/tutorial/body-fields.md
@@ -1,8 +1,8 @@
-# 请求体 - 字段
+# 请求体 - 字段 { #body-fields }
与在*路径操作函数*中使用 `Query`、`Path` 、`Body` 声明校验与元数据的方式一样,可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。
-## 导入 `Field`
+## 导入 `Field` { #import-field }
首先,从 Pydantic 中导入 `Field`:
@@ -14,7 +14,7 @@
///
-## 声明模型属性
+## 声明模型属性 { #declare-model-attributes }
然后,使用 `Field` 定义模型的属性:
@@ -24,7 +24,7 @@
/// note | 技术细节
-实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。
+实际上,`Query`、`Path` 以及你接下来会看到的其它对象,会创建公共 `Param` 类的子类的对象,而 `Param` 本身是 Pydantic 中 `FieldInfo` 的子类。
Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。
@@ -40,13 +40,20 @@ Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。
///
-## 添加更多信息
+## 添加更多信息 { #add-extra-information }
`Field`、`Query`、`Body` 等对象里可以声明更多信息,并且 JSON Schema 中也会集成这些信息。
*声明示例*一章中将详细介绍添加更多信息的知识。
-## 小结
+/// warning | 警告
+
+传递给 `Field` 的额外键也会出现在你的应用生成的 OpenAPI 架构中。
+由于这些键不一定属于 OpenAPI 规范的一部分,某些 OpenAPI 工具(例如 [OpenAPI 验证器](https://validator.swagger.io/))可能无法处理你生成的架构。
+
+///
+
+## 小结 { #recap }
Pydantic 的 `Field` 可以为模型属性声明更多校验和元数据。
diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md
index b4356fdcb..7d0ddfc1e 100644
--- a/docs/zh/docs/tutorial/body-multiple-params.md
+++ b/docs/zh/docs/tutorial/body-multiple-params.md
@@ -1,8 +1,8 @@
-# 请求体 - 多个参数
+# 请求体 - 多个参数 { #body-multiple-parameters }
既然我们已经知道了如何使用 `Path` 和 `Query`,下面让我们来了解一下请求体声明的更高级用法。
-## 混合使用 `Path`、`Query` 和请求体参数
+## 混合使用 `Path`、`Query` 和请求体参数 { #mix-path-query-and-body-parameters }
首先,毫无疑问地,你可以随意地混合使用 `Path`、`Query` 和请求体参数声明,**FastAPI** 会知道该如何处理。
@@ -10,13 +10,13 @@
{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
-/// note
+/// note | 注意
请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。
///
-## 多个请求体参数
+## 多个请求体参数 { #multiple-body-parameters }
在上面的示例中,*路径操作*将期望一个具有 `Item` 的属性的 JSON 请求体,就像:
@@ -52,7 +52,7 @@
}
```
-/// note
+/// note | 注意
请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。
@@ -62,7 +62,7 @@
它将执行对复合数据的校验,并且像现在这样为 OpenAPI 模式和自动化文档对其进行记录。
-## 请求体中的单一值
+## 请求体中的单一值 { #singular-values-in-body }
与使用 `Query` 和 `Path` 为查询参数和路径参数定义额外数据的方式相同,**FastAPI** 提供了一个同等的 `Body`。
@@ -72,12 +72,10 @@
但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。
-
{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
在这种情况下,**FastAPI** 将期望像这样的请求体:
-
```JSON
{
"item": {
@@ -96,27 +94,33 @@
同样的,它将转换数据类型,校验,生成文档等。
-## 多个请求体参数和查询参数
+## 多个请求体参数和查询参数 { #multiple-body-params-and-query }
当然,除了请求体参数外,你还可以在任何需要的时候声明额外的查询参数。
-由于默认情况下单一值被解释为查询参数,因此你不必显式地添加 `Query`,你可以仅执行以下操作:
+由于默认情况下单一值会被解释为查询参数,因此你不必显式地添加 `Query`,你可以这样写:
```Python
-q: str = None
+q: str | None = None
+```
+
+或者在 Python 3.9 中:
+
+```Python
+q: Union[str, None] = None
```
比如:
-{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *}
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
-/// info
+/// info | 信息
`Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。
///
-## 嵌入单个请求体参数
+## 嵌入单个请求体参数 { #embed-a-single-body-parameter }
假设你只有一个来自 Pydantic 模型 `Item` 的请求体参数 `item`。
@@ -156,7 +160,7 @@ item: Item = Body(embed=True)
}
```
-## 总结
+## 总结 { #recap }
你可以添加多个请求体参数到*路径操作函数*中,即使一个请求只能有一个请求体。
diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md
index df96d96b4..242aa5822 100644
--- a/docs/zh/docs/tutorial/body-nested-models.md
+++ b/docs/zh/docs/tutorial/body-nested-models.md
@@ -1,53 +1,42 @@
-# 请求体 - 嵌套模型
+# 请求体 - 嵌套模型 { #body-nested-models }
使用 **FastAPI**,你可以定义、校验、记录文档并使用任意深度嵌套的模型(归功于Pydantic)。
-## List 字段
+## List 字段 { #list-fields }
-你可以将一个属性定义为拥有子元素的类型。例如 Python `list`:
+你可以将一个属性定义为一个子类型。例如,Python `list`:
{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。
-## 具有子类型的 List 字段
+## 带类型参数的 List 字段 { #list-fields-with-type-parameter }
-但是 Python 有一种特定的方法来声明具有子类型的列表:
+不过,Python 有一种用于声明具有内部类型(类型参数)的列表的特定方式:
-### 从 typing 导入 `List`
+### 声明带类型参数的 `list` { #declare-a-list-with-a-type-parameter }
-首先,从 Python 的标准库 `typing` 模块中导入 `List`:
-
-{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}
-
-### 声明具有子类型的 List
-
-要声明具有子类型的类型,例如 `list`、`dict`、`tuple`:
-
-* 从 `typing` 模块导入它们
-* 使用方括号 `[` 和 `]` 将子类型作为「类型参数」传入
+要声明具有类型参数(内部类型)的类型,例如 `list`、`dict`、`tuple`,使用方括号 `[` 和 `]` 传入内部类型作为「类型参数」:
```Python
-from typing import List
-
-my_list: List[str]
+my_list: list[str]
```
这完全是用于类型声明的标准 Python 语法。
-对具有子类型的模型属性也使用相同的标准语法。
+对具有内部类型的模型属性也使用相同的标准语法。
因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」:
{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
-## Set 类型
+## Set 类型 { #set-types }
但是随后我们考虑了一下,意识到标签不应该重复,它们很大可能会是唯一的字符串。
-Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `set`。
+而 Python 有一种用于保存唯一元素集合的特殊数据类型 `set`。
-然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`:
+然后我们可以将 `tags` 声明为一个由字符串组成的 set:
{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
@@ -57,7 +46,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se
并且还会被相应地标注 / 记录文档。
-## 嵌套模型
+## 嵌套模型 { #nested-models }
Pydantic 模型的每个属性都具有类型。
@@ -67,13 +56,13 @@ Pydantic 模型的每个属性都具有类型。
上述这些都可以任意的嵌套。
-### 定义子模型
+### 定义子模型 { #define-a-submodel }
例如,我们可以定义一个 `Image` 模型:
{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
-### 将子模型用作类型
+### 将子模型用作类型 { #use-the-submodel-as-a-type }
然后我们可以将其用作一个属性的类型:
@@ -102,11 +91,11 @@ Pydantic 模型的每个属性都具有类型。
* 数据校验
* 自动生成文档
-## 特殊的类型和校验
+## 特殊的类型和校验 { #special-types-and-validation }
除了普通的单一值类型(如 `str`、`int`、`float` 等)外,你还可以使用从 `str` 继承的更复杂的单一值类型。
-要了解所有的可用选项,请查看关于 来自 Pydantic 的外部类型 的文档。你将在下一章节中看到一些示例。
+要了解所有的可用选项,请查看 Pydantic 的类型概览。你将在下一章节中看到一些示例。
例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`:
@@ -114,7 +103,7 @@ Pydantic 模型的每个属性都具有类型。
该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。
-## 带有一组子模型的属性
+## 带有一组子模型的属性 { #attributes-with-lists-of-submodels }
你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型:
@@ -146,49 +135,49 @@ Pydantic 模型的每个属性都具有类型。
}
```
-/// info
+/// info | 信息
请注意 `images` 键现在具有一组 image 对象是如何发生的。
///
-## 深度嵌套模型
+## 深度嵌套模型 { #deeply-nested-models }
你可以定义任意深度的嵌套模型:
{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
-/// info
+/// info | 信息
请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。
///
-## 纯列表请求体
+## 纯列表请求体 { #bodies-of-pure-lists }
如果你期望的 JSON 请求体的最外层是一个 JSON `array`(即 Python `list`),则可以在路径操作函数的参数中声明此类型,就像声明 Pydantic 模型一样:
```Python
-images: List[Image]
+images: list[Image]
```
例如:
{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
-## 无处不在的编辑器支持
+## 无处不在的编辑器支持 { #editor-support-everywhere }
你可以随处获得编辑器支持。
即使是列表中的元素:
-
+
如果你直接使用 `dict` 而不是 Pydantic 模型,那你将无法获得这种编辑器支持。
但是你根本不必担心这两者,传入的字典会自动被转换,你的输出也会自动被转换为 JSON。
-## 任意 `dict` 构成的请求体
+## 任意 `dict` 构成的请求体 { #bodies-of-arbitrary-dicts }
你也可以将请求体声明为使用某类型的键和其他类型值的 `dict`。
@@ -206,7 +195,7 @@ images: List[Image]
{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
-/// tip
+/// tip | 提示
请记住 JSON 仅支持将 `str` 作为键。
@@ -218,7 +207,7 @@ images: List[Image]
///
-## 总结
+## 总结 { #recap }
使用 **FastAPI** 你可以拥有 Pydantic 模型提供的极高灵活性,同时保持代码的简单、简短和优雅。
diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md
index 87f88f255..000201de9 100644
--- a/docs/zh/docs/tutorial/body-updates.md
+++ b/docs/zh/docs/tutorial/body-updates.md
@@ -1,18 +1,18 @@
-# 请求体 - 更新数据
+# 请求体 - 更新数据 { #body-updates }
-## 用 `PUT` 更新数据
+## 用 `PUT` 替换式更新 { #update-replacing-with-put }
-更新数据请用 HTTP `PUT` 操作。
+更新数据可以使用 HTTP `PUT` 操作。
把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`。
-{* ../../docs_src/body_updates/tutorial001.py hl[30:35] *}
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
`PUT` 用于接收替换现有数据的数据。
-### 关于更新数据的警告
+### 关于替换的警告 { #warning-about-replacing }
-用 `PUT` 把数据项 `bar` 更新为以下内容时:
+用 `PUT` 把数据项 `bar` 更新为以下请求体时:
```Python
{
@@ -22,78 +22,79 @@
}
```
-因为上述数据未包含已存储的属性 `"tax": 20.2`,新的输入模型会把 `"tax": 10.5` 作为默认值。
+因为其中未包含已存储的属性 `"tax": 20.2`,输入模型会取 `"tax": 10.5` 的默认值。
-因此,本次操作把 `tax` 的值「更新」为 `10.5`。
+因此,保存的数据会带有这个“新的” `tax` 值 `10.5`。
-## 用 `PATCH` 进行部分更新
+## 用 `PATCH` 进行部分更新 { #partial-updates-with-patch }
-HTTP `PATCH` 操作用于更新 *部分* 数据。
+也可以使用 HTTP `PATCH` 操作对数据进行*部分*更新。
-即,只发送要更新的数据,其余数据保持不变。
+也就是说,你只需发送想要更新的数据,其余数据保持不变。
-/// note | 笔记
+/// note | 注意
-`PATCH` 没有 `PUT` 知名,也怎么不常用。
+`PATCH` 没有 `PUT` 知名,也没那么常用。
-很多人甚至只用 `PUT` 实现部分更新。
+很多团队甚至只用 `PUT` 实现部分更新。
-**FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。
+你可以**随意**选择如何使用它们,**FastAPI** 不做任何限制。
-但本指南也会分别介绍这两种操作各自的用途。
+但本指南会大致展示它们的预期用法。
///
-### 使用 Pydantic 的 `exclude_unset` 参数
+### 使用 Pydantic 的 `exclude_unset` 参数 { #using-pydantics-exclude-unset-parameter }
-更新部分数据时,可以在 Pydantic 模型的 `.dict()` 中使用 `exclude_unset` 参数。
+如果要接收部分更新,建议在 Pydantic 模型的 `.model_dump()` 中使用 `exclude_unset` 参数。
-比如,`item.dict(exclude_unset=True)`。
+比如,`item.model_dump(exclude_unset=True)`。
-这段代码生成的 `dict` 只包含创建 `item` 模型时显式设置的数据,而不包括默认值。
+这会生成一个 `dict`,只包含创建 `item` 模型时显式设置的数据,不包含默认值。
-然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`:
+然后再用它生成一个只含已设置(在请求中发送)数据、且省略默认值的 `dict`:
-{* ../../docs_src/body_updates/tutorial002.py hl[34] *}
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
-### 使用 Pydantic 的 `update` 参数
+### 使用 Pydantic 的 `update` 参数 { #using-pydantics-update-parameter }
-接下来,用 `.copy()` 为已有模型创建调用 `update` 参数的副本,该参数为包含更新数据的 `dict`。
+接下来,用 `.model_copy()` 为已有模型创建副本,并传入 `update` 参数,值为包含更新数据的 `dict`。
-例如,`stored_item_model.copy(update=update_data)`:
+例如,`stored_item_model.model_copy(update=update_data)`:
-{* ../../docs_src/body_updates/tutorial002.py hl[35] *}
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
-### 更新部分数据小结
+### 部分更新小结 { #partial-updates-recap }
-简而言之,更新部分数据应:
+简而言之,应用部分更新应当:
-* 使用 `PATCH` 而不是 `PUT` (可选,也可以用 `PUT`);
-* 提取存储的数据;
-* 把数据放入 Pydantic 模型;
-* 生成不含输入模型默认值的 `dict` (使用 `exclude_unset` 参数);
- * 只更新用户设置过的值,不用模型中的默认值覆盖已存储过的值。
-* 为已存储的模型创建副本,用接收的数据更新其属性 (使用 `update` 参数)。
+* (可选)使用 `PATCH` 而不是 `PUT`。
+* 提取已存储的数据。
+* 把该数据放入 Pydantic 模型。
+* 生成不含输入模型默认值的 `dict`(使用 `exclude_unset`)。
+ * 这样只会更新用户实际设置的值,而不会用模型中的默认值覆盖已存储的值。
+* 为已存储的模型创建副本,用接收到的部分更新数据更新其属性(使用 `update` 参数)。
* 把模型副本转换为可存入数据库的形式(比如,使用 `jsonable_encoder`)。
- * 这种方式与 Pydantic 模型的 `.dict()` 方法类似,但能确保把值转换为适配 JSON 的数据类型,例如, 把 `datetime` 转换为 `str` 。
-* 把数据保存至数据库;
+ * 这类似于再次调用模型的 `.model_dump()` 方法,但会确保(并转换)值为可转换为 JSON 的数据类型,例如把 `datetime` 转换为 `str`。
+* 把数据保存至数据库。
* 返回更新后的模型。
-{* ../../docs_src/body_updates/tutorial002.py hl[30:37] *}
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
/// tip | 提示
-实际上,HTTP `PUT` 也可以完成相同的操作。
-但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。
+实际上,HTTP `PUT` 也可以使用同样的技巧。
+
+但这里用 `PATCH` 举例,因为它就是为这种用例设计的。
///
-/// note | 笔记
+/// note | 注意
-注意,输入模型仍需验证。
+注意,输入模型仍会被验证。
-因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。
+因此,如果希望接收的部分更新可以省略所有属性,则需要一个所有属性都标记为可选(带默认值或 `None`)的模型。
-为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。
+为了区分用于**更新**(全部可选)和用于**创建**(必填)的模型,可以参考[更多模型](extra-models.md){.internal-link target=_blank} 中介绍的思路。
///
diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md
index 3820fc747..60088a048 100644
--- a/docs/zh/docs/tutorial/body.md
+++ b/docs/zh/docs/tutorial/body.md
@@ -1,30 +1,30 @@
-# 请求体
+# 请求体 { #request-body }
-FastAPI 使用**请求体**从客户端(例如浏览器)向 API 发送数据。
+当你需要从客户端(比如浏览器)向你的 API 发送数据时,会把它作为**请求体**发送。
-**请求体**是客户端发送给 API 的数据。**响应体**是 API 发送给客户端的数据。
+**请求体**是客户端发送给你的 API 的数据。**响应体**是你的 API 发送给客户端的数据。
-API 基本上肯定要发送**响应体**,但是客户端不一定发送**请求体**。
+你的 API 几乎总是需要发送**响应体**。但客户端不一定总是要发送**请求体**,有时它们只请求某个路径,可能带一些查询参数,但不会发送请求体。
-使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。
+使用 Pydantic 模型来声明**请求体**,能充分利用它的功能和优点。
-/// info | 说明
+/// info | 信息
-发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。
+发送数据应使用以下之一:`POST`(最常见)、`PUT`、`DELETE` 或 `PATCH`。
-规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。
+规范中没有定义用 `GET` 请求发送请求体的行为,但 FastAPI 仍支持这种方式,只用于非常复杂/极端的用例。
-我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。
+由于不推荐,在使用 `GET` 时,Swagger UI 的交互式文档不会显示请求体的文档,而且中间的代理可能也不支持它。
///
-## 导入 Pydantic 的 `BaseModel`
+## 导入 Pydantic 的 `BaseModel` { #import-pydantics-basemodel }
从 `pydantic` 中导入 `BaseModel`:
{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
-## 创建数据模型
+## 创建数据模型 { #create-your-data-model }
把数据模型声明为继承 `BaseModel` 的类。
@@ -32,9 +32,9 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请
{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
-与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。
+与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。把默认值设为 `None` 可使其变为可选。
-例如,上述模型声明如下 JSON **对象**(即 Python **字典**):
+例如,上述模型声明如下 JSON "object"(即 Python `dict`):
```JSON
{
@@ -45,7 +45,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请
}
```
-……由于 `description` 和 `tax` 是可选的(默认值为 `None`),下面的 JSON **对象**也有效:
+...由于 `description` 和 `tax` 是可选的(默认值为 `None`),下面的 JSON "object" 也有效:
```JSON
{
@@ -54,40 +54,40 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请
}
```
-## 声明请求体参数
+## 声明为参数 { #declare-it-as-a-parameter }
-使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*:
+使用与声明路径和查询参数相同的方式,把它添加至*路径操作*:
{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
-……此处,请求体参数的类型为 `Item` 模型。
+...并把其类型声明为你创建的模型 `Item`。
-## 结论
+## 结果 { #results }
-仅使用 Python 类型声明,**FastAPI** 就可以:
+仅使用这些 Python 类型声明,**FastAPI** 就可以:
-* 以 JSON 形式读取请求体
-* (在必要时)把请求体转换为对应的类型
-* 校验数据:
- * 数据无效时返回错误信息,并指出错误数据的确切位置和内容
-* 把接收的数据赋值给参数 `item`
- * 把函数中请求体参数的类型声明为 `Item`,还能获得代码补全等编辑器支持
-* 为模型生成 JSON Schema,在项目中所需的位置使用
-* 这些概图是 OpenAPI 概图的部件,用于 API 文档 UI
+* 以 JSON 形式读取请求体。
+* (在必要时)把请求体转换为对应的类型。
+* 校验数据。
+ * 数据无效时返回清晰的错误信息,并指出错误数据的确切位置和内容。
+* 把接收的数据赋值给参数 `item`。
+ * 因为你把函数中的参数类型声明为 `Item`,所以还能获得所有属性及其类型的编辑器支持(补全等)。
+* 为你的模型生成 JSON Schema 定义,如果对你的项目有意义,还可以在其他地方使用它们。
+* 这些 schema 会成为生成的 OpenAPI Schema 的一部分,并被自动文档的 UIs 使用。
-## API 文档
+## 自动文档 { #automatic-docs }
-Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文档中显示:
+你的模型的 JSON Schema 会成为生成的 OpenAPI Schema 的一部分,并显示在交互式 API 文档中:
-而且,还会用于 API 文档中使用了概图的*路径操作*:
+并且,还会用于需要它们的每个*路径操作*的 API 文档中:
-## 编辑器支持
+## 编辑器支持 { #editor-support }
-在编辑器中,函数内部均可使用类型提示、代码补全(如果接收的不是 Pydantic 模型,而是**字典**,就没有这样的支持):
+在编辑器中,函数内部你会在各处得到类型提示与补全(如果接收的不是 Pydantic 模型,而是 `dict`,就不会有这样的支持):
@@ -95,23 +95,23 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文
-这并非偶然,整个 **FastAPI** 框架都是围绕这种思路精心设计的。
+这并非偶然,整个框架都是围绕这种设计构建的。
-并且,在 FastAPI 的设计阶段,我们就已经进行了全面测试,以确保 FastAPI 可以获得所有编辑器的支持。
+并且在设计阶段、实现之前就进行了全面测试,以确保它能在所有编辑器中正常工作。
-我们还改进了 Pydantic,让它也支持这些功能。
+我们甚至对 Pydantic 本身做了一些改动以支持这些功能。
-虽然上面的截图取自 Visual Studio Code。
+上面的截图来自 Visual Studio Code。
-但 PyCharm 和大多数 Python 编辑器也支持同样的功能:
+但使用 PyCharm 和大多数其他 Python 编辑器,你也会获得相同的编辑器支持:
/// tip | 提示
-使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。
+如果你使用 PyCharm 作为编辑器,可以使用 Pydantic PyCharm 插件。
-该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下:
+它能改进对 Pydantic 模型的编辑器支持,包括:
* 自动补全
* 类型检查
@@ -121,42 +121,44 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文
///
-## 使用模型
+## 使用模型 { #use-the-model }
-在*路径操作*函数内部直接访问模型对象的属性:
+在*路径操作*函数内部直接访问模型对象的所有属性:
-{* ../../docs_src/body/tutorial002_py310.py hl[19] *}
+{* ../../docs_src/body/tutorial002_py310.py *}
-## 请求体 + 路径参数
+## 请求体 + 路径参数 { #request-body-path-parameters }
-**FastAPI** 支持同时声明路径参数和请求体。
+可以同时声明路径参数和请求体。
-**FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。
+**FastAPI** 能识别与**路径参数**匹配的函数参数应该**从路径中获取**,而声明为 Pydantic 模型的函数参数应该**从请求体中获取**。
{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
-## 请求体 + 路径参数 + 查询参数
+## 请求体 + 路径 + 查询参数 { #request-body-path-query-parameters }
-**FastAPI** 支持同时声明**请求体**、**路径参数**和**查询参数**。
+也可以同时声明**请求体**、**路径**和**查询**参数。
-**FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。
+**FastAPI** 会分别识别它们,并从正确的位置获取数据。
{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
函数参数按如下规则进行识别:
-- **路径**中声明了相同参数的参数,是路径参数
-- 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数
-- 类型是 **Pydantic 模型**的参数,是**请求体**
+* 如果该参数也在**路径**中声明了,它就是路径参数。
+* 如果该参数是(`int`、`float`、`str`、`bool` 等)**单一类型**,它会被当作**查询**参数。
+* 如果该参数的类型声明为 **Pydantic 模型**,它会被当作请求**体**。
-/// note | 笔记
+/// note | 注意
-因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。
+FastAPI 会根据默认值 `= None` 知道 `q` 的值不是必填的。
-FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。
+`str | None`(Python 3.10+)或 `Union[str, None]`(Python 3.9+ 中的 `Union`)并不是 FastAPI 用来判断是否必填的依据;是否必填由是否有默认值 `= None` 决定。
+
+但添加这些类型注解可以让你的编辑器提供更好的支持并检测错误。
///
-## 不使用 Pydantic
+## 不使用 Pydantic { #without-pydantic }
-即便不使用 Pydantic 模型也能使用 **Body** 参数。详见[请求体 - 多参数:请求体中的单值](body-multiple-params.md#_2){.internal-link target=\_blank}。
+即便不使用 Pydantic 模型也能使用 **Body** 参数。详见[请求体 - 多参数:请求体中的单值](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}。
diff --git a/docs/zh/docs/tutorial/cookie-param-models.md b/docs/zh/docs/tutorial/cookie-param-models.md
index 6a7b09e25..707a6a9c7 100644
--- a/docs/zh/docs/tutorial/cookie-param-models.md
+++ b/docs/zh/docs/tutorial/cookie-param-models.md
@@ -1,22 +1,22 @@
-# Cookie 参数模型
+# Cookie 参数模型 { #cookie-parameter-models }
如果您有一组相关的 **cookie**,您可以创建一个 **Pydantic 模型**来声明它们。🍪
这将允许您在**多个地方**能够**重用模型**,并且可以一次性声明所有参数的验证方式和元数据。😎
-/// note
+/// note | 注意
自 FastAPI 版本 `0.115.0` 起支持此功能。🤓
///
-/// tip
+/// tip | 提示
此技术同样适用于 `Query` 、 `Cookie` 和 `Header` 。😎
///
-## 带有 Pydantic 模型的 Cookie
+## 带有 Pydantic 模型的 Cookie { #cookies-with-a-pydantic-model }
在 **Pydantic** 模型中声明所需的 **cookie** 参数,然后将参数声明为 `Cookie` :
@@ -24,7 +24,7 @@
**FastAPI** 将从请求中接收到的 **cookie** 中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。
-## 查看文档
+## 查看文档 { #check-the-docs }
您可以在文档 UI 的 `/docs` 中查看定义的 cookie:
@@ -32,7 +32,7 @@
-## 快捷方式
+## 快捷方式 { #shortcut }
-但是您可以看到,我们在这里有一些代码重复了,编写了`CommonQueryParams`两次:
+但是你可以看到,我们在这里有一些代码重复了,编写了`CommonQueryParams`两次:
+
+//// tab | Python 3.9+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.9+ 未使用 Annotated
+
+/// tip | 提示
+
+尽可能使用 `Annotated` 版本。
+
+///
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
+////
+
**FastAPI** 为这些情况提供了一个快捷方式,在这些情况下,依赖项 *明确地* 是一个类,**FastAPI** 将 "调用" 它来创建类本身的一个实例。
-对于这些特定的情况,您可以跟随以下操作:
+对于这些特定的情况,你可以按如下操作:
不是写成这样:
+//// tab | Python 3.9+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.9+ 未使用 Annotated
+
+/// tip | 提示
+
+尽可能使用 `Annotated` 版本。
+
+///
+
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
+////
+
...而是这样写:
+//// tab | Python 3.9+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.9+ 未使用 Annotated
+
+/// tip | 提示
+
+尽可能使用 `Annotated` 版本。
+
+///
+
```Python
commons: CommonQueryParams = Depends()
```
-您声明依赖项作为参数的类型,并使用 `Depends()` 作为该函数的参数的 "默认" 值(在 `=` 之后),而在 `Depends()` 中没有任何参数,而不是在 `Depends(CommonQueryParams)` 编写完整的类。
+////
+
+你声明依赖项作为参数的类型,并使用 `Depends()` 作为该函数的参数的 "默认" 值(在 `=` 之后),而在 `Depends()` 中没有任何参数,而不是在 `Depends(CommonQueryParams)` 中*再次*编写完整的类。
同样的例子看起来像这样:
-{* ../../docs_src/dependencies/tutorial004_py310.py hl[17] *}
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
... **FastAPI** 会知道怎么处理。
-/// tip
+/// tip | 提示
如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。
-这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。
+这只是一个快捷方式。因为 **FastAPI** 关心的是帮助你减少代码重复。
///
diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 51b3e9fc3..02fcf62a0 100644
--- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -1,4 +1,4 @@
-# 路径操作装饰器依赖项
+# 路径操作装饰器依赖项 { #dependencies-in-path-operation-decorators }
有时,我们并不需要在*路径操作函数*中使用依赖项的返回值。
@@ -8,15 +8,15 @@
对于这种情况,不必在声明*路径操作函数*的参数时使用 `Depends`,而是可以在*路径操作装饰器*中添加一个由 `dependencies` 组成的 `list`。
-## 在*路径操作装饰器*中添加 `dependencies` 参数
+## 在*路径操作装饰器*中添加 `dependencies` 参数 { #add-dependencies-to-the-path-operation-decorator }
-*路径操作装饰器*支持可选参数 ~ `dependencies`。
+*路径操作装饰器*支持可选参数 `dependencies`。
该参数的值是由 `Depends()` 组成的 `list`:
-{* ../../docs_src/dependencies/tutorial006.py hl[17] *}
+{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *}
-路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。
+路径操作装饰器依赖项的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。
/// tip | 提示
@@ -36,34 +36,34 @@
///
-## 依赖项错误和返回值
+## 依赖项错误和返回值 { #dependencies-errors-and-return-values }
路径装饰器依赖项也可以使用普通的依赖项*函数*。
-### 依赖项的需求项
+### 依赖项的需求项 { #dependency-requirements }
路径装饰器依赖项可以声明请求的需求项(比如响应头)或其他子依赖项:
-{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *}
+{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *}
-### 触发异常
+### 触发异常 { #raise-exceptions }
路径装饰器依赖项与正常的依赖项一样,可以 `raise` 异常:
-{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *}
+{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *}
-### 返回值
+### 返回值 { #return-values }
无论路径装饰器依赖项是否返回值,路径操作都不会使用这些值。
因此,可以复用在其他位置使用过的、(能返回值的)普通依赖项,即使没有使用这个值,也会执行该依赖项:
-{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *}
+{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *}
-## 为一组路径操作定义依赖项
+## 为一组路径操作定义依赖项 { #dependencies-for-a-group-of-path-operations }
-稍后,[大型应用 - 多文件](../../tutorial/bigger-applications.md){.internal-link target=\_blank}一章中会介绍如何使用多个文件创建大型应用程序,在这一章中,您将了解到如何为一组*路径操作*声明单个 `dependencies` 参数。
+稍后,[大型应用 - 多文件](../../tutorial/bigger-applications.md){.internal-link target=_blank}一章中会介绍如何使用多个文件创建大型应用程序,在这一章中,您将了解到如何为一组*路径操作*声明单个 `dependencies` 参数。
-## 全局依赖项
+## 全局依赖项 { #global-dependencies }
接下来,我们将学习如何为 `FastAPI` 应用程序添加全局依赖项,创建应用于每个*路径操作*的依赖项。
diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
index a863bb861..bf495c9f3 100644
--- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,136 +1,139 @@
-# 使用yield的依赖项
+# 使用 yield 的依赖项 { #dependencies-with-yield }
-FastAPI支持在完成后执行一些额外步骤的依赖项.
+FastAPI 支持那些在完成后执行一些额外步骤的依赖项。
-为此,你需要使用 `yield` 而不是 `return`,然后再编写这些额外的步骤(代码)。
+为此,使用 `yield` 而不是 `return`,并把这些额外步骤(代码)写在后面。
/// tip | 提示
-确保在每个依赖中只使用一次 `yield`。
+确保在每个依赖里只使用一次 `yield`。
///
/// note | 技术细节
-任何一个可以与以下内容一起使用的函数:
+任何可以与以下装饰器一起使用的函数:
-* `@contextlib.contextmanager` 或者
+* `@contextlib.contextmanager` 或
* `@contextlib.asynccontextmanager`
都可以作为 **FastAPI** 的依赖项。
-实际上,FastAPI内部就使用了这两个装饰器。
+实际上,FastAPI 在内部就是用的这两个装饰器。
///
-## 使用 `yield` 的数据库依赖项
+## 使用 `yield` 的数据库依赖项 { #a-database-dependency-with-yield }
-例如,你可以使用这种方式创建一个数据库会话,并在完成后关闭它。
+例如,你可以用这种方式创建一个数据库会话,并在完成后将其关闭。
-在发送响应之前,只会执行 `yield` 语句及之前的代码:
+在创建响应之前,只会执行 `yield` 语句及其之前的代码:
-{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
-生成的值会注入到 *路由函数* 和其他依赖项中:
+`yield` 产生的值会注入到 *路径操作* 和其他依赖项中:
-{* ../../docs_src/dependencies/tutorial007.py hl[4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
-`yield` 语句后面的代码会在创建响应后,发送响应前执行:
+`yield` 语句后面的代码会在响应之后执行:
-{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
/// tip | 提示
你可以使用 `async` 或普通函数。
-**FastAPI** 会像处理普通依赖一样,对每个依赖做正确的处理。
+**FastAPI** 会像处理普通依赖一样对它们进行正确处理。
///
-## 包含 `yield` 和 `try` 的依赖项
+## 同时使用 `yield` 和 `try` 的依赖项 { #a-dependency-with-yield-and-try }
-如果在包含 `yield` 的依赖中使用 `try` 代码块,你会捕获到使用依赖时抛出的任何异常。
+如果你在带有 `yield` 的依赖中使用了 `try` 代码块,那么当使用该依赖时抛出的任何异常你都会收到。
-例如,如果某段代码在另一个依赖中或在 *路由函数* 中使数据库事务"回滚"或产生任何其他错误,你将会在依赖中捕获到异常。
+例如,如果在中间的某处代码中(在另一个依赖或在某个 *路径操作* 中)发生了数据库事务“回滚”或产生了其他异常,你会在你的依赖中收到这个异常。
-因此,你可以使用 `except SomeException` 在依赖中捕获特定的异常。
+因此,你可以在该依赖中用 `except SomeException` 来捕获这个特定异常。
-同样,你也可以使用 `finally` 来确保退出步骤得到执行,无论是否存在异常。
+同样地,你可以使用 `finally` 来确保退出步骤一定会被执行,无论是否发生异常。
-{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *}
-## 使用 `yield` 的子依赖项
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
-你可以声明任意数量和层级的树状依赖,而且它们中的任何一个或所有的都可以使用 `yield`。
+## 使用 `yield` 的子依赖项 { #sub-dependencies-with-yield }
-**FastAPI** 会确保每个带有 `yield` 的依赖中的"退出代码"按正确顺序运行。
+你可以声明任意大小和形状的子依赖及其“树”,其中任意一个或全部都可以使用 `yield`。
-例如,`dependency_c` 可以依赖于 `dependency_b`,而 `dependency_b` 则依赖于 `dependency_a`。
+**FastAPI** 会确保每个带有 `yield` 的依赖中的“退出代码”按正确的顺序运行。
+
+例如,`dependency_c` 可以依赖 `dependency_b`,而 `dependency_b` 则依赖 `dependency_a`:
{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *}
-所有这些依赖都可以使用 `yield`。
+并且它们都可以使用 `yield`。
-在这种情况下,`dependency_c` 在执行其退出代码时需要 `dependency_b`(此处称为 `dep_b`)的值仍然可用。
+在这种情况下,`dependency_c` 在执行其退出代码时需要 `dependency_b`(此处命名为 `dep_b`)的值仍然可用。
-而 `dependency_b` 反过来则需要 `dependency_a`(此处称为 `dep_a` )的值在其退出代码中可用。
+而 `dependency_b` 又需要 `dependency_a`(此处命名为 `dep_a`)的值在其退出代码中可用。
{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *}
-同样,你可以混合使用带有 `yield` 或 `return` 的依赖。
+同样地,你可以将一些依赖用 `yield`,另一些用 `return`,并让其中一些依赖依赖于另一些。
-你也可以声明一个依赖于多个带有 `yield` 的依赖,等等。
+你也可以有一个依赖需要多个带有 `yield` 的依赖,等等。
你可以拥有任何你想要的依赖组合。
-**FastAPI** 将确保按正确的顺序运行所有内容。
+**FastAPI** 将确保一切都按正确的顺序运行。
/// note | 技术细节
-这是由 Python 的上下文管理器完成的。
+这要归功于 Python 的上下文管理器。
**FastAPI** 在内部使用它们来实现这一点。
///
-## 包含 `yield` 和 `HTTPException` 的依赖项
+## 同时使用 `yield` 和 `HTTPException` 的依赖项 { #dependencies-with-yield-and-httpexception }
-你可以使用带有 `yield` 的依赖项,并且可以包含 `try` 代码块用于捕获异常。
+你已经看到可以在带有 `yield` 的依赖中使用 `try` 块尝试执行一些代码,然后在 `finally` 之后运行一些退出代码。
-同样,你可以在 `yield` 之后的退出代码中抛出一个 `HTTPException` 或类似的异常。
+你也可以使用 `except` 来捕获引发的异常并对其进行处理。
+
+例如,你可以抛出一个不同的异常,如 `HTTPException`。
/// tip | 提示
-这是一种相对高级的技巧,在大多数情况下你并不需要使用它,因为你可以在其他代码中抛出异常(包括 `HTTPException` ),例如在 *路由函数* 中。
+这是一种相对高级的技巧,在大多数情况下你并不需要使用它,因为你可以在应用的其他代码中(例如在 *路径操作函数* 里)抛出异常(包括 `HTTPException`)。
-但是如果你需要,你也可以在依赖项中做到这一点。🤓
+但是如果你需要,它就在这里。🤓
///
{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *}
-你还可以创建一个 [自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} 用于捕获异常(同时也可以抛出另一个 `HTTPException`)。
+如果你想捕获异常并基于它创建一个自定义响应,请创建一个[自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}。
-## 包含 `yield` 和 `except` 的依赖项
+## 同时使用 `yield` 和 `except` 的依赖项 { #dependencies-with-yield-and-except }
-如果你在包含 `yield` 的依赖项中使用 `except` 捕获了一个异常,然后你没有重新抛出该异常(或抛出一个新异常),与在普通的Python代码中相同,FastAPI不会注意到发生了异常。
+如果你在带有 `yield` 的依赖中使用 `except` 捕获了一个异常,并且你没有再次抛出它(或抛出一个新异常),FastAPI 将无法察觉发生过异常,就像普通的 Python 代码那样:
{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *}
-在示例代码的情况下,客户端将会收到 *HTTP 500 Internal Server Error* 的响应,因为我们没有抛出 `HTTPException` 或者类似的异常,并且服务器也 **不会有任何日志** 或者其他提示来告诉我们错误是什么。😱
+在这种情况下,客户端会像预期那样看到一个 *HTTP 500 Internal Server Error* 响应,因为我们没有抛出 `HTTPException` 或类似异常,但服务器将**没有任何日志**或其他关于错误是什么的提示。😱
-### 在包含 `yield` 和 `except` 的依赖项中一定要 `raise`
+### 在带有 `yield` 和 `except` 的依赖中务必 `raise` { #always-raise-in-dependencies-with-yield-and-except }
-如果你在使用 `yield` 的依赖项中捕获到了一个异常,你应该再次抛出捕获到的异常,除非你抛出 `HTTPException` 或类似的其他异常,
+如果你在带有 `yield` 的依赖中捕获到了一个异常,除非你抛出另一个 `HTTPException` 或类似异常,**否则你应该重新抛出原始异常**。
-你可以使用 `raise` 再次抛出捕获到的异常。
+你可以使用 `raise` 重新抛出同一个异常:
{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *}
-现在客户端同样会得到 *HTTP 500 Internal Server Error* 响应,但是服务器日志会记录下我们自定义的 `InternalError`。
+现在客户端仍会得到同样的 *HTTP 500 Internal Server Error* 响应,但服务器日志中会有我们自定义的 `InternalError`。😎
-## 使用 `yield` 的依赖项的执行
+## 使用 `yield` 的依赖项的执行 { #execution-of-dependencies-with-yield }
-执行顺序大致如下时序图所示。时间轴从上到下,每一列都代表交互或者代码执行的一部分。
+执行顺序大致如下图所示。时间轴从上到下,每一列都代表交互或执行代码的一部分。
```mermaid
sequenceDiagram
@@ -167,63 +170,78 @@ participant tasks as Background tasks
end
```
-/// info | 说明
+/// info | 信息
-只会向客户端发送 **一次响应** ,可能是一个错误响应,也可能是来自 *路由函数* 的响应。
+只会向客户端发送**一次响应**。它可能是某个错误响应,或者是来自 *路径操作* 的响应。
-在发送了其中一个响应之后,就无法再发送其他响应了。
+在其中一个响应发送之后,就不能再发送其他响应了。
///
/// tip | 提示
-这个时序图展示了 `HTTPException`,除此之外你也可以抛出任何你在使用 `yield` 的依赖项中或者[自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}中捕获的异常。
-
-如果你引发任何异常,它将传递给使用 `yield` 的依赖项,包括 `HTTPException`。在大多数情况下你应当从使用 `yield` 的依赖项中重新抛出捕获的异常或者一个新的异常来确保它会被正确的处理。
+如果你在 *路径操作函数* 的代码中引发任何异常,它都会被传递给带有 `yield` 的依赖项,包括 `HTTPException`。在大多数情况下,你会希望在带有 `yield` 的依赖中重新抛出相同的异常或一个新的异常,以确保它被正确处理。
///
-## 包含 `yield`, `HTTPException`, `except` 的依赖项和后台任务
+## 提前退出与 `scope` { #early-exit-and-scope }
-/// warning | 注意
+通常,带有 `yield` 的依赖的退出代码会在响应发送给客户端**之后**执行。
-你大概率不需要了解这些技术细节,可以跳过这一章节继续阅读后续的内容。
+但如果你知道在从 *路径操作函数* 返回之后不再需要使用该依赖,你可以使用 `Depends(scope="function")` 告诉 FastAPI:应当在 *路径操作函数* 返回后、但在**响应发送之前**关闭该依赖。
-如果你使用的FastAPI的版本早于0.106.0,并且在使用后台任务中使用了包含 `yield` 的依赖项中的资源,那么这些细节会对你有一些用处。
+{* ../../docs_src/dependencies/tutorial008e_an_py39.py hl[12,16] *}
-///
+`Depends()` 接收一个 `scope` 参数,可为:
-### 包含 `yield` 和 `except` 的依赖项的技术细节
+* `"function"`:在处理请求的 *路径操作函数* 之前启动依赖,在 *路径操作函数* 结束后结束依赖,但在响应发送给客户端**之前**。因此,依赖函数将围绕这个*路径操作函数*执行。
+* `"request"`:在处理请求的 *路径操作函数* 之前启动依赖(与使用 `"function"` 时类似),但在响应发送给客户端**之后**结束。因此,依赖函数将围绕这个**请求**与响应周期执行。
-在FastAPI 0.110.0版本之前,如果使用了一个包含 `yield` 的依赖项,你在依赖项中使用 `except` 捕获了一个异常,但是你没有再次抛出该异常,这个异常会被自动抛出/转发到异常处理器或者内部服务错误处理器。
+如果未指定且依赖包含 `yield`,则默认 `scope` 为 `"request"`。
-### 后台任务和使用 `yield` 的依赖项的技术细节
+### 子依赖的 `scope` { #scope-for-sub-dependencies }
-在FastAPI 0.106.0版本之前,在 `yield` 后面抛出异常是不可行的,因为 `yield` 之后的退出代码是在响应被发送之后再执行,这个时候异常处理器已经执行过了。
+当你声明一个 `scope="request"`(默认)的依赖时,任何子依赖也需要有 `"request"` 的 `scope`。
-这样设计的目的主要是为了允许在后台任务中使用被依赖项`yield`的对象,因为退出代码会在后台任务结束后再执行。
+但一个 `scope` 为 `"function"` 的依赖可以有 `scope` 为 `"function"` 和 `"request"` 的子依赖。
-然而这也意味着在等待响应通过网络传输的同时,非必要的持有一个 `yield` 依赖项中的资源(例如数据库连接),这一行为在FastAPI 0.106.0被改变了。
+这是因为任何依赖都需要能够在子依赖之前运行其退出代码,因为它的退出代码中可能还需要使用这些子依赖。
-/// tip | 提示
+```mermaid
+sequenceDiagram
-除此之外,后台任务通常是一组独立的逻辑,应该被单独处理,并且使用它自己的资源(例如它自己的数据库连接)。
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
-这样也会让你的代码更加简洁。
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
-///
+## 包含 `yield`、`HTTPException`、`except` 和后台任务的依赖项 { #dependencies-with-yield-httpexception-except-and-background-tasks }
-如果你之前依赖于这一行为,那么现在你应该在后台任务中创建并使用它自己的资源,不要在内部使用属于 `yield` 依赖项的资源。
+带有 `yield` 的依赖项随着时间演进以涵盖不同的用例并修复了一些问题。
-例如,你应该在后台任务中创建一个新的数据库会话用于查询数据,而不是使用相同的会话。你应该将对象的ID作为参数传递给后台任务函数,然后在该函数中重新获取该对象,而不是直接将数据库对象作为参数。
+如果你想了解在不同 FastAPI 版本中发生了哪些变化,可以在进阶指南中阅读更多:[高级依赖项 —— 包含 `yield`、`HTTPException`、`except` 和后台任务的依赖项](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks){.internal-link target=_blank}。
-## 上下文管理器
+## 上下文管理器 { #context-managers }
-### 什么是"上下文管理器"
+### 什么是“上下文管理器” { #what-are-context-managers }
-"上下文管理器"是你可以在 `with` 语句中使用的任何Python对象。
+“上下文管理器”是你可以在 `with` 语句中使用的任意 Python 对象。
-例如,你可以使用`with`读取文件:
+例如,你可以用 `with` 来读取文件:
```Python
with open("./somefile.txt") as f:
@@ -231,37 +249,39 @@ with open("./somefile.txt") as f:
print(contents)
```
-在底层,`open("./somefile.txt")`创建了一个被称为"上下文管理器"的对象。
+在底层,`open("./somefile.txt")` 会创建一个“上下文管理器”对象。
-当 `with` 代码块结束时,它会确保关闭文件,即使发生了异常也是如此。
+当 `with` 代码块结束时,它会确保文件被关闭,即使期间发生了异常。
-当你使用 `yield` 创建一个依赖项时,**FastAPI** 会在内部将其转换为上下文管理器,并与其他相关工具结合使用。
+当你用 `yield` 创建一个依赖时,**FastAPI** 会在内部为它创建一个上下文管理器,并与其他相关工具结合使用。
-### 在使用 `yield` 的依赖项中使用上下文管理器
+### 在带有 `yield` 的依赖中使用上下文管理器 { #using-context-managers-in-dependencies-with-yield }
-/// warning | 注意
+/// warning | 警告
-这是一个更为"高级"的想法。
+这算是一个“高级”概念。
-如果你刚开始使用 **FastAPI** ,你可以暂时可以跳过它。
+如果你刚开始使用 **FastAPI**,现在可以先跳过。
///
-在Python中,你可以通过创建一个带有`__enter__()`和`__exit__()`方法的类来创建上下文管理器。
+在 Python 中,你可以通过创建一个带有 `__enter__()` 和 `__exit__()` 方法的类来创建上下文管理器。
-你也可以在 **FastAPI** 的 `yield` 依赖项中通过 `with` 或者 `async with` 语句来使用它们:
+你也可以在 **FastAPI** 的带有 `yield` 的依赖中,使用依赖函数内部的 `with` 或 `async with` 语句来使用它们:
-{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *}
+{* ../../docs_src/dependencies/tutorial010_py39.py hl[1:9,13] *}
/// tip | 提示
-另一种创建上下文管理器的方法是:
+另一种创建上下文管理器的方式是:
-* `@contextlib.contextmanager`或者
-* `@contextlib.asynccontextmanager`
+* `@contextlib.contextmanager` 或
+* `@contextlib.asynccontextmanager`
-使用它们装饰一个只有单个 `yield` 的函数。这就是 **FastAPI** 内部对于 `yield` 依赖项的处理方式。
+用它们去装饰一个只包含单个 `yield` 的函数。
-但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。
+这正是 **FastAPI** 在内部处理带有 `yield` 的依赖时所使用的方式。
+
+但你不需要(也不应该)为 FastAPI 的依赖去使用这些装饰器。FastAPI 会在内部为你处理好。
///
diff --git a/docs/zh/docs/tutorial/dependencies/global-dependencies.md b/docs/zh/docs/tutorial/dependencies/global-dependencies.md
index 797fd76b7..36cf9cf44 100644
--- a/docs/zh/docs/tutorial/dependencies/global-dependencies.md
+++ b/docs/zh/docs/tutorial/dependencies/global-dependencies.md
@@ -1,15 +1,15 @@
-# 全局依赖项
+# 全局依赖项 { #global-dependencies }
有时,我们要为整个应用添加依赖项。
-通过与定义[*路径装饰器依赖项*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 类似的方式,可以把依赖项添加至整个 `FastAPI` 应用。
+通过与[将 `dependencies` 添加到*路径操作装饰器*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 类似的方式,可以把依赖项添加至整个 `FastAPI` 应用。
这样一来,就可以为所有*路径操作*应用该依赖项:
-{* ../../docs_src/dependencies/tutorial012.py hl[15] *}
+{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[17] *}
-[*路径装饰器依赖项*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 一章的思路均适用于全局依赖项, 在本例中,这些依赖项可以用于应用中的所有*路径操作*。
+[将 `dependencies` 添加到*路径操作装饰器*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 一章的思路均适用于全局依赖项, 在本例中,这些依赖项可以用于应用中的所有*路径操作*。
-## 为一组路径操作定义依赖项
+## 为一组路径操作定义依赖项 { #dependencies-for-groups-of-path-operations }
稍后,[大型应用 - 多文件](../../tutorial/bigger-applications.md){.internal-link target=_blank}一章中会介绍如何使用多个文件创建大型应用程序,在这一章中,您将了解到如何为一组*路径操作*声明单个 `dependencies` 参数。
diff --git a/docs/zh/docs/tutorial/dependencies/index.md b/docs/zh/docs/tutorial/dependencies/index.md
index 9eec69ed5..20d2c0b64 100644
--- a/docs/zh/docs/tutorial/dependencies/index.md
+++ b/docs/zh/docs/tutorial/dependencies/index.md
@@ -1,85 +1,97 @@
-# 依赖项
+# 依赖项 { #dependencies }
-FastAPI 提供了简单易用,但功能强大的**依赖注入**系统。
+**FastAPI** 提供了简单直观但功能强大的**依赖注入**系统。
-这个依赖系统设计的简单易用,可以让开发人员轻松地把组件集成至 **FastAPI**。
+它被设计得非常易用,能让任何开发者都能轻松把其他组件与 **FastAPI** 集成。
-## 什么是「依赖注入」
+## 什么是「依赖注入」 { #what-is-dependency-injection }
-编程中的**「依赖注入」**是声明代码(本文中为*路径操作函数* )运行所需的,或要使用的「依赖」的一种方式。
+在编程中,**「依赖注入」**指的是,你的代码(本文中为*路径操作函数*)声明其运行所需并要使用的东西:“依赖”。
-然后,由系统(本文中为 **FastAPI**)负责执行任意需要的逻辑,为代码提供这些依赖(「注入」依赖项)。
+然后,由该系统(本文中为 **FastAPI**)负责执行所有必要的逻辑,为你的代码提供这些所需的依赖(“注入”依赖)。
-依赖注入常用于以下场景:
+当你需要以下内容时,这非常有用:
-* 共享业务逻辑(复用相同的代码逻辑)
+* 共享业务逻辑(同一段代码逻辑反复复用)
* 共享数据库连接
-* 实现安全、验证、角色权限
-* 等……
+* 实施安全、认证、角色权限等要求
+* 以及更多其他内容...
-上述场景均可以使用**依赖注入**,将代码重复最小化。
+同时尽量减少代码重复。
-## 第一步
+## 第一步 { #first-steps }
-接下来,我们学习一个非常简单的例子,尽管它过于简单,不是很实用。
+先来看一个非常简单的例子。它现在简单到几乎没什么用。
-但通过这个例子,您可以初步了解「依赖注入」的工作机制。
+但这样我们就可以专注于**依赖注入**系统是如何工作的。
-### 创建依赖项
+### 创建依赖项,或“dependable” { #create-a-dependency-or-dependable }
-首先,要关注的是依赖项。
+首先关注依赖项。
-依赖项就是一个函数,且可以使用与*路径操作函数*相同的参数:
+它只是一个函数,且可以接收与*路径操作函数*相同的所有参数:
-{* ../../docs_src/dependencies/tutorial001.py hl[8:11] *}
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
大功告成。
只用了**2 行**代码。
-依赖项函数的形式和结构与*路径操作函数*一样。
+它的形式和结构与所有*路径操作函数*相同。
-因此,可以把依赖项当作没有「装饰器」(即,没有 `@app.get("/some-path")` )的路径操作函数。
+你可以把它当作没有“装饰器”(没有 `@app.get("/some-path")`)的*路径操作函数*。
-依赖项可以返回各种内容。
+而且它可以返回任何你想要的内容。
-本例中的依赖项预期接收如下参数:
+本例中的依赖项预期接收:
* 类型为 `str` 的可选查询参数 `q`
-* 类型为 `int` 的可选查询参数 `skip`,默认值是 `0`
-* 类型为 `int` 的可选查询参数 `limit`,默认值是 `100`
+* 类型为 `int` 的可选查询参数 `skip`,默认值 `0`
+* 类型为 `int` 的可选查询参数 `limit`,默认值 `100`
-然后,依赖项函数返回包含这些值的 `dict`。
+然后它只需返回一个包含这些值的 `dict`。
-### 导入 `Depends`
+/// info | 信息
-{* ../../docs_src/dependencies/tutorial001.py hl[3] *}
+FastAPI 在 0.95.0 版本中新增了对 `Annotated` 的支持(并开始推荐使用)。
-### 声明依赖项
+如果你的版本较旧,尝试使用 `Annotated` 会报错。
-与在*路径操作函数*参数中使用 `Body`、`Query` 的方式相同,声明依赖项需要使用 `Depends` 和一个新的参数:
-
-{* ../../docs_src/dependencies/tutorial001.py hl[15,20] *}
-
-虽然,在路径操作函数的参数中使用 `Depends` 的方式与 `Body`、`Query` 相同,但 `Depends` 的工作方式略有不同。
-
-这里只能传给 Depends 一个参数。
-
-且该参数必须是可调用对象,比如函数。
-
-该函数接收的参数和*路径操作函数*的参数一样。
-
-/// tip | 提示
-
-下一章介绍,除了函数还有哪些「对象」可以用作依赖项。
+在使用 `Annotated` 之前,请确保[升级 FastAPI 版本](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}到至少 0.95.1。
///
-接收到新的请求时,**FastAPI** 执行如下操作:
+### 导入 `Depends` { #import-depends }
-* 用正确的参数调用依赖项函数(「可依赖项」)
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### 在“dependant”中声明依赖项 { #declare-the-dependency-in-the-dependant }
+
+与在*路径操作函数*的参数中使用 `Body`、`Query` 等相同,给参数使用 `Depends` 来声明一个新的依赖项:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+虽然你在函数参数中使用 `Depends` 的方式与 `Body`、`Query` 等相同,但 `Depends` 的工作方式略有不同。
+
+这里只能给 `Depends` 传入一个参数。
+
+这个参数必须是类似函数的可调用对象。
+
+你不需要直接调用它(不要在末尾加括号),只需将其作为参数传给 `Depends()`。
+
+该函数接收的参数与*路径操作函数*的参数相同。
+
+/// tip | 提示
+
+下一章会介绍除了函数之外,还有哪些“东西”可以用作依赖项。
+
+///
+
+接收到新的请求时,**FastAPI** 会负责:
+
+* 用正确的参数调用你的依赖项(“dependable”)函数
* 获取函数返回的结果
-* 把函数返回的结果赋值给*路径操作函数*的参数
+* 将该结果赋值给你的*路径操作函数*中的参数
```mermaid
graph TB
@@ -92,95 +104,121 @@ common_parameters --> read_items
common_parameters --> read_users
```
-这样,只编写一次代码,**FastAPI** 就可以为多个*路径操作*共享这段代码 。
+这样,你只需编写一次共享代码,**FastAPI** 会在你的*路径操作*中为你调用它。
/// check | 检查
-注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。
+注意,无需创建专门的类并传给 **FastAPI** 去“注册”之类的操作。
-只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。
+只要把它传给 `Depends`,**FastAPI** 就知道该怎么做了。
///
-## 要不要使用 `async`?
+## 共享 `Annotated` 依赖项 { #share-annotated-dependencies }
-**FastAPI** 调用依赖项的方式与*路径操作函数*一样,因此,定义依赖项函数,也要应用与路径操作函数相同的规则。
+在上面的示例中,你会发现这里有一点点**代码重复**。
-即,既可以使用异步的 `async def`,也可以使用普通的 `def` 定义依赖项。
+当你需要使用 `common_parameters()` 这个依赖时,你必须写出完整的带类型注解和 `Depends()` 的参数:
-在普通的 `def` *路径操作函数*中,可以声明异步的 `async def` 依赖项;也可以在异步的 `async def` *路径操作函数*中声明普通的 `def` 依赖项。
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
-上述这些操作都是可行的,**FastAPI** 知道该怎么处理。
+但因为我们使用了 `Annotated`,可以把这个 `Annotated` 的值存到一个变量里,在多个地方复用:
-/// note | 笔记
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
-如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。
+/// tip | 提示
+
+这只是标准的 Python,叫做“类型别名”,并不是 **FastAPI** 特有的。
+
+但因为 **FastAPI** 基于 Python 标准(包括 `Annotated`),你就可以在代码里使用这个技巧。😎
///
-## 与 OpenAPI 集成
+这些依赖会照常工作,而**最棒的是**,**类型信息会被保留**,这意味着你的编辑器依然能提供**自动补全**、**行内报错**等。同样适用于 `mypy` 等其他工具。
-依赖项及子依赖项的所有请求声明、验证和需求都可以集成至同一个 OpenAPI 概图。
+当你在**大型代码库**中,在**很多*路径操作***里反复使用**相同的依赖**时,这会特别有用。
-所以,交互文档里也会显示依赖项的所有信息:
+## 要不要使用 `async`? { #to-async-or-not-to-async }
+
+由于依赖项也会由 **FastAPI** 调用(与*路径操作函数*相同),因此定义函数时同样的规则也适用。
+
+你可以使用 `async def` 或普通的 `def`。
+
+你可以在普通的 `def` *路径操作函数*中声明 `async def` 的依赖项;也可以在异步的 `async def` *路径操作函数*中声明普通的 `def` 依赖项,等等。
+
+都没关系,**FastAPI** 知道该怎么处理。
+
+/// note | 注意
+
+如果不了解异步,请参阅文档中关于 `async` 和 `await` 的章节:[异步:*“着急了?”*](../../async.md#in-a-hurry){.internal-link target=_blank}。
+
+///
+
+## 与 OpenAPI 集成 { #integrated-with-openapi }
+
+依赖项及子依赖项中声明的所有请求、验证和需求都会集成到同一个 OpenAPI 模式中。
+
+因此,交互式文档中也会包含这些依赖项的所有信息:
-## 简单用法
+## 简单用法 { #simple-usage }
-观察一下就会发现,只要*路径* 和*操作*匹配,就可以使用声明的路径操作函数。然后,**FastAPI** 会用正确的参数调用函数,并提取请求中的数据。
+观察一下就会发现,只要*路径*和*操作*匹配,就会使用声明的*路径操作函数*。随后,**FastAPI** 会用正确的参数调用该函数,并从请求中提取数据。
-实际上,所有(或大多数)网络框架的工作方式都是这样的。
+事实上,所有(或大多数)Web 框架的工作方式都是这样的。
-开发人员永远都不需要直接调用这些函数,这些函数是由框架(在此为 **FastAPI** )调用的。
+你从不会直接调用这些函数。它们由你的框架(此处为 **FastAPI**)调用。
-通过依赖注入系统,只要告诉 **FastAPI** *路径操作函数* 还要「依赖」其他在*路径操作函数*之前执行的内容,**FastAPI** 就会执行函数代码,并「注入」函数返回的结果。
+通过依赖注入系统,你还可以告诉 **FastAPI**,你的*路径操作函数*还“依赖”某些应在*路径操作函数*之前执行的内容,**FastAPI** 会负责执行它并“注入”结果。
-其他与「依赖注入」概念相同的术语为:
+“依赖注入”的其他常见术语包括:
-* 资源(Resource)
-* 提供方(Provider)
-* 服务(Service)
-* 可注入(Injectable)
-* 组件(Component)
+* 资源(resources)
+* 提供方(providers)
+* 服务(services)
+* 可注入(injectables)
+* 组件(components)
-## **FastAPI** 插件
+## **FastAPI** 插件 { #fastapi-plug-ins }
-**依赖注入**系统支持构建集成和「插件」。但实际上,FastAPI 根本**不需要创建「插件」**,因为使用依赖项可以声明不限数量的、可用于*路径操作函数*的集成与交互。
+可以使用**依赖注入**系统构建集成和“插件”。但实际上,根本**不需要创建“插件”**,因为通过依赖项可以声明无限多的集成与交互,使其可用于*路径操作函数*。
-创建依赖项非常简单、直观,并且还支持导入 Python 包。毫不夸张地说,只要几行代码就可以把需要的 Python 包与 API 函数集成在一起。
+依赖项可以用非常简单直观的方式创建,你只需导入所需的 Python 包,用*字面意义上的*几行代码就能把它们与你的 API 函数集成起来。
-下一章将详细介绍在关系型数据库、NoSQL 数据库、安全等方面使用依赖项的例子。
+在接下来的章节中,你会看到关于关系型数据库、NoSQL 数据库、安全等方面的示例。
-## **FastAPI** 兼容性
+## **FastAPI** 兼容性 { #fastapi-compatibility }
-依赖注入系统如此简洁的特性,让 **FastAPI** 可以与下列系统兼容:
+依赖注入系统的简洁让 **FastAPI** 能与以下内容兼容:
-* 关系型数据库
+* 各类关系型数据库
* NoSQL 数据库
-* 外部支持库
+* 外部包
* 外部 API
-* 认证和鉴权系统
+* 认证与授权系统
* API 使用监控系统
* 响应数据注入系统
-* 等等……
+* 等等...
-## 简单而强大
+## 簡单而强大 { #simple-and-powerful }
-虽然,**层级式依赖注入系统**的定义与使用十分简单,但它却非常强大。
+虽然**层级式依赖注入系统**的定义与使用非常简单,但它依然非常强大。
-比如,可以定义依赖其他依赖项的依赖项。
+你可以定义依赖其他依赖项的依赖项。
-最后,依赖项层级树构建后,**依赖注入系统**会处理所有依赖项及其子依赖项,并为每一步操作提供(注入)结果。
+最终会构建出一个依赖项的层级树,**依赖注入**系统会处理所有这些依赖(及其子依赖),并在每一步提供(注入)相应的结果。
-比如,下面有 4 个 API 路径操作(*端点*):
+例如,假设你有 4 个 API 路径操作(*端点*):
* `/items/public/`
* `/items/private/`
* `/users/{user_id}/activate`
* `/items/pro/`
-开发人员可以使用依赖项及其子依赖项为这些路径操作添加不同的权限:
+你可以仅通过依赖项及其子依赖项为它们添加不同的权限要求:
```mermaid
graph TB
@@ -205,8 +243,8 @@ admin_user --> activate_user
paying_user --> pro_items
```
-## 与 **OpenAPI** 集成
+## 与 **OpenAPI** 集成 { #integrated-with-openapi_1 }
-在声明需求时,所有这些依赖项还会把参数、验证等功能添加至路径操作。
+在声明需求的同时,所有这些依赖项也会为你的*路径操作*添加参数、验证等内容。
-**FastAPI** 负责把上述内容全部添加到 OpenAPI 概图,并显示在交互文档中。
+**FastAPI** 会负责把这些全部添加到 OpenAPI 模式中,以便它们显示在交互式文档系统里。
diff --git a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md
index 2e7746433..0b73c392d 100644
--- a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md
@@ -1,4 +1,4 @@
-# 子依赖项
+# 子依赖项 { #sub-dependencies }
FastAPI 支持创建含**子依赖项**的依赖项。
@@ -6,34 +6,34 @@ FastAPI 支持创建含**子依赖项**的依赖项。
**FastAPI** 负责处理解析不同深度的子依赖项。
-### 第一层依赖项
+## 第一层依赖项 “dependable” { #first-dependency-dependable }
-下列代码创建了第一层依赖项:
+你可以创建一个第一层依赖项(“dependable”),如下:
-{* ../../docs_src/dependencies/tutorial005.py hl[8:9] *}
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
这段代码声明了类型为 `str` 的可选查询参数 `q`,然后返回这个查询参数。
这个函数很简单(不过也没什么用),但却有助于让我们专注于了解子依赖项的工作方式。
-### 第二层依赖项
+## 第二层依赖项,“dependable”和“dependant” { #second-dependency-dependable-and-dependant }
-接下来,创建另一个依赖项函数,并同时用该依赖项自身再声明一个依赖项(所以这也是一个「依赖项」):
+接下来,创建另一个依赖项函数(一个“dependable”),并同时为它自身再声明一个依赖项(因此它同时也是一个“dependant”):
-{* ../../docs_src/dependencies/tutorial005.py hl[13] *}
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
这里重点说明一下声明的参数:
-* 尽管该函数自身是依赖项,但还声明了另一个依赖项(它「依赖」于其他对象)
+* 尽管该函数自身是依赖项(“dependable”),但还声明了另一个依赖项(它“依赖”于其他对象)
* 该函数依赖 `query_extractor`, 并把 `query_extractor` 的返回值赋给参数 `q`
* 同时,该函数还声明了类型是 `str` 的可选 cookie(`last_query`)
* 用户未提供查询参数 `q` 时,则使用上次使用后保存在 cookie 中的查询
-### 使用依赖项
+## 使用依赖项 { #use-the-dependency }
接下来,就可以使用依赖项:
-{* ../../docs_src/dependencies/tutorial005.py hl[22] *}
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
/// info | 信息
@@ -54,20 +54,39 @@ read_query["/items/"]
query_extractor --> query_or_cookie_extractor --> read_query
```
-## 多次使用同一个依赖项
+## 多次使用同一个依赖项 { #using-the-same-dependency-multiple-times }
如果在同一个*路径操作* 多次声明了同一个依赖项,例如,多个依赖项共用一个子依赖项,**FastAPI** 在处理同一请求时,只调用一次该子依赖项。
FastAPI 不会为同一个请求多次调用同一个依赖项,而是把依赖项的返回值进行「缓存」,并把它传递给同一请求中所有需要使用该返回值的「依赖项」。
-在高级使用场景中,如果不想使用「缓存」值,而是为需要在同一请求的每一步操作(多次)中都实际调用依赖项,可以把 `Depends` 的参数 `use_cache` 的值设置为 `False` :
+在高级使用场景中,如果不想使用「缓存」值,而是为需要在同一请求的每一步操作(多次)中都实际调用依赖项,可以把 `Depends` 的参数 `use_cache` 的值设置为 `False`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.9+ 非 Annotated
+
+/// tip | 提示
+
+尽可能优先使用 `Annotated` 版本。
+
+///
```Python hl_lines="1"
async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
return {"fresh_value": fresh_value}
```
-## 小结
+////
+
+## 小结 { #recap }
千万别被本章里这些花里胡哨的词藻吓倒了,其实**依赖注入**系统非常简单。
diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md
index e52aaa2ed..f47a09201 100644
--- a/docs/zh/docs/tutorial/encoder.md
+++ b/docs/zh/docs/tutorial/encoder.md
@@ -1,4 +1,4 @@
-# JSON 兼容编码器
+# JSON 兼容编码器 { #json-compatible-encoder }
在某些情况下,您可能需要将数据类型(如Pydantic模型)转换为与JSON兼容的数据类型(如`dict`、`list`等)。
@@ -6,7 +6,7 @@
对于这种要求, **FastAPI**提供了`jsonable_encoder()`函数。
-## 使用`jsonable_encoder`
+## 使用`jsonable_encoder` { #using-the-jsonable-encoder }
让我们假设你有一个数据库名为`fake_db`,它只能接收与JSON兼容的数据。
@@ -28,7 +28,7 @@
这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。
-/// note
+/// note | 注意
`jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。
diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md
index b064ee551..2cefd163d 100644
--- a/docs/zh/docs/tutorial/extra-data-types.md
+++ b/docs/zh/docs/tutorial/extra-data-types.md
@@ -1,4 +1,4 @@
-# 额外数据类型
+# 额外数据类型 { #extra-data-types }
到目前为止,您一直在使用常见的数据类型,如:
@@ -15,9 +15,9 @@
* 传入请求的数据转换。
* 响应数据转换。
* 数据验证。
-* 自动补全和文档。
+* 自动注解和文档。
-## 其他数据类型
+## 其他数据类型 { #other-data-types }
下面是一些你可以使用的其他数据类型:
@@ -36,12 +36,12 @@
* `datetime.timedelta`:
* 一个 Python `datetime.timedelta`.
* 在请求和响应中将表示为 `float` 代表总秒数。
- * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", 查看文档了解更多信息。
+ * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", 查看文档了解更多信息。
* `frozenset`:
* 在请求和响应中,作为 `set` 对待:
* 在请求中,列表将被读取,消除重复,并将其转换为一个 `set`。
* 在响应中 `set` 将被转换为 `list` 。
- * 产生的模式将指定那些 `set` 的值是唯一的 (使用 JSON 模式的 `uniqueItems`)。
+ * 产生的模式将指定那些 `set` 的值是唯一的 (使用 JSON Schema 的 `uniqueItems`)。
* `bytes`:
* 标准的 Python `bytes`。
* 在请求和响应中被当作 `str` 处理。
@@ -49,9 +49,9 @@
* `Decimal`:
* 标准的 Python `Decimal`。
* 在请求和响应中被当做 `float` 一样处理。
-* 您可以在这里检查所有有效的pydantic数据类型: Pydantic data types.
+* 您可以在这里检查所有有效的 Pydantic 数据类型: Pydantic data types.
-## 例子
+## 例子 { #example }
下面是一个*路径操作*的示例,其中的参数使用了上面的一些类型。
diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md
index ccfb3aa5a..4d18c76ec 100644
--- a/docs/zh/docs/tutorial/extra-models.md
+++ b/docs/zh/docs/tutorial/extra-models.md
@@ -1,4 +1,4 @@
-# 更多模型
+# 更多模型 { #extra-models }
书接上文,多个关联模型这种情况很常见。
@@ -6,29 +6,29 @@
* **输入模型**应该含密码
* **输出模型**不应含密码
-* **数据库模型**需要加密的密码
+* **数据库模型**可能需要包含哈希后的密码
-/// danger | 危险
+/// danger
-千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。
+不要存储用户的明文密码。始终只存储之后可用于校验的“安全哈希”。
-如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。
+如果你还不了解,可以在[安全性章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}中学习什么是“密码哈希”。
///
-## 多个模型
+## 多个模型 { #multiple-models }
下面的代码展示了不同模型处理密码字段的方式,及使用位置的大致思路:
{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
-### `**user_in.dict()` 简介
+### 关于 `**user_in.model_dump()` { #about-user-in-model-dump }
-#### Pydantic 的 `.dict()`
+#### Pydantic 的 `.model_dump()` { #pydantics-model-dump }
`user_in` 是类 `UserIn` 的 Pydantic 模型。
-Pydantic 模型支持 `.dict()` 方法,能返回包含模型数据的**字典**。
+Pydantic 模型有 `.model_dump()` 方法,会返回包含模型数据的 `dict`。
因此,如果使用如下方式创建 Pydantic 对象 `user_in`:
@@ -39,10 +39,10 @@ user_in = UserIn(username="john", password="secret", email="john.doe@example.com
就能以如下方式调用:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
```
-现在,变量 `user_dict`中的就是包含数据的**字典**(变量 `user_dict` 是字典,不是 Pydantic 模型对象)。
+现在,变量 `user_dict` 中的是包含数据的 `dict`(它是 `dict`,不是 Pydantic 模型对象)。
以如下方式调用:
@@ -50,7 +50,7 @@ user_dict = user_in.dict()
print(user_dict)
```
-输出的就是 Python **字典**:
+输出的就是 Python `dict`:
```Python
{
@@ -61,9 +61,9 @@ print(user_dict)
}
```
-#### 解包 `dict`
+#### 解包 `dict` { #unpacking-a-dict }
-把**字典** `user_dict` 以 `**user_dict` 形式传递给函数(或类),Python 会执行**解包**操作。它会把 `user_dict` 的键和值作为关键字参数直接传递。
+把 `dict`(如 `user_dict`)以 `**user_dict` 形式传递给函数(或类),Python 会执行“解包”。它会把 `user_dict` 的键和值作为关键字参数直接传递。
因此,接着上面的 `user_dict` 继续编写如下代码:
@@ -82,7 +82,7 @@ UserInDB(
)
```
-或更精准,直接把可能会用到的内容与 `user_dict` 一起使用:
+或更精准,直接使用 `user_dict`(无论它将来包含什么字段):
```Python
UserInDB(
@@ -93,31 +93,31 @@ UserInDB(
)
```
-#### 用其它模型中的内容生成 Pydantic 模型
+#### 用另一个模型的内容生成 Pydantic 模型 { #a-pydantic-model-from-the-contents-of-another }
-上例中 ,从 `user_in.dict()` 中得到了 `user_dict`,下面的代码:
+上例中 ,从 `user_in.model_dump()` 中得到了 `user_dict`,下面的代码:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
UserInDB(**user_dict)
```
等效于:
```Python
-UserInDB(**user_in.dict())
+UserInDB(**user_in.model_dump())
```
-……因为 `user_in.dict()` 是字典,在传递给 `UserInDB` 时,把 `**` 加在 `user_in.dict()` 前,可以让 Python 进行**解包**。
+……因为 `user_in.model_dump()` 是 `dict`,在传递给 `UserInDB` 时,把 `**` 加在 `user_in.model_dump()` 前,可以让 Python 进行解包。
这样,就可以用其它 Pydantic 模型中的数据生成 Pydantic 模型。
-#### 解包 `dict` 和更多关键字
+#### 解包 `dict` 并添加额外关键字参数 { #unpacking-a-dict-and-extra-keywords }
接下来,继续添加关键字参数 `hashed_password=hashed_password`,例如:
```Python
-UserInDB(**user_in.dict(), hashed_password=hashed_password)
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
```
……输出结果如下:
@@ -132,68 +132,80 @@ UserInDB(
)
```
-/// warning | 警告
+/// warning
-辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。
+配套的辅助函数 `fake_password_hasher` 和 `fake_save_user` 仅用于演示可能的数据流,当然并不提供真实的安全性。
///
-## 减少重复
+## 减少重复 { #reduce-duplication }
-**FastAPI** 的核心思想就是减少代码重复。
+减少代码重复是 **FastAPI** 的核心思想之一。
代码重复会导致 bug、安全问题、代码失步等问题(更新了某个位置的代码,但没有同步更新其它位置的代码)。
上面的这些模型共享了大量数据,拥有重复的属性名和类型。
-FastAPI 可以做得更好。
+我们可以做得更好。
-声明 `UserBase` 模型作为其它模型的基类。然后,用该类衍生出继承其属性(类型声明、验证等)的子类。
+声明 `UserBase` 模型作为其它模型的基类。然后,用该类衍生出继承其属性(类型声明、校验等)的子类。
所有数据转换、校验、文档等功能仍将正常运行。
-这样,就可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码)。
-
-通过这种方式,可以只声明模型之间的区别(分别包含明文密码、哈希密码,以及无密码的模型)。
+这样,就可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码):
{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
-## `Union` 或者 `anyOf`
+## `Union` 或 `anyOf` { #union-or-anyof }
-响应可以声明为两种类型的 `Union` 类型,即该响应可以是两种类型中的任意类型。
+响应可以声明为两个或多个类型的 `Union`,即该响应可以是这些类型中的任意一种。
-在 OpenAPI 中可以使用 `anyOf` 定义。
+在 OpenAPI 中会用 `anyOf` 表示。
为此,请使用 Python 标准类型提示 `typing.Union`:
-/// note | 笔记
+/// note
-定义 `Union` 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。
+定义 `Union` 类型时,要把更具体的类型写在前面,然后是不太具体的类型。下例中,更具体的 `PlaneItem` 位于 `Union[PlaneItem, CarItem]` 中的 `CarItem` 之前。
///
{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
-## 模型列表
+### Python 3.10 中的 `Union` { #union-in-python-3-10 }
-使用同样的方式也可以声明由对象列表构成的响应。
+在这个示例中,我们把 `Union[PlaneItem, CarItem]` 作为参数 `response_model` 的值传入。
-为此,请使用标准的 Python `typing.List`:
+因为这是作为“参数的值”而不是放在“类型注解”中,所以即使在 Python 3.10 也必须使用 `Union`。
+
+如果是在类型注解中,我们就可以使用竖线:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+但如果把它写成赋值 `response_model=PlaneItem | CarItem`,就会报错,因为 Python 会尝试在 `PlaneItem` 和 `CarItem` 之间执行一个“无效的运算”,而不是把它当作类型注解来解析。
+
+## 模型列表 { #list-of-models }
+
+同样地,你可以声明由对象列表构成的响应。
+
+为此,请使用标准的 Python `typing.List`(在 Python 3.9+ 中也可以直接用 `list`):
{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *}
-## 任意 `dict` 构成的响应
+## 任意 `dict` 的响应 { #response-with-arbitrary-dict }
-任意的 `dict` 都能用于声明响应,只要声明键和值的类型,无需使用 Pydantic 模型。
+你也可以使用普通的任意 `dict` 来声明响应,只需声明键和值的类型,无需使用 Pydantic 模型。
-事先不知道可用的字段 / 属性名时(Pydantic 模型必须知道字段是什么),这种方式特别有用。
+如果你事先不知道有效的字段/属性名(Pydantic 模型需要预先知道字段)时,这很有用。
-此时,可以使用 `typing.Dict`:
+此时,可以使用 `typing.Dict`(在 Python 3.9+ 中也可以直接用 `dict`):
{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *}
-## 小结
+## 小结 { #recap }
-针对不同场景,可以随意使用不同的 Pydantic 模型继承定义的基类。
+针对不同场景,可以随意使用不同的 Pydantic 模型并通过继承复用。
-实体必须具有不同的**状态**时,不必为不同状态的实体单独定义数据模型。例如,用户**实体**就有包含 `password`、包含 `password_hash` 以及不含密码等多种状态。
+当一个实体需要具备不同的“状态”时,无需只为该实体定义一个数据模型。例如,用户“实体”就可能有包含 `password`、包含 `password_hash` 以及不含密码等多种状态。
diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md
index 2d7c35c8c..5d01884b8 100644
--- a/docs/zh/docs/tutorial/first-steps.md
+++ b/docs/zh/docs/tutorial/first-steps.md
@@ -1,8 +1,8 @@
-# 第一步
+# 第一步 { #first-steps }
最简单的 FastAPI 文件可能像下面这样:
-{* ../../docs_src/first_steps/tutorial001.py *}
+{* ../../docs_src/first_steps/tutorial001_py39.py *}
将其复制到 `main.py` 文件中。
@@ -56,7 +56,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
该行显示了你的应用在本机所提供服务的 URL 地址。
-### 查看
+### 查看 { #check-it }
打开浏览器访问 http://127.0.0.1:8000。
@@ -66,7 +66,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
{"message": "Hello World"}
```
-### 交互式 API 文档
+### 交互式 API 文档 { #interactive-api-docs }
跳转到 http://127.0.0.1:8000/docs。
@@ -74,7 +74,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

-### 可选的 API 文档
+### 可选的 API 文档 { #alternative-api-docs }
前往 http://127.0.0.1:8000/redoc。
@@ -82,35 +82,35 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

-### OpenAPI
+### OpenAPI { #openapi }
**FastAPI** 使用定义 API 的 **OpenAPI** 标准将你的所有 API 转换成「模式」。
-#### 「模式」
+#### 「模式」 { #schema }
「模式」是对事物的一种定义或描述。它并非具体的实现代码,而只是抽象的描述。
-#### API「模式」
+#### API「模式」 { #api-schema }
在这种场景下,OpenAPI 是一种规定如何定义 API 模式的规范。
「模式」的定义包括你的 API 路径,以及它们可能使用的参数等等。
-#### 数据「模式」
+#### 数据「模式」 { #data-schema }
「模式」这个术语也可能指的是某些数据比如 JSON 的结构。
在这种情况下,它可以表示 JSON 的属性及其具有的数据类型,等等。
-#### OpenAPI 和 JSON Schema
+#### OpenAPI 和 JSON Schema { #openapi-and-json-schema }
OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送和接收的数据的定义(或称为「模式」),这些定义通过 JSON 数据模式标准 **JSON Schema** 所生成。
-#### 查看 `openapi.json`
+#### 查看 `openapi.json` { #check-the-openapi-json }
如果你对原始的 OpenAPI 模式长什么样子感到好奇,FastAPI 自动生成了包含所有 API 描述的 JSON(模式)。
-你可以直接在:http://127.0.0.1:8000/openapi.json 看到它。
+你可以直接在:http://127.0.0.1:800api.json 看到它。
它将显示以如下内容开头的 JSON:
@@ -135,7 +135,7 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送
...
```
-#### OpenAPI 的用途
+#### OpenAPI 的用途 { #what-is-openapi-for }
驱动 FastAPI 内置的 2 个交互式文档系统的正是 OpenAPI 模式。
@@ -143,11 +143,47 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送
你还可以使用它自动生成与你的 API 进行通信的客户端代码。例如 web 前端,移动端或物联网嵌入程序。
-## 分步概括
+### 部署你的应用(可选) { #deploy-your-app-optional }
-### 步骤 1:导入 `FastAPI`
+你可以选择将 FastAPI 应用部署到 FastAPI Cloud,如果还没有,先去加入候补名单。🚀
-{* ../../docs_src/first_steps/tutorial001.py hl[1] *}
+如果你已经拥有 **FastAPI Cloud** 账户(我们从候补名单邀请了你 😉),你可以用一条命令部署应用。
+
+部署前,先确保已登录:
+
+
-## 禁止额外的 Headers
+## 禁止额外的 Headers { #forbid-extra-headers }
在某些特殊使用情况下(可能并不常见),您可能希望**限制**您想要接收的 headers。
@@ -51,6 +51,22 @@
}
```
-## 总结
+## 禁用下划线转换 { #disable-convert-underscores }
+
+与常规的 header 参数相同,当参数名中包含下划线时,会**自动转换为连字符**。
+
+例如,如果你的代码中有一个名为 `save_data` 的 header 参数,那么预期的 HTTP 头将是 `save-data`,并且在文档中也会以这种形式显示。
+
+如果由于某些原因你需要禁用这种自动转换,你也可以在用于 header 参数的 Pydantic 模型中进行设置。
+
+{* ../../docs_src/header_param_models/tutorial003_an_py310.py hl[19] *}
+
+/// warning | 警告
+
+在将 `convert_underscores` 设为 `False` 之前,请注意某些 HTTP 代理和服务器不允许使用带下划线的 headers。
+
+///
+
+## 总结 { #summary }
您可以使用 **Pydantic 模型**在 **FastAPI** 中声明 **headers**。😎
diff --git a/docs/zh/docs/tutorial/header-params.md b/docs/zh/docs/tutorial/header-params.md
index 19bb455cf..ccb88ae7f 100644
--- a/docs/zh/docs/tutorial/header-params.md
+++ b/docs/zh/docs/tutorial/header-params.md
@@ -1,14 +1,14 @@
-# Header 参数
+# Header 参数 { #header-parameters }
定义 `Header` 参数的方式与定义 `Query`、`Path`、`Cookie` 参数相同。
-## 导入 `Header`
+## 导入 `Header` { #import-header }
首先,导入 `Header`:
{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *}
-## 声明 `Header` 参数
+## 声明 `Header` 参数 { #declare-header-parameters }
然后,使用和 `Path`、`Query`、`Cookie` 一样的结构定义 header 参数。
@@ -24,13 +24,13 @@
///
-/// info | 说明
+/// info | 信息
必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。
///
-## 自动转换
+## 自动转换 { #automatic-conversion }
`Header` 比 `Path`、`Query` 和 `Cookie` 提供了更多功能。
@@ -54,7 +54,7 @@
///
-## 重复的请求头
+## 重复的请求头 { #duplicate-headers }
有时,可能需要接收重复的请求头。即同一个请求头有多个值。
@@ -84,7 +84,7 @@ X-Token: bar
}
```
-## 小结
+## 小结 { #recap }
使用 `Header` 声明请求头的方式与 `Query`、`Path` 、`Cookie` 相同。
diff --git a/docs/zh/docs/tutorial/index.md b/docs/zh/docs/tutorial/index.md
index 3ca927337..793458302 100644
--- a/docs/zh/docs/tutorial/index.md
+++ b/docs/zh/docs/tutorial/index.md
@@ -1,12 +1,12 @@
-# 教程 - 用户指南
+# 教程 - 用户指南 { #tutorial-user-guide }
本教程将一步步向您展示如何使用 **FastAPI** 的绝大部分特性。
-各个章节的内容循序渐进,但是又围绕着单独的主题,所以您可以直接跳转到某个章节以解决您的特定需求。
+各个章节的内容循序渐进,但是又围绕着单独的主题,所以您可以直接跳转到某个章节以解决您的特定 API 需求。
本教程同样可以作为将来的参考手册,所以您可以随时回到本教程并查阅您需要的内容。
-## 运行代码
+## 运行代码 { #run-the-code }
所有代码片段都可以复制后直接使用(它们实际上是经过测试的 Python 文件)。
@@ -58,7 +58,7 @@ $ fastapi dev
-/// note
+/// note | 注意
-当您使用 `pip install "fastapi[standard]"` 进行安装时,它会附带一些默认的可选标准依赖项。
+当您使用 `pip install "fastapi[standard]"` 安装时,它会附带一些默认的可选标准依赖项,其中包括 `fastapi-cloud-cli`,它可以让您部署到 FastAPI Cloud。
如果您不想安装这些可选依赖,可以选择安装 `pip install fastapi`。
+如果您想安装标准依赖但不包含 `fastapi-cloud-cli`,可以使用 `pip install "fastapi[standard-no-fastapi-cloud-cli]"` 安装。
+
///
-## 进阶用户指南
+## 进阶用户指南 { #advanced-user-guide }
在本**教程-用户指南**之后,您可以阅读**进阶用户指南**。
diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md
index d29a1e6d0..6ec7e9add 100644
--- a/docs/zh/docs/tutorial/metadata.md
+++ b/docs/zh/docs/tutorial/metadata.md
@@ -1,28 +1,28 @@
-# 元数据和文档 URL
+# 元数据和文档 URL { #metadata-and-docs-urls }
你可以在 FastAPI 应用程序中自定义多个元数据配置。
-## API 元数据
+## API 元数据 { #metadata-for-api }
你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段:
| 参数 | 类型 | 描述 |
|------------|------|-------------|
| `title` | `str` | API 的标题。 |
-| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。. |
-| `description` | `str` | API 的简短描述。可以使用Markdown。 |
-| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 |
+| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。 |
+| `description` | `str` | API 的简短描述。可以使用 Markdown。 |
+| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0`。 |
| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 |
-| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。contact 字段参数 Type 描述 namestr联系人/组织的识别名称。 urlstr指向联系信息的 URL。必须采用 URL 格式。 emailstr联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。 license_info 字段参数 类型 描述 namestr必须的 (如果设置了 license_info). 用于 API 的许可证名称。identifierstr一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。urlstr用于 API 的许可证的 URL。必须采用 URL 格式。 contact 字段参数 类型 描述 namestr联系人/组织的识别名称。 urlstr指向联系信息的 URL。必须采用 URL 格式。 emailstr联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。 license_info 字段参数 类型 描述 namestr必须(如果设置了 license_info)。用于 API 的许可证名称。identifierstrAPI 的 SPDX 许可证表达式。字段 identifier 与字段 url 互斥。自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。urlstr用于 API 的许可证的 URL。必须采用 URL 格式。
-## 标签元数据
+## 许可证标识符 { #license-identifier }
-### 创建标签元数据
+自 OpenAPI 3.1.0 和 FastAPI 0.99.0 起,你还可以在 `license_info` 中使用 `identifier` 而不是 `url`。
+
+例如:
+
+{* ../../docs_src/metadata/tutorial001_1_py39.py hl[31] *}
+
+## 标签元数据 { #metadata-for-tags }
+
+你也可以通过参数 `openapi_tags` 为用于分组路径操作的不同标签添加额外的元数据。
+
+它接收一个列表,列表中每个标签对应一个字典。
+
+每个字典可以包含:
+
+- `name`(必填):一个 `str`,与在你的*路径操作*和 `APIRouter` 的 `tags` 参数中使用的标签名相同。
+- `description`:一个 `str`,该标签的简短描述。可以使用 Markdown,并会显示在文档 UI 中。
+- `externalDocs`:一个 `dict`,描述外部文档,包含:
+ - `description`:一个 `str`,该外部文档的简短描述。
+ - `url`(必填):一个 `str`,该外部文档的 URL。
+
+### 创建标签元数据 { #create-metadata-for-tags }
让我们在带有标签的示例中为 `users` 和 `items` 试一下。
创建标签元数据并把它传递给 `openapi_tags` 参数:
-{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *}
+{* ../../docs_src/metadata/tutorial004_py39.py hl[3:16,18] *}
注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。
@@ -48,11 +68,11 @@
///
-### 使用你的标签
+### 使用你的标签 { #use-your-tags }
将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签:
-{* ../../docs_src/metadata/tutorial004.py hl[21,26] *}
+{* ../../docs_src/metadata/tutorial004_py39.py hl[21,26] *}
/// info | 信息
@@ -60,19 +80,19 @@
///
-### 查看文档
+### 查看文档 { #check-the-docs }
如果你现在查看文档,它们会显示所有附加的元数据:
-### 标签顺序
+### 标签顺序 { #order-of-tags }
每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。
例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。
-## OpenAPI URL
+## OpenAPI URL { #openapi-url }
默认情况下,OpenAPI 模式服务于 `/openapi.json`。
@@ -80,21 +100,21 @@
例如,将其设置为服务于 `/api/v1/openapi.json`:
-{* ../../docs_src/metadata/tutorial002.py hl[3] *}
+{* ../../docs_src/metadata/tutorial002_py39.py hl[3] *}
如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。
-## 文档 URLs
+## 文档 URLs { #docs-urls }
你可以配置两个文档用户界面,包括:
-* **Swagger UI**:服务于 `/docs`。
- * 可以使用参数 `docs_url` 设置它的 URL。
- * 可以通过设置 `docs_url=None` 禁用它。
-* ReDoc:服务于 `/redoc`。
- * 可以使用参数 `redoc_url` 设置它的 URL。
- * 可以通过设置 `redoc_url=None` 禁用它。
+- **Swagger UI**:服务于 `/docs`。
+ - 可以使用参数 `docs_url` 设置它的 URL。
+ - 可以通过设置 `docs_url=None` 禁用它。
+- **ReDoc**:服务于 `/redoc`。
+ - 可以使用参数 `redoc_url` 设置它的 URL。
+ - 可以通过设置 `redoc_url=None` 禁用它。
例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc:
-{* ../../docs_src/metadata/tutorial003.py hl[3] *}
+{* ../../docs_src/metadata/tutorial003_py39.py hl[3] *}
diff --git a/docs/zh/docs/tutorial/middleware.md b/docs/zh/docs/tutorial/middleware.md
index 5608c4ee1..a3f833d78 100644
--- a/docs/zh/docs/tutorial/middleware.md
+++ b/docs/zh/docs/tutorial/middleware.md
@@ -1,66 +1,95 @@
-# 中间件
+# 中间件 { #middleware }
-你可以向 **FastAPI** 应用添加中间件.
+你可以向 **FastAPI** 应用添加中间件。
-"中间件"是一个函数,它在每个**请求**被特定的*路径操作*处理之前,以及在每个**响应**返回之前工作.
+“中间件”是一个函数,它会在每个特定的*路径操作*处理每个**请求**之前运行,也会在返回每个**响应**之前运行。
-* 它接收你的应用程序的每一个**请求**.
-* 然后它可以对这个**请求**做一些事情或者执行任何需要的代码.
-* 然后它将**请求**传递给应用程序的其他部分 (通过某种*路径操作*).
-* 然后它获取应用程序生产的**响应** (通过某种*路径操作*).
-* 它可以对该**响应**做些什么或者执行任何需要的代码.
-* 然后它返回这个 **响应**.
+* 它接收你的应用的每一个**请求**。
+* 然后它可以对这个**请求**做一些事情或者执行任何需要的代码。
+* 然后它将这个**请求**传递给应用程序的其他部分(某个*路径操作*)处理。
+* 之后它获取应用程序生成的**响应**(由某个*路径操作*产生)。
+* 它可以对该**响应**做一些事情或者执行任何需要的代码。
+* 然后它返回这个**响应**。
/// note | 技术细节
-如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行.
+如果你有使用 `yield` 的依赖,依赖中的退出代码会在中间件之后运行。
-如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行.
+如果有任何后台任务(会在[后台任务](background-tasks.md){.internal-link target=_blank}一节中介绍,你稍后会看到),它们会在所有中间件之后运行。
///
-## 创建中间件
+## 创建中间件 { #create-a-middleware }
-要创建中间件你可以在函数的顶部使用装饰器 `@app.middleware("http")`.
+要创建中间件,你可以在函数的顶部使用装饰器 `@app.middleware("http")`。
-中间件参数接收如下参数:
+中间件函数会接收:
-* `request`.
-* 一个函数 `call_next` 它将接收 `request` 作为参数.
- * 这个函数将 `request` 传递给相应的 *路径操作*.
- * 然后它将返回由相应的*路径操作*生成的 `response`.
-* 然后你可以在返回 `response` 前进一步修改它.
+* `request`。
+* 一个函数 `call_next`,它会把 `request` 作为参数接收。
+ * 这个函数会把 `request` 传递给相应的*路径操作*。
+ * 然后它返回由相应*路径操作*生成的 `response`。
+* 在返回之前,你可以进一步修改 `response`。
-{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *}
+{* ../../docs_src/middleware/tutorial001_py39.py hl[8:9,11,14] *}
/// tip
-请记住可以 用'X-' 前缀添加专有自定义请求头.
+请记住可以使用 `X-` 前缀添加专有自定义请求头。
-但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中.
+但是如果你有希望让浏览器中的客户端可见的自定义请求头,你需要把它们加到你的 CORS 配置([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})的 `expose_headers` 参数中,参见 Starlette 的 CORS 文档。
///
/// note | 技术细节
-你也可以使用 `from starlette.requests import Request`.
+你也可以使用 `from starlette.requests import Request`。
-**FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette.
+**FastAPI** 为了开发者方便提供了该对象,但它直接来自 Starlette。
///
-### 在 `response` 的前和后
+### 在 `response` 之前与之后 { #before-and-after-the-response }
-在任何*路径操作*收到`request`前,可以添加要和请求一起运行的代码.
+你可以在任何*路径操作*接收 `request` 之前,添加要与该 `request` 一起运行的代码。
-也可以在*响应*生成但是返回之前添加代码.
+也可以在生成 `response` 之后、返回之前添加代码。
-例如你可以添加自定义请求头 `X-Process-Time` 包含以秒为单位的接收请求和生成响应的时间:
+例如,你可以添加一个自定义请求头 `X-Process-Time`,其值为处理请求并生成响应所花费的秒数:
-{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *}
+{* ../../docs_src/middleware/tutorial001_py39.py hl[10,12:13] *}
-## 其他中间件
+/// tip
-你可以稍后在 [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}阅读更多关于中间件的教程.
+这里我们使用 `time.perf_counter()` 而不是 `time.time()`,因为在这类场景中它可能更精确。🤓
-你将在下一节中学习如何使用中间件处理 CORS .
+///
+
+## 多个中间件的执行顺序 { #multiple-middleware-execution-order }
+
+当你使用 `@app.middleware()` 装饰器或 `app.add_middleware()` 方法添加多个中间件时,每个新中间件都会包裹应用,形成一个栈。最后添加的中间件是“最外层”的,最先添加的是“最内层”的。
+
+在请求路径上,最外层的中间件先运行。
+
+在响应路径上,它最后运行。
+
+例如:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+这会产生如下执行顺序:
+
+* 请求:MiddlewareB → MiddlewareA → 路由
+
+* 响应:路由 → MiddlewareA → MiddlewareB
+
+这种栈式行为确保中间件按可预测且可控的顺序执行。
+
+## 其他中间件 { #other-middlewares }
+
+你可以稍后在[高级用户指南:高级中间件](../advanced/middleware.md){.internal-link target=_blank}中阅读更多关于其他中间件的内容。
+
+你将在下一节中了解如何使用中间件处理 CORS。
diff --git a/docs/zh/docs/tutorial/path-operation-configuration.md b/docs/zh/docs/tutorial/path-operation-configuration.md
index adeca2d3f..49b7baabc 100644
--- a/docs/zh/docs/tutorial/path-operation-configuration.md
+++ b/docs/zh/docs/tutorial/path-operation-configuration.md
@@ -1,66 +1,76 @@
-# 路径操作配置
+# 路径操作配置 { #path-operation-configuration }
*路径操作装饰器*支持多种配置参数。
/// warning | 警告
-注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。
+注意:以下参数应直接传递给*路径操作装饰器*,不能传递给*路径操作函数*。
///
-## `status_code` 状态码
+## 响应状态码 { #response-status-code }
-`status_code` 用于定义*路径操作*响应中的 HTTP 状态码。
+可以在*路径操作*的响应中定义(HTTP)`status_code`。
-可以直接传递 `int` 代码, 比如 `404`。
+可以直接传递 `int` 代码,比如 `404`。
-如果记不住数字码的涵义,也可以用 `status` 的快捷常量:
+如果记不住数字码的含义,也可以用 `status` 的快捷常量:
-{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *}
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
-状态码在响应中使用,并会被添加到 OpenAPI 概图。
+该状态码会用于响应中,并会被添加到 OpenAPI 概图。
/// note | 技术细节
也可以使用 `from starlette import status` 导入状态码。
-**FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。
+**FastAPI** 提供的 `fastapi.status` 与 `starlette.status` 相同,方便你作为开发者使用。实际上它直接来自 Starlette。
///
-## `tags` 参数
+## 标签 { #tags }
-`tags` 参数的值是由 `str` 组成的 `list` (一般只有一个 `str` ),`tags` 用于为*路径操作*添加标签:
+可以通过传入由 `str` 组成的 `list`(通常只有一个 `str`)的参数 `tags`,为*路径操作*添加标签:
-{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *}
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
OpenAPI 概图会自动添加标签,供 API 文档接口使用:
-## `summary` 和 `description` 参数
+### 使用 Enum 的标签 { #tags-with-enums }
-路径装饰器还支持 `summary` 和 `description` 这两个参数:
+如果你的应用很大,可能会积累出很多标签,你会希望确保相关的*路径操作*始终使用相同的标签。
-{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *}
+这种情况下,把标签存放在 `Enum` 中会更合适。
-## 文档字符串(`docstring`)
+**FastAPI** 对此的支持与使用普通字符串相同:
-描述内容比较长且占用多行时,可以在函数的 docstring 中声明*路径操作*的描述,**FastAPI** 支持从文档字符串中读取描述内容。
+{* ../../docs_src/path_operation_configuration/tutorial002b_py39.py hl[1,8:10,13,18] *}
+
+## 摘要和描述 { #summary-and-description }
+
+可以添加 `summary` 和 `description`:
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## 从 docstring 获取描述 { #description-from-docstring }
+
+描述内容比较长且占用多行时,可以在函数的 docstring 中声明*路径操作*的描述,**FastAPI** 会从中读取。
文档字符串支持 Markdown,能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进。
-{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *}
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
下图为 Markdown 文本在 API 文档中的显示效果:
-## 响应描述
+## 响应描述 { #response-description }
`response_description` 参数用于定义响应的描述说明:
-{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *}
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
/// info | 说明
@@ -78,11 +88,11 @@ OpenAPI 规定每个*路径操作*都要有响应描述。
-## 弃用*路径操作*
+## 弃用*路径操作* { #deprecate-a-path-operation }
`deprecated` 参数可以把*路径操作*标记为弃用,无需直接删除:
-{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
API 文档会把该路径操作标记为弃用:
@@ -92,6 +102,6 @@ API 文档会把该路径操作标记为弃用:
-## 小结
+## 小结 { #recap }
-通过传递参数给*路径操作装饰器* ,即可轻松地配置*路径操作*、添加元数据。
+通过传递参数给*路径操作装饰器*,即可轻松地配置*路径操作*、添加元数据。
diff --git a/docs/zh/docs/tutorial/path-params-numeric-validations.md b/docs/zh/docs/tutorial/path-params-numeric-validations.md
index ff6242835..ff8b1762c 100644
--- a/docs/zh/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/zh/docs/tutorial/path-params-numeric-validations.md
@@ -1,91 +1,128 @@
-# 路径参数和数值校验
+# 路径参数和数值校验 { #path-parameters-and-numeric-validations }
与使用 `Query` 为查询参数声明更多的校验和元数据的方式相同,你也可以使用 `Path` 为路径参数声明相同类型的校验和元数据。
-## 导入 Path
+## 导入 `Path` { #import-path }
-首先,从 `fastapi` 导入 `Path`:
+首先,从 `fastapi` 导入 `Path`,并导入 `Annotated`:
{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
-## 声明元数据
+/// info | 信息
-你可以声明与 `Query` 相同的所有参数。
+FastAPI 在 0.95.0 版本添加了对 `Annotated` 的支持(并开始推荐使用它)。
-例如,要声明路径参数 `item_id`的 `title` 元数据值,你可以输入:
+如果你使用的是更旧的版本,尝试使用 `Annotated` 会报错。
-{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
-
-/// note
-
-路径参数总是必需的,因为它必须是路径的一部分。
-
-所以,你应该在声明时使用 `...` 将其标记为必需参数。
-
-然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。
+请确保在使用 `Annotated` 之前,将 FastAPI 版本[升级](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}到至少 0.95.1。
///
-## 按需对参数排序
+## 声明元数据 { #declare-metadata }
-假设你想要声明一个必需的 `str` 类型查询参数 `q`。
+你可以声明与 `Query` 相同的所有参数。
-而且你不需要为该参数声明任何其他内容,所以实际上你并不需要使用 `Query`。
+例如,要为路径参数 `item_id` 声明 `title` 元数据值,你可以这样写:
-但是你仍然需要使用 `Path` 来声明路径参数 `item_id`。
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
-如果你将带有「默认值」的参数放在没有「默认值」的参数之前,Python 将会报错。
+/// note | 注意
-但是你可以对其重新排序,并将不带默认值的值(查询参数 `q`)放到最前面。
+路径参数总是必需的,因为它必须是路径的一部分。即使你将其声明为 `None` 或设置了默认值,也不会产生任何影响,它依然始终是必需参数。
-对 **FastAPI** 来说这无关紧要。它将通过参数的名称、类型和默认值声明(`Query`、`Path` 等)来检测参数,而不在乎参数的顺序。
+///
+
+## 按需对参数排序 { #order-the-parameters-as-you-need }
+
+/// tip | 提示
+
+如果你使用 `Annotated`,这点可能不那么重要或必要。
+
+///
+
+假设你想要将查询参数 `q` 声明为必需的 `str`。
+
+并且你不需要为该参数声明其他内容,所以实际上不需要用到 `Query`。
+
+但是你仍然需要为路径参数 `item_id` 使用 `Path`。并且出于某些原因你不想使用 `Annotated`。
+
+如果你将带有“默认值”的参数放在没有“默认值”的参数之前,Python 会报错。
+
+不过你可以重新排序,让没有默认值的参数(查询参数 `q`)放在最前面。
+
+对 **FastAPI** 来说这无关紧要。它会通过参数的名称、类型和默认值声明(`Query`、`Path` 等)来检测参数,而不关心顺序。
因此,你可以将函数声明为:
-{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
-## 按需对参数排序的技巧
+但请记住,如果你使用 `Annotated`,你就不会遇到这个问题,因为你没有使用 `Query()` 或 `Path()` 作为函数参数的默认值。
-如果你想不使用 `Query` 声明没有默认值的查询参数 `q`,同时使用 `Path` 声明路径参数 `item_id`,并使它们的顺序与上面不同,Python 对此有一些特殊的语法。
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *}
-传递 `*` 作为函数的第一个参数。
+## 按需对参数排序的技巧 { #order-the-parameters-as-you-need-tricks }
-Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参数都应作为关键字参数(键值对),也被称为 kwargs,来调用。即使它们没有默认值。
+/// tip | 提示
-{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+如果你使用 `Annotated`,这点可能不那么重要或必要。
-## 数值校验:大于等于
+///
-使用 `Query` 和 `Path`(以及你将在后面看到的其他类)可以声明字符串约束,但也可以声明数值约束。
+这里有一个小技巧,可能会很方便,但你并不会经常需要它。
-像下面这样,添加 `ge=1` 后,`item_id` 将必须是一个大于(`g`reater than)或等于(`e`qual)`1` 的整数。
+如果你想要:
-{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *}
+* 在没有 `Query` 且没有任何默认值的情况下声明查询参数 `q`
+* 使用 `Path` 声明路径参数 `item_id`
+* 让它们的顺序与上面不同
+* 不使用 `Annotated`
-## 数值校验:大于和小于等于
+...Python 为此有一个小的特殊语法。
-同样的规则适用于:
+在函数的第一个参数位置传入 `*`。
+
+Python 不会对这个 `*` 做任何事,但它会知道之后的所有参数都应该作为关键字参数(键值对)来调用,也被称为 kwargs。即使它们没有默认值。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+
+### 使用 `Annotated` 更好 { #better-with-annotated }
+
+请记住,如果你使用 `Annotated`,因为你没有使用函数参数的默认值,所以你不会有这个问题,你大概率也不需要使用 `*`。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+
+## 数值校验:大于等于 { #number-validations-greater-than-or-equal }
+
+使用 `Query` 和 `Path`(以及你稍后会看到的其他类)你可以声明数值约束。
+
+在这里,使用 `ge=1` 后,`item_id` 必须是一个整数,值要「`g`reater than or `e`qual」1。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## 数值校验:大于和小于等于 { #number-validations-greater-than-and-less-than-or-equal }
+
+同样适用于:
* `gt`:大于(`g`reater `t`han)
* `le`:小于等于(`l`ess than or `e`qual)
-{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
-## 数值校验:浮点数、大于和小于
+## 数值校验:浮点数、大于和小于 { #number-validations-floats-greater-than-and-less-than }
数值校验同样适用于 `float` 值。
-能够声明 gt 而不仅仅是 ge 在这个前提下变得重要起来。例如,你可以要求一个值必须大于 `0`,即使它小于 `1`。
+能够声明 gt 而不仅仅是 ge 在这里变得很重要。例如,你可以要求一个值必须大于 `0`,即使它小于 `1`。
-因此,`0.5` 将是有效值。但是 `0.0`或 `0` 不是。
+因此,`0.5` 将是有效值。但是 `0.0` 或 `0` 不是。
-对于 lt 也是一样的。
+对于 lt 也是一样的。
-{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
-## 总结
+## 总结 { #recap }
-你能够以与 [查询参数和字符串校验](query-params-str-validations.md){.internal-link target=_blank} 相同的方式使用 `Query`、`Path`(以及其他你还没见过的类)声明元数据和字符串校验。
+你能够以与[查询参数和字符串校验](query-params-str-validations.md){.internal-link target=_blank}相同的方式使用 `Query`、`Path`(以及其他你还没见过的类)声明元数据和字符串校验。
而且你还可以声明数值校验:
@@ -94,24 +131,24 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
* `lt`:小于(`l`ess `t`han)
* `le`:小于等于(`l`ess than or `e`qual)
-/// info
+/// info | 信息
-`Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。
+`Query`、`Path` 以及你后面会看到的其他类,都是一个通用 `Param` 类的子类。
-而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。
+它们都共享相同的参数,用于你已看到的额外校验和元数据。
///
/// note | 技术细节
-当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。
+当你从 `fastapi` 导入 `Query`、`Path` 和其他对象时,它们实际上是函数。
-当被调用时,它们返回同名类的实例。
+当被调用时,它们会返回同名类的实例。
-如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。
+也就是说,你导入的是函数 `Query`。当你调用它时,它会返回一个同名的 `Query` 类的实例。
-因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
+之所以使用这些函数(而不是直接使用类),是为了让你的编辑器不要因为它们的类型而标记错误。
-这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
+这样你就可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
///
diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md
index ac9df0831..fa4c9514a 100644
--- a/docs/zh/docs/tutorial/path-params.md
+++ b/docs/zh/docs/tutorial/path-params.md
@@ -1,10 +1,10 @@
-# 路径参数
+# 路径参数 { #path-parameters }
-FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**变量**):
+你可以使用与 Python 字符串格式化相同的语法声明路径“参数”或“变量”:
-{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
-这段代码把路径参数 `item_id` 的值传递给路径函数的参数 `item_id`。
+路径参数 `item_id` 的值会作为参数 `item_id` 传递给你的函数。
运行示例并访问 http://127.0.0.1:8000/items/foo,可获得如下响应:
@@ -12,11 +12,11 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
{"item_id":"foo"}
```
-## 声明路径参数的类型
+## 声明路径参数的类型 { #path-parameters-with-types }
-使用 Python 标准类型注解,声明路径操作函数中路径参数的类型。
+使用 Python 标准类型注解,声明路径操作函数中路径参数的类型:
-{* ../../docs_src/path_params/tutorial002.py hl[7] *}
+{* ../../docs_src/path_params/tutorial002_py39.py hl[7] *}
本例把 `item_id` 的类型声明为 `int`。
@@ -26,7 +26,7 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
///
-## 数据转换
+## 数据转换 { #data-conversion }
运行示例并访问 http://127.0.0.1:8000/items/3,返回的响应如下:
@@ -42,56 +42,57 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
///
-## 数据校验
+## 数据校验 { #data-validation }
通过浏览器访问 http://127.0.0.1:8000/items/foo,接收如下 HTTP 错误信息:
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
}
```
-这是因为路径参数 `item_id` 的值 (`"foo"`)的类型不是 `int`。
+这是因为路径参数 `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
/// check | 检查
-**FastAPI** 使用 Python 类型声明实现了数据校验。
+**FastAPI** 使用同样的 Python 类型声明实现了数据校验。
-注意,上面的错误清晰地指出了未通过校验的具体原因。
+注意,上面的错误清晰地指出了未通过校验的具体位置。
这在开发调试与 API 交互的代码时非常有用。
///
-## 查看文档
+## 文档 { #documentation }
-访问 http://127.0.0.1:8000/docs,查看自动生成的 API 文档:
+访问 http://127.0.0.1:8000/docs,查看自动生成的交互式 API 文档:
/// check | 检查
-还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。
+还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)自动交互式文档。
注意,路径参数的类型是整数。
///
-## 基于标准的好处,备选文档
+## 基于标准的好处,备选文档 { #standards-based-benefits-alternative-documentation }
-**FastAPI** 使用 OpenAPI 生成概图,所以能兼容很多工具。
+**FastAPI** 使用 OpenAPI 生成概图,所以能兼容很多工具。
因此,**FastAPI** 还内置了 ReDoc 生成的备选 API 文档,可在此查看 http://127.0.0.1:8000/redoc:
@@ -99,15 +100,15 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
同样,还有很多兼容工具,包括多种语言的代码生成工具。
-## Pydantic
+## Pydantic { #pydantic }
FastAPI 充分地利用了 Pydantic 的优势,用它在后台校验数据。众所周知,Pydantic 擅长的就是数据校验。
同样,`str`、`float`、`bool` 以及很多复合数据类型都可以使用类型声明。
-下一章介绍详细内容。
+接下来的章节会介绍其中的好几种。
-## 顺序很重要
+## 顺序很重要 { #order-matters }
有时,*路径操作*中的路径是写死的。
@@ -117,15 +118,21 @@ FastAPI 充分地利用了 `Enum` 类型接收预设的*路径参数*。
+{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
-### 创建 `Enum` 类
+由于路径首先匹配,始终会使用第一个定义的。
+
+## 预设值 { #predefined-values }
+
+路径操作使用 Python 的 `Enum` 类型接收预设的路径参数。
+
+### 创建 `Enum` 类 { #create-an-enum-class }
导入 `Enum` 并创建继承自 `str` 和 `Enum` 的子类。
@@ -133,47 +140,41 @@ FastAPI 充分地利用了 枚举(即 enums)。
-
-///
+{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
/// tip | 提示
-**AlexNet**、**ResNet**、**LeNet** 是机器学习模型。
+**AlexNet**、**ResNet**、**LeNet** 是机器学习模型的名字。
///
-### 声明*路径参数*
+### 声明路径参数 { #declare-a-path-parameter }
-使用 Enum 类(`ModelName`)创建使用类型注解的*路径参数*:
+使用 Enum 类(`ModelName`)创建使用类型注解的路径参数:
-{* ../../docs_src/path_params/tutorial005.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
-### 查看文档
+### 查看文档 { #check-the-docs }
- API 文档会显示预定义*路径参数*的可用值:
+API 文档会显示预定义路径参数的可用值:
-### 使用 Python _枚举类型_
+### 使用 Python 枚举 { #working-with-python-enumerations }
-*路径参数*的值是枚举的元素。
+路径参数的值是一个枚举成员。
-#### 比较*枚举元素*
+#### 比较枚举成员 { #compare-enumeration-members }
-枚举类 `ModelName` 中的*枚举元素*支持比较操作:
+可以将其与枚举类 `ModelName` 中的枚举成员进行比较:
-{* ../../docs_src/path_params/tutorial005.py hl[17] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[17] *}
-#### 获取*枚举值*
+#### 获取枚举值 { #get-the-enumeration-value }
-使用 `model_name.value` 或 `your_enum_member.value` 获取实际的值(本例中为**字符串**):
+使用 `model_name.value` 或通用的 `your_enum_member.value` 获取实际的值(本例中为 `str`):
-{* ../../docs_src/path_params/tutorial005.py hl[20] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[20] *}
/// tip | 提示
@@ -181,13 +182,13 @@ Python 3.4 及之后版本支持解析**
+- 数据 "解析"
- 数据校验
-- API 注解和 API 文档
+- API 注解和自动文档
只需要声明一次即可。
diff --git a/docs/zh/docs/tutorial/query-param-models.md b/docs/zh/docs/tutorial/query-param-models.md
index c6a79a71a..fc691839d 100644
--- a/docs/zh/docs/tutorial/query-param-models.md
+++ b/docs/zh/docs/tutorial/query-param-models.md
@@ -1,16 +1,16 @@
-# 查询参数模型
+# 查询参数模型 { #query-parameter-models }
如果你有一组具有相关性的**查询参数**,你可以创建一个 **Pydantic 模型**来声明它们。
这将允许你在**多个地方**去**复用模型**,并且一次性为所有参数声明验证和元数据。😎
-/// note
+/// note | 注意
FastAPI 从 `0.115.0` 版本开始支持这个特性。🤓
///
-## 使用 Pydantic 模型的查询参数
+## 使用 Pydantic 模型的查询参数 { #query-parameters-with-a-pydantic-model }
在一个 **Pydantic 模型**中声明你需要的**查询参数**,然后将参数声明为 `Query`:
@@ -18,7 +18,7 @@ FastAPI 从 `0.115.0` 版本开始支持这个特性。🤓
**FastAPI** 将会从请求的**查询参数**中**提取**出**每个字段**的数据,并将其提供给你定义的 Pydantic 模型。
-## 查看文档
+## 查看文档 { #check-the-docs }
你可以在 `/docs` 页面的 UI 中查看查询参数:
@@ -26,11 +26,11 @@ FastAPI 从 `0.115.0` 版本开始支持这个特性。🤓
-## 禁止额外的查询参数
+## 禁止额外的查询参数 { #forbid-extra-query-parameters }
在一些特殊的使用场景中(可能不是很常见),你可能希望**限制**你要接收的查询参数。
-你可以使用 Pydantic 的模型配置来 `forbid`(意为禁止 —— 译者注)任何 `extra`(意为额外的 —— 译者注)字段:
+你可以使用 Pydantic 的模型配置来 `forbid` 任何 `extra` 字段:
{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *}
@@ -57,11 +57,11 @@ https://example.com/items/?limit=10&tool=plumbus
}
```
-## 总结
+## 总结 { #summary }
你可以使用 **Pydantic 模型**在 **FastAPI** 中声明**查询参数**。😎
-/// tip
+/// tip | 提示
剧透警告:你也可以使用 Pydantic 模型来声明 cookie 和 headers,但你将在本教程的后面部分阅读到这部分内容。🤫
diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md
index c2f9a7e9f..62552e6d0 100644
--- a/docs/zh/docs/tutorial/query-params-str-validations.md
+++ b/docs/zh/docs/tutorial/query-params-str-validations.md
@@ -1,142 +1,271 @@
-# 查询参数和字符串校验
+# 查询参数和字符串校验 { #query-parameters-and-string-validations }
**FastAPI** 允许你为参数声明额外的信息和校验。
-让我们以下面的应用程序为例:
+让我们以下面的应用为例:
{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *}
-查询参数 `q` 的类型为 `str`,默认值为 `None`,因此它是可选的。
+查询参数 `q` 的类型为 `str | None`,这意味着它是 `str` 类型,但也可以是 `None`。其默认值确实为 `None`,所以 FastAPI 会知道它不是必填的。
-## 额外的校验
+/// note | 注意
-我们打算添加约束条件:即使 `q` 是可选的,但只要提供了该参数,则该参数值**不能超过50个字符的长度**。
+FastAPI 会因为默认值 `= None` 而知道 `q` 的值不是必填的。
-### 导入 `Query`
-
-为此,首先从 `fastapi` 导入 `Query`:
-
-{* ../../docs_src/query_params_str_validations/tutorial002.py hl[1] *}
-
-## 使用 `Query` 作为默认值
-
-现在,将 `Query` 用作查询参数的默认值,并将它的 `max_length` 参数设置为 50:
-
-{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *}
-
-由于我们必须用 `Query(default=None)` 替换默认值 `None`,`Query` 的第一个参数同样也是用于定义默认值。
-
-所以:
-
-```Python
-q: Union[str, None] = Query(default=None)
-```
-
-...使得参数可选,等同于:
-
-```Python
-q: str = None
-```
-
-但是 `Query` 显式地将其声明为查询参数。
-
-然后,我们可以将更多的参数传递给 `Query`。在本例中,适用于字符串的 `max_length` 参数:
-
-```Python
-q: Union[str, None] = Query(default=None, max_length=50)
-```
-
-将会校验数据,在数据无效时展示清晰的错误信息,并在 OpenAPI 模式的*路径操作*中记录该参数。
-
-## 添加更多校验
-
-你还可以添加 `min_length` 参数:
-
-{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *}
-
-## 添加正则表达式
-
-你可以定义一个参数值必须匹配的正则表达式:
-
-{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *}
-
-这个指定的正则表达式通过以下规则检查接收到的参数值:
-
-* `^`:以该符号之后的字符开头,符号之前没有字符。
-* `fixedquery`: 值精确地等于 `fixedquery`。
-* `$`: 到此结束,在 `fixedquery` 之后没有更多字符。
-
-如果你对所有的这些**「正则表达式」**概念感到迷茫,请不要担心。对于许多人来说这都是一个困难的主题。你仍然可以在无需正则表达式的情况下做很多事情。
-
-但是,一旦你需要用到并去学习它们时,请了解你已经可以在 **FastAPI** 中直接使用它们。
-
-## 默认值
-
-你可以向 `Query` 的第一个参数传入 `None` 用作查询参数的默认值,以同样的方式你也可以传递其他默认值。
-
-假设你想要声明查询参数 `q`,使其 `min_length` 为 `3`,并且默认值为 `fixedquery`:
-
-{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *}
-
-/// note
-
-具有默认值还会使该参数成为可选参数。
+将类型标注为 `str | None` 能让你的编辑器提供更好的辅助和错误检测。
///
-## 声明为必需参数
+## 额外校验 { #additional-validation }
-当我们不需要声明额外的校验或元数据时,只需不声明默认值就可以使 `q` 参数成为必需参数,例如:
+我们打算添加约束:即使 `q` 是可选的,但只要提供了该参数,**其长度不能超过 50 个字符**。
+
+### 导入 `Query` 和 `Annotated` { #import-query-and-annotated }
+
+为此,先导入:
+
+- 从 `fastapi` 导入 `Query`
+- 从 `typing` 导入 `Annotated`
+
+{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[1,3] *}
+
+/// info | 信息
+
+FastAPI 在 0.95.0 版本中添加了对 `Annotated` 的支持(并开始推荐使用)。
+
+如果你的版本更旧,使用 `Annotated` 会报错。
+
+在使用 `Annotated` 之前,请确保先[升级 FastAPI 版本](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}到至少 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` 给参数添加元数据吗?
+
+现在正是与 FastAPI 搭配使用它的时候。🚀
+
+我们之前的类型标注是:
+
+//// tab | Python 3.10+
```Python
-q: str
+q: str | None = None
```
-代替:
+////
+
+//// tab | Python 3.9+
```Python
q: Union[str, None] = None
```
-但是现在我们正在用 `Query` 声明它,例如:
+////
+
+我们要做的是用 `Annotated` 把它包起来,变成:
+
+//// tab | Python 3.10+
```Python
-q: Union[str, None] = Query(default=None, min_length=3)
+q: Annotated[str | None] = None
```
-因此,当你在使用 `Query` 且需要声明一个值是必需的时,只需不声明默认参数:
+////
-{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *}
+//// tab | Python 3.9+
-### 使用`None`声明必需参数
+```Python
+q: Annotated[Union[str, None]] = None
+```
-你可以声明一个参数可以接收`None`值,但它仍然是必需的。这将强制客户端发送一个值,即使该值是`None`。
+////
-为此,你可以声明`None`是一个有效的类型,并仍然使用`default=...`:
+这两种写法含义相同,`q` 是一个可以是 `str` 或 `None` 的参数,默认是 `None`。
-{* ../../docs_src/query_params_str_validations/tutorial006c.py hl[9] *}
+现在进入更有趣的部分。🎉
-/// tip
+## 在 `q` 的 `Annotated` 中添加 `Query` { #add-query-to-annotated-in-the-q-parameter }
-Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。
+有了 `Annotated` 之后,我们就可以放入更多信息(本例中是额外的校验)。在 `Annotated` 中添加 `Query`,并把参数 `max_length` 设为 `50`:
+
+{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *}
+
+注意默认值依然是 `None`,所以该参数仍是可选的。
+
+但现在把 `Query(max_length=50)` 放到 `Annotated` 里,我们就在告诉 FastAPI,这个值需要**额外校验**,最大长度为 50 个字符。😎
+
+/// tip | 提示
+
+这里用的是 `Query()`,因为这是一个**查询参数**。稍后我们还会看到 `Path()`、`Body()`、`Header()` 和 `Cookie()`,它们也接受与 `Query()` 相同的参数。
///
-## 查询参数列表 / 多个值
+FastAPI 现在会:
-当你使用 `Query` 显式地定义查询参数时,你还可以声明它去接收一组值,或换句话来说,接收多个值。
+- 对数据进行**校验**,确保最大长度为 50 个字符
+- 当数据无效时向客户端展示**清晰的错误**
+- 在 OpenAPI 模式的*路径操作*中**记录**该参数(因此会出现在**自动文档 UI** 中)
+
+## 另一种(旧的)方式:把 `Query` 作为默认值 { #alternative-old-query-as-the-default-value }
+
+早期版本的 FastAPI(0.95.0 之前)要求你把 `Query` 作为参数的默认值,而不是放在 `Annotated` 里。你很可能会在别处看到这种写法,所以我也给你解释一下。
+
+/// tip | 提示
+
+对于新代码以及在可能的情况下,请按上文所述使用 `Annotated`。它有多项优势(如下所述),没有劣势。🍰
+
+///
+
+像这样把 `Query()` 作为函数参数的默认值,并把参数 `max_length` 设为 50:
+
+{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *}
+
+由于这种情况下(不使用 `Annotated`)我们必须把函数中的默认值 `None` 替换为 `Query()`,因此需要通过参数 `Query(default=None)` 来设置默认值,它起到同样的作用(至少对 FastAPI 来说)。
+
+所以:
+
+```Python
+q: str | None = Query(default=None)
+```
+
+……会让参数变成可选,默认值为 `None`,等同于:
+
+```Python
+q: str | None = None
+```
+
+但使用 `Query` 的版本会显式把它声明为一个查询参数。
+
+然后,我们可以向 `Query` 传入更多参数。本例中是适用于字符串的 `max_length` 参数:
+
+```Python
+q: str | None = Query(default=None, max_length=50)
+```
+
+这会校验数据、在数据无效时展示清晰的错误,并在 OpenAPI 模式的*路径操作*中记录该参数。
+
+### 在默认值中使用 `Query` 或在 `Annotated` 中使用 `Query` { #query-as-the-default-value-or-in-annotated }
+
+注意,当你在 `Annotated` 中使用 `Query` 时,不能再给 `Query` 传 `default` 参数。
+
+相反,应使用函数参数本身的实际默认值。否则会不一致。
+
+例如,下面这样是不允许的:
+
+```Python
+q: Annotated[str, Query(default="rick")] = "morty"
+```
+
+……因为不清楚默认值应该是 `"rick"` 还是 `"morty"`。
+
+因此,你应该这样用(推荐):
+
+```Python
+q: Annotated[str, Query()] = "rick"
+```
+
+……或者在旧代码库中你会见到:
+
+```Python
+q: str = Query(default="rick")
+```
+
+### `Annotated` 的优势 { #advantages-of-annotated }
+
+**推荐使用 `Annotated`**,而不是把 `Query` 放在函数参数的默认值里,这样做在多方面都**更好**。🤓
+
+函数参数的**默认值**就是**真正的默认值**,这与 Python 的直觉更一致。😌
+
+你可以在**其他地方**不通过 FastAPI **直接调用**这个函数,而且它会**按预期工作**。如果有**必填**参数(没有默认值),你的**编辑器**会报错提示;如果在运行时没有传入必填参数,**Python** 也会报错。
+
+当你不使用 `Annotated` 而是使用**(旧的)默认值风格**时,如果你在**其他地方**不通过 FastAPI 调用该函数,你必须**记得**给函数传参,否则得到的值会和预期不同(例如得到 `QueryInfo` 之类的对象而不是 `str`)。而你的编辑器不会报错,Python 也不会在调用时报错,只有在函数内部的操作出错时才会暴露问题。
+
+由于 `Annotated` 可以包含多个元数据标注,你甚至可以用同一个函数与其他工具配合,例如 Typer。🚀
+
+## 添加更多校验 { #add-more-validations }
+
+你还可以添加 `min_length` 参数:
+
+{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *}
+
+## 添加正则表达式 { #add-regular-expressions }
+
+你可以定义一个参数必须匹配的 正则表达式 `pattern`:
+
+{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
+
+这个特定的正则表达式通过以下规则检查接收到的参数值:
+
+- `^`:必须以接下来的字符开头,前面没有其他字符。
+- `fixedquery`:值必须精确等于 `fixedquery`。
+- `$`:到此结束,在 `fixedquery` 之后没有更多字符。
+
+如果你对这些**「正则表达式」**概念感到迷茫,不必担心。对很多人来说这都是个难点。你仍然可以在不使用正则表达式的情况下做很多事情。
+
+现在你知道了,一旦需要时,你可以在 **FastAPI** 中直接使用它们。
+
+## 默认值 { #default-values }
+
+当然,你也可以使用 `None` 以外的默认值。
+
+假设你想要声明查询参数 `q` 的 `min_length` 为 `3`,并且默认值为 `"fixedquery"`:
+
+{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *}
+
+/// note | 注意
+
+任何类型的默认值(包括 `None`)都会让该参数变为可选(非必填)。
+
+///
+
+## 必填参数 { #required-parameters }
+
+当我们不需要声明更多校验或元数据时,只需不声明默认值就可以让查询参数 `q` 成为必填参数,例如:
+
+```Python
+q: str
+```
+
+而不是:
+
+```Python
+q: str | None = None
+```
+
+但现在我们用 `Query` 来声明它,例如:
+
+```Python
+q: Annotated[str | None, Query(min_length=3)] = None
+```
+
+因此,在使用 `Query` 的同时需要把某个值声明为必填时,只需不声明默认值:
+
+{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *}
+
+### 必填,但可以为 `None` { #required-can-be-none }
+
+你可以声明一个参数可以接收 `None`,但它仍然是必填的。这将强制客户端必须发送一个值,即使该值是 `None`。
+
+为此,你可以声明 `None` 是有效类型,但不声明默认值:
+
+{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *}
+
+## 查询参数列表 / 多个值 { #query-parameter-list-multiple-values }
+
+当你用 `Query` 显式地定义查询参数时,你还可以声明它接收一个值列表,换句话说,接收多个值。
例如,要声明一个可在 URL 中出现多次的查询参数 `q`,你可以这样写:
-{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *}
-然后,输入如下网址:
+然后,访问如下 URL:
```
http://localhost:8000/items/?q=foo&q=bar
```
-你会在*路径操作函数*的*函数参数* `q` 中以一个 Python `list` 的形式接收到*查询参数* `q` 的多个值(`foo` 和 `bar`)。
+你会在*路径操作函数*的*函数参数* `q` 中以一个 Python `list` 的形式接收到多个 `q` *查询参数* 的值(`foo` 和 `bar`)。
因此,该 URL 的响应将会是:
@@ -149,21 +278,21 @@ http://localhost:8000/items/?q=foo&q=bar
}
```
-/// tip
+/// tip | 提示
-要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。
+要声明类型为 `list` 的查询参数(如上例),你需要显式地使用 `Query`,否则它会被解释为请求体。
///
-交互式 API 文档将会相应地进行更新,以允许使用多个值:
+交互式 API 文档会相应更新,以支持多个值:
-
+
-### 具有默认值的查询参数列表 / 多个值
+### 具有默认值的查询参数列表 / 多个值 { #query-parameter-list-multiple-values-with-defaults }
-你还可以定义在没有任何给定值时的默认 `list` 值:
+你还可以定义在没有给定值时的默认 `list`:
-{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *}
如果你访问:
@@ -182,93 +311,163 @@ http://localhost:8000/items/
}
```
-#### 使用 `list`
+#### 只使用 `list` { #using-just-list }
-你也可以直接使用 `list` 代替 `List [str]`:
+你也可以直接使用 `list`,而不是 `list[str]`:
-{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *}
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}
-/// note
+/// note | 注意
-请记住,在这种情况下 FastAPI 将不会检查列表的内容。
+请记住,在这种情况下 FastAPI 不会检查列表的内容。
-例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。
+例如,`list[int]` 会检查(并记录到文档)列表的内容必须是整数。但仅用 `list` 不会。
///
-## 声明更多元数据
+## 声明更多元数据 { #declare-more-metadata }
你可以添加更多有关该参数的信息。
-这些信息将包含在生成的 OpenAPI 模式中,并由文档用户界面和外部工具所使用。
+这些信息会包含在生成的 OpenAPI 中,并被文档用户界面和外部工具使用。
-/// note
+/// note | 注意
请记住,不同的工具对 OpenAPI 的支持程度可能不同。
-其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。
+其中一些可能还不会展示所有已声明的额外信息,尽管在大多数情况下,缺失的功能已经在计划开发中。
///
你可以添加 `title`:
-{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *}
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
以及 `description`:
-{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *}
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
-## 别名参数
+## 别名参数 { #alias-parameters }
-假设你想要查询参数为 `item-query`。
+假设你想要参数名为 `item-query`。
-像下面这样:
+像这样:
```
http://127.0.0.1:8000/items/?item-query=foobaritems
```
-但是 `item-query` 不是一个有效的 Python 变量名称。
+但 `item-query` 不是有效的 Python 变量名。
最接近的有效名称是 `item_query`。
-但是你仍然要求它在 URL 中必须是 `item-query`...
+但你仍然需要它在 URL 中就是 `item-query`……
-这时你可以用 `alias` 参数声明一个别名,该别名将用于在 URL 中查找查询参数值:
+这时可以用 `alias` 参数声明一个别名,FastAPI 会用该别名在 URL 中查找参数值:
-{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
-## 弃用参数
+## 弃用参数 { #deprecating-parameters }
-现在假设你不再喜欢此参数。
+现在假设你不再喜欢这个参数了。
-你不得不将其保留一段时间,因为有些客户端正在使用它,但你希望文档清楚地将其展示为已弃用。
+由于还有客户端在使用它,你不得不保留一段时间,但你希望文档清楚地将其展示为已弃用。
-那么将参数 `deprecated=True` 传入 `Query`:
+那么将参数 `deprecated=True` 传给 `Query`:
-{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *}
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
文档将会像下面这样展示它:
-
+
-## 总结
+## 从 OpenAPI 中排除参数 { #exclude-parameters-from-openapi }
-你可以为查询参数声明额外的校验和元数据。
+要把某个查询参数从生成的 OpenAPI 模式中排除(从而也不会出现在自动文档系统中),将 `Query` 的参数 `include_in_schema` 设为 `False`:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## 自定义校验 { #custom-validation }
+
+有些情况下你需要做一些无法通过上述参数完成的**自定义校验**。
+
+在这些情况下,你可以使用**自定义校验函数**,该函数会在正常校验之后应用(例如,在先校验值是 `str` 之后)。
+
+你可以在 `Annotated` 中使用 Pydantic 的 `AfterValidator` 来实现。
+
+/// tip | 提示
+
+Pydantic 还有 `BeforeValidator` 等。🤓
+
+///
+
+例如,这个自定义校验器会检查条目 ID 是否以 `isbn-`(用于 ISBN 书号)或 `imdb-`(用于 IMDB 电影 URL 的 ID)开头:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | 信息
+
+这在 Pydantic 2 或更高版本中可用。😎
+
+///
+
+/// tip | 提示
+
+如果你需要进行任何需要与**外部组件**通信的校验,例如数据库或其他 API,你应该改用 **FastAPI 依赖项**,稍后你会学到它们。
+
+这些自定义校验器用于只需检查请求中**同一份数据**即可完成的事情。
+
+///
+
+### 理解这段代码 { #understand-that-code }
+
+关键点仅仅是:在 `Annotated` 中使用带函数的 **`AfterValidator`**。不感兴趣可以跳过这一节。🤸
+
+---
+
+但如果你对这个具体示例好奇,并且还愿意继续看,这里有一些额外细节。
+
+#### 字符串与 `value.startswith()` { #string-with-value-startswith }
+
+注意到了吗?字符串的 `value.startswith()` 可以接收一个元组,它会检查元组中的每个值:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### 一个随机条目 { #a-random-item }
+
+使用 `data.items()` 我们会得到一个包含每个字典项键和值的元组的 可迭代对象。
+
+我们用 `list(data.items())` 把这个可迭代对象转换成一个真正的 `list`。
+
+然后用 `random.choice()` 可以从该列表中获取一个**随机值**,也就是一个 `(id, name)` 的元组。它可能像 `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")` 这样。
+
+接着我们把这个元组的**两个值**分别赋给变量 `id` 和 `name`。
+
+所以,即使用户没有提供条目 ID,他们仍然会收到一个随机推荐。
+
+……而我们把这些都放在**一行简单的代码**里完成。🤯 你不爱 Python 吗?🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## 总结 { #recap }
+
+你可以为参数声明额外的校验和元数据。
通用的校验和元数据:
-* `alias`
-* `title`
-* `description`
-* `deprecated`
+- `alias`
+- `title`
+- `description`
+- `deprecated`
-特定于字符串的校验:
+字符串特有的校验:
-* `min_length`
-* `max_length`
-* `regex`
+- `min_length`
+- `max_length`
+- `pattern`
-在这些示例中,你了解了如何声明对 `str` 值的校验。
+也可以使用 `AfterValidator` 进行自定义校验。
-请参阅下一章节,以了解如何声明对其他类型例如数值的校验。
+在这些示例中,你看到了如何为 `str` 值声明校验。
+
+参阅下一章节,了解如何为其他类型(例如数值)声明校验。
diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md
index cc2e74b9e..9ef998731 100644
--- a/docs/zh/docs/tutorial/query-params.md
+++ b/docs/zh/docs/tutorial/query-params.md
@@ -1,8 +1,8 @@
-# 查询参数
+# 查询参数 { #query-parameters }
声明的参数不是路径参数时,路径操作函数会把该参数自动解释为**查询**参数。
-{* ../../docs_src/query_params/tutorial001.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,以 `&` 分隔。
@@ -26,9 +26,9 @@ http://127.0.0.1:8000/items/?skip=0&limit=10
* (显而易见的)编辑器支持
* 数据**解析**
* 数据校验
-* API 文档
+* 自动文档
-## 默认值
+## 默认值 { #defaults }
查询参数不是路径的固定内容,它是可选的,还支持默认值。
@@ -57,7 +57,7 @@ http://127.0.0.1:8000/items/?skip=20
* `skip=20`:在 URL 中设定的值
* `limit=10`:使用默认值
-## 可选参数
+## 可选参数 { #optional-parameters }
同理,把默认值设为 `None` 即可声明**可选的**查询参数:
@@ -71,15 +71,7 @@ http://127.0.0.1:8000/items/?skip=20
///
-/// note | 笔记
-
-因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。
-
-FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。
-
-///
-
-## 查询参数类型转换
+## 查询参数类型转换 { #query-parameter-type-conversion }
参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型:
@@ -116,10 +108,10 @@ http://127.0.0.1:8000/items/foo?short=on
http://127.0.0.1:8000/items/foo?short=yes
```
-或其它任意大小写形式(大写、首字母大写等),函数接收的 `short` 参数都是布尔值 `True`。值为 `False` 时也一样。
+或其它任意大小写形式(大写、首字母大写等),函数接收的 `short` 参数都是布尔值 `True`。否则为 `False`。
-## 多个路径和查询参数
+## 多个路径和查询参数 { #multiple-path-and-query-parameters }
**FastAPI** 可以识别同时声明的多个路径参数和查询参数。
@@ -129,7 +121,7 @@ FastAPI 通过参数名进行检测:
{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
-## 必选查询参数
+## 必选查询参数 { #required-query-parameters }
为不是路径参数的参数声明默认值(至此,仅有查询参数),该参数就**不是必选**的了。
@@ -137,7 +129,7 @@ FastAPI 通过参数名进行检测:
如果要把查询参数设置为**必选**,就不要声明默认值:
-{* ../../docs_src/query_params/tutorial005.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
这里的查询参数 `needy` 是类型为 `str` 的必选查询参数。
@@ -151,16 +143,17 @@ http://127.0.0.1:8000/items/foo-item
```JSON
{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
}
```
@@ -191,6 +184,6 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
/// tip | 提示
-还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。
+还可以像在[路径参数](path-params.md#predefined-values){.internal-link target=_blank} 中那样使用 `Enum`。
///
diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md
index 81ddc7238..927bd093b 100644
--- a/docs/zh/docs/tutorial/request-files.md
+++ b/docs/zh/docs/tutorial/request-files.md
@@ -1,159 +1,163 @@
-# 请求文件
+# 请求文件 { #request-files }
-`File` 用于定义客户端的上传文件。
+你可以使用 `File` 定义由客户端上传的文件。
-/// info | 说明
+/// info | 信息
-因为上传文件以「表单数据」形式发送。
+要接收上传的文件,请先安装 `python-multipart`。
-所以接收上传文件,要预先安装 `python-multipart`。
+请确保你创建一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank}、激活它,然后安装,例如:
-例如: `pip install python-multipart`。
+```console
+$ pip install python-multipart
+```
+
+这是因为上传文件是以「表单数据」发送的。
///
-## 导入 `File`
+## 导入 `File` { #import-file }
从 `fastapi` 导入 `File` 和 `UploadFile`:
-{* ../../docs_src/request_files/tutorial001.py hl[1] *}
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *}
-## 定义 `File` 参数
+## 定义 `File` 参数 { #define-file-parameters }
-创建文件(`File`)参数的方式与 `Body` 和 `Form` 一样:
+像为 `Body` 或 `Form` 一样创建文件参数:
-{* ../../docs_src/request_files/tutorial001.py hl[7] *}
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *}
-/// info | 说明
+/// info | 信息
`File` 是直接继承自 `Form` 的类。
-注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。
+但要注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。
///
/// tip | 提示
-声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
+声明文件体必须使用 `File`,否则,这些参数会被当作查询参数或请求体(JSON)参数。
///
-文件作为「表单数据」上传。
+文件将作为「表单数据」上传。
-如果把*路径操作函数*参数的类型声明为 `bytes`,**FastAPI** 将以 `bytes` 形式读取和接收文件内容。
+如果把*路径操作函数*参数的类型声明为 `bytes`,**FastAPI** 会为你读取文件,并以 `bytes` 的形式接收其内容。
-这种方式把文件的所有内容都存储在内存里,适用于小型文件。
+请注意,这意味着整个内容会存储在内存中,适用于小型文件。
-不过,很多情况下,`UploadFile` 更好用。
+不过,在很多情况下,使用 `UploadFile` 会更有优势。
-## 含 `UploadFile` 的文件参数
+## 含 `UploadFile` 的文件参数 { #file-parameters-with-uploadfile }
-定义文件参数时使用 `UploadFile`:
+将文件参数的类型声明为 `UploadFile`:
-{* ../../docs_src/request_files/tutorial001.py hl[12] *}
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *}
-`UploadFile` 与 `bytes` 相比有更多优势:
+与 `bytes` 相比,使用 `UploadFile` 有多项优势:
-* 使用 `spooled` 文件:
- * 存储在内存的文件超出最大上限时,FastAPI 会把文件存入磁盘;
-* 这种方式更适于处理图像、视频、二进制文件等大型文件,好处是不会占用所有内存;
-* 可获取上传文件的元数据;
-* 自带 file-like `async` 接口;
-* 暴露的 Python `SpooledTemporaryFile` 对象,可直接传递给其他预期「file-like」对象的库。
+* 无需在参数的默认值中使用 `File()`。
+* 它使用“spooled”文件:
+ * 文件会先存储在内存中,直到达到最大上限,超过该上限后会写入磁盘。
+* 因此,非常适合处理图像、视频、大型二进制等大文件,而不会占用所有内存。
+* 你可以获取上传文件的元数据。
+* 它提供 file-like 的 `async` 接口。
+* 它暴露了一个实际的 Python `SpooledTemporaryFile` 对象,你可以直接传给期望「file-like」对象的其他库。
-### `UploadFile`
+### `UploadFile` { #uploadfile }
`UploadFile` 的属性如下:
-* `filename`:上传文件名字符串(`str`),例如, `myimage.jpg`;
-* `content_type`:内容类型(MIME 类型 / 媒体类型)字符串(`str`),例如,`image/jpeg`;
-* `file`: `SpooledTemporaryFile`( file-like 对象)。其实就是 Python文件,可直接传递给其他预期 `file-like` 对象的函数或支持库。
+* `filename`:上传的原始文件名字符串(`str`),例如 `myimage.jpg`。
+* `content_type`:内容类型(MIME 类型 / 媒体类型)的字符串(`str`),例如 `image/jpeg`。
+* `file`:`SpooledTemporaryFile`(一个 file-like 对象)。这是实际的 Python 文件对象,你可以直接传递给其他期望「file-like」对象的函数或库。
-`UploadFile` 支持以下 `async` 方法,(使用内部 `SpooledTemporaryFile`)可调用相应的文件方法。
+`UploadFile` 具有以下 `async` 方法。它们都会在底层调用对应的文件方法(使用内部的 `SpooledTemporaryFile`)。
-* `write(data)`:把 `data` (`str` 或 `bytes`)写入文件;
-* `read(size)`:按指定数量的字节或字符(`size` (`int`))读取文件内容;
-* `seek(offset)`:移动至文件 `offset` (`int`)字节处的位置;
- * 例如,`await myfile.seek(0) ` 移动到文件开头;
- * 执行 `await myfile.read()` 后,需再次读取已读取内容时,这种方法特别好用;
+* `write(data)`:将 `data`(`str` 或 `bytes`)写入文件。
+* `read(size)`:读取文件中 `size`(`int`)个字节/字符。
+* `seek(offset)`:移动到文件中字节位置 `offset`(`int`)。
+ * 例如,`await myfile.seek(0)` 会移动到文件开头。
+ * 如果你先运行过 `await myfile.read()`,然后需要再次读取内容时,这尤其有用。
* `close()`:关闭文件。
-因为上述方法都是 `async` 方法,要搭配「await」使用。
+由于这些方法都是 `async` 方法,你需要对它们使用 await。
-例如,在 `async` *路径操作函数* 内,要用以下方式读取文件内容:
+例如,在 `async` *路径操作函数* 内,你可以这样获取内容:
```Python
contents = await myfile.read()
```
-在普通 `def` *路径操作函数* 内,则可以直接访问 `UploadFile.file`,例如:
+如果是在普通 `def` *路径操作函数* 内,你可以直接访问 `UploadFile.file`,例如:
```Python
contents = myfile.file.read()
```
-/// note | `async` 技术细节
+/// note | 注意
-使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。
+当你使用这些 `async` 方法时,**FastAPI** 会在线程池中运行相应的文件方法并等待其完成。
///
-/// note | Starlette 技术细节
+/// note | 注意
-**FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。
+**FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要的部分,使其与 **Pydantic** 以及 FastAPI 的其他部分兼容。
///
-## 什么是 「表单数据」
+## 什么是「表单数据」 { #what-is-form-data }
-与 JSON 不同,HTML 表单(``)向服务器发送数据通常使用「特殊」的编码。
+HTML 表单(``)向服务器发送数据的方式通常会对数据使用一种「特殊」的编码,这与 JSON 不同。
-**FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。
+**FastAPI** 会确保从正确的位置读取这些数据,而不是从 JSON 中读取。
-/// note | 技术细节
+/// note | 注意
-不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。
+当不包含文件时,来自表单的数据通常使用「媒体类型」`application/x-www-form-urlencoded` 编码。
-但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。
+但当表单包含文件时,会编码为 `multipart/form-data`。如果你使用 `File`,**FastAPI** 会知道需要从请求体的正确位置获取文件。
-编码和表单字段详见 MDN Web 文档的 POST 小节。
+如果你想进一步了解这些编码和表单字段,请参阅 MDN web docs for POST。
///
/// warning | 警告
-可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。
+你可以在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明希望以 JSON 接收的 `Body` 字段,因为此时请求体会使用 `multipart/form-data` 编码,而不是 `application/json`。
-这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+这不是 **FastAPI** 的限制,而是 HTTP 协议的一部分。
///
-## 可选文件上传
+## 可选文件上传 { #optional-file-upload }
您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选:
-{* ../../docs_src/request_files/tutorial001_02_py310.py hl[7,14] *}
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
-## 带有额外元数据的 `UploadFile`
+## 带有额外元数据的 `UploadFile` { #uploadfile-with-additional-metadata }
您也可以将 `File()` 与 `UploadFile` 一起使用,例如,设置额外的元数据:
-{* ../../docs_src/request_files/tutorial001_03.py hl[13] *}
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
-## 多文件上传
+## 多文件上传 { #multiple-file-uploads }
FastAPI 支持同时上传多个文件。
-可用同一个「表单字段」发送含多个文件的「表单数据」。
+它们会被关联到同一个通过「表单数据」发送的「表单字段」。
-上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`):
+要实现这一点,声明一个由 `bytes` 或 `UploadFile` 组成的列表(`List`):
-{* ../../docs_src/request_files/tutorial002_py39.py hl[8,13] *}
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。
-
-/// note | 技术细节
+/// note | 注意
也可以使用 `from starlette.responses import HTMLResponse`。
@@ -161,12 +165,12 @@ FastAPI 支持同时上传多个文件。
///
-### 带有额外元数据的多文件上传
+### 带有额外元数据的多文件上传 { #multiple-file-uploads-with-additional-metadata }
-和之前的方式一样, 您可以为 `File()` 设置额外参数, 即使是 `UploadFile`:
+和之前的方式一样,你可以为 `File()` 设置额外参数,即使是 `UploadFile`:
-{* ../../docs_src/request_files/tutorial003_py39.py hl[16] *}
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
-## 小结
+## 小结 { #recap }
-本节介绍了如何用 `File` 把上传文件声明为(表单数据的)输入参数。
+使用 `File`、`bytes` 和 `UploadFile` 来声明在请求中上传的文件,它们以表单数据发送。
diff --git a/docs/zh/docs/tutorial/request-form-models.md b/docs/zh/docs/tutorial/request-form-models.md
index e639e4b9f..4eb98ea22 100644
--- a/docs/zh/docs/tutorial/request-form-models.md
+++ b/docs/zh/docs/tutorial/request-form-models.md
@@ -1,12 +1,12 @@
-# 表单模型
+# 表单模型 { #form-models }
-您可以使用 **Pydantic 模型**在 FastAPI 中声明**表单字段**。
+你可以在 FastAPI 中使用 **Pydantic 模型**声明**表单字段**。
-/// info
+/// info | 信息
-要使用表单,需预先安装 `python-multipart` 。
+要使用表单,首先安装 `python-multipart`。
-确保您创建、激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank}后再安装。
+确保你创建一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank},激活它,然后再安装,例如:
```console
$ pip install python-multipart
@@ -14,51 +14,51 @@ $ pip install python-multipart
///
-/// note
+/// note | 注意
自 FastAPI 版本 `0.113.0` 起支持此功能。🤓
///
-## 表单的 Pydantic 模型
+## 表单的 Pydantic 模型 { #pydantic-models-for-forms }
-您只需声明一个 **Pydantic 模型**,其中包含您希望接收的**表单字段**,然后将参数声明为 `Form` :
+你只需声明一个 **Pydantic 模型**,其中包含你希望接收的**表单字段**,然后将参数声明为 `Form`:
{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
-**FastAPI** 将从请求中的**表单数据**中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。
+**FastAPI** 将从请求中的**表单数据**中**提取**出**每个字段**的数据,并提供你定义的 Pydantic 模型。
-## 检查文档
+## 检查文档 { #check-the-docs }
-您可以在文档 UI 中验证它,地址为 `/docs` :
+你可以在文档 UI 中验证它,地址为 `/docs`:
POST小节。
+如果你想了解更多关于这些编码和表单字段的信息,请参阅 MDN Web 文档的 POST。
///
-/// warning | 警告
+/// warning
-可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。
+你可以在一个路径操作中声明多个 `Form` 参数,但不能同时再声明要接收为 JSON 的 `Body` 字段,因为此时请求体会使用 `application/x-www-form-urlencoded` 而不是 `application/json` 进行编码。
-这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+这不是 **FastAPI** 的限制,而是 HTTP 协议的一部分。
///
-## 小结
+## 小结 { #recap }
-本节介绍了如何使用 `Form` 声明表单数据输入参数。
+使用 `Form` 来声明表单数据输入参数。
diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md
index 049cd1223..791eb66fb 100644
--- a/docs/zh/docs/tutorial/response-model.md
+++ b/docs/zh/docs/tutorial/response-model.md
@@ -1,6 +1,35 @@
-# 响应模型
+# 响应模型 - 返回类型 { #response-model-return-type }
-你可以在任意的*路径操作*中使用 `response_model` 参数来声明用于响应的模型:
+你可以通过为*路径操作函数*的**返回类型**添加注解来声明用于响应的类型。
+
+和为输入数据在函数**参数**里做类型注解的方式相同,你可以使用 Pydantic 模型、`list`、`dict`、以及整数、布尔值等标量类型。
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+FastAPI 会使用这个返回类型来:
+
+* 对返回数据进行**校验**。
+ * 如果数据无效(例如缺少某个字段),这意味着你的应用代码有问题,没有返回应有的数据,FastAPI 将返回服务器错误而不是返回错误的数据。这样你和你的客户端都可以确定会收到期望的数据及其结构。
+* 在 OpenAPI 的*路径操作*中为响应添加**JSON Schema**。
+ * 它会被**自动文档**使用。
+ * 它也会被自动客户端代码生成工具使用。
+
+但更重要的是:
+
+* 它会将输出数据**限制并过滤**为返回类型中定义的内容。
+ * 这对**安全性**尤为重要,下面会进一步介绍。
+
+## `response_model` 参数 { #response-model-parameter }
+
+在一些情况下,你需要或希望返回的数据与声明的类型不完全一致。
+
+例如,你可能希望**返回一个字典**或数据库对象,但**将其声明为一个 Pydantic 模型**。这样 Pydantic 模型就会为你返回的对象(例如字典或数据库对象)完成文档、校验等工作。
+
+如果你添加了返回类型注解,工具和编辑器会(正确地)报错,提示你的函数返回的类型(例如 `dict`)与声明的类型(例如一个 Pydantic 模型)不同。
+
+在这些情况下,你可以使用*路径操作装饰器*参数 `response_model`,而不是返回类型。
+
+你可以在任意*路径操作*中使用 `response_model` 参数:
* `@app.get()`
* `@app.post()`
@@ -10,102 +39,209 @@
{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
-/// note
+/// note | 注意
-注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+注意,`response_model` 是「装饰器」方法(`get`、`post` 等)的一个参数。不是你的*路径操作函数*的参数,不像所有查询参数和请求体那样。
///
-它接收的类型与你将为 Pydantic 模型属性所声明的类型相同,因此它可以是一个 Pydantic 模型,但也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。
+`response_model` 接收的类型与为 Pydantic 模型字段声明的类型相同,因此它可以是一个 Pydantic 模型,也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。
-FastAPI 将使用此 `response_model` 来:
+FastAPI 会使用这个 `response_model` 来完成数据文档、校验等,并且还会将输出数据**转换并过滤**为其类型声明。
-* 将输出数据转换为其声明的类型。
-* 校验数据。
-* 在 OpenAPI 的*路径操作*中为响应添加一个 JSON Schema。
-* 并在自动生成文档系统中使用。
+/// tip | 提示
-但最重要的是:
+如果你的编辑器、mypy 等进行严格类型检查,你可以将函数返回类型声明为 `Any`。
-* 会将输出数据限制在该模型定义内。下面我们会看到这一点有多重要。
-
-/// note | 技术细节
-
-响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。
+这样你告诉编辑器你是有意返回任意类型。但 FastAPI 仍会使用 `response_model` 做数据文档、校验、过滤等工作。
///
-## 返回与输入相同的数据
+### `response_model` 的优先级 { #response-model-priority }
-现在我们声明一个 `UserIn` 模型,它将包含一个明文密码属性。
+如果你同时声明了返回类型和 `response_model`,`response_model` 会具有优先级并由 FastAPI 使用。
-{* ../../docs_src/response_model/tutorial002.py hl[9,11] *}
+这样,即使你返回的类型与响应模型不同,你也可以为函数添加正确的类型注解,供编辑器和 mypy 等工具使用。同时你仍然可以让 FastAPI 使用 `response_model` 进行数据校验、文档等。
-我们正在使用此模型声明输入数据,并使用同一模型声明输出数据:
+你也可以使用 `response_model=None` 来禁用该*路径操作*的响应模型生成;当你为一些不是有效 Pydantic 字段的东西添加类型注解时,可能需要这样做,下面的章节会有示例。
-{* ../../docs_src/response_model/tutorial002.py hl[17:18] *}
+## 返回与输入相同的数据 { #return-the-same-input-data }
-现在,每当浏览器使用一个密码创建用户时,API 都会在响应中返回相同的密码。
+这里我们声明一个 `UserIn` 模型,它包含一个明文密码:
-在这个案例中,这可能不算是问题,因为用户自己正在发送密码。
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
-但是,如果我们在其他的*路径操作*中使用相同的模型,则可能会将用户的密码发送给每个客户端。
+/// info | 信息
-/// danger
+要使用 `EmailStr`,首先安装 `email-validator`。
-永远不要存储用户的明文密码,也不要在响应中发送密码。
+请先创建并激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后安装,例如:
+
+```console
+$ pip install email-validator
+```
+
+或者:
+
+```console
+$ pip install "pydantic[email]"
+```
///
-## 添加输出模型
+我们使用这个模型来声明输入,同时也用相同的模型来声明输出:
-相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型:
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
+
+现在,每当浏览器使用密码创建用户时,API 会在响应中返回相同的密码。
+
+在这个场景下,这可能不算问题,因为发送密码的是同一个用户。
+
+但如果我们在其他*路径操作*中使用相同的模型,就可能会把用户的密码发送给每个客户端。
+
+/// danger | 危险
+
+除非你非常清楚所有注意事项并确实知道自己在做什么,否则永远不要存储用户的明文密码,也不要像这样在响应中发送它。
+
+///
+
+## 添加输出模型 { #add-an-output-model }
+
+相反,我们可以创建一个包含明文密码的输入模型和一个不包含它的输出模型:
{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
-这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户:
+这里,即使我们的*路径操作函数*返回的是包含密码的同一个输入用户:
{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
-...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型:
+……我们仍将 `response_model` 声明为不包含密码的 `UserOut` 模型:
{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
-因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。
+因此,**FastAPI** 会负责过滤掉输出模型中未声明的所有数据(使用 Pydantic)。
-## 在文档中查看
+### `response_model` 还是返回类型 { #response-model-or-return-type }
-当你查看自动化文档时,你可以检查输入模型和输出模型是否都具有自己的 JSON Schema:
+在这个例子中,因为两个模型不同,如果我们将函数返回类型注解为 `UserOut`,编辑器和工具会抱怨我们返回了无效类型,因为它们是不同的类。
-
+这就是为什么在这个例子里我们必须在 `response_model` 参数中声明它。
-并且两种模型都将在交互式 API 文档中使用:
+……但继续往下读,看看如何更好地处理这种情况。
-
+## 返回类型与数据过滤 { #return-type-and-data-filtering }
-## 响应模型编码参数
+延续上一个例子。我们希望**用一种类型来注解函数**,但希望从函数返回的内容实际上可以**包含更多数据**。
+
+我们希望 FastAPI 继续使用响应模型来**过滤**数据。这样即使函数返回了更多数据,响应也只会包含响应模型中声明的字段。
+
+在上一个例子中,因为类不同,我们不得不使用 `response_model` 参数。但这也意味着我们无法从编辑器和工具处获得对函数返回类型的检查支持。
+
+不过在大多数需要这样做的场景里,我们只是希望模型像这个例子中那样**过滤/移除**一部分数据。
+
+在这些场景里,我们可以使用类和继承,既利用函数的**类型注解**获取更好的编辑器和工具支持,又能获得 FastAPI 的**数据过滤**。
+
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
+
+这样一来,我们既能从编辑器和 mypy 获得工具支持(这段代码在类型上是正确的),也能从 FastAPI 获得数据过滤。
+
+这是如何做到的?我们来看看。🤓
+
+### 类型注解与工具链 { #type-annotations-and-tooling }
+
+先看看编辑器、mypy 和其他工具会如何看待它。
+
+`BaseUser` 有基础字段。然后 `UserIn` 继承自 `BaseUser` 并新增了 `password` 字段,因此它包含了两个模型的全部字段。
+
+我们把函数返回类型注解为 `BaseUser`,但实际上返回的是一个 `UserIn` 实例。
+
+编辑器、mypy 和其他工具不会对此抱怨,因为在类型系统里,`UserIn` 是 `BaseUser` 的子类,这意味着当期望 `BaseUser` 时,返回 `UserIn` 是*合法*的。
+
+### FastAPI 的数据过滤 { #fastapi-data-filtering }
+
+对于 FastAPI,它会查看返回类型并确保你返回的内容**只**包含该类型中声明的字段。
+
+FastAPI 在内部配合 Pydantic 做了多项处理,确保不会把类继承的这些规则用于返回数据的过滤,否则你可能会返回比预期多得多的数据。
+
+这样,你就能兼得两方面的优势:带有**工具支持**的类型注解和**数据过滤**。
+
+## 在文档中查看 { #see-it-in-the-docs }
+
+当你查看自动文档时,你会看到输入模型和输出模型都会有各自的 JSON Schema:
+
+
+
+并且两个模型都会用于交互式 API 文档:
+
+
+
+## 其他返回类型注解 { #other-return-type-annotations }
+
+有些情况下你会返回一些不是有效 Pydantic 字段的内容,并在函数上做了相应注解,只是为了获得工具链(编辑器、mypy 等)的支持。
+
+### 直接返回 Response { #return-a-response-directly }
+
+最常见的情况是[直接返回 Response,详见进阶文档](../advanced/response-directly.md){.internal-link target=_blank}。
+
+{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
+
+这个简单场景 FastAPI 会自动处理,因为返回类型注解是 `Response`(或其子类)。
+
+工具也会满意,因为 `RedirectResponse` 和 `JSONResponse` 都是 `Response` 的子类,所以类型注解是正确的。
+
+### 注解 Response 的子类 { #annotate-a-response-subclass }
+
+你也可以在类型注解中使用 `Response` 的子类:
+
+{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
+
+这同样可行,因为 `RedirectResponse` 是 `Response` 的子类,FastAPI 会自动处理这个简单场景。
+
+### 无效的返回类型注解 { #invalid-return-type-annotations }
+
+但当你返回其他任意对象(如数据库对象)而它不是有效的 Pydantic 类型,并在函数中按此进行了注解时,FastAPI 会尝试基于该类型注解创建一个 Pydantic 响应模型,但会失败。
+
+如果你有一个在多个类型之间的联合类型,其中一个或多个不是有效的 Pydantic 类型,也会发生同样的情况,例如这个会失败 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+……它失败是因为该类型注解不是 Pydantic 类型,也不只是单个 `Response` 类或其子类,而是 `Response` 与 `dict` 的联合类型(任意其一)。
+
+### 禁用响应模型 { #disable-response-model }
+
+延续上面的例子,你可能不想要 FastAPI 执行默认的数据校验、文档、过滤等。
+
+但你可能仍然想在函数上保留返回类型注解,以获得编辑器和类型检查器(如 mypy)的支持。
+
+在这种情况下,你可以通过设置 `response_model=None` 来禁用响应模型生成:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+这会让 FastAPI 跳过响应模型的生成,这样你就可以按需使用任意返回类型注解,而不会影响你的 FastAPI 应用。🤓
+
+## 响应模型的编码参数 { #response-model-encoding-parameters }
你的响应模型可以具有默认值,例如:
-{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *}
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
-* `description: Union[str, None] = None` 具有默认值 `None`。
-* `tax: float = 10.5` 具有默认值 `10.5`.
-* `tags: List[str] = []` 具有一个空列表作为默认值: `[]`.
+* `description: Union[str, None] = None`(或在 Python 3.10 中的 `str | None = None`)默认值为 `None`。
+* `tax: float = 10.5` 默认值为 `10.5`。
+* `tags: List[str] = []` 默认值为一个空列表:`[]`。
-但如果它们并没有存储实际的值,你可能想从结果中忽略它们的默认值。
+但如果它们并没有被实际存储,你可能希望在结果中省略这些默认值。
-举个例子,当你在 NoSQL 数据库中保存了具有许多可选属性的模型,但你又不想发送充满默认值的很长的 JSON 响应。
+例如,当你在 NoSQL 数据库中保存了具有许多可选属性的模型,但又不想发送充满默认值的冗长 JSON 响应。
-### 使用 `response_model_exclude_unset` 参数
+### 使用 `response_model_exclude_unset` 参数 { #use-the-response-model-exclude-unset-parameter }
-你可以设置*路径操作装饰器*的 `response_model_exclude_unset=True` 参数:
+你可以设置*路径操作装饰器*参数 `response_model_exclude_unset=True`:
-{* ../../docs_src/response_model/tutorial004.py hl[24] *}
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
-然后响应中将不会包含那些默认值,而是仅有实际设置的值。
+这样响应中将不会包含那些默认值,而只包含实际设置的值。
-因此,如果你向*路径操作*发送 ID 为 `foo` 的商品的请求,则响应(不包括默认值)将为:
+因此,如果你向该*路径操作*请求 ID 为 `foo` 的商品,响应(不包括默认值)将为:
```JSON
{
@@ -114,24 +250,18 @@ FastAPI 将使用此 `response_model` 来:
}
```
-/// info
-
-FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。
-
-///
-
-/// info
+/// info | 信息
你还可以使用:
* `response_model_exclude_defaults=True`
* `response_model_exclude_none=True`
-参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。
+详见 Pydantic 文档中对 `exclude_defaults` 和 `exclude_none` 的说明。
///
-#### 默认值字段有实际值的数据
+#### 默认字段有实际值的数据 { #data-with-values-for-fields-with-defaults }
但是,如果你的数据在具有默认值的模型字段中有实际的值,例如 ID 为 `bar` 的项:
@@ -146,7 +276,7 @@ FastAPI 通过 Pydantic 模型的 `.dict()` 配合 `http.HTTPStatus`。
@@ -31,7 +31,7 @@
-/// note | 笔记
+/// note | 注意
某些响应状态码表示响应没有响应体(参阅下一章)。
@@ -39,9 +39,9 @@ FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
///
-## 关于 HTTP 状态码
+## 关于 HTTP 状态码 { #about-http-status-codes }
-/// note | 笔记
+/// note | 注意
如果已经了解 HTTP 状态码,请跳到下一章。
@@ -53,40 +53,40 @@ FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
简言之:
-* `100` 及以上的状态码用于返回**信息**。这类状态码很少直接使用。具有这些状态码的响应不能包含响应体
-* **`200`** 及以上的状态码用于表示**成功**。这些状态码是最常用的
- * `200` 是默认状态代码,表示一切**正常**
- * `201` 表示**已创建**,通常在数据库中创建新记录后使用
- * `204` 是一种特殊的例子,表示**无内容**。该响应在没有为客户端返回内容时使用,因此,该响应不能包含响应体
-* **`300`** 及以上的状态码用于**重定向**。具有这些状态码的响应不一定包含响应体,但 `304`**未修改**是个例外,该响应不得包含响应体
-* **`400`** 及以上的状态码用于表示**客户端错误**。这些可能是第二常用的类型
- * `404`,用于**未找到**响应
+* `100 - 199` 用于返回“信息”。这类状态码很少直接使用。具有这些状态码的响应不能包含响应体
+* **`200 - 299`** 用于表示“成功”。这些状态码是最常用的
+ * `200` 是默认状态码,表示一切“OK”
+ * `201` 表示“已创建”,通常在数据库中创建新记录后使用
+ * `204` 是一种特殊的例子,表示“无内容”。该响应在没有为客户端返回内容时使用,因此,该响应不能包含响应体
+* **`300 - 399`** 用于“重定向”。具有这些状态码的响应不一定包含响应体,但 `304`“未修改”是个例外,该响应不得包含响应体
+* **`400 - 499`** 用于表示“客户端错误”。这些可能是第二常用的类型
+ * `404`,用于“未找到”响应
* 对于来自客户端的一般错误,可以只使用 `400`
-* `500` 及以上的状态码用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态代码
+* `500 - 599` 用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态码
/// tip | 提示
-状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。
+状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。
///
-## 状态码名称快捷方式
+## 状态码名称快捷方式 { #shortcut-to-remember-the-names }
再看下之前的例子:
-{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
-`201` 表示**已创建**的状态码。
+`201` 表示“已创建”的状态码。
但我们没有必要记住所有代码的含义。
可以使用 `fastapi.status` 中的快捷变量。
-{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
这只是一种快捷方式,具有相同的数字代码,但它可以使用编辑器的自动补全功能:
-
+
/// note | 技术细节
@@ -96,6 +96,6 @@ FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
///
-## 更改默认状态码
+## 更改默认状态码 { #changing-the-default }
[高级用户指南](../advanced/response-change-status-code.md){.internal-link target=_blank}中,将介绍如何返回与在此声明的默认状态码不同的状态码。
diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md
index 6c132eed3..818ff5087 100644
--- a/docs/zh/docs/tutorial/schema-extra-example.md
+++ b/docs/zh/docs/tutorial/schema-extra-example.md
@@ -1,55 +1,202 @@
-# 模式的额外信息 - 例子
+# 声明请求示例数据 { #declare-request-example-data }
-您可以在JSON模式中定义额外的信息。
+你可以为你的应用将接收的数据声明示例。
-一个常见的用例是添加一个将在文档中显示的`example`。
+这里有几种实现方式。
-有几种方法可以声明额外的 JSON 模式信息。
+## Pydantic 模型中的额外 JSON Schema 数据 { #extra-json-schema-data-in-pydantic-models }
-## Pydantic `schema_extra`
+你可以为一个 Pydantic 模型声明 `examples`,它们会被添加到生成的 JSON Schema 中。
-您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如Pydantic 文档:定制 Schema 中所述:
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
-{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:21] *}
+这些额外信息会原样添加到该模型输出的 JSON Schema 中,并会在 API 文档中使用。
-这些额外的信息将按原样添加到输出的JSON模式中。
+你可以使用属性 `model_config`,它接收一个 `dict`,详见 Pydantic 文档:配置。
-## `Field` 的附加参数
+你可以设置 `"json_schema_extra"`,其值为一个 `dict`,包含你希望出现在生成 JSON Schema 中的任意附加数据,包括 `examples`。
-在 `Field`, `Path`, `Query`, `Body` 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 `example`:
+/// tip | 提示
-{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+你也可以用同样的技巧扩展 JSON Schema,添加你自己的自定义额外信息。
-/// warning
-
-请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。
+例如,你可以用它为前端用户界面添加元数据等。
///
-## `Body` 额外参数
+/// info | 信息
-你可以通过传递额外信息给 `Field` 同样的方式操作`Path`, `Query`, `Body`等。
+OpenAPI 3.1.0(自 FastAPI 0.99.0 起使用)增加了对 `examples` 的支持,它是 JSON Schema 标准的一部分。
-比如,你可以将请求体的一个 `example` 传递给 `Body`:
+在此之前,只支持使用单个示例的关键字 `example`。OpenAPI 3.1.0 仍然支持它,但它已被弃用,并不属于 JSON Schema 标准。因此,建议你把 `example` 迁移到 `examples`。🤓
-{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:27] *}
+你可以在本页末尾阅读更多内容。
-## 文档 UI 中的例子
+///
-使用上面的任何方法,它在 `/docs` 中看起来都是这样的:
+## `Field` 的附加参数 { #field-additional-arguments }
+
+在 Pydantic 模型中使用 `Field()` 时,你也可以声明额外的 `examples`:
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## JSON Schema 中的 `examples` - OpenAPI { #examples-in-json-schema-openapi }
+
+在以下任意场景中使用:
+
+- `Path()`
+- `Query()`
+- `Header()`
+- `Cookie()`
+- `Body()`
+- `Form()`
+- `File()`
+
+你也可以声明一组 `examples`,这些带有附加信息的示例将被添加到它们在 OpenAPI 中的 JSON Schema 里。
+
+### 带有 `examples` 的 `Body` { #body-with-examples }
+
+这里我们向 `Body()` 传入 `examples`,其中包含一个期望的数据示例:
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### 文档 UI 中的示例 { #example-in-the-docs-ui }
+
+使用上述任一方法,在 `/docs` 中看起来会是这样:
-## 技术细节
+### 带有多个 `examples` 的 `Body` { #body-with-multiple-examples }
-关于 `example` 和 `examples`...
+当然,你也可以传入多个 `examples`:
-JSON Schema在最新的一个版本中定义了一个字段 `examples` ,但是 OpenAPI 基于之前的一个旧版JSON Schema,并没有 `examples`.
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
-所以 OpenAPI为了相似的目的定义了自己的 `example` (使用 `example`, 而不是 `examples`), 这也是文档 UI 所使用的 (使用 Swagger UI).
+这样做时,这些示例会成为该请求体数据内部 JSON Schema 的一部分。
-所以,虽然 `example` 不是JSON Schema的一部分,但它是OpenAPI的一部分,这将被文档UI使用。
+不过,在撰写本文时,用于展示文档 UI 的 Swagger UI 并不支持显示 JSON Schema 中数据的多个示例。但请继续阅读,下面有一种变通方法。
-## 其他信息
+### OpenAPI 特定的 `examples` { #openapi-specific-examples }
-同样的方法,你可以添加你自己的额外信息,这些信息将被添加到每个模型的JSON模式中,例如定制前端用户界面,等等。
+在 JSON Schema 支持 `examples` 之前,OpenAPI 就已支持一个同名但不同的字段 `examples`。
+
+这个面向 OpenAPI 的 `examples` 位于 OpenAPI 规范的另一处。它放在每个路径操作的详细信息中,而不是每个 JSON Schema 里。
+
+而 Swagger UI 早就支持这个特定的 `examples` 字段。因此,你可以用它在文档 UI 中展示不同的示例。
+
+这个 OpenAPI 特定字段 `examples` 的结构是一个包含多个示例的 `dict`(而不是一个 `list`),每个示例都包含会被添加到 OpenAPI 的额外信息。
+
+这不放在 OpenAPI 内部包含的各个 JSON Schema 里,而是直接放在路径操作上。
+
+### 使用 `openapi_examples` 参数 { #using-the-openapi-examples-parameter }
+
+你可以在 FastAPI 中通过参数 `openapi_examples` 来声明这个 OpenAPI 特定的 `examples`,适用于:
+
+- `Path()`
+- `Query()`
+- `Header()`
+- `Cookie()`
+- `Body()`
+- `Form()`
+- `File()`
+
+这个 `dict` 的键用于标识每个示例,每个值是另一个 `dict`。
+
+`examples` 中每个具体示例的 `dict` 可以包含:
+
+- `summary`:该示例的简短描述。
+- `description`:较长描述,可以包含 Markdown 文本。
+- `value`:实际展示的示例,例如一个 `dict`。
+- `externalValue`:`value` 的替代项,指向该示例的 URL。不过它的工具支持度可能不如 `value`。
+
+你可以这样使用:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### 文档 UI 中的 OpenAPI 示例 { #openapi-examples-in-the-docs-ui }
+
+当把 `openapi_examples` 添加到 `Body()` 后,`/docs` 会如下所示:
+
+
+
+## 技术细节 { #technical-details }
+
+/// tip | 提示
+
+如果你已经在使用 FastAPI 版本 0.99.0 或更高版本,你大概率可以跳过这些细节。
+
+它们对更早版本(OpenAPI 3.1.0 尚不可用之前)更相关。
+
+你可以把这当作一堂简短的 OpenAPI 和 JSON Schema 历史课。🤓
+
+///
+
+/// warning | 警告
+
+以下是关于 JSON Schema 和 OpenAPI 标准的非常技术性的细节。
+
+如果上面的思路对你已经足够可用,你可能不需要这些细节,可以直接跳过。
+
+///
+
+在 OpenAPI 3.1.0 之前,OpenAPI 使用的是一个更旧且经过修改的 JSON Schema 版本。
+
+当时 JSON Schema 没有 `examples`,所以 OpenAPI 在它修改过的版本中添加了自己的 `example` 字段。
+
+OpenAPI 还在规范的其他部分添加了 `example` 和 `examples` 字段:
+
+- `Parameter Object`(规范中),被 FastAPI 的以下内容使用:
+ - `Path()`
+ - `Query()`
+ - `Header()`
+ - `Cookie()`
+- `Request Body Object` 中的 `content` 字段里的 `Media Type Object`(规范中),被 FastAPI 的以下内容使用:
+ - `Body()`
+ - `File()`
+ - `Form()`
+
+/// info | 信息
+
+这个旧的、OpenAPI 特定的 `examples` 参数,自 FastAPI `0.103.0` 起改名为 `openapi_examples`。
+
+///
+
+### JSON Schema 的 `examples` 字段 { #json-schemas-examples-field }
+
+后来,JSON Schema 在新版本的规范中添加了 `examples` 字段。
+
+随后新的 OpenAPI 3.1.0 基于最新版本(JSON Schema 2020-12),其中包含了这个新的 `examples` 字段。
+
+现在,这个新的 `examples` 字段优先于旧的单个(且自定义的)`example` 字段,后者已被弃用。
+
+JSON Schema 中这个新的 `examples` 字段只是一个由示例组成的 `list`,而不是像上面提到的 OpenAPI 其他位置那样带有额外元数据的 `dict`。
+
+/// info | 信息
+
+即使在 OpenAPI 3.1.0 发布、并与 JSON Schema 有了这种更简单的集成之后,有一段时间里,提供自动文档的 Swagger UI 并不支持 OpenAPI 3.1.0(它自 5.0.0 版本起已支持 🎉)。
+
+因此,FastAPI 0.99.0 之前的版本仍然使用低于 3.1.0 的 OpenAPI 版本。
+
+///
+
+### Pydantic 与 FastAPI 的 `examples` { #pydantic-and-fastapi-examples }
+
+当你在 Pydantic 模型中添加 `examples`,通过 `schema_extra` 或 `Field(examples=["something"])`,这些示例会被添加到该 Pydantic 模型的 JSON Schema 中。
+
+这个 Pydantic 模型的 JSON Schema 会被包含到你的 API 的 OpenAPI 中,然后在文档 UI 中使用。
+
+在 FastAPI 0.99.0 之前的版本(0.99.0 及以上使用更新的 OpenAPI 3.1.0),当你在其他工具(`Query()`、`Body()` 等)中使用 `example` 或 `examples` 时,这些示例不会被添加到描述该数据的 JSON Schema 中(甚至不会添加到 OpenAPI 自己的 JSON Schema 版本中),而是会直接添加到 OpenAPI 的路径操作声明中(在 OpenAPI 使用 JSON Schema 的部分之外)。
+
+但现在 FastAPI 0.99.0 及以上使用 OpenAPI 3.1.0(其使用 JSON Schema 2020-12)以及 Swagger UI 5.0.0 及以上后,一切更加一致,示例会包含在 JSON Schema 中。
+
+### Swagger UI 与 OpenAPI 特定的 `examples` { #swagger-ui-and-openapi-specific-examples }
+
+此前,由于 Swagger UI 不支持多个 JSON Schema 示例(截至 2023-08-26),用户无法在文档中展示多个示例。
+
+为了解决这个问题,FastAPI `0.103.0` 通过新增参数 `openapi_examples`,为声明同样的旧式 OpenAPI 特定 `examples` 字段提供了支持。🤓
+
+### 总结 { #summary }
+
+我曾经说我不太喜欢历史……结果现在在这儿上“技术史”课。😅
+
+简而言之,升级到 FastAPI 0.99.0 或更高版本,一切会更简单、一致、直观,你也不必了解这些历史细节。😎
diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md
index 225eb2695..43b7c6657 100644
--- a/docs/zh/docs/tutorial/security/first-steps.md
+++ b/docs/zh/docs/tutorial/security/first-steps.md
@@ -1,197 +1,203 @@
-# 安全 - 第一步
+# 安全 - 第一步 { #security-first-steps }
-假设**后端** API 在某个域。
+假设你的**后端** API 位于某个域名下。
-**前端**在另一个域,或(移动应用中)在同一个域的不同路径下。
+而**前端**在另一个域名,或同一域名的不同路径(或在移动应用中)。
-并且,前端要使用后端的 **username** 与 **password** 验证用户身份。
+你希望前端能通过**username** 和 **password** 与后端进行身份验证。
-固然,**FastAPI** 支持 **OAuth2** 身份验证。
+我们可以用 **OAuth2** 在 **FastAPI** 中实现它。
-但为了节省开发者的时间,不要只为了查找很少的内容,不得不阅读冗长的规范文档。
+但为了节省你的时间,不必为获取少量信息而通读冗长的规范。
-我们建议使用 **FastAPI** 的安全工具。
+我们直接使用 **FastAPI** 提供的安全工具。
-## 概览
+## 效果预览 { #how-it-looks }
-首先,看看下面的代码是怎么运行的,然后再回过头来了解其背后的原理。
+先直接运行代码看看效果,之后再回过头理解其背后的原理。
-## 创建 `main.py`
+## 创建 `main.py` { #create-main-py }
把下面的示例代码复制到 `main.py`:
{* ../../docs_src/security/tutorial001_an_py39.py *}
-## 运行
+## 运行 { #run-it }
-/// info | 说明
+/// info | 信息
-先安装 `python-multipart`。
+当你使用命令 `pip install "fastapi[standard]"` 安装 **FastAPI** 时,`python-multipart` 包会自动安装。
-安装命令: `pip install python-multipart`。
+但是,如果你使用 `pip install fastapi`,默认不会包含 `python-multipart` 包。
-这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。
+如需手动安装,请先创建并激活[虚拟环境](../../virtual-environments.md){.internal-link target=_blank},然后执行:
+
+```console
+$ pip install python-multipart
+```
+
+这是因为 **OAuth2** 使用“表单数据”来发送 `username` 和 `password`。
///
-用下面的命令运行该示例:
+用下面的命令运行示例:
/// check | Authorize 按钮!
-页面右上角出现了一个「**Authorize**」按钮。
+页面右上角已经有一个崭新的“Authorize”按钮。
-*路径操作*的右上角也出现了一个可以点击的小锁图标。
+你的*路径操作*右上角还有一个可点击的小锁图标。
///
-点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段:
+点击它,会弹出一个授权表单,可输入 `username` 和 `password`(以及其它可选字段):
-/// note | 笔记
+/// note | 注意
-目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。
+目前无论在表单中输入什么都不会生效,我们稍后就会实现它。
///
-虽然此文档不是给前端最终用户使用的,但这个自动工具非常实用,可在文档中与所有 API 交互。
+这当然不是面向最终用户的前端,但它是一个很棒的自动化工具,可交互式地为整个 API 提供文档。
-前端团队(可能就是开发者本人)可以使用本工具。
+前端团队(也可能就是你自己)可以使用它。
-第三方应用与系统也可以调用本工具。
+第三方应用和系统也可以使用它。
-开发者也可以用它来调试、检查、测试应用。
+你也可以用它来调试、检查和测试同一个应用。
-## 密码流
+## `password` 流 { #the-password-flow }
-现在,我们回过头来介绍这段代码的原理。
+现在回过头来理解这些内容。
-`Password` **流**是 OAuth2 定义的,用于处理安全与身份验证的方式(**流**)。
+`password` “流”(flow)是 OAuth2 定义的处理安全与身份验证的一种方式。
-OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户身份。
+OAuth2 的设计目标是让后端或 API 与负责用户认证的服务器解耦。
-但在本例中,**FastAPI** 应用会处理 API 与身份验证。
+但在这个例子中,**FastAPI** 应用同时处理 API 和认证。
-下面,我们来看一下简化的运行流程:
+从这个简化的角度来看看流程:
-- 用户在前端输入 `username` 与`password`,并点击**回车**
-- (用户浏览器中运行的)前端把 `username` 与`password` 发送至 API 中指定的 URL(使用 `tokenUrl="token"` 声明)
-- API 检查 `username` 与`password`,并用令牌(`Token`) 响应(暂未实现此功能):
- - 令牌只是用于验证用户的字符串
- - 一般来说,令牌会在一段时间后过期
- - 过时后,用户要再次登录
- - 这样一来,就算令牌被人窃取,风险也较低。因为它与永久密钥不同,**在绝大多数情况下**不会长期有效
-- 前端临时将令牌存储在某个位置
-- 用户点击前端,前往前端应用的其它部件
-- 前端需要从 API 中提取更多数据:
- - 为指定的端点(Endpoint)进行身份验证
- - 因此,用 API 验证身份时,要发送值为 `Bearer` + 令牌的请求头 `Authorization`
- - 假如令牌为 `foobar`,`Authorization` 请求头就是: `Bearer foobar`
+* 用户在前端输入 `username` 和 `password`,然后按下 `Enter`。
+* 前端(运行在用户浏览器中)把 `username` 和 `password` 发送到我们 API 中的特定 URL(使用 `tokenUrl="token"` 声明)。
+* API 校验 `username` 和 `password`,并返回一个“令牌”(这些我们尚未实现)。
+ * “令牌”只是一个字符串,包含一些内容,之后可用来验证该用户。
+ * 通常,令牌会在一段时间后过期。
+ * 因此,用户过一段时间需要重新登录。
+ * 如果令牌被窃取,风险也更小。它不像一把永久有效的钥匙(在大多数情况下)。
+* 前端会把令牌临时存储在某处。
+* 用户在前端中点击跳转到前端应用的其他部分。
+* 前端需要从 API 获取更多数据。
+ * 但该端点需要身份验证。
+ * 因此,为了与我们的 API 进行身份验证,它会发送一个 `Authorization` 请求头,值为 `Bearer ` 加上令牌。
+ * 如果令牌内容是 `foobar`,`Authorization` 请求头的内容就是:`Bearer foobar`。
-## **FastAPI** 的 `OAuth2PasswordBearer`
+## **FastAPI** 的 `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }
-**FastAPI** 提供了不同抽象级别的安全工具。
+**FastAPI** 在不同抽象层级提供了多种安全工具。
-本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。
+本示例将使用 **OAuth2** 的 **Password** 流程并配合 **Bearer** 令牌,通过 `OAuth2PasswordBearer` 类来实现。
-/// info | 说明
+/// info | 信息
-`Bearer` 令牌不是唯一的选择。
+“Bearer” 令牌并非唯一选项。
-但它是最适合这个用例的方案。
+但它非常适合我们的用例。
-甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。
+对于大多数用例,它也可能是最佳选择,除非你是 OAuth2 专家,并明确知道为何其他方案更适合你的需求。
-本例中,**FastAPI** 还提供了构建工具。
+在那种情况下,**FastAPI** 同样提供了相应的构建工具。
///
-创建 `OAuth2PasswordBearer` 的类实例时,要传递 `tokenUrl` 参数。该参数包含客户端(用户浏览器中运行的前端) 的 URL,用于发送 `username` 与 `password`,并获取令牌。
+创建 `OAuth2PasswordBearer` 类实例时,需要传入 `tokenUrl` 参数。该参数包含客户端(运行在用户浏览器中的前端)用来发送 `username` 和 `password` 以获取令牌的 URL。
-{* ../../docs_src/security/tutorial001.py hl[6] *}
+{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *}
/// tip | 提示
-在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。
+这里的 `tokenUrl="token"` 指向的是尚未创建的相对 URL `token`,等价于 `./token`。
-因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。
+因为使用的是相对 URL,若你的 API 位于 `https://example.com/`,它将指向 `https://example.com/token`;若你的 API 位于 `https://example.com/api/v1/`,它将指向 `https://example.com/api/v1/token`。
-使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。
+使用相对 URL 很重要,这能确保你的应用在诸如[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}等高级用例中依然正常工作。
///
-该参数不会创建端点或*路径操作*,但会声明客户端用来获取令牌的 URL `/token` 。此信息用于 OpenAPI 及 API 文档。
+这个参数不会创建该端点/*路径操作*,而是声明客户端应使用 `/token` 这个 URL 来获取令牌。这些信息会用于 OpenAPI,进而用于交互式 API 文档系统。
-接下来,学习如何创建实际的路径操作。
+我们很快也会创建对应的实际路径操作。
-/// info | 说明
+/// info | 信息
-严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。
+如果你是非常严格的 “Pythonista”,可能不喜欢使用参数名 `tokenUrl` 而不是 `token_url`。
-这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。
+这是因为它使用了与 OpenAPI 规范中相同的名称。这样当你需要深入了解这些安全方案时,可以直接复制粘贴去查找更多信息。
///
-`oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的实例,也是**可调用项**。
+`oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的一个实例,同时它也是“可调用”的。
-以如下方式调用:
+可以像这样调用:
```Python
oauth2_scheme(some, parameters)
```
-因此,`Depends` 可以调用 `oauth2_scheme` 变量。
+因此,它可以与 `Depends` 一起使用。
-### 使用
+### 使用 { #use-it }
-接下来,使用 `Depends` 把 `oauth2_scheme` 传入依赖项。
+现在你可以通过 `Depends` 将 `oauth2_scheme` 作为依赖传入。
-{* ../../docs_src/security/tutorial001.py hl[10] *}
+{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
-该依赖项使用字符串(`str`)接收*路径操作函数*的参数 `token` 。
+该依赖会提供一个 `str`,赋值给*路径操作函数*的参数 `token`。
-**FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。
+**FastAPI** 会据此在 OpenAPI 架构(以及自动生成的 API 文档)中定义一个“安全方案”。
/// info | 技术细节
-**FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。
+**FastAPI** 之所以知道可以使用(在依赖中声明的)`OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,是因为它继承自 `fastapi.security.oauth2.OAuth2`,而后者又继承自 `fastapi.security.base.SecurityBase`。
-所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。
+所有与 OpenAPI(以及自动 API 文档)集成的安全工具都继承自 `SecurityBase`,这就是 **FastAPI** 能将它们集成到 OpenAPI 的方式。
///
-## 实现的操作
+## 它做了什么 { #what-it-does }
-FastAPI 校验请求中的 `Authorization` 请求头,核对请求头的值是不是由 `Bearer ` + 令牌组成, 并返回令牌字符串(`str`)。
+它会在请求中查找 `Authorization` 请求头,检查其值是否为 `Bearer ` 加上一些令牌,并将该令牌作为 `str` 返回。
-如果没有找到 `Authorization` 请求头,或请求头的值不是 `Bearer ` + 令牌。FastAPI 直接返回 401 错误状态码(`UNAUTHORIZED`)。
+如果没有 `Authorization` 请求头,或者其值不包含 `Bearer ` 令牌,它会直接返回 401 状态码错误(`UNAUTHORIZED`)。
-开发者不需要检查错误信息,查看令牌是否存在,只要该函数能够执行,函数中就会包含令牌字符串。
+你甚至无需检查令牌是否存在即可返回错误;只要你的函数被执行,就可以确定会拿到一个 `str` 类型的令牌。
-正如下图所示,API 文档已经包含了这项功能:
+你已经可以在交互式文档中试试了:
-目前,暂时还没有实现验证令牌是否有效的功能,不过后文很快就会介绍的。
+我们还没有验证令牌是否有效,但这已经是一个良好的开端。
-## 小结
+## 小结 { #recap }
-看到了吧,只要多写三四行代码,就可以添加基础的安全表单。
+只需增加三四行代码,你就已经拥有了一种初步的安全机制。
diff --git a/docs/zh/docs/tutorial/security/get-current-user.md b/docs/zh/docs/tutorial/security/get-current-user.md
index 1f254a103..c14bba28a 100644
--- a/docs/zh/docs/tutorial/security/get-current-user.md
+++ b/docs/zh/docs/tutorial/security/get-current-user.md
@@ -1,23 +1,23 @@
-# 获取当前用户
+# 获取当前用户 { #get-current-user }
上一章中,(基于依赖注入系统的)安全系统向*路径操作函数*传递了 `str` 类型的 `token`:
-{* ../../docs_src/security/tutorial001.py hl[10] *}
+{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
但这并不实用。
接下来,我们学习如何返回当前用户。
-## 创建用户模型
+## 创建用户模型 { #create-a-user-model }
首先,创建 Pydantic 用户模型。
与使用 Pydantic 声明请求体相同,并且可在任何位置使用:
-{* ../../docs_src/security/tutorial002.py hl[5,12:16] *}
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
-## 创建 `get_current_user` 依赖项
+## 创建 `get_current_user` 依赖项 { #create-a-get-current-user-dependency }
创建 `get_current_user` 依赖项。
@@ -27,19 +27,19 @@
与之前直接在路径操作中的做法相同,新的 `get_current_user` 依赖项从子依赖项 `oauth2_scheme` 中接收 `str` 类型的 `token`:
-{* ../../docs_src/security/tutorial002.py hl[25] *}
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
-## 获取用户
+## 获取用户 { #get-the-user }
`get_current_user` 使用创建的(伪)工具函数,该函数接收 `str` 类型的令牌,并返回 Pydantic 的 `User` 模型:
-{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *}
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
-## 注入当前用户
+## 注入当前用户 { #inject-the-current-user }
在*路径操作* 的 `Depends` 中使用 `get_current_user`:
-{* ../../docs_src/security/tutorial002.py hl[31] *}
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
注意,此处把 `current_user` 的类型声明为 Pydantic 的 `User` 模型。
@@ -61,7 +61,7 @@
///
-## 其它模型
+## 其它模型 { #other-models }
接下来,直接在*路径操作函数*中获取当前用户,并用 `Depends` 在**依赖注入**系统中处理安全机制。
@@ -78,7 +78,7 @@
尽管使用应用所需的任何模型、类、数据库。**FastAPI** 通过依赖注入系统都能帮您搞定。
-## 代码大小
+## 代码大小 { #code-size }
这个示例看起来有些冗长。毕竟这个文件同时包含了安全、数据模型的工具函数,以及路径操作等代码。
@@ -94,9 +94,9 @@
所有*路径操作*只需 3 行代码就可以了:
-{* ../../docs_src/security/tutorial002.py hl[30:32] *}
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
-## 小结
+## 小结 { #recap }
现在,我们可以直接在*路径操作函数*中获取当前用户。
diff --git a/docs/zh/docs/tutorial/security/index.md b/docs/zh/docs/tutorial/security/index.md
index 1484b99fd..589f93c3e 100644
--- a/docs/zh/docs/tutorial/security/index.md
+++ b/docs/zh/docs/tutorial/security/index.md
@@ -1,4 +1,4 @@
-# 安全性
+# 安全性 { #security }
有许多方法可以处理安全性、身份认证和授权等问题。
@@ -10,11 +10,11 @@
但首先,让我们来看一些小的概念。
-## 没有时间?
+## 没有时间? { #in-a-hurry }
-如果你不关心这些术语,而只需要*立即*通过基于用户名和密码的身份认证来增加安全性,请跳转到下一章。
+如果你不关心这些术语,而只需要*立即*通过基于用户名和密码的身份认证来增加安全性,请跳转到接下来的章节。
-## OAuth2
+## OAuth2 { #oauth2 }
OAuth2是一个规范,它定义了几种处理身份认证和授权的方法。
@@ -24,7 +24,7 @@ OAuth2是一个规范,它定义了几种处理身份认证和授权的方法
这就是所有带有「使用 Facebook,Google,X (Twitter),GitHub 登录」的系统背后所使用的机制。
-### OAuth 1
+### OAuth 1 { #oauth-1 }
有一个 OAuth 1,它与 OAuth2 完全不同,并且更为复杂,因为它直接包含了有关如何加密通信的规范。
@@ -32,13 +32,13 @@ OAuth2是一个规范,它定义了几种处理身份认证和授权的方法
OAuth2 没有指定如何加密通信,它期望你为应用程序使用 HTTPS 进行通信。
-/// tip
+/// tip | 提示
在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。
///
-## OpenID Connect
+## OpenID Connect { #openid-connect }
OpenID Connect 是另一个基于 **OAuth2** 的规范。
@@ -48,7 +48,7 @@ OpenID Connect 是另一个基于 **OAuth2** 的规范。
但是 Facebook 登录不支持 OpenID Connect。它具有自己的 OAuth2 风格。
-### OpenID(非「OpenID Connect」)
+### OpenID(非「OpenID Connect」) { #openid-not-openid-connect }
还有一个「OpenID」规范。它试图解决与 **OpenID Connect** 相同的问题,但它不是基于 OAuth2。
@@ -56,7 +56,7 @@ OpenID Connect 是另一个基于 **OAuth2** 的规范。
如今它已经不是很流行,没有被广泛使用了。
-## OpenAPI
+## OpenAPI { #openapi }
OpenAPI(以前称为 Swagger)是用于构建 API 的开放规范(现已成为 Linux Foundation 的一部分)。
@@ -75,7 +75,7 @@ OpenAPI 定义了以下安全方案:
* 请求头。
* cookie。
* `http`:标准的 HTTP 身份认证系统,包括:
- * `bearer`: 一个值为 `Bearer` 加令牌字符串的 `Authorization` 请求头。这是从 OAuth2 继承的。
+ * `bearer`: 一个值为 `Bearer ` 加令牌字符串的 `Authorization` 请求头。这是从 OAuth2 继承的。
* HTTP Basic 认证方式。
* HTTP Digest,等等。
* `oauth2`:所有的 OAuth2 处理安全性的方式(称为「流程」)。
@@ -89,7 +89,7 @@ OpenAPI 定义了以下安全方案:
* 此自动发现机制是 OpenID Connect 规范中定义的内容。
-/// tip
+/// tip | 提示
集成其他身份认证/授权提供者(例如Google,Facebook,X (Twitter),GitHub等)也是可能的,而且较为容易。
@@ -97,10 +97,10 @@ OpenAPI 定义了以下安全方案:
///
-## **FastAPI** 实用工具
+## **FastAPI** 实用工具 { #fastapi-utilities }
FastAPI 在 `fastapi.security` 模块中为每个安全方案提供了几种工具,这些工具简化了这些安全机制的使用方法。
-在下一章中,你将看到如何使用 **FastAPI** 所提供的这些工具为你的 API 增加安全性。
+在接下来的章节中,你将看到如何使用 **FastAPI** 所提供的这些工具为你的 API 增加安全性。
而且你还将看到它如何自动地被集成到交互式文档系统中。
diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md
index 7d338419b..c7eb9bd90 100644
--- a/docs/zh/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md
@@ -1,34 +1,36 @@
-# OAuth2 实现密码哈希与 Bearer JWT 令牌验证
+# 使用密码(及哈希)的 OAuth2,基于 JWT 的 Bearer 令牌 { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
-至此,我们已经编写了所有安全流,本章学习如何使用 JWT 令牌(Token)和安全密码哈希(Hash)实现真正的安全机制。
+现在我们已经有了完整的安全流程,接下来用 JWT 令牌和安全的密码哈希,让应用真正安全起来。
-本章的示例代码真正实现了在应用的数据库中保存哈希密码等功能。
+这些代码可以直接用于你的应用,你可以把密码哈希保存到数据库中,等等。
-接下来,我们紧接上一章,继续完善安全机制。
+我们将从上一章结束的地方继续,逐步完善。
-## JWT 简介
+## 关于 JWT { #about-jwt }
-JWT 即**JSON 网络令牌**(JSON Web Tokens)。
+JWT 意为 “JSON Web Tokens”。
-JWT 是一种将 JSON 对象编码为没有空格,且难以理解的长字符串的标准。JWT 的内容如下所示:
+它是一种标准,把一个 JSON 对象编码成没有空格、很密集的一长串字符串。看起来像这样:
```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
```
-JWT 字符串没有加密,任何人都能用它恢复原始信息。
+它不是加密的,所以任何人都可以从内容中恢复信息。
-但 JWT 使用了签名机制。接受令牌时,可以用签名校验令牌。
+但它是“签名”的。因此,当你收到一个自己签发的令牌时,你可以验证它确实是你签发的。
-使用 JWT 创建有效期为一周的令牌。第二天,用户持令牌再次访问时,仍为登录状态。
+这样你就可以创建一个例如有效期为 1 周的令牌。然后当用户第二天带着这个令牌回来时,你能知道该用户仍然处于登录状态。
-令牌于一周后过期,届时,用户身份验证就会失败。只有再次登录,才能获得新的令牌。如果用户(或第三方)篡改令牌的过期时间,因为签名不匹配会导致身份验证失败。
+一周后令牌过期,用户将不再被授权,需要重新登录以获取新令牌。而如果用户(或第三方)尝试修改令牌来更改过期时间,你也能发现,因为签名将不匹配。
-如需深入了解 JWT 令牌,了解它的工作方式,请参阅 https://jwt.io。
+如果你想动手体验 JWT 令牌并了解它的工作方式,请访问 https://jwt.io。
-## 安装 `PyJWT`
+## 安装 `PyJWT` { #install-pyjwt }
-安装 `PyJWT`,在 Python 中生成和校验 JWT 令牌:
+我们需要安装 `PyJWT`,以便在 Python 中生成和校验 JWT 令牌。
+
+请确保创建并激活一个[虚拟环境](../../virtual-environments.md){.internal-link target=_blank},然后安装 `pyjwt`:
+
-用与上一章同样的方式实现应用授权。
+像之前一样进行授权。
-使用如下凭证:
+使用以下凭证:
-用户名: `johndoe` 密码: `secret`
+用户名: `johndoe`
+密码: `secret`
/// check | 检查
-注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。
+注意,代码中的任何地方都没有明文密码 “`secret`”,我们只有它的哈希版本。
///
-
+
-调用 `/users/me/` 端点,收到下面的响应:
+调用 `/users/me/` 端点,你将得到如下响应:
```JSON
{
@@ -225,46 +228,46 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。
}
```
-
+
-打开浏览器的开发者工具,查看数据是怎么发送的,而且数据里只包含了令牌,只有验证用户的第一个请求才发送密码,并获取访问令牌,但之后不会再发送密码:
+如果你打开开发者工具,你会看到发送的数据只包含令牌。密码只会在第一个请求中用于认证用户并获取访问令牌,之后就不会再发送密码了:
-
+
-/// note | 笔记
+/// note | 注意
-注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。
+注意 `Authorization` 请求头,其值以 `Bearer ` 开头。
///
-## `scopes` 高级用法
+## 使用 `scopes` 的高级用法 { #advanced-usage-with-scopes }
-OAuth2 支持**`scopes`**(作用域)。
+OAuth2 支持 “scopes”(作用域)。
-**`scopes`**为 JWT 令牌添加指定权限。
+你可以用它们为 JWT 令牌添加一组特定的权限。
-让持有令牌的用户或第三方在指定限制条件下与 API 交互。
+然后你可以把这个令牌直接交给用户或第三方,在一组限制条件下与 API 交互。
-**高级用户指南**中将介绍如何使用 `scopes`,及如何把 `scopes` 集成至 **FastAPI**。
+在**高级用户指南**中你将学习如何使用它们,以及它们如何集成进 **FastAPI**。
-## 小结
+## 小结 { #recap }
-至此,您可以使用 OAuth2 和 JWT 等标准配置安全的 **FastAPI** 应用。
+通过目前所学内容,你可以使用 OAuth2 和 JWT 等标准来搭建一个安全的 **FastAPI** 应用。
-几乎在所有框架中,处理安全问题很快都会变得非常复杂。
+在几乎任何框架中,处理安全问题都会很快变得相当复杂。
-有些包为了简化安全流,不得不在数据模型、数据库和功能上做出妥协。而有些过于简化的软件包其实存在了安全隐患。
+许多把安全流程大幅简化的包,往往要在数据模型、数据库和可用特性上做出大量妥协。而有些过度简化的包实际上在底层存在安全隐患。
---
-**FastAPI** 不向任何数据库、数据模型或工具做妥协。
+**FastAPI** 不会在任何数据库、数据模型或工具上做妥协。
-开发者可以灵活选择最适合项目的安全机制。
+它给予你完全的灵活性,选择最适合你项目的方案。
-还可以直接使用 `passlib` 和 `PyJWT` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。
+而且你可以直接使用许多维护良好、广泛使用的包,比如 `pwdlib` 和 `PyJWT`,因为 **FastAPI** 不需要复杂机制来集成外部包。
-而且,**FastAPI** 还提供了一些工具,在不影响灵活、稳定和安全的前提下,尽可能地简化安全机制。
+同时它也为你提供尽可能简化流程的工具,而不牺牲灵活性、健壮性或安全性。
-**FastAPI** 还支持以相对简单的方式,使用 OAuth2 等安全、标准的协议。
+你可以以相对简单的方式使用和实现像 OAuth2 这样的安全、标准协议。
-**高级用户指南**中详细介绍了 OAuth2**`scopes`**的内容,遵循同样的标准,实现更精密的权限系统。OAuth2 的作用域是脸书、谷歌、GitHub、微软、推特等第三方身份验证应用使用的机制,让用户授权第三方应用与 API 交互。
+在**高级用户指南**中,你可以进一步了解如何使用 OAuth2 的 “scopes”,以遵循相同标准实现更细粒度的权限系统。带作用域的 OAuth2 是许多大型身份认证提供商(如 Facebook、Google、GitHub、Microsoft、X(Twitter)等)用来授权第三方应用代表其用户与其 API 交互的机制。
diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md
index f70678df8..3037a983b 100644
--- a/docs/zh/docs/tutorial/security/simple-oauth2.md
+++ b/docs/zh/docs/tutorial/security/simple-oauth2.md
@@ -1,8 +1,8 @@
-# OAuth2 实现简单的 Password 和 Bearer 验证
+# OAuth2 实现简单的 Password 和 Bearer 验证 { #simple-oauth2-with-password-and-bearer }
本章添加上一章示例中欠缺的部分,实现完整的安全流。
-## 获取 `username` 和 `password`
+## 获取 `username` 和 `password` { #get-the-username-and-password }
首先,使用 **FastAPI** 安全工具获取 `username` 和 `password`。
@@ -18,7 +18,7 @@ OAuth2 规范要求使用**密码流**时,客户端或用户必须以表单数
该规范要求必须以表单数据形式发送 `username` 和 `password`,因此,不能使用 JSON 对象。
-### `Scope`(作用域)
+### `scope` { #scope }
OAuth2 还支持客户端发送**`scope`**表单字段。
@@ -32,7 +32,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。
* 脸书和 Instagram 使用 `instagram_basic`
* 谷歌使用 `https://www.googleapis.com/auth/drive`
-/// info | 说明
+/// info | 信息
OAuth2 中,**作用域**只是声明指定权限的字符串。
@@ -44,15 +44,15 @@ OAuth2 中,**作用域**只是声明指定权限的字符串。
///
-## 获取 `username` 和 `password` 的代码
+## 获取 `username` 和 `password` 的代码 { #code-to-get-the-username-and-password }
接下来,使用 **FastAPI** 工具获取用户名与密码。
-### `OAuth2PasswordRequestForm`
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
首先,导入 `OAuth2PasswordRequestForm`,然后,在 `/token` *路径操作* 中,用 `Depends` 把该类作为依赖项。
-{* ../../docs_src/security/tutorial003.py hl[4,76] *}
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
`OAuth2PasswordRequestForm` 是用以下几项内容声明表单请求体的类依赖项:
@@ -72,7 +72,7 @@ OAuth2 中,**作用域**只是声明指定权限的字符串。
* 可选的 `client_id`(本例未使用)
* 可选的 `client_secret`(本例未使用)
-/// info | 说明
+/// info | 信息
`OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。
@@ -84,7 +84,7 @@ OAuth2 中,**作用域**只是声明指定权限的字符串。
///
-### 使用表单数据
+### 使用表单数据 { #use-the-form-data }
/// tip | 提示
@@ -100,9 +100,9 @@ OAuth2 中,**作用域**只是声明指定权限的字符串。
本例使用 `HTTPException` 异常显示此错误:
-{* ../../docs_src/security/tutorial003.py hl[3,77:79] *}
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
-### 校验密码
+### 校验密码 { #check-the-password }
至此,我们已经从数据库中获取了用户数据,但尚未校验密码。
@@ -112,7 +112,7 @@ OAuth2 中,**作用域**只是声明指定权限的字符串。
如果密码不匹配,则返回与上面相同的错误。
-#### 密码哈希
+#### 密码哈希 { #password-hashing }
**哈希**是指,将指定内容(本例中为密码)转换为形似乱码的字节序列(其实就是字符串)。
@@ -120,15 +120,15 @@ OAuth2 中,**作用域**只是声明指定权限的字符串。
但这个乱码无法转换回传入的密码。
-##### 为什么使用密码哈希
+##### 为什么使用密码哈希 { #why-use-password-hashing }
原因很简单,假如数据库被盗,窃贼无法获取用户的明文密码,得到的只是哈希值。
这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大。
-{* ../../docs_src/security/tutorial003.py hl[80:83] *}
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
-#### 关于 `**user_dict`
+#### 关于 `**user_dict` { #about-user-dict }
`UserInDB(**user_dict)` 是指:
@@ -144,13 +144,13 @@ UserInDB(
)
```
-/// info | 说明
+/// info | 信息
-`user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。
+`user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#about-user-in-dict){.internal-link target=_blank}。
///
-## 返回 Token
+## 返回 Token { #return-the-token }
`token` 端点的响应必须是 JSON 对象。
@@ -162,13 +162,13 @@ UserInDB(
/// tip | 提示
-下一章介绍使用哈希密码和 JWT Token 的真正安全机制。
+下一章介绍使用哈希密码和 JWT Token 的真正安全机制。
但现在,仅关注所需的特定细节。
///
-{* ../../docs_src/security/tutorial003.py hl[85] *}
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
/// tip | 提示
@@ -182,7 +182,7 @@ UserInDB(
///
-## 更新依赖项
+## 更新依赖项 { #update-the-dependencies }
接下来,更新依赖项。
@@ -194,9 +194,9 @@ UserInDB(
因此,在端点中,只有当用户存在、通过身份验证、且状态为激活时,才能获得该用户:
-{* ../../docs_src/security/tutorial003.py hl[58:67,69:72,90] *}
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
-/// info | 说明
+/// info | 信息
此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。
@@ -210,15 +210,15 @@ UserInDB(
说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。
-这就是遵循标准的好处……
+这就是遵循标准的好处...
///
-## 实际效果
+## 实际效果 { #see-it-in-action }
打开 API 文档:http://127.0.0.1:8000/docs。
-### 身份验证
+### 身份验证 { #authenticate }
点击**Authorize**按钮。
@@ -228,13 +228,13 @@ UserInDB(
密码:`secret`
-
+
通过身份验证后,显示下图所示的内容:
-
+
-### 获取当前用户数据
+### 获取当前用户数据 { #get-your-own-user-data }
使用 `/users/me` 路径的 `GET` 操作。
@@ -250,7 +250,7 @@ UserInDB(
}
```
-
+
点击小锁图标,注销后,再执行同样的操作,则会得到 HTTP 401 错误:
@@ -260,7 +260,7 @@ UserInDB(
}
```
-### 未激活用户
+### 未激活用户 { #inactive-user }
测试未激活用户,输入以下信息,进行身份验证:
@@ -278,7 +278,7 @@ UserInDB(
}
```
-## 小结
+## 小结 { #recap }
使用本章的工具实现基于 `username` 和 `password` 的完整 API 安全系统。
@@ -286,4 +286,4 @@ UserInDB(
唯一欠缺的是,它仍然不是真的**安全**。
-下一章,介绍使用密码哈希支持库与 JWT 令牌实现真正的安全机制。
+下一章,介绍使用密码哈希支持库与 JWT 令牌实现真正的安全机制。
diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md
index fbdf3be6c..944e960a7 100644
--- a/docs/zh/docs/tutorial/sql-databases.md
+++ b/docs/zh/docs/tutorial/sql-databases.md
@@ -1,40 +1,40 @@
-# SQL(关系型)数据库
+# SQL(关系型)数据库 { #sql-relational-databases }
-**FastAPI** 并不要求您使用 SQL(关系型)数据库。您可以使用**任何**想用的数据库。
+**FastAPI** 并不要求你使用 SQL(关系型)数据库。你可以使用你想用的**任何数据库**。
这里,我们来看一个使用 SQLModel 的示例。
-**SQLModel** 是基于 SQLAlchemy 和 Pydantic 构建的。它由 **FastAPI** 的同一作者制作,旨在完美匹配需要使用 **SQL 数据库**的 FastAPI 应用程序。
+**SQLModel** 基于 SQLAlchemy 和 Pydantic 构建。它由 **FastAPI** 的同一作者制作,旨在完美匹配需要使用**SQL 数据库**的 FastAPI 应用程序。
-/// tip
+/// tip | 提示
-您可以使用任何其他您想要的 SQL 或 NoSQL 数据库(在某些情况下称为 “ORM”),FastAPI 不会强迫您使用任何东西。😎
+你可以使用任意其他你想要的 SQL 或 NoSQL 数据库库(在某些情况下称为 "ORMs"),FastAPI 不会强迫你使用任何东西。😎
///
-由于 SQLModel 基于 SQLAlchemy,因此您可以轻松使用任何由 SQLAlchemy **支持的数据库**(这也让它们被 SQLModel 支持),例如:
+由于 SQLModel 基于 SQLAlchemy,因此你可以轻松使用任何由 SQLAlchemy **支持的数据库**(这也让它们被 SQLModel 支持),例如:
* PostgreSQL
* MySQL
* SQLite
* Oracle
-* Microsoft SQL Server 等.
+* Microsoft SQL Server 等
-在这个例子中,我们将使用 **SQLite**,因为它使用单个文件,并且 Python 对其有集成支持。因此,您可以直接复制这个例子并运行。
+在这个示例中,我们将使用 **SQLite**,因为它使用单个文件,并且 Python 对其有集成支持。因此,你可以直接复制这个示例并运行。
-之后,对于您的生产应用程序,您可能会想要使用像 PostgreSQL 这样的数据库服务器。
+之后,对于你的生产应用程序,你可能会想要使用像 **PostgreSQL** 这样的数据库服务器。
-/// tip
+/// tip | 提示
-有一个使用 **FastAPI** 和 **PostgreSQL** 的官方的项目生成器,其中包括了前端和更多工具: https://github.com/fastapi/full-stack-fastapi-template
+有一个使用 **FastAPI** 和 **PostgreSQL** 的官方项目生成器,其中包括了前端和更多工具: https://github.com/fastapi/full-stack-fastapi-template
///
-这是一个非常简单和简短的教程。如果您想了解一般的数据库、SQL 或更高级的功能,请查看 SQLModel 文档。
+这是一个非常简单和简短的教程。如果你想了解一般的数据库、SQL 或更高级的功能,请查看 SQLModel 文档。
-## 安装 `SQLModel`
+## 安装 `SQLModel` { #install-sqlmodel }
-首先,确保您创建并激活了[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后安装了 `sqlmodel` :
+首先,确保你创建并激活了[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后安装 `sqlmodel`:
httpx - Required if you want to use the `TestClient`.
* jinja2 - Required if you want to use the default template configuration.
-* python-multipart - Required if you want to support form "parsing", with `request.form()`.
+* python-multipart - Required if you want to support form "parsing", with `request.form()`.
Used by FastAPI:
diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md
index dbc91409a..be85303bf 100644
--- a/docs/en/docs/advanced/dataclasses.md
+++ b/docs/en/docs/advanced/dataclasses.md
@@ -64,7 +64,7 @@ In that case, you can simply swap the standard `dataclasses` with `pydantic.data
6. Here we are returning a dictionary that contains `items` which is a list of dataclasses.
- FastAPI is still capable of serializing the data to JSON.
+ FastAPI is still capable of serializing the data to JSON.
7. Here the `response_model` is using a type annotation of a list of `Author` dataclasses.
diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md
index e0e3c96a0..3d7bfdee5 100644
--- a/docs/en/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md
@@ -141,7 +141,7 @@ You could do that with `openapi_extra`:
{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py39.py hl[19:36, 39:40] *}
-In this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way.
+In this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way.
Nevertheless, we can declare the expected schema for the request body.
diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md
index e65681543..73a6c1cb5 100644
--- a/docs/en/docs/alternatives.md
+++ b/docs/en/docs/alternatives.md
@@ -137,7 +137,7 @@ There are several Flask REST frameworks, but after investing the time and work i
### Marshmallow { #marshmallow }
-One of the main features needed by API systems is data "serialization" which is taking data from the code (Python) and converting it into something that can be sent through the network. For example, converting an object containing data from a database into a JSON object. Converting `datetime` objects into strings, etc.
+One of the main features needed by API systems is data "serialization" which is taking data from the code (Python) and converting it into something that can be sent through the network. For example, converting an object containing data from a database into a JSON object. Converting `datetime` objects into strings, etc.
Another big feature needed by APIs is data validation, making sure that the data is valid, given certain parameters. For example, that some field is an `int`, and not some random string. This is especially useful for incoming data.
@@ -145,7 +145,7 @@ Without a data validation system, you would have to do all the checks by hand, i
These features are what Marshmallow was built to provide. It is a great library, and I have used it a lot before.
-But it was created before there existed Python type hints. So, to define every schema you need to use specific utils and classes provided by Marshmallow.
+But it was created before there existed Python type hints. So, to define every schema you need to use specific utils and classes provided by Marshmallow.
/// check | Inspired **FastAPI** to
@@ -155,7 +155,7 @@ Use code to define "schemas" that provide data types and validation, automatical
### Webargs { #webargs }
-Another big feature required by APIs is parsing data from incoming requests.
+Another big feature required by APIs is parsing data from incoming requests.
Webargs is a tool that was made to provide that on top of several frameworks, including Flask.
@@ -419,7 +419,7 @@ Handle all the data validation, data serialization and automatic model documenta
### Starlette { #starlette }
-Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services.
+Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services.
It is very simple and intuitive. It's designed to be easily extensible, and have modular components.
diff --git a/docs/en/docs/css/custom.css b/docs/en/docs/css/custom.css
index 87111ff64..7c50dbd9b 100644
--- a/docs/en/docs/css/custom.css
+++ b/docs/en/docs/css/custom.css
@@ -203,3 +203,8 @@ Inspired by Termynal's CSS tricks with modifications
-webkit-box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930;
box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930;
}
+
+.md-typeset dfn {
+ border-bottom: .05rem dotted var(--md-default-fg-color--light);
+ cursor: help;
+}
diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md
index 7219f3afc..0f15a60a4 100644
--- a/docs/en/docs/deployment/docker.md
+++ b/docs/en/docs/deployment/docker.md
@@ -454,7 +454,7 @@ Without using containers, making applications run on startup and with restarts c
## Replication - Number of Processes { #replication-number-of-processes }
-If you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Uvicorn with workers) in each container.
+If you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Uvicorn with workers) in each container.
One of those distributed container management systems like Kubernetes normally has some integrated way of handling **replication of containers** while still supporting **load balancing** for the incoming requests. All at the **cluster level**.
diff --git a/docs/en/docs/deployment/https.md b/docs/en/docs/deployment/https.md
index a249a3672..6ae1228b9 100644
--- a/docs/en/docs/deployment/https.md
+++ b/docs/en/docs/deployment/https.md
@@ -65,7 +65,7 @@ Here's an example of how an HTTPS API could look like, step by step, paying atte
It would probably all start by you **acquiring** some **domain name**. Then, you would configure it in a DNS server (possibly your same cloud provider).
-You would probably get a cloud server (a virtual machine) or something similar, and it would have a fixed **public IP address**.
+You would probably get a cloud server (a virtual machine) or something similar, and it would have a fixed **public IP address**.
In the DNS server(s) you would configure a record (an "`A record`") to point **your domain** to the public **IP address of your server**.
diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md
index a345e4a0e..307607ad7 100644
--- a/docs/en/docs/features.md
+++ b/docs/en/docs/features.md
@@ -6,7 +6,7 @@
### Based on open standards { #based-on-open-standards }
-* OpenAPI for API creation, including declarations of path operations, parameters, request bodies, security, etc.
+* OpenAPI for API creation, including declarations of path operations, parameters, request bodies, security, etc.
* Automatic data model documentation with JSON Schema (as OpenAPI itself is based on JSON Schema).
* Designed around these standards, after a meticulous study. Instead of an afterthought layer on top.
* This also allows using automatic **client code generation** in many languages.
@@ -136,7 +136,7 @@ All built as reusable tools and components that are easy to integrate with your
### Dependency Injection { #dependency-injection }
-FastAPI includes an extremely easy to use, but extremely powerful Dependency Injection system.
+FastAPI includes an extremely easy to use, but extremely powerful Dependency Injection system.
* Even dependencies can have dependencies, creating a hierarchy or **"graph" of dependencies**.
* All **automatically handled** by the framework.
@@ -153,8 +153,8 @@ Any integration is designed to be so simple to use (with dependencies) that you
### Tested { #tested }
-* 100% test coverage.
-* 100% type annotated code base.
+* 100% test coverage.
+* 100% type annotated code base.
* Used in production applications.
## Starlette features { #starlette-features }
@@ -190,7 +190,7 @@ With **FastAPI** you get all of **Pydantic**'s features (as FastAPI is based on
* **No brainfuck**:
* No new schema definition micro-language to learn.
* If you know Python types you know how to use Pydantic.
-* Plays nicely with your **IDE/linter/brain**:
+* Plays nicely with your **IDE/linter/brain**:
* Because pydantic data structures are just instances of classes you define; auto-completion, linting, mypy and your intuition should all work properly with your validated data.
* Validate **complex structures**:
* Use of hierarchical Pydantic models, Python `typing`’s `List` and `Dict`, etc.
diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md
index ff0f4e9d9..7f9d5efbf 100644
--- a/docs/en/docs/index.md
+++ b/docs/en/docs/index.md
@@ -40,7 +40,7 @@ The key features are:
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
-* **Intuitive**: Great editor support. Completion everywhere. Less time debugging.
+* **Intuitive**: Great editor support. Completion everywhere. Less time debugging.
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
* **Robust**: Get production-ready code. With automatic interactive documentation.
@@ -368,7 +368,7 @@ item: Item
* Validation of data:
* Automatic and clear errors when the data is invalid.
* Validation even for deeply nested JSON objects.
-* Conversion of input data: coming from the network to Python data and types. Reading from:
+* Conversion of input data: coming from the network to Python data and types. Reading from:
* JSON.
* Path parameters.
* Query parameters.
@@ -376,7 +376,7 @@ item: Item
* Headers.
* Forms.
* Files.
-* Conversion of output data: converting from Python data and types to network data (as JSON):
+* Conversion of output data: converting from Python data and types to network data (as JSON):
* Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
* `datetime` objects.
* `UUID` objects.
@@ -439,7 +439,7 @@ For a more complete example including more features, see the Dependency Injection** system.
+* A very powerful and easy to use **Dependency Injection** system.
* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
* **GraphQL** integration with Strawberry and other libraries.
@@ -524,7 +524,7 @@ Used by Starlette:
* httpx - Required if you want to use the `TestClient`.
* jinja2 - Required if you want to use the default template configuration.
-* python-multipart - Required if you want to support form "parsing", with `request.form()`.
+* python-multipart - Required if you want to support form "parsing", with `request.form()`.
Used by FastAPI:
diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md
index b685deef2..6de170ada 100644
--- a/docs/en/docs/python-types.md
+++ b/docs/en/docs/python-types.md
@@ -2,7 +2,7 @@
Python has support for optional "type hints" (also called "type annotations").
-These **"type hints"** or annotations are a special syntax that allow declaring the type of a variable.
+These **"type hints"** or annotations are a special syntax that allow declaring the type of a variable.
By declaring types for your variables, editors and tools can give you better support.
@@ -34,7 +34,7 @@ The function does the following:
* Takes a `first_name` and `last_name`.
* Converts the first letter of each one to upper case with `title()`.
-* Concatenates them with a space in the middle.
+* Concatenates them with a space in the middle.
{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
@@ -222,7 +222,7 @@ You can declare that a variable can be any of **several types**, for example, an
In Python 3.6 and above (including Python 3.10) you can use the `Union` type from `typing` and put inside the square brackets the possible types to accept.
-In Python 3.10 there's also a **new syntax** where you can put the possible types separated by a vertical bar (`|`).
+In Python 3.10 there's also a **new syntax** where you can put the possible types separated by a vertical bar (`|`).
//// tab | Python 3.10+
@@ -336,7 +336,7 @@ And the same as with previous Python versions, from the `typing` module:
* `Optional`
* ...and others.
-In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the vertical bar (`|`) to declare unions of types, that's a lot better and simpler.
+In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the vertical bar (`|`) to declare unions of types, that's a lot better and simpler.
////
@@ -411,7 +411,7 @@ Pydantic has a special behavior when you use `Optional` or `Union[Something, Non
## Type Hints with Metadata Annotations { #type-hints-with-metadata-annotations }
-Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`.
+Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`.
Since Python 3.9, `Annotated` is a part of the standard library, so you can import it from `typing`.
diff --git a/docs/en/docs/tutorial/cookie-param-models.md b/docs/en/docs/tutorial/cookie-param-models.md
index 016a65d7f..609838f76 100644
--- a/docs/en/docs/tutorial/cookie-param-models.md
+++ b/docs/en/docs/tutorial/cookie-param-models.md
@@ -46,7 +46,7 @@ But even if you **fill the data** and click "Execute", because the docs UI works
In some special use cases (probably not very common), you might want to **restrict** the cookies that you want to receive.
-Your API now has the power to control its own cookie consent. 🤪🍪
+Your API now has the power to control its own cookie consent. 🤪🍪
You can use Pydantic's model configuration to `forbid` any `extra` fields:
@@ -54,9 +54,9 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields:
If a client tries to send some **extra cookies**, they will receive an **error** response.
-Poor cookie banners with all their effort to get your consent for the API to reject it. 🍪
+Poor cookie banners with all their effort to get your consent for the API to reject it. 🍪
-For example, if the client tries to send a `santa_tracker` cookie with a value of `good-list-please`, the client will receive an **error** response telling them that the `santa_tracker` cookie is not allowed:
+For example, if the client tries to send a `santa_tracker` cookie with a value of `good-list-please`, the client will receive an **error** response telling them that the `santa_tracker` cookie is not allowed:
```json
{
@@ -73,4 +73,4 @@ For example, if the client tries to send a `santa_tracker` cookie with a value o
## Summary { #summary }
-You can use **Pydantic models** to declare **cookies** in **FastAPI**. 😎
+You can use **Pydantic models** to declare **cookies** in **FastAPI**. 😎
diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
index d9f334561..cfcd961ba 100644
--- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,6 +1,6 @@
# Dependencies with yield { #dependencies-with-yield }
-FastAPI supports dependencies that do some extra steps after finishing.
+FastAPI supports dependencies that do some extra steps after finishing.
To do this, use `yield` instead of `return`, and write the extra steps (code) after.
diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md
index d1116b2be..4a1bb774d 100644
--- a/docs/en/docs/tutorial/dependencies/index.md
+++ b/docs/en/docs/tutorial/dependencies/index.md
@@ -1,6 +1,6 @@
# Dependencies { #dependencies }
-**FastAPI** has a very powerful but intuitive **Dependency Injection** system.
+**FastAPI** has a very powerful but intuitive **Dependency Injection** system.
It is designed to be very simple to use, and to make it very easy for any developer to integrate other components with **FastAPI**.
diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
index 967bffda7..b9a4e3ce7 100644
--- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
@@ -58,7 +58,7 @@ query_extractor --> query_or_cookie_extractor --> read_query
If one of your dependencies is declared multiple times for the same *path operation*, for example, multiple dependencies have a common sub-dependency, **FastAPI** will know to call that sub-dependency only once per request.
-And it will save the returned value in a "cache" and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request.
+And it will save the returned value in a "cache" and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request.
In an advanced scenario where you know you need the dependency to be called at every step (possibly multiple times) in the same request instead of using the "cached" value, you can set the parameter `use_cache=False` when using `Depends`:
diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md
index df8e91ecd..a3263593d 100644
--- a/docs/en/docs/tutorial/first-steps.md
+++ b/docs/en/docs/tutorial/first-steps.md
@@ -271,7 +271,7 @@ We are going to call them "**operations**" too.
The `@app.get("/")` tells **FastAPI** that the function right below is in charge of handling requests that go to:
* the path `/`
-* using a get operation
+* using a get operation
/// info | `@decorator` Info
diff --git a/docs/en/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md
index 1bb7ee554..f5c603880 100644
--- a/docs/en/docs/tutorial/path-operation-configuration.md
+++ b/docs/en/docs/tutorial/path-operation-configuration.md
@@ -56,7 +56,7 @@ You can add a `summary` and `description`:
## Description from docstring { #description-from-docstring }
-As descriptions tend to be long and cover multiple lines, you can declare the *path operation* description in the function docstring and **FastAPI** will read it from there.
+As descriptions tend to be long and cover multiple lines, you can declare the *path operation* description in the function docstring and **FastAPI** will read it from there.
You can write Markdown in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation).
@@ -90,7 +90,7 @@ So, if you don't provide one, **FastAPI** will automatically generate one of "Su
## Deprecate a *path operation* { #deprecate-a-path-operation }
-If you need to mark a *path operation* as deprecated, but without removing it, pass the parameter `deprecated`:
+If you need to mark a *path operation* as deprecated, but without removing it, pass the parameter `deprecated`:
{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md
index ea4307900..cf312f1fe 100644
--- a/docs/en/docs/tutorial/path-params.md
+++ b/docs/en/docs/tutorial/path-params.md
@@ -26,7 +26,7 @@ This will give you editor support inside of your function, with error checks, co
///
-## Data conversion { #data-conversion }
+## Data conversion { #data-conversion }
If you run this example and open your browser at http://127.0.0.1:8000/items/3, you will see a response of:
@@ -38,7 +38,7 @@ If you run this example and open your browser at "parsing".
+So, with that type declaration, **FastAPI** gives you automatic request "parsing".
///
@@ -144,7 +144,7 @@ Then create class attributes with fixed values, which will be the available vali
/// tip
-If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models.
+If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models.
///
@@ -242,7 +242,7 @@ In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double
With **FastAPI**, by using short, intuitive and standard Python type declarations, you get:
* Editor support: error checks, autocompletion, etc.
-* Data "parsing"
+* Data "parsing"
* Data validation
* API annotation and automatic documentation
diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md
index 4b8cc9d29..1846ad56a 100644
--- a/docs/en/docs/tutorial/query-params-str-validations.md
+++ b/docs/en/docs/tutorial/query-params-str-validations.md
@@ -109,7 +109,7 @@ FastAPI will now:
## Alternative (old): `Query` as the default value { #alternative-old-query-as-the-default-value }
-Previous versions of FastAPI (before 0.95.0) required you to use `Query` as the default value of your parameter, instead of putting it in `Annotated`, there's a high chance that you will see code using it around, so I'll explain it to you.
+Previous versions of FastAPI (before 0.95.0) required you to use `Query` as the default value of your parameter, instead of putting it in `Annotated`, there's a high chance that you will see code using it around, so I'll explain it to you.
/// tip
@@ -192,7 +192,7 @@ You can also add a parameter `min_length`:
## Add regular expressions { #add-regular-expressions }
-You can define a regular expression `pattern` that the parameter should match:
+You can define a regular expression `pattern` that the parameter should match:
{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
@@ -372,7 +372,7 @@ Then you can declare an `alias`, and that alias is what will be used to find the
Now let's say you don't like this parameter anymore.
-You have to leave it there a while because there are clients using it, but you want the docs to clearly show it as deprecated.
+You have to leave it there a while because there are clients using it, but you want the docs to clearly show it as deprecated.
Then pass the parameter `deprecated=True` to `Query`:
@@ -402,7 +402,7 @@ Pydantic also has ISBN book number or with `imdb-` for an IMDB movie URL ID:
+For example, this custom validator checks that the item ID starts with `isbn-` for an ISBN book number or with `imdb-` for an IMDB movie URL ID:
{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
@@ -436,7 +436,7 @@ Did you notice? a string using `value.startswith()` can take a tuple, and it wil
#### A Random Item { #a-random-item }
-With `data.items()` we get an iterable object with tuples containing the key and value for each dictionary item.
+With `data.items()` we get an iterable object with tuples containing the key and value for each dictionary item.
We convert this iterable object into a proper `list` with `list(data.items())`.
diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md
index 3c9c225fb..eeb59f925 100644
--- a/docs/en/docs/tutorial/query-params.md
+++ b/docs/en/docs/tutorial/query-params.md
@@ -24,7 +24,7 @@ But when you declare them with Python types (in the example above, as `int`), th
All the same process that applied for path parameters also applies for query parameters:
* Editor support (obviously)
-* Data "parsing"
+* Data "parsing"
* Data validation
* Automatic documentation
diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md
index d743c2ec4..d63ffd565 100644
--- a/docs/en/docs/tutorial/request-forms.md
+++ b/docs/en/docs/tutorial/request-forms.md
@@ -28,7 +28,7 @@ Create form parameters the same way you would for `Body` or `Query`:
For example, in one of the ways the OAuth2 specification can be used (called "password flow") it is required to send a `username` and `password` as form fields.
-The spec requires the fields to be exactly named `username` and `password`, and to be sent as form fields, not JSON.
+The spec requires the fields to be exactly named `username` and `password`, and to be sent as form fields, not JSON.
With `Form` you can declare the same configurations as with `Body` (and `Query`, `Path`, `Cookie`), including validation, examples, an alias (e.g. `user-name` instead of `username`), etc.
diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
index b287cdf50..ac35390fa 100644
--- a/docs/en/docs/tutorial/response-model.md
+++ b/docs/en/docs/tutorial/response-model.md
@@ -201,7 +201,7 @@ This will also work because `RedirectResponse` is a subclass of `Response`, and
But when you return some other arbitrary object that is not a valid Pydantic type (e.g. a database object) and you annotate it like that in the function, FastAPI will try to create a Pydantic response model from that type annotation, and will fail.
-The same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥:
+The same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥:
{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md
index daaea73c8..432f58b1e 100644
--- a/docs/en/docs/tutorial/schema-extra-example.md
+++ b/docs/en/docs/tutorial/schema-extra-example.md
@@ -74,7 +74,7 @@ You can of course also pass multiple `examples`:
When you do this, the examples will be part of the internal **JSON Schema** for that body data.
-Nevertheless, at the time of writing this, Swagger UI, the tool in charge of showing the docs UI, doesn't support showing multiple examples for the data in **JSON Schema**. But read below for a workaround.
+Nevertheless, at the time of writing this, Swagger UI, the tool in charge of showing the docs UI, doesn't support showing multiple examples for the data in **JSON Schema**. But read below for a workaround.
### OpenAPI-specific `examples` { #openapi-specific-examples }
diff --git a/docs/en/docs/virtual-environments.md b/docs/en/docs/virtual-environments.md
index c02e43ab9..615d7949f 100644
--- a/docs/en/docs/virtual-environments.md
+++ b/docs/en/docs/virtual-environments.md
@@ -53,7 +53,7 @@ $ cd awesome-project
## Create a Virtual Environment { #create-a-virtual-environment }
-When you start working on a Python project **for the first time**, create a virtual environment **inside your project**.
+When you start working on a Python project **for the first time**, create a virtual environment **inside your project**.
/// tip
From ff721017df331de1357270f03f1f03382a50477f Mon Sep 17 00:00:00 2001
From: "github-actions[bot]" lt
-* XWT
-* PSGI
-
-### O abbr fornece uma explicação { #the-abbr-gives-an-explanation }
-
-* cluster
-* Deep Learning
+* GTD
+* lt
+* XWT
+* PSGI
### O abbr fornece uma frase completa e uma explicação { #the-abbr-gives-a-full-phrase-and-an-explanation }
@@ -224,6 +219,11 @@ Veja a seção `### HTML abbr elements` no prompt geral em `scripts/translate.py
////
+## Elementos HTML "dfn" { #html-dfn-elements }
+
+* cluster
+* Deep Learning
+
## Títulos { #headings }
//// tab | Teste
diff --git a/docs/ru/docs/_llm-test.md b/docs/ru/docs/_llm-test.md
index 6a0272f3a..247d3a964 100644
--- a/docs/ru/docs/_llm-test.md
+++ b/docs/ru/docs/_llm-test.md
@@ -202,11 +202,6 @@ works(foo="bar") # Это работает 🎉
* XWT
* PSGI
-### abbr даёт объяснение { #the-abbr-gives-an-explanation }
-
-* кластер
-* Глубокое обучение
-
### abbr даёт полную расшифровку и объяснение { #the-abbr-gives-a-full-phrase-and-an-explanation }
* MDN
@@ -224,6 +219,11 @@ works(foo="bar") # Это работает 🎉
////
+## HTML-элементы "dfn" { #html-dfn-elements }
+
+* кластер
+* Глубокое обучение
+
## Заголовки { #headings }
//// tab | Тест
diff --git a/scripts/general-llm-prompt.md b/scripts/general-llm-prompt.md
index d45ab8eb0..23926bd8e 100644
--- a/scripts/general-llm-prompt.md
+++ b/scripts/general-llm-prompt.md
@@ -353,7 +353,9 @@ Erstelle eine [Virtuelle Umgebung](../virtual-environments.md){.internal-link ta
Translate HTML abbr elements (`text`) as follows:
-- If the text surrounded by the abbr element is an abbreviation (the text may be surrounded by further HTML or Markdown markup or quotes, for example text or `text` or "text", ignore that further markup when deciding if the text is an abbreviation), and if the description (the text inside the title attribute) contains the full phrase for this abbreviation, then append a dash (-) to the full phrase, followed by the translation of the full phrase.
+- The text inside abbr tag may be surrounded by further HTML or Markdown markup or quotes, for example text or `text` or "text". Preserve markup and only translate visible text inside the abbr element.
+
+- If the description (the text inside the title attribute) contains the full phrase for this abbreviation, then append a dash (-) to the full phrase, followed by the translation of the full phrase.
Conversion scheme:
@@ -421,45 +423,7 @@ Result (German):
ASGI
```
-- If the description is not a full phrase for an abbreviation which the abbr element surrounds, but some other information, then just translate the description.
-
-Conversion scheme:
-
-Source (English):
-
-```
-{text}
-```
-
-Result:
-
-```
-{translation of text}
-```
-
-Examples:
-
- Source (English):
-
-```
-path
-linter
-parsing
-0.95.0
-at the time of writing this
-```
-
-Result (German):
-
-```
-Pfad
-Linter
-Parsen
-0.95.0
-zum Zeitpunkt als das hier geschrieben wurde
-```
-
-- If the text surrounded by the abbr element is an abbreviation and the description contains both the full phrase for that abbreviation, and other information, separated by a colon (`:`), then append a dash (`-`) and the translation of the full phrase to the original full phrase and translate the other information.
+- If the title of abbr element contains a full phrase for that abbreviation, and other information, separated by a colon (`:`), then append a dash (`-`) and the translation of the full phrase to the original full phrase and translate the other information.
Conversion scheme:
@@ -526,3 +490,23 @@ Result (German):
- If there is an existing translation, and it has ADDITIONAL abbr elements in a sentence, and these additional abbr elements do not exist in the related sentence in the English text, then KEEP those additional abbr elements in the translation. Do not remove them. Except when you remove the whole sentence from the translation, because the whole sentence was removed from the English text, then also remove the abbr element. The reasoning for this rule is, that such additional abbr elements are manually added by the human editor of the translation, in order to translate or explain an English word to the human readers of the translation. These additional abbr elements would not make sense in the English text, but they do make sense in the translation. So keep them in the translation, even though they are not part of the English text. This rule only applies to abbr elements.
- Apply above rules also when there is an existing translation! Make sure that all title attributes in abbr elements get properly translated or updated, using the schemes given above. However, leave the ADDITIONAL abbr's described above alone. Do not change their formatting or content.
+
+### HTML dfn elements
+
+For HTML dfn elements (`text`), translate the text inside the dfn element and the title attribute. Do not include the original English text in the title attribute.
+
+Examples:
+
+Source (English):
+
+```
+path
+linter
+```
+
+Result (German):
+
+```
+Pfad
+Linter
+```
From 65da3dde120c7efee7868890ff3e6e788a860ed6 Mon Sep 17 00:00:00 2001
From: "github-actions[bot]" kwargs. Even if they don't have a default value.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
### Better with `Annotated` { #better-with-annotated }
Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
## Number validations: greater than or equal { #number-validations-greater-than-or-equal }
@@ -97,7 +97,7 @@ With `Query` and `Path` (and others you'll see later) you can declare number con
Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`.
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
## Number validations: greater than and less than or equal { #number-validations-greater-than-and-less-than-or-equal }
@@ -106,7 +106,7 @@ The same applies for:
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
## Number validations: floats, greater than and less than { #number-validations-floats-greater-than-and-less-than }
@@ -118,7 +118,7 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not.
And the same for lt.
-{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
## Recap { #recap }
diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md
index cf312f1fe..8adbbcfa1 100644
--- a/docs/en/docs/tutorial/path-params.md
+++ b/docs/en/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
You can declare path "parameters" or "variables" with the same syntax used by Python format strings:
-{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
The value of the path parameter `item_id` will be passed to your function as the argument `item_id`.
@@ -16,7 +16,7 @@ So, if you run this example and go to Item:
- if x_token != fake_secret_token:
- raise HTTPException(status_code=400, detail="Invalid X-Token header")
- if item.id in fake_db:
- raise HTTPException(status_code=409, detail="Item already exists")
- fake_db[item.id] = item.model_dump()
- return item
diff --git a/docs_src/app_testing/app_b_an_py39/test_main.py b/docs_src/app_testing/app_b_an_py39/test_main.py
deleted file mode 100644
index 4e1c51ecc..000000000
--- a/docs_src/app_testing/app_b_an_py39/test_main.py
+++ /dev/null
@@ -1,65 +0,0 @@
-from fastapi.testclient import TestClient
-
-from .main import app
-
-client = TestClient(app)
-
-
-def test_read_item():
- response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})
- assert response.status_code == 200
- assert response.json() == {
- "id": "foo",
- "title": "Foo",
- "description": "There goes my hero",
- }
-
-
-def test_read_item_bad_token():
- response = client.get("/items/foo", headers={"X-Token": "hailhydra"})
- assert response.status_code == 400
- assert response.json() == {"detail": "Invalid X-Token header"}
-
-
-def test_read_nonexistent_item():
- response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})
- assert response.status_code == 404
- assert response.json() == {"detail": "Item not found"}
-
-
-def test_create_item():
- response = client.post(
- "/items/",
- headers={"X-Token": "coneofsilence"},
- json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"},
- )
- assert response.status_code == 200
- assert response.json() == {
- "id": "foobar",
- "title": "Foo Bar",
- "description": "The Foo Barters",
- }
-
-
-def test_create_item_bad_token():
- response = client.post(
- "/items/",
- headers={"X-Token": "hailhydra"},
- json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"},
- )
- assert response.status_code == 400
- assert response.json() == {"detail": "Invalid X-Token header"}
-
-
-def test_create_existing_item():
- response = client.post(
- "/items/",
- headers={"X-Token": "coneofsilence"},
- json={
- "id": "foo",
- "title": "The Foo ID Stealers",
- "description": "There goes my stealer",
- },
- )
- assert response.status_code == 409
- assert response.json() == {"detail": "Item already exists"}
diff --git a/docs_src/app_testing/app_b_py39/main.py b/docs_src/app_testing/app_b_py39/main.py
deleted file mode 100644
index ed38f4721..000000000
--- a/docs_src/app_testing/app_b_py39/main.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Header, HTTPException
-from pydantic import BaseModel
-
-fake_secret_token = "coneofsilence"
-
-fake_db = {
- "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
- "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
-}
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- id: str
- title: str
- description: Union[str, None] = None
-
-
-@app.get("/items/{item_id}", response_model=Item)
-async def read_main(item_id: str, x_token: str = Header()):
- if x_token != fake_secret_token:
- raise HTTPException(status_code=400, detail="Invalid X-Token header")
- if item_id not in fake_db:
- raise HTTPException(status_code=404, detail="Item not found")
- return fake_db[item_id]
-
-
-@app.post("/items/")
-async def create_item(item: Item, x_token: str = Header()) -> Item:
- if x_token != fake_secret_token:
- raise HTTPException(status_code=400, detail="Invalid X-Token header")
- if item.id in fake_db:
- raise HTTPException(status_code=409, detail="Item already exists")
- fake_db[item.id] = item.model_dump()
- return item
diff --git a/docs_src/app_testing/app_b_py39/test_main.py b/docs_src/app_testing/app_b_py39/test_main.py
deleted file mode 100644
index 4e1c51ecc..000000000
--- a/docs_src/app_testing/app_b_py39/test_main.py
+++ /dev/null
@@ -1,65 +0,0 @@
-from fastapi.testclient import TestClient
-
-from .main import app
-
-client = TestClient(app)
-
-
-def test_read_item():
- response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})
- assert response.status_code == 200
- assert response.json() == {
- "id": "foo",
- "title": "Foo",
- "description": "There goes my hero",
- }
-
-
-def test_read_item_bad_token():
- response = client.get("/items/foo", headers={"X-Token": "hailhydra"})
- assert response.status_code == 400
- assert response.json() == {"detail": "Invalid X-Token header"}
-
-
-def test_read_nonexistent_item():
- response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})
- assert response.status_code == 404
- assert response.json() == {"detail": "Item not found"}
-
-
-def test_create_item():
- response = client.post(
- "/items/",
- headers={"X-Token": "coneofsilence"},
- json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"},
- )
- assert response.status_code == 200
- assert response.json() == {
- "id": "foobar",
- "title": "Foo Bar",
- "description": "The Foo Barters",
- }
-
-
-def test_create_item_bad_token():
- response = client.post(
- "/items/",
- headers={"X-Token": "hailhydra"},
- json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"},
- )
- assert response.status_code == 400
- assert response.json() == {"detail": "Invalid X-Token header"}
-
-
-def test_create_existing_item():
- response = client.post(
- "/items/",
- headers={"X-Token": "coneofsilence"},
- json={
- "id": "foo",
- "title": "The Foo ID Stealers",
- "description": "There goes my stealer",
- },
- )
- assert response.status_code == 409
- assert response.json() == {"detail": "Item already exists"}
diff --git a/docs_src/app_testing/tutorial001_py310.py b/docs_src/app_testing/tutorial001_py310.py
new file mode 100644
index 000000000..79a853b48
--- /dev/null
+++ b/docs_src/app_testing/tutorial001_py310.py
@@ -0,0 +1,18 @@
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+app = FastAPI()
+
+
+@app.get("/")
+async def read_main():
+ return {"msg": "Hello World"}
+
+
+client = TestClient(app)
+
+
+def test_read_main():
+ response = client.get("/")
+ assert response.status_code == 200
+ assert response.json() == {"msg": "Hello World"}
diff --git a/docs_src/app_testing/tutorial002_py310.py b/docs_src/app_testing/tutorial002_py310.py
new file mode 100644
index 000000000..71c898b3c
--- /dev/null
+++ b/docs_src/app_testing/tutorial002_py310.py
@@ -0,0 +1,31 @@
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from fastapi.websockets import WebSocket
+
+app = FastAPI()
+
+
+@app.get("/")
+async def read_main():
+ return {"msg": "Hello World"}
+
+
+@app.websocket("/ws")
+async def websocket(websocket: WebSocket):
+ await websocket.accept()
+ await websocket.send_json({"msg": "Hello WebSocket"})
+ await websocket.close()
+
+
+def test_read_main():
+ client = TestClient(app)
+ response = client.get("/")
+ assert response.status_code == 200
+ assert response.json() == {"msg": "Hello World"}
+
+
+def test_websocket():
+ client = TestClient(app)
+ with client.websocket_connect("/ws") as websocket:
+ data = websocket.receive_json()
+ assert data == {"msg": "Hello WebSocket"}
diff --git a/docs_src/app_testing/tutorial003_py310.py b/docs_src/app_testing/tutorial003_py310.py
new file mode 100644
index 000000000..ca6b45ce0
--- /dev/null
+++ b/docs_src/app_testing/tutorial003_py310.py
@@ -0,0 +1,24 @@
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+app = FastAPI()
+
+items = {}
+
+
+@app.on_event("startup")
+async def startup_event():
+ items["foo"] = {"name": "Fighters"}
+ items["bar"] = {"name": "Tenders"}
+
+
+@app.get("/items/{item_id}")
+async def read_items(item_id: str):
+ return items[item_id]
+
+
+def test_read_items():
+ with TestClient(app) as client:
+ response = client.get("/items/foo")
+ assert response.status_code == 200
+ assert response.json() == {"name": "Fighters"}
diff --git a/docs_src/app_testing/tutorial004_py310.py b/docs_src/app_testing/tutorial004_py310.py
new file mode 100644
index 000000000..f83ac9ae9
--- /dev/null
+++ b/docs_src/app_testing/tutorial004_py310.py
@@ -0,0 +1,43 @@
+from contextlib import asynccontextmanager
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+items = {}
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ items["foo"] = {"name": "Fighters"}
+ items["bar"] = {"name": "Tenders"}
+ yield
+ # clean up items
+ items.clear()
+
+
+app = FastAPI(lifespan=lifespan)
+
+
+@app.get("/items/{item_id}")
+async def read_items(item_id: str):
+ return items[item_id]
+
+
+def test_read_items():
+ # Before the lifespan starts, "items" is still empty
+ assert items == {}
+
+ with TestClient(app) as client:
+ # Inside the "with TestClient" block, the lifespan starts and items added
+ assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}}
+
+ response = client.get("/items/foo")
+ assert response.status_code == 200
+ assert response.json() == {"name": "Fighters"}
+
+ # After the requests is done, the items are still there
+ assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}}
+
+ # The end of the "with TestClient" block simulates terminating the app, so
+ # the lifespan ends and items are cleaned up
+ assert items == {}
diff --git a/docs_src/app_testing/app_b_py39/__init__.py b/docs_src/async_tests/app_a_py310/__init__.py
similarity index 100%
rename from docs_src/app_testing/app_b_py39/__init__.py
rename to docs_src/async_tests/app_a_py310/__init__.py
diff --git a/docs_src/async_tests/app_a_py310/main.py b/docs_src/async_tests/app_a_py310/main.py
new file mode 100644
index 000000000..9594f859c
--- /dev/null
+++ b/docs_src/async_tests/app_a_py310/main.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+async def root():
+ return {"message": "Tomato"}
diff --git a/docs_src/async_tests/app_a_py310/test_main.py b/docs_src/async_tests/app_a_py310/test_main.py
new file mode 100644
index 000000000..a57a31f7d
--- /dev/null
+++ b/docs_src/async_tests/app_a_py310/test_main.py
@@ -0,0 +1,14 @@
+import pytest
+from httpx import ASGITransport, AsyncClient
+
+from .main import app
+
+
+@pytest.mark.anyio
+async def test_root():
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as ac:
+ response = await ac.get("/")
+ assert response.status_code == 200
+ assert response.json() == {"message": "Tomato"}
diff --git a/docs_src/authentication_error_status_code/tutorial001_an_py310.py b/docs_src/authentication_error_status_code/tutorial001_an_py310.py
new file mode 100644
index 000000000..7bbc2f717
--- /dev/null
+++ b/docs_src/authentication_error_status_code/tutorial001_an_py310.py
@@ -0,0 +1,21 @@
+from typing import Annotated
+
+from fastapi import Depends, FastAPI, HTTPException, status
+from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
+
+app = FastAPI()
+
+
+class HTTPBearer403(HTTPBearer):
+ def make_not_authenticated_error(self) -> HTTPException:
+ return HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated"
+ )
+
+
+CredentialsDep = Annotated[HTTPAuthorizationCredentials, Depends(HTTPBearer403())]
+
+
+@app.get("/me")
+def read_me(credentials: CredentialsDep):
+ return {"message": "You are authenticated", "token": credentials.credentials}
diff --git a/docs_src/background_tasks/tutorial001_py310.py b/docs_src/background_tasks/tutorial001_py310.py
new file mode 100644
index 000000000..1720a7433
--- /dev/null
+++ b/docs_src/background_tasks/tutorial001_py310.py
@@ -0,0 +1,15 @@
+from fastapi import BackgroundTasks, FastAPI
+
+app = FastAPI()
+
+
+def write_notification(email: str, message=""):
+ with open("log.txt", mode="w") as email_file:
+ content = f"notification for {email}: {message}"
+ email_file.write(content)
+
+
+@app.post("/send-notification/{email}")
+async def send_notification(email: str, background_tasks: BackgroundTasks):
+ background_tasks.add_task(write_notification, email, message="some notification")
+ return {"message": "Notification sent in the background"}
diff --git a/docs_src/background_tasks/tutorial002_an_py39.py b/docs_src/background_tasks/tutorial002_an_py39.py
deleted file mode 100644
index bfdd14875..000000000
--- a/docs_src/background_tasks/tutorial002_an_py39.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import BackgroundTasks, Depends, FastAPI
-
-app = FastAPI()
-
-
-def write_log(message: str):
- with open("log.txt", mode="a") as log:
- log.write(message)
-
-
-def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
- if q:
- message = f"found query: {q}\n"
- background_tasks.add_task(write_log, message)
- return q
-
-
-@app.post("/send-notification/{email}")
-async def send_notification(
- email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
-):
- message = f"message to {email}\n"
- background_tasks.add_task(write_log, message)
- return {"message": "Message sent"}
diff --git a/docs_src/background_tasks/tutorial002_py39.py b/docs_src/background_tasks/tutorial002_py39.py
deleted file mode 100644
index 2e1b2f6c6..000000000
--- a/docs_src/background_tasks/tutorial002_py39.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Union
-
-from fastapi import BackgroundTasks, Depends, FastAPI
-
-app = FastAPI()
-
-
-def write_log(message: str):
- with open("log.txt", mode="a") as log:
- log.write(message)
-
-
-def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
- if q:
- message = f"found query: {q}\n"
- background_tasks.add_task(write_log, message)
- return q
-
-
-@app.post("/send-notification/{email}")
-async def send_notification(
- email: str, background_tasks: BackgroundTasks, q: str = Depends(get_query)
-):
- message = f"message to {email}\n"
- background_tasks.add_task(write_log, message)
- return {"message": "Message sent"}
diff --git a/docs_src/behind_a_proxy/tutorial001_01_py310.py b/docs_src/behind_a_proxy/tutorial001_01_py310.py
new file mode 100644
index 000000000..52b114395
--- /dev/null
+++ b/docs_src/behind_a_proxy/tutorial001_01_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/items/")
+def read_items():
+ return ["plumbus", "portal gun"]
diff --git a/docs_src/behind_a_proxy/tutorial001_py310.py b/docs_src/behind_a_proxy/tutorial001_py310.py
new file mode 100644
index 000000000..ede59ada1
--- /dev/null
+++ b/docs_src/behind_a_proxy/tutorial001_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI, Request
+
+app = FastAPI()
+
+
+@app.get("/app")
+def read_main(request: Request):
+ return {"message": "Hello World", "root_path": request.scope.get("root_path")}
diff --git a/docs_src/behind_a_proxy/tutorial002_py310.py b/docs_src/behind_a_proxy/tutorial002_py310.py
new file mode 100644
index 000000000..c1600cde9
--- /dev/null
+++ b/docs_src/behind_a_proxy/tutorial002_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI, Request
+
+app = FastAPI(root_path="/api/v1")
+
+
+@app.get("/app")
+def read_main(request: Request):
+ return {"message": "Hello World", "root_path": request.scope.get("root_path")}
diff --git a/docs_src/behind_a_proxy/tutorial003_py310.py b/docs_src/behind_a_proxy/tutorial003_py310.py
new file mode 100644
index 000000000..3b7d8be01
--- /dev/null
+++ b/docs_src/behind_a_proxy/tutorial003_py310.py
@@ -0,0 +1,14 @@
+from fastapi import FastAPI, Request
+
+app = FastAPI(
+ servers=[
+ {"url": "https://stag.example.com", "description": "Staging environment"},
+ {"url": "https://prod.example.com", "description": "Production environment"},
+ ],
+ root_path="/api/v1",
+)
+
+
+@app.get("/app")
+def read_main(request: Request):
+ return {"message": "Hello World", "root_path": request.scope.get("root_path")}
diff --git a/docs_src/behind_a_proxy/tutorial004_py310.py b/docs_src/behind_a_proxy/tutorial004_py310.py
new file mode 100644
index 000000000..51bd5babc
--- /dev/null
+++ b/docs_src/behind_a_proxy/tutorial004_py310.py
@@ -0,0 +1,15 @@
+from fastapi import FastAPI, Request
+
+app = FastAPI(
+ servers=[
+ {"url": "https://stag.example.com", "description": "Staging environment"},
+ {"url": "https://prod.example.com", "description": "Production environment"},
+ ],
+ root_path="/api/v1",
+ root_path_in_servers=False,
+)
+
+
+@app.get("/app")
+def read_main(request: Request):
+ return {"message": "Hello World", "root_path": request.scope.get("root_path")}
diff --git a/docs_src/bigger_applications/app_py39/internal/__init__.py b/docs_src/bigger_applications/app_an_py310/__init__.py
similarity index 100%
rename from docs_src/bigger_applications/app_py39/internal/__init__.py
rename to docs_src/bigger_applications/app_an_py310/__init__.py
diff --git a/docs_src/bigger_applications/app_an_py310/dependencies.py b/docs_src/bigger_applications/app_an_py310/dependencies.py
new file mode 100644
index 000000000..5c7612aa0
--- /dev/null
+++ b/docs_src/bigger_applications/app_an_py310/dependencies.py
@@ -0,0 +1,13 @@
+from typing import Annotated
+
+from fastapi import Header, HTTPException
+
+
+async def get_token_header(x_token: Annotated[str, Header()]):
+ if x_token != "fake-super-secret-token":
+ raise HTTPException(status_code=400, detail="X-Token header invalid")
+
+
+async def get_query_token(token: str):
+ if token != "jessica":
+ raise HTTPException(status_code=400, detail="No Jessica token provided")
diff --git a/docs_src/bigger_applications/app_py39/routers/__init__.py b/docs_src/bigger_applications/app_an_py310/internal/__init__.py
similarity index 100%
rename from docs_src/bigger_applications/app_py39/routers/__init__.py
rename to docs_src/bigger_applications/app_an_py310/internal/__init__.py
diff --git a/docs_src/bigger_applications/app_py39/internal/admin.py b/docs_src/bigger_applications/app_an_py310/internal/admin.py
similarity index 100%
rename from docs_src/bigger_applications/app_py39/internal/admin.py
rename to docs_src/bigger_applications/app_an_py310/internal/admin.py
diff --git a/docs_src/bigger_applications/app_an_py310/main.py b/docs_src/bigger_applications/app_an_py310/main.py
new file mode 100644
index 000000000..ae544a3aa
--- /dev/null
+++ b/docs_src/bigger_applications/app_an_py310/main.py
@@ -0,0 +1,23 @@
+from fastapi import Depends, FastAPI
+
+from .dependencies import get_query_token, get_token_header
+from .internal import admin
+from .routers import items, users
+
+app = FastAPI(dependencies=[Depends(get_query_token)])
+
+
+app.include_router(users.router)
+app.include_router(items.router)
+app.include_router(
+ admin.router,
+ prefix="/admin",
+ tags=["admin"],
+ dependencies=[Depends(get_token_header)],
+ responses={418: {"description": "I'm a teapot"}},
+)
+
+
+@app.get("/")
+async def root():
+ return {"message": "Hello Bigger Applications!"}
diff --git a/docs_src/bigger_applications/app_an_py310/routers/__init__.py b/docs_src/bigger_applications/app_an_py310/routers/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/docs_src/bigger_applications/app_py39/routers/items.py b/docs_src/bigger_applications/app_an_py310/routers/items.py
similarity index 100%
rename from docs_src/bigger_applications/app_py39/routers/items.py
rename to docs_src/bigger_applications/app_an_py310/routers/items.py
diff --git a/docs_src/bigger_applications/app_py39/routers/users.py b/docs_src/bigger_applications/app_an_py310/routers/users.py
similarity index 100%
rename from docs_src/bigger_applications/app_py39/routers/users.py
rename to docs_src/bigger_applications/app_an_py310/routers/users.py
diff --git a/docs_src/body/tutorial001_py39.py b/docs_src/body/tutorial001_py39.py
deleted file mode 100644
index f93317274..000000000
--- a/docs_src/body/tutorial001_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-app = FastAPI()
-
-
-@app.post("/items/")
-async def create_item(item: Item):
- return item
diff --git a/docs_src/body/tutorial002_py39.py b/docs_src/body/tutorial002_py39.py
deleted file mode 100644
index fb212e8e7..000000000
--- a/docs_src/body/tutorial002_py39.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-app = FastAPI()
-
-
-@app.post("/items/")
-async def create_item(item: Item):
- item_dict = item.model_dump()
- if item.tax is not None:
- price_with_tax = item.price + item.tax
- item_dict.update({"price_with_tax": price_with_tax})
- return item_dict
diff --git a/docs_src/body/tutorial003_py39.py b/docs_src/body/tutorial003_py39.py
deleted file mode 100644
index 636ba2275..000000000
--- a/docs_src/body/tutorial003_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-app = FastAPI()
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- return {"item_id": item_id, **item.model_dump()}
diff --git a/docs_src/body/tutorial004_py39.py b/docs_src/body/tutorial004_py39.py
deleted file mode 100644
index 2c157abfa..000000000
--- a/docs_src/body/tutorial004_py39.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-app = FastAPI()
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item, q: Union[str, None] = None):
- result = {"item_id": item_id, **item.model_dump()}
- if q:
- result.update({"q": q})
- return result
diff --git a/docs_src/body_fields/tutorial001_an_py39.py b/docs_src/body_fields/tutorial001_an_py39.py
deleted file mode 100644
index 6ef14470c..000000000
--- a/docs_src/body_fields/tutorial001_an_py39.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel, Field
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = Field(
- default=None, title="The description of the item", max_length=300
- )
- price: float = Field(gt=0, description="The price must be greater than zero")
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_fields/tutorial001_py39.py b/docs_src/body_fields/tutorial001_py39.py
deleted file mode 100644
index cbeebd614..000000000
--- a/docs_src/body_fields/tutorial001_py39.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel, Field
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = Field(
- default=None, title="The description of the item", max_length=300
- )
- price: float = Field(gt=0, description="The price must be greater than zero")
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item = Body(embed=True)):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_multiple_params/tutorial001_an_py39.py b/docs_src/body_multiple_params/tutorial001_an_py39.py
deleted file mode 100644
index 1c0ac3a7b..000000000
--- a/docs_src/body_multiple_params/tutorial001_an_py39.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Path
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(
- item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
- q: Union[str, None] = None,
- item: Union[Item, None] = None,
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- if item:
- results.update({"item": item})
- return results
diff --git a/docs_src/body_multiple_params/tutorial001_py39.py b/docs_src/body_multiple_params/tutorial001_py39.py
deleted file mode 100644
index a73975b3a..000000000
--- a/docs_src/body_multiple_params/tutorial001_py39.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Path
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(
- *,
- item_id: int = Path(title="The ID of the item to get", ge=0, le=1000),
- q: Union[str, None] = None,
- item: Union[Item, None] = None,
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- if item:
- results.update({"item": item})
- return results
diff --git a/docs_src/body_multiple_params/tutorial002_py39.py b/docs_src/body_multiple_params/tutorial002_py39.py
deleted file mode 100644
index 2d7160ae8..000000000
--- a/docs_src/body_multiple_params/tutorial002_py39.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-class User(BaseModel):
- username: str
- full_name: Union[str, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item, user: User):
- results = {"item_id": item_id, "item": item, "user": user}
- return results
diff --git a/docs_src/body_multiple_params/tutorial003_an_py39.py b/docs_src/body_multiple_params/tutorial003_an_py39.py
deleted file mode 100644
index 042351e0b..000000000
--- a/docs_src/body_multiple_params/tutorial003_an_py39.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-class User(BaseModel):
- username: str
- full_name: Union[str, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(
- item_id: int, item: Item, user: User, importance: Annotated[int, Body()]
-):
- results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
- return results
diff --git a/docs_src/body_multiple_params/tutorial003_py39.py b/docs_src/body_multiple_params/tutorial003_py39.py
deleted file mode 100644
index cf344e6c5..000000000
--- a/docs_src/body_multiple_params/tutorial003_py39.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-class User(BaseModel):
- username: str
- full_name: Union[str, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item, user: User, importance: int = Body()):
- results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
- return results
diff --git a/docs_src/body_multiple_params/tutorial004_an_py39.py b/docs_src/body_multiple_params/tutorial004_an_py39.py
deleted file mode 100644
index 567427c03..000000000
--- a/docs_src/body_multiple_params/tutorial004_an_py39.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-class User(BaseModel):
- username: str
- full_name: Union[str, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(
- *,
- item_id: int,
- item: Item,
- user: User,
- importance: Annotated[int, Body(gt=0)],
- q: Union[str, None] = None,
-):
- results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/body_multiple_params/tutorial004_py39.py b/docs_src/body_multiple_params/tutorial004_py39.py
deleted file mode 100644
index 8ce4c7a97..000000000
--- a/docs_src/body_multiple_params/tutorial004_py39.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-class User(BaseModel):
- username: str
- full_name: Union[str, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(
- *,
- item_id: int,
- item: Item,
- user: User,
- importance: int = Body(gt=0),
- q: Union[str, None] = None,
-):
- results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/body_multiple_params/tutorial005_an_py39.py b/docs_src/body_multiple_params/tutorial005_an_py39.py
deleted file mode 100644
index 9a52425c1..000000000
--- a/docs_src/body_multiple_params/tutorial005_an_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_multiple_params/tutorial005_py39.py b/docs_src/body_multiple_params/tutorial005_py39.py
deleted file mode 100644
index 29e6e14b7..000000000
--- a/docs_src/body_multiple_params/tutorial005_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item = Body(embed=True)):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial001_py39.py b/docs_src/body_nested_models/tutorial001_py39.py
deleted file mode 100644
index 37ef6dda5..000000000
--- a/docs_src/body_nested_models/tutorial001_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: list = []
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial002_py39.py b/docs_src/body_nested_models/tutorial002_py39.py
deleted file mode 100644
index 8a93a7233..000000000
--- a/docs_src/body_nested_models/tutorial002_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: list[str] = []
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial003_py39.py b/docs_src/body_nested_models/tutorial003_py39.py
deleted file mode 100644
index b590ece36..000000000
--- a/docs_src/body_nested_models/tutorial003_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: set[str] = set()
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial004_py39.py b/docs_src/body_nested_models/tutorial004_py39.py
deleted file mode 100644
index dc2b175fb..000000000
--- a/docs_src/body_nested_models/tutorial004_py39.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Image(BaseModel):
- url: str
- name: str
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: set[str] = set()
- image: Union[Image, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial005_py39.py b/docs_src/body_nested_models/tutorial005_py39.py
deleted file mode 100644
index 47db90008..000000000
--- a/docs_src/body_nested_models/tutorial005_py39.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel, HttpUrl
-
-app = FastAPI()
-
-
-class Image(BaseModel):
- url: HttpUrl
- name: str
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: set[str] = set()
- image: Union[Image, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial006_py39.py b/docs_src/body_nested_models/tutorial006_py39.py
deleted file mode 100644
index b14409703..000000000
--- a/docs_src/body_nested_models/tutorial006_py39.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel, HttpUrl
-
-app = FastAPI()
-
-
-class Image(BaseModel):
- url: HttpUrl
- name: str
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: set[str] = set()
- images: Union[list[Image], None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial007_py39.py b/docs_src/body_nested_models/tutorial007_py39.py
deleted file mode 100644
index 59cf01e23..000000000
--- a/docs_src/body_nested_models/tutorial007_py39.py
+++ /dev/null
@@ -1,32 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel, HttpUrl
-
-app = FastAPI()
-
-
-class Image(BaseModel):
- url: HttpUrl
- name: str
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: set[str] = set()
- images: Union[list[Image], None] = None
-
-
-class Offer(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- items: list[Item]
-
-
-@app.post("/offers/")
-async def create_offer(offer: Offer):
- return offer
diff --git a/docs_src/body_nested_models/tutorial008_py310.py b/docs_src/body_nested_models/tutorial008_py310.py
new file mode 100644
index 000000000..854a7a5a4
--- /dev/null
+++ b/docs_src/body_nested_models/tutorial008_py310.py
@@ -0,0 +1,14 @@
+from fastapi import FastAPI
+from pydantic import BaseModel, HttpUrl
+
+app = FastAPI()
+
+
+class Image(BaseModel):
+ url: HttpUrl
+ name: str
+
+
+@app.post("/images/multiple/")
+async def create_multiple_images(images: list[Image]):
+ return images
diff --git a/docs_src/body_nested_models/tutorial009_py310.py b/docs_src/body_nested_models/tutorial009_py310.py
new file mode 100644
index 000000000..59c1e5082
--- /dev/null
+++ b/docs_src/body_nested_models/tutorial009_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.post("/index-weights/")
+async def create_index_weights(weights: dict[int, float]):
+ return weights
diff --git a/docs_src/body_updates/tutorial001_py39.py b/docs_src/body_updates/tutorial001_py39.py
deleted file mode 100644
index 999bcdb82..000000000
--- a/docs_src/body_updates/tutorial001_py39.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from fastapi.encoders import jsonable_encoder
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: Union[str, None] = None
- description: Union[str, None] = None
- price: Union[float, None] = None
- tax: float = 10.5
- tags: list[str] = []
-
-
-items = {
- "foo": {"name": "Foo", "price": 50.2},
- "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
- "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
-}
-
-
-@app.get("/items/{item_id}", response_model=Item)
-async def read_item(item_id: str):
- return items[item_id]
-
-
-@app.put("/items/{item_id}", response_model=Item)
-async def update_item(item_id: str, item: Item):
- update_item_encoded = jsonable_encoder(item)
- items[item_id] = update_item_encoded
- return update_item_encoded
diff --git a/docs_src/body_updates/tutorial002_py39.py b/docs_src/body_updates/tutorial002_py39.py
deleted file mode 100644
index 3714b5a55..000000000
--- a/docs_src/body_updates/tutorial002_py39.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from fastapi.encoders import jsonable_encoder
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: Union[str, None] = None
- description: Union[str, None] = None
- price: Union[float, None] = None
- tax: float = 10.5
- tags: list[str] = []
-
-
-items = {
- "foo": {"name": "Foo", "price": 50.2},
- "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
- "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
-}
-
-
-@app.get("/items/{item_id}", response_model=Item)
-async def read_item(item_id: str):
- return items[item_id]
-
-
-@app.patch("/items/{item_id}")
-async def update_item(item_id: str, item: Item) -> Item:
- stored_item_data = items[item_id]
- stored_item_model = Item(**stored_item_data)
- update_data = item.model_dump(exclude_unset=True)
- updated_item = stored_item_model.model_copy(update=update_data)
- items[item_id] = jsonable_encoder(updated_item)
- return updated_item
diff --git a/docs_src/conditional_openapi/tutorial001_py310.py b/docs_src/conditional_openapi/tutorial001_py310.py
new file mode 100644
index 000000000..eedb0d274
--- /dev/null
+++ b/docs_src/conditional_openapi/tutorial001_py310.py
@@ -0,0 +1,16 @@
+from fastapi import FastAPI
+from pydantic_settings import BaseSettings
+
+
+class Settings(BaseSettings):
+ openapi_url: str = "/openapi.json"
+
+
+settings = Settings()
+
+app = FastAPI(openapi_url=settings.openapi_url)
+
+
+@app.get("/")
+def root():
+ return {"message": "Hello World"}
diff --git a/docs_src/configure_swagger_ui/tutorial001_py310.py b/docs_src/configure_swagger_ui/tutorial001_py310.py
new file mode 100644
index 000000000..6c24ce758
--- /dev/null
+++ b/docs_src/configure_swagger_ui/tutorial001_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI(swagger_ui_parameters={"syntaxHighlight": False})
+
+
+@app.get("/users/{username}")
+async def read_user(username: str):
+ return {"message": f"Hello {username}"}
diff --git a/docs_src/configure_swagger_ui/tutorial002_py310.py b/docs_src/configure_swagger_ui/tutorial002_py310.py
new file mode 100644
index 000000000..cc75c2196
--- /dev/null
+++ b/docs_src/configure_swagger_ui/tutorial002_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI(swagger_ui_parameters={"syntaxHighlight": {"theme": "obsidian"}})
+
+
+@app.get("/users/{username}")
+async def read_user(username: str):
+ return {"message": f"Hello {username}"}
diff --git a/docs_src/configure_swagger_ui/tutorial003_py310.py b/docs_src/configure_swagger_ui/tutorial003_py310.py
new file mode 100644
index 000000000..b4449f5c6
--- /dev/null
+++ b/docs_src/configure_swagger_ui/tutorial003_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI(swagger_ui_parameters={"deepLinking": False})
+
+
+@app.get("/users/{username}")
+async def read_user(username: str):
+ return {"message": f"Hello {username}"}
diff --git a/docs_src/cookie_param_models/tutorial001_an_py39.py b/docs_src/cookie_param_models/tutorial001_an_py39.py
deleted file mode 100644
index 3d90c2007..000000000
--- a/docs_src/cookie_param_models/tutorial001_an_py39.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Cookie, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Cookies(BaseModel):
- session_id: str
- fatebook_tracker: Union[str, None] = None
- googall_tracker: Union[str, None] = None
-
-
-@app.get("/items/")
-async def read_items(cookies: Annotated[Cookies, Cookie()]):
- return cookies
diff --git a/docs_src/cookie_param_models/tutorial001_py39.py b/docs_src/cookie_param_models/tutorial001_py39.py
deleted file mode 100644
index cc65c43e1..000000000
--- a/docs_src/cookie_param_models/tutorial001_py39.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import Union
-
-from fastapi import Cookie, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Cookies(BaseModel):
- session_id: str
- fatebook_tracker: Union[str, None] = None
- googall_tracker: Union[str, None] = None
-
-
-@app.get("/items/")
-async def read_items(cookies: Cookies = Cookie()):
- return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_an_py39.py b/docs_src/cookie_param_models/tutorial002_an_py39.py
deleted file mode 100644
index a906ce6a1..000000000
--- a/docs_src/cookie_param_models/tutorial002_an_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Cookie, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Cookies(BaseModel):
- model_config = {"extra": "forbid"}
-
- session_id: str
- fatebook_tracker: Union[str, None] = None
- googall_tracker: Union[str, None] = None
-
-
-@app.get("/items/")
-async def read_items(cookies: Annotated[Cookies, Cookie()]):
- return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_py39.py b/docs_src/cookie_param_models/tutorial002_py39.py
deleted file mode 100644
index 9679e890f..000000000
--- a/docs_src/cookie_param_models/tutorial002_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Union
-
-from fastapi import Cookie, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Cookies(BaseModel):
- model_config = {"extra": "forbid"}
-
- session_id: str
- fatebook_tracker: Union[str, None] = None
- googall_tracker: Union[str, None] = None
-
-
-@app.get("/items/")
-async def read_items(cookies: Cookies = Cookie()):
- return cookies
diff --git a/docs_src/cookie_params/tutorial001_an_py39.py b/docs_src/cookie_params/tutorial001_an_py39.py
deleted file mode 100644
index e18d0a332..000000000
--- a/docs_src/cookie_params/tutorial001_an_py39.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Cookie, FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):
- return {"ads_id": ads_id}
diff --git a/docs_src/cookie_params/tutorial001_py39.py b/docs_src/cookie_params/tutorial001_py39.py
deleted file mode 100644
index c4a497fda..000000000
--- a/docs_src/cookie_params/tutorial001_py39.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from typing import Union
-
-from fastapi import Cookie, FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(ads_id: Union[str, None] = Cookie(default=None)):
- return {"ads_id": ads_id}
diff --git a/docs_src/cors/tutorial001_py310.py b/docs_src/cors/tutorial001_py310.py
new file mode 100644
index 000000000..d59ab27ac
--- /dev/null
+++ b/docs_src/cors/tutorial001_py310.py
@@ -0,0 +1,24 @@
+from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+
+app = FastAPI()
+
+origins = [
+ "http://localhost.tiangolo.com",
+ "https://localhost.tiangolo.com",
+ "http://localhost",
+ "http://localhost:8080",
+]
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=origins,
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+
+@app.get("/")
+async def main():
+ return {"message": "Hello World"}
diff --git a/docs_src/custom_docs_ui/tutorial001_py310.py b/docs_src/custom_docs_ui/tutorial001_py310.py
new file mode 100644
index 000000000..1cfcce19a
--- /dev/null
+++ b/docs_src/custom_docs_ui/tutorial001_py310.py
@@ -0,0 +1,38 @@
+from fastapi import FastAPI
+from fastapi.openapi.docs import (
+ get_redoc_html,
+ get_swagger_ui_html,
+ get_swagger_ui_oauth2_redirect_html,
+)
+
+app = FastAPI(docs_url=None, redoc_url=None)
+
+
+@app.get("/docs", include_in_schema=False)
+async def custom_swagger_ui_html():
+ return get_swagger_ui_html(
+ openapi_url=app.openapi_url,
+ title=app.title + " - Swagger UI",
+ oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
+ swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js",
+ swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css",
+ )
+
+
+@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
+async def swagger_ui_redirect():
+ return get_swagger_ui_oauth2_redirect_html()
+
+
+@app.get("/redoc", include_in_schema=False)
+async def redoc_html():
+ return get_redoc_html(
+ openapi_url=app.openapi_url,
+ title=app.title + " - ReDoc",
+ redoc_js_url="https://unpkg.com/redoc@2/bundles/redoc.standalone.js",
+ )
+
+
+@app.get("/users/{username}")
+async def read_user(username: str):
+ return {"message": f"Hello {username}"}
diff --git a/docs_src/custom_docs_ui/tutorial002_py310.py b/docs_src/custom_docs_ui/tutorial002_py310.py
new file mode 100644
index 000000000..23ea368f8
--- /dev/null
+++ b/docs_src/custom_docs_ui/tutorial002_py310.py
@@ -0,0 +1,41 @@
+from fastapi import FastAPI
+from fastapi.openapi.docs import (
+ get_redoc_html,
+ get_swagger_ui_html,
+ get_swagger_ui_oauth2_redirect_html,
+)
+from fastapi.staticfiles import StaticFiles
+
+app = FastAPI(docs_url=None, redoc_url=None)
+
+app.mount("/static", StaticFiles(directory="static"), name="static")
+
+
+@app.get("/docs", include_in_schema=False)
+async def custom_swagger_ui_html():
+ return get_swagger_ui_html(
+ openapi_url=app.openapi_url,
+ title=app.title + " - Swagger UI",
+ oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
+ swagger_js_url="/static/swagger-ui-bundle.js",
+ swagger_css_url="/static/swagger-ui.css",
+ )
+
+
+@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
+async def swagger_ui_redirect():
+ return get_swagger_ui_oauth2_redirect_html()
+
+
+@app.get("/redoc", include_in_schema=False)
+async def redoc_html():
+ return get_redoc_html(
+ openapi_url=app.openapi_url,
+ title=app.title + " - ReDoc",
+ redoc_js_url="/static/redoc.standalone.js",
+ )
+
+
+@app.get("/users/{username}")
+async def read_user(username: str):
+ return {"message": f"Hello {username}"}
diff --git a/docs_src/custom_request_and_route/tutorial001_an_py39.py b/docs_src/custom_request_and_route/tutorial001_an_py39.py
deleted file mode 100644
index 076727e64..000000000
--- a/docs_src/custom_request_and_route/tutorial001_an_py39.py
+++ /dev/null
@@ -1,35 +0,0 @@
-import gzip
-from typing import Annotated, Callable
-
-from fastapi import Body, FastAPI, Request, Response
-from fastapi.routing import APIRoute
-
-
-class GzipRequest(Request):
- async def body(self) -> bytes:
- if not hasattr(self, "_body"):
- body = await super().body()
- if "gzip" in self.headers.getlist("Content-Encoding"):
- body = gzip.decompress(body)
- self._body = body
- return self._body
-
-
-class GzipRoute(APIRoute):
- def get_route_handler(self) -> Callable:
- original_route_handler = super().get_route_handler()
-
- async def custom_route_handler(request: Request) -> Response:
- request = GzipRequest(request.scope, request.receive)
- return await original_route_handler(request)
-
- return custom_route_handler
-
-
-app = FastAPI()
-app.router.route_class = GzipRoute
-
-
-@app.post("/sum")
-async def sum_numbers(numbers: Annotated[list[int], Body()]):
- return {"sum": sum(numbers)}
diff --git a/docs_src/custom_request_and_route/tutorial001_py39.py b/docs_src/custom_request_and_route/tutorial001_py39.py
deleted file mode 100644
index 54b20b942..000000000
--- a/docs_src/custom_request_and_route/tutorial001_py39.py
+++ /dev/null
@@ -1,35 +0,0 @@
-import gzip
-from typing import Callable
-
-from fastapi import Body, FastAPI, Request, Response
-from fastapi.routing import APIRoute
-
-
-class GzipRequest(Request):
- async def body(self) -> bytes:
- if not hasattr(self, "_body"):
- body = await super().body()
- if "gzip" in self.headers.getlist("Content-Encoding"):
- body = gzip.decompress(body)
- self._body = body
- return self._body
-
-
-class GzipRoute(APIRoute):
- def get_route_handler(self) -> Callable:
- original_route_handler = super().get_route_handler()
-
- async def custom_route_handler(request: Request) -> Response:
- request = GzipRequest(request.scope, request.receive)
- return await original_route_handler(request)
-
- return custom_route_handler
-
-
-app = FastAPI()
-app.router.route_class = GzipRoute
-
-
-@app.post("/sum")
-async def sum_numbers(numbers: list[int] = Body()):
- return {"sum": sum(numbers)}
diff --git a/docs_src/custom_request_and_route/tutorial002_an_py39.py b/docs_src/custom_request_and_route/tutorial002_an_py39.py
deleted file mode 100644
index e7de09de4..000000000
--- a/docs_src/custom_request_and_route/tutorial002_an_py39.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from typing import Annotated, Callable
-
-from fastapi import Body, FastAPI, HTTPException, Request, Response
-from fastapi.exceptions import RequestValidationError
-from fastapi.routing import APIRoute
-
-
-class ValidationErrorLoggingRoute(APIRoute):
- def get_route_handler(self) -> Callable:
- original_route_handler = super().get_route_handler()
-
- async def custom_route_handler(request: Request) -> Response:
- try:
- return await original_route_handler(request)
- except RequestValidationError as exc:
- body = await request.body()
- detail = {"errors": exc.errors(), "body": body.decode()}
- raise HTTPException(status_code=422, detail=detail)
-
- return custom_route_handler
-
-
-app = FastAPI()
-app.router.route_class = ValidationErrorLoggingRoute
-
-
-@app.post("/")
-async def sum_numbers(numbers: Annotated[list[int], Body()]):
- return sum(numbers)
diff --git a/docs_src/custom_request_and_route/tutorial002_py39.py b/docs_src/custom_request_and_route/tutorial002_py39.py
deleted file mode 100644
index c4e474828..000000000
--- a/docs_src/custom_request_and_route/tutorial002_py39.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from typing import Callable
-
-from fastapi import Body, FastAPI, HTTPException, Request, Response
-from fastapi.exceptions import RequestValidationError
-from fastapi.routing import APIRoute
-
-
-class ValidationErrorLoggingRoute(APIRoute):
- def get_route_handler(self) -> Callable:
- original_route_handler = super().get_route_handler()
-
- async def custom_route_handler(request: Request) -> Response:
- try:
- return await original_route_handler(request)
- except RequestValidationError as exc:
- body = await request.body()
- detail = {"errors": exc.errors(), "body": body.decode()}
- raise HTTPException(status_code=422, detail=detail)
-
- return custom_route_handler
-
-
-app = FastAPI()
-app.router.route_class = ValidationErrorLoggingRoute
-
-
-@app.post("/")
-async def sum_numbers(numbers: list[int] = Body()):
- return sum(numbers)
diff --git a/docs_src/custom_request_and_route/tutorial003_py39.py b/docs_src/custom_request_and_route/tutorial003_py39.py
deleted file mode 100644
index aabe76068..000000000
--- a/docs_src/custom_request_and_route/tutorial003_py39.py
+++ /dev/null
@@ -1,39 +0,0 @@
-import time
-from typing import Callable
-
-from fastapi import APIRouter, FastAPI, Request, Response
-from fastapi.routing import APIRoute
-
-
-class TimedRoute(APIRoute):
- def get_route_handler(self) -> Callable:
- original_route_handler = super().get_route_handler()
-
- async def custom_route_handler(request: Request) -> Response:
- before = time.time()
- response: Response = await original_route_handler(request)
- duration = time.time() - before
- response.headers["X-Response-Time"] = str(duration)
- print(f"route duration: {duration}")
- print(f"route response: {response}")
- print(f"route response headers: {response.headers}")
- return response
-
- return custom_route_handler
-
-
-app = FastAPI()
-router = APIRouter(route_class=TimedRoute)
-
-
-@app.get("/")
-async def not_timed():
- return {"message": "Not timed"}
-
-
-@router.get("/timed")
-async def timed():
- return {"message": "It's the time of my life"}
-
-
-app.include_router(router)
diff --git a/docs_src/custom_response/tutorial001_py310.py b/docs_src/custom_response/tutorial001_py310.py
new file mode 100644
index 000000000..0f09bdf77
--- /dev/null
+++ b/docs_src/custom_response/tutorial001_py310.py
@@ -0,0 +1,9 @@
+from fastapi import FastAPI
+from fastapi.responses import UJSONResponse
+
+app = FastAPI()
+
+
+@app.get("/items/", response_class=UJSONResponse)
+async def read_items():
+ return [{"item_id": "Foo"}]
diff --git a/docs_src/custom_response/tutorial001b_py310.py b/docs_src/custom_response/tutorial001b_py310.py
new file mode 100644
index 000000000..95e6ca763
--- /dev/null
+++ b/docs_src/custom_response/tutorial001b_py310.py
@@ -0,0 +1,9 @@
+from fastapi import FastAPI
+from fastapi.responses import ORJSONResponse
+
+app = FastAPI()
+
+
+@app.get("/items/", response_class=ORJSONResponse)
+async def read_items():
+ return ORJSONResponse([{"item_id": "Foo"}])
diff --git a/docs_src/custom_response/tutorial002_py310.py b/docs_src/custom_response/tutorial002_py310.py
new file mode 100644
index 000000000..23c495867
--- /dev/null
+++ b/docs_src/custom_response/tutorial002_py310.py
@@ -0,0 +1,18 @@
+from fastapi import FastAPI
+from fastapi.responses import HTMLResponse
+
+app = FastAPI()
+
+
+@app.get("/items/", response_class=HTMLResponse)
+async def read_items():
+ return """
+
+
+ Look ma! HTML!
+
+
+ """
diff --git a/docs_src/custom_response/tutorial003_py310.py b/docs_src/custom_response/tutorial003_py310.py
new file mode 100644
index 000000000..51ad3c146
--- /dev/null
+++ b/docs_src/custom_response/tutorial003_py310.py
@@ -0,0 +1,19 @@
+from fastapi import FastAPI
+from fastapi.responses import HTMLResponse
+
+app = FastAPI()
+
+
+@app.get("/items/")
+async def read_items():
+ html_content = """
+
+
+ Look ma! HTML!
+
+
+ """
+ return HTMLResponse(content=html_content, status_code=200)
diff --git a/docs_src/custom_response/tutorial004_py310.py b/docs_src/custom_response/tutorial004_py310.py
new file mode 100644
index 000000000..0e90f2012
--- /dev/null
+++ b/docs_src/custom_response/tutorial004_py310.py
@@ -0,0 +1,23 @@
+from fastapi import FastAPI
+from fastapi.responses import HTMLResponse
+
+app = FastAPI()
+
+
+def generate_html_response():
+ html_content = """
+
+
+ Look ma! HTML!
+
+
+ """
+ return HTMLResponse(content=html_content, status_code=200)
+
+
+@app.get("/items/", response_class=HTMLResponse)
+async def read_items():
+ return generate_html_response()
diff --git a/docs_src/custom_response/tutorial005_py310.py b/docs_src/custom_response/tutorial005_py310.py
new file mode 100644
index 000000000..3d58f57fb
--- /dev/null
+++ b/docs_src/custom_response/tutorial005_py310.py
@@ -0,0 +1,9 @@
+from fastapi import FastAPI
+from fastapi.responses import PlainTextResponse
+
+app = FastAPI()
+
+
+@app.get("/", response_class=PlainTextResponse)
+async def main():
+ return "Hello World"
diff --git a/docs_src/custom_response/tutorial006_py310.py b/docs_src/custom_response/tutorial006_py310.py
new file mode 100644
index 000000000..332f8f87f
--- /dev/null
+++ b/docs_src/custom_response/tutorial006_py310.py
@@ -0,0 +1,9 @@
+from fastapi import FastAPI
+from fastapi.responses import RedirectResponse
+
+app = FastAPI()
+
+
+@app.get("/typer")
+async def redirect_typer():
+ return RedirectResponse("https://typer.tiangolo.com")
diff --git a/docs_src/custom_response/tutorial006b_py310.py b/docs_src/custom_response/tutorial006b_py310.py
new file mode 100644
index 000000000..03a7be399
--- /dev/null
+++ b/docs_src/custom_response/tutorial006b_py310.py
@@ -0,0 +1,9 @@
+from fastapi import FastAPI
+from fastapi.responses import RedirectResponse
+
+app = FastAPI()
+
+
+@app.get("/fastapi", response_class=RedirectResponse)
+async def redirect_fastapi():
+ return "https://fastapi.tiangolo.com"
diff --git a/docs_src/custom_response/tutorial006c_py310.py b/docs_src/custom_response/tutorial006c_py310.py
new file mode 100644
index 000000000..87c720364
--- /dev/null
+++ b/docs_src/custom_response/tutorial006c_py310.py
@@ -0,0 +1,9 @@
+from fastapi import FastAPI
+from fastapi.responses import RedirectResponse
+
+app = FastAPI()
+
+
+@app.get("/pydantic", response_class=RedirectResponse, status_code=302)
+async def redirect_pydantic():
+ return "https://docs.pydantic.dev/"
diff --git a/docs_src/custom_response/tutorial007_py310.py b/docs_src/custom_response/tutorial007_py310.py
new file mode 100644
index 000000000..e2a53a211
--- /dev/null
+++ b/docs_src/custom_response/tutorial007_py310.py
@@ -0,0 +1,14 @@
+from fastapi import FastAPI
+from fastapi.responses import StreamingResponse
+
+app = FastAPI()
+
+
+async def fake_video_streamer():
+ for i in range(10):
+ yield b"some fake video bytes"
+
+
+@app.get("/")
+async def main():
+ return StreamingResponse(fake_video_streamer())
diff --git a/docs_src/custom_response/tutorial008_py310.py b/docs_src/custom_response/tutorial008_py310.py
new file mode 100644
index 000000000..fc071cbee
--- /dev/null
+++ b/docs_src/custom_response/tutorial008_py310.py
@@ -0,0 +1,14 @@
+from fastapi import FastAPI
+from fastapi.responses import StreamingResponse
+
+some_file_path = "large-video-file.mp4"
+app = FastAPI()
+
+
+@app.get("/")
+def main():
+ def iterfile(): # (1)
+ with open(some_file_path, mode="rb") as file_like: # (2)
+ yield from file_like # (3)
+
+ return StreamingResponse(iterfile(), media_type="video/mp4")
diff --git a/docs_src/custom_response/tutorial009_py310.py b/docs_src/custom_response/tutorial009_py310.py
new file mode 100644
index 000000000..71cf50cc1
--- /dev/null
+++ b/docs_src/custom_response/tutorial009_py310.py
@@ -0,0 +1,10 @@
+from fastapi import FastAPI
+from fastapi.responses import FileResponse
+
+some_file_path = "large-video-file.mp4"
+app = FastAPI()
+
+
+@app.get("/")
+async def main():
+ return FileResponse(some_file_path)
diff --git a/docs_src/custom_response/tutorial009b_py310.py b/docs_src/custom_response/tutorial009b_py310.py
new file mode 100644
index 000000000..27200ee4b
--- /dev/null
+++ b/docs_src/custom_response/tutorial009b_py310.py
@@ -0,0 +1,10 @@
+from fastapi import FastAPI
+from fastapi.responses import FileResponse
+
+some_file_path = "large-video-file.mp4"
+app = FastAPI()
+
+
+@app.get("/", response_class=FileResponse)
+async def main():
+ return some_file_path
diff --git a/docs_src/custom_response/tutorial009c_py310.py b/docs_src/custom_response/tutorial009c_py310.py
new file mode 100644
index 000000000..de6b6688e
--- /dev/null
+++ b/docs_src/custom_response/tutorial009c_py310.py
@@ -0,0 +1,19 @@
+from typing import Any
+
+import orjson
+from fastapi import FastAPI, Response
+
+app = FastAPI()
+
+
+class CustomORJSONResponse(Response):
+ media_type = "application/json"
+
+ def render(self, content: Any) -> bytes:
+ assert orjson is not None, "orjson must be installed"
+ return orjson.dumps(content, option=orjson.OPT_INDENT_2)
+
+
+@app.get("/", response_class=CustomORJSONResponse)
+async def main():
+ return {"message": "Hello World"}
diff --git a/docs_src/custom_response/tutorial010_py310.py b/docs_src/custom_response/tutorial010_py310.py
new file mode 100644
index 000000000..57cb06260
--- /dev/null
+++ b/docs_src/custom_response/tutorial010_py310.py
@@ -0,0 +1,9 @@
+from fastapi import FastAPI
+from fastapi.responses import ORJSONResponse
+
+app = FastAPI(default_response_class=ORJSONResponse)
+
+
+@app.get("/items/")
+async def read_items():
+ return [{"item_id": "Foo"}]
diff --git a/docs_src/dataclasses_/tutorial001_py39.py b/docs_src/dataclasses_/tutorial001_py39.py
deleted file mode 100644
index 2954c391f..000000000
--- a/docs_src/dataclasses_/tutorial001_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from dataclasses import dataclass
-from typing import Union
-
-from fastapi import FastAPI
-
-
-@dataclass
-class Item:
- name: str
- price: float
- description: Union[str, None] = None
- tax: Union[float, None] = None
-
-
-app = FastAPI()
-
-
-@app.post("/items/")
-async def create_item(item: Item):
- return item
diff --git a/docs_src/dataclasses_/tutorial002_py39.py b/docs_src/dataclasses_/tutorial002_py39.py
deleted file mode 100644
index 0c23765d8..000000000
--- a/docs_src/dataclasses_/tutorial002_py39.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from dataclasses import dataclass, field
-from typing import Union
-
-from fastapi import FastAPI
-
-
-@dataclass
-class Item:
- name: str
- price: float
- tags: list[str] = field(default_factory=list)
- description: Union[str, None] = None
- tax: Union[float, None] = None
-
-
-app = FastAPI()
-
-
-@app.get("/items/next", response_model=Item)
-async def read_next_item():
- return {
- "name": "Island In The Moon",
- "price": 12.99,
- "description": "A place to be playin' and havin' fun",
- "tags": ["breater"],
- }
diff --git a/docs_src/dataclasses_/tutorial003_py39.py b/docs_src/dataclasses_/tutorial003_py39.py
deleted file mode 100644
index 991708c00..000000000
--- a/docs_src/dataclasses_/tutorial003_py39.py
+++ /dev/null
@@ -1,55 +0,0 @@
-from dataclasses import field # (1)
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic.dataclasses import dataclass # (2)
-
-
-@dataclass
-class Item:
- name: str
- description: Union[str, None] = None
-
-
-@dataclass
-class Author:
- name: str
- items: list[Item] = field(default_factory=list) # (3)
-
-
-app = FastAPI()
-
-
-@app.post("/authors/{author_id}/items/", response_model=Author) # (4)
-async def create_author_items(author_id: str, items: list[Item]): # (5)
- return {"name": author_id, "items": items} # (6)
-
-
-@app.get("/authors/", response_model=list[Author]) # (7)
-def get_authors(): # (8)
- return [ # (9)
- {
- "name": "Breaters",
- "items": [
- {
- "name": "Island In The Moon",
- "description": "A place to be playin' and havin' fun",
- },
- {"name": "Holy Buddies"},
- ],
- },
- {
- "name": "System of an Up",
- "items": [
- {
- "name": "Salt",
- "description": "The kombucha mushroom people's favorite",
- },
- {"name": "Pad Thai"},
- {
- "name": "Lonely Night",
- "description": "The mostests lonliest nightiest of allest",
- },
- ],
- },
- ]
diff --git a/docs_src/debugging/tutorial001_py310.py b/docs_src/debugging/tutorial001_py310.py
new file mode 100644
index 000000000..3de21d2a8
--- /dev/null
+++ b/docs_src/debugging/tutorial001_py310.py
@@ -0,0 +1,15 @@
+import uvicorn
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+def root():
+ a = "a"
+ b = "b" + a
+ return {"hello world": b}
+
+
+if __name__ == "__main__":
+ uvicorn.run(app, host="0.0.0.0", port=8000)
diff --git a/docs_src/dependencies/tutorial001_02_an_py39.py b/docs_src/dependencies/tutorial001_02_an_py39.py
deleted file mode 100644
index df969ae9c..000000000
--- a/docs_src/dependencies/tutorial001_02_an_py39.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-async def common_parameters(
- q: Union[str, None] = None, skip: int = 0, limit: int = 100
-):
- return {"q": q, "skip": skip, "limit": limit}
-
-
-CommonsDep = Annotated[dict, Depends(common_parameters)]
-
-
-@app.get("/items/")
-async def read_items(commons: CommonsDep):
- return commons
-
-
-@app.get("/users/")
-async def read_users(commons: CommonsDep):
- return commons
diff --git a/docs_src/dependencies/tutorial001_an_py39.py b/docs_src/dependencies/tutorial001_an_py39.py
deleted file mode 100644
index 5d9fe6ddf..000000000
--- a/docs_src/dependencies/tutorial001_an_py39.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-async def common_parameters(
- q: Union[str, None] = None, skip: int = 0, limit: int = 100
-):
- return {"q": q, "skip": skip, "limit": limit}
-
-
-@app.get("/items/")
-async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
- return commons
-
-
-@app.get("/users/")
-async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
- return commons
diff --git a/docs_src/dependencies/tutorial001_py39.py b/docs_src/dependencies/tutorial001_py39.py
deleted file mode 100644
index b1275103a..000000000
--- a/docs_src/dependencies/tutorial001_py39.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-async def common_parameters(
- q: Union[str, None] = None, skip: int = 0, limit: int = 100
-):
- return {"q": q, "skip": skip, "limit": limit}
-
-
-@app.get("/items/")
-async def read_items(commons: dict = Depends(common_parameters)):
- return commons
-
-
-@app.get("/users/")
-async def read_users(commons: dict = Depends(common_parameters)):
- return commons
diff --git a/docs_src/dependencies/tutorial002_an_py39.py b/docs_src/dependencies/tutorial002_an_py39.py
deleted file mode 100644
index 844a23c5a..000000000
--- a/docs_src/dependencies/tutorial002_an_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
-
-
-class CommonQueryParams:
- def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
- self.q = q
- self.skip = skip
- self.limit = limit
-
-
-@app.get("/items/")
-async def read_items(commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]):
- response = {}
- if commons.q:
- response.update({"q": commons.q})
- items = fake_items_db[commons.skip : commons.skip + commons.limit]
- response.update({"items": items})
- return response
diff --git a/docs_src/dependencies/tutorial002_py39.py b/docs_src/dependencies/tutorial002_py39.py
deleted file mode 100644
index 8e863e4fa..000000000
--- a/docs_src/dependencies/tutorial002_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
-
-
-class CommonQueryParams:
- def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
- self.q = q
- self.skip = skip
- self.limit = limit
-
-
-@app.get("/items/")
-async def read_items(commons: CommonQueryParams = Depends(CommonQueryParams)):
- response = {}
- if commons.q:
- response.update({"q": commons.q})
- items = fake_items_db[commons.skip : commons.skip + commons.limit]
- response.update({"items": items})
- return response
diff --git a/docs_src/dependencies/tutorial003_an_py39.py b/docs_src/dependencies/tutorial003_an_py39.py
deleted file mode 100644
index 9e9123ad2..000000000
--- a/docs_src/dependencies/tutorial003_an_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from typing import Annotated, Any, Union
-
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
-
-
-class CommonQueryParams:
- def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
- self.q = q
- self.skip = skip
- self.limit = limit
-
-
-@app.get("/items/")
-async def read_items(commons: Annotated[Any, Depends(CommonQueryParams)]):
- response = {}
- if commons.q:
- response.update({"q": commons.q})
- items = fake_items_db[commons.skip : commons.skip + commons.limit]
- response.update({"items": items})
- return response
diff --git a/docs_src/dependencies/tutorial003_py39.py b/docs_src/dependencies/tutorial003_py39.py
deleted file mode 100644
index 34614e539..000000000
--- a/docs_src/dependencies/tutorial003_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
-
-
-class CommonQueryParams:
- def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
- self.q = q
- self.skip = skip
- self.limit = limit
-
-
-@app.get("/items/")
-async def read_items(commons=Depends(CommonQueryParams)):
- response = {}
- if commons.q:
- response.update({"q": commons.q})
- items = fake_items_db[commons.skip : commons.skip + commons.limit]
- response.update({"items": items})
- return response
diff --git a/docs_src/dependencies/tutorial004_an_py39.py b/docs_src/dependencies/tutorial004_an_py39.py
deleted file mode 100644
index 74268626b..000000000
--- a/docs_src/dependencies/tutorial004_an_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
-
-
-class CommonQueryParams:
- def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
- self.q = q
- self.skip = skip
- self.limit = limit
-
-
-@app.get("/items/")
-async def read_items(commons: Annotated[CommonQueryParams, Depends()]):
- response = {}
- if commons.q:
- response.update({"q": commons.q})
- items = fake_items_db[commons.skip : commons.skip + commons.limit]
- response.update({"items": items})
- return response
diff --git a/docs_src/dependencies/tutorial004_py39.py b/docs_src/dependencies/tutorial004_py39.py
deleted file mode 100644
index d9fe88148..000000000
--- a/docs_src/dependencies/tutorial004_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
-
-
-class CommonQueryParams:
- def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
- self.q = q
- self.skip = skip
- self.limit = limit
-
-
-@app.get("/items/")
-async def read_items(commons: CommonQueryParams = Depends()):
- response = {}
- if commons.q:
- response.update({"q": commons.q})
- items = fake_items_db[commons.skip : commons.skip + commons.limit]
- response.update({"items": items})
- return response
diff --git a/docs_src/dependencies/tutorial005_an_py39.py b/docs_src/dependencies/tutorial005_an_py39.py
deleted file mode 100644
index d5dd8dca9..000000000
--- a/docs_src/dependencies/tutorial005_an_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Cookie, Depends, FastAPI
-
-app = FastAPI()
-
-
-def query_extractor(q: Union[str, None] = None):
- return q
-
-
-def query_or_cookie_extractor(
- q: Annotated[str, Depends(query_extractor)],
- last_query: Annotated[Union[str, None], Cookie()] = None,
-):
- if not q:
- return last_query
- return q
-
-
-@app.get("/items/")
-async def read_query(
- query_or_default: Annotated[str, Depends(query_or_cookie_extractor)],
-):
- return {"q_or_cookie": query_or_default}
diff --git a/docs_src/dependencies/tutorial005_py39.py b/docs_src/dependencies/tutorial005_py39.py
deleted file mode 100644
index 697332b5b..000000000
--- a/docs_src/dependencies/tutorial005_py39.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from typing import Union
-
-from fastapi import Cookie, Depends, FastAPI
-
-app = FastAPI()
-
-
-def query_extractor(q: Union[str, None] = None):
- return q
-
-
-def query_or_cookie_extractor(
- q: str = Depends(query_extractor),
- last_query: Union[str, None] = Cookie(default=None),
-):
- if not q:
- return last_query
- return q
-
-
-@app.get("/items/")
-async def read_query(query_or_default: str = Depends(query_or_cookie_extractor)):
- return {"q_or_cookie": query_or_default}
diff --git a/docs_src/dependencies/tutorial006_an_py310.py b/docs_src/dependencies/tutorial006_an_py310.py
new file mode 100644
index 000000000..11976ed6a
--- /dev/null
+++ b/docs_src/dependencies/tutorial006_an_py310.py
@@ -0,0 +1,21 @@
+from typing import Annotated
+
+from fastapi import Depends, FastAPI, Header, HTTPException
+
+app = FastAPI()
+
+
+async def verify_token(x_token: Annotated[str, Header()]):
+ if x_token != "fake-super-secret-token":
+ raise HTTPException(status_code=400, detail="X-Token header invalid")
+
+
+async def verify_key(x_key: Annotated[str, Header()]):
+ if x_key != "fake-super-secret-key":
+ raise HTTPException(status_code=400, detail="X-Key header invalid")
+ return x_key
+
+
+@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
+async def read_items():
+ return [{"item": "Foo"}, {"item": "Bar"}]
diff --git a/docs_src/dependencies/tutorial006_py310.py b/docs_src/dependencies/tutorial006_py310.py
new file mode 100644
index 000000000..9aff4154f
--- /dev/null
+++ b/docs_src/dependencies/tutorial006_py310.py
@@ -0,0 +1,19 @@
+from fastapi import Depends, FastAPI, Header, HTTPException
+
+app = FastAPI()
+
+
+async def verify_token(x_token: str = Header()):
+ if x_token != "fake-super-secret-token":
+ raise HTTPException(status_code=400, detail="X-Token header invalid")
+
+
+async def verify_key(x_key: str = Header()):
+ if x_key != "fake-super-secret-key":
+ raise HTTPException(status_code=400, detail="X-Key header invalid")
+ return x_key
+
+
+@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
+async def read_items():
+ return [{"item": "Foo"}, {"item": "Bar"}]
diff --git a/docs_src/dependencies/tutorial007_py310.py b/docs_src/dependencies/tutorial007_py310.py
new file mode 100644
index 000000000..2e4ab4777
--- /dev/null
+++ b/docs_src/dependencies/tutorial007_py310.py
@@ -0,0 +1,6 @@
+async def get_db():
+ db = DBSession()
+ try:
+ yield db
+ finally:
+ db.close()
diff --git a/docs_src/dependencies/tutorial008_an_py310.py b/docs_src/dependencies/tutorial008_an_py310.py
new file mode 100644
index 000000000..acc804c32
--- /dev/null
+++ b/docs_src/dependencies/tutorial008_an_py310.py
@@ -0,0 +1,27 @@
+from typing import Annotated
+
+from fastapi import Depends
+
+
+async def dependency_a():
+ dep_a = generate_dep_a()
+ try:
+ yield dep_a
+ finally:
+ dep_a.close()
+
+
+async def dependency_b(dep_a: Annotated[DepA, Depends(dependency_a)]):
+ dep_b = generate_dep_b()
+ try:
+ yield dep_b
+ finally:
+ dep_b.close(dep_a)
+
+
+async def dependency_c(dep_b: Annotated[DepB, Depends(dependency_b)]):
+ dep_c = generate_dep_c()
+ try:
+ yield dep_c
+ finally:
+ dep_c.close(dep_b)
diff --git a/docs_src/dependencies/tutorial008_py310.py b/docs_src/dependencies/tutorial008_py310.py
new file mode 100644
index 000000000..8472f642d
--- /dev/null
+++ b/docs_src/dependencies/tutorial008_py310.py
@@ -0,0 +1,25 @@
+from fastapi import Depends
+
+
+async def dependency_a():
+ dep_a = generate_dep_a()
+ try:
+ yield dep_a
+ finally:
+ dep_a.close()
+
+
+async def dependency_b(dep_a=Depends(dependency_a)):
+ dep_b = generate_dep_b()
+ try:
+ yield dep_b
+ finally:
+ dep_b.close(dep_a)
+
+
+async def dependency_c(dep_b=Depends(dependency_b)):
+ dep_c = generate_dep_c()
+ try:
+ yield dep_c
+ finally:
+ dep_c.close(dep_b)
diff --git a/docs_src/dependencies/tutorial008b_an_py310.py b/docs_src/dependencies/tutorial008b_an_py310.py
new file mode 100644
index 000000000..3b8434c81
--- /dev/null
+++ b/docs_src/dependencies/tutorial008b_an_py310.py
@@ -0,0 +1,32 @@
+from typing import Annotated
+
+from fastapi import Depends, FastAPI, HTTPException
+
+app = FastAPI()
+
+
+data = {
+ "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
+ "portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
+}
+
+
+class OwnerError(Exception):
+ pass
+
+
+def get_username():
+ try:
+ yield "Rick"
+ except OwnerError as e:
+ raise HTTPException(status_code=400, detail=f"Owner error: {e}")
+
+
+@app.get("/items/{item_id}")
+def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
+ if item_id not in data:
+ raise HTTPException(status_code=404, detail="Item not found")
+ item = data[item_id]
+ if item["owner"] != username:
+ raise OwnerError(username)
+ return item
diff --git a/docs_src/dependencies/tutorial008b_py310.py b/docs_src/dependencies/tutorial008b_py310.py
new file mode 100644
index 000000000..163e96600
--- /dev/null
+++ b/docs_src/dependencies/tutorial008b_py310.py
@@ -0,0 +1,30 @@
+from fastapi import Depends, FastAPI, HTTPException
+
+app = FastAPI()
+
+
+data = {
+ "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
+ "portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
+}
+
+
+class OwnerError(Exception):
+ pass
+
+
+def get_username():
+ try:
+ yield "Rick"
+ except OwnerError as e:
+ raise HTTPException(status_code=400, detail=f"Owner error: {e}")
+
+
+@app.get("/items/{item_id}")
+def get_item(item_id: str, username: str = Depends(get_username)):
+ if item_id not in data:
+ raise HTTPException(status_code=404, detail="Item not found")
+ item = data[item_id]
+ if item["owner"] != username:
+ raise OwnerError(username)
+ return item
diff --git a/docs_src/dependencies/tutorial008c_an_py310.py b/docs_src/dependencies/tutorial008c_an_py310.py
new file mode 100644
index 000000000..da92efa9c
--- /dev/null
+++ b/docs_src/dependencies/tutorial008c_an_py310.py
@@ -0,0 +1,29 @@
+from typing import Annotated
+
+from fastapi import Depends, FastAPI, HTTPException
+
+app = FastAPI()
+
+
+class InternalError(Exception):
+ pass
+
+
+def get_username():
+ try:
+ yield "Rick"
+ except InternalError:
+ print("Oops, we didn't raise again, Britney 😱")
+
+
+@app.get("/items/{item_id}")
+def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
+ if item_id == "portal-gun":
+ raise InternalError(
+ f"The portal gun is too dangerous to be owned by {username}"
+ )
+ if item_id != "plumbus":
+ raise HTTPException(
+ status_code=404, detail="Item not found, there's only a plumbus here"
+ )
+ return item_id
diff --git a/docs_src/dependencies/tutorial008c_py310.py b/docs_src/dependencies/tutorial008c_py310.py
new file mode 100644
index 000000000..4b99a5a31
--- /dev/null
+++ b/docs_src/dependencies/tutorial008c_py310.py
@@ -0,0 +1,27 @@
+from fastapi import Depends, FastAPI, HTTPException
+
+app = FastAPI()
+
+
+class InternalError(Exception):
+ pass
+
+
+def get_username():
+ try:
+ yield "Rick"
+ except InternalError:
+ print("Oops, we didn't raise again, Britney 😱")
+
+
+@app.get("/items/{item_id}")
+def get_item(item_id: str, username: str = Depends(get_username)):
+ if item_id == "portal-gun":
+ raise InternalError(
+ f"The portal gun is too dangerous to be owned by {username}"
+ )
+ if item_id != "plumbus":
+ raise HTTPException(
+ status_code=404, detail="Item not found, there's only a plumbus here"
+ )
+ return item_id
diff --git a/docs_src/dependencies/tutorial008d_an_py310.py b/docs_src/dependencies/tutorial008d_an_py310.py
new file mode 100644
index 000000000..99bd5cb91
--- /dev/null
+++ b/docs_src/dependencies/tutorial008d_an_py310.py
@@ -0,0 +1,30 @@
+from typing import Annotated
+
+from fastapi import Depends, FastAPI, HTTPException
+
+app = FastAPI()
+
+
+class InternalError(Exception):
+ pass
+
+
+def get_username():
+ try:
+ yield "Rick"
+ except InternalError:
+ print("We don't swallow the internal error here, we raise again 😎")
+ raise
+
+
+@app.get("/items/{item_id}")
+def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
+ if item_id == "portal-gun":
+ raise InternalError(
+ f"The portal gun is too dangerous to be owned by {username}"
+ )
+ if item_id != "plumbus":
+ raise HTTPException(
+ status_code=404, detail="Item not found, there's only a plumbus here"
+ )
+ return item_id
diff --git a/docs_src/dependencies/tutorial008d_py310.py b/docs_src/dependencies/tutorial008d_py310.py
new file mode 100644
index 000000000..93039343d
--- /dev/null
+++ b/docs_src/dependencies/tutorial008d_py310.py
@@ -0,0 +1,28 @@
+from fastapi import Depends, FastAPI, HTTPException
+
+app = FastAPI()
+
+
+class InternalError(Exception):
+ pass
+
+
+def get_username():
+ try:
+ yield "Rick"
+ except InternalError:
+ print("We don't swallow the internal error here, we raise again 😎")
+ raise
+
+
+@app.get("/items/{item_id}")
+def get_item(item_id: str, username: str = Depends(get_username)):
+ if item_id == "portal-gun":
+ raise InternalError(
+ f"The portal gun is too dangerous to be owned by {username}"
+ )
+ if item_id != "plumbus":
+ raise HTTPException(
+ status_code=404, detail="Item not found, there's only a plumbus here"
+ )
+ return item_id
diff --git a/docs_src/dependencies/tutorial008e_an_py310.py b/docs_src/dependencies/tutorial008e_an_py310.py
new file mode 100644
index 000000000..80a44c7e2
--- /dev/null
+++ b/docs_src/dependencies/tutorial008e_an_py310.py
@@ -0,0 +1,17 @@
+from typing import Annotated
+
+from fastapi import Depends, FastAPI
+
+app = FastAPI()
+
+
+def get_username():
+ try:
+ yield "Rick"
+ finally:
+ print("Cleanup up before response is sent")
+
+
+@app.get("/users/me")
+def get_user_me(username: Annotated[str, Depends(get_username, scope="function")]):
+ return username
diff --git a/docs_src/dependencies/tutorial008e_py310.py b/docs_src/dependencies/tutorial008e_py310.py
new file mode 100644
index 000000000..1ed056e91
--- /dev/null
+++ b/docs_src/dependencies/tutorial008e_py310.py
@@ -0,0 +1,15 @@
+from fastapi import Depends, FastAPI
+
+app = FastAPI()
+
+
+def get_username():
+ try:
+ yield "Rick"
+ finally:
+ print("Cleanup up before response is sent")
+
+
+@app.get("/users/me")
+def get_user_me(username: str = Depends(get_username, scope="function")):
+ return username
diff --git a/docs_src/dependencies/tutorial010_py310.py b/docs_src/dependencies/tutorial010_py310.py
new file mode 100644
index 000000000..c27f1b170
--- /dev/null
+++ b/docs_src/dependencies/tutorial010_py310.py
@@ -0,0 +1,14 @@
+class MySuperContextManager:
+ def __init__(self):
+ self.db = DBSession()
+
+ def __enter__(self):
+ return self.db
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.db.close()
+
+
+async def get_db():
+ with MySuperContextManager() as db:
+ yield db
diff --git a/docs_src/dependencies/tutorial011_an_py310.py b/docs_src/dependencies/tutorial011_an_py310.py
new file mode 100644
index 000000000..68b7434ec
--- /dev/null
+++ b/docs_src/dependencies/tutorial011_an_py310.py
@@ -0,0 +1,23 @@
+from typing import Annotated
+
+from fastapi import Depends, FastAPI
+
+app = FastAPI()
+
+
+class FixedContentQueryChecker:
+ def __init__(self, fixed_content: str):
+ self.fixed_content = fixed_content
+
+ def __call__(self, q: str = ""):
+ if q:
+ return self.fixed_content in q
+ return False
+
+
+checker = FixedContentQueryChecker("bar")
+
+
+@app.get("/query-checker/")
+async def read_query_check(fixed_content_included: Annotated[bool, Depends(checker)]):
+ return {"fixed_content_in_query": fixed_content_included}
diff --git a/docs_src/dependencies/tutorial011_py310.py b/docs_src/dependencies/tutorial011_py310.py
new file mode 100644
index 000000000..5d22f6823
--- /dev/null
+++ b/docs_src/dependencies/tutorial011_py310.py
@@ -0,0 +1,21 @@
+from fastapi import Depends, FastAPI
+
+app = FastAPI()
+
+
+class FixedContentQueryChecker:
+ def __init__(self, fixed_content: str):
+ self.fixed_content = fixed_content
+
+ def __call__(self, q: str = ""):
+ if q:
+ return self.fixed_content in q
+ return False
+
+
+checker = FixedContentQueryChecker("bar")
+
+
+@app.get("/query-checker/")
+async def read_query_check(fixed_content_included: bool = Depends(checker)):
+ return {"fixed_content_in_query": fixed_content_included}
diff --git a/docs_src/dependencies/tutorial012_an_py310.py b/docs_src/dependencies/tutorial012_an_py310.py
new file mode 100644
index 000000000..6503591fc
--- /dev/null
+++ b/docs_src/dependencies/tutorial012_an_py310.py
@@ -0,0 +1,27 @@
+from typing import Annotated
+
+from fastapi import Depends, FastAPI, Header, HTTPException
+
+
+async def verify_token(x_token: Annotated[str, Header()]):
+ if x_token != "fake-super-secret-token":
+ raise HTTPException(status_code=400, detail="X-Token header invalid")
+
+
+async def verify_key(x_key: Annotated[str, Header()]):
+ if x_key != "fake-super-secret-key":
+ raise HTTPException(status_code=400, detail="X-Key header invalid")
+ return x_key
+
+
+app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
+
+
+@app.get("/items/")
+async def read_items():
+ return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
+
+
+@app.get("/users/")
+async def read_users():
+ return [{"username": "Rick"}, {"username": "Morty"}]
diff --git a/docs_src/dependencies/tutorial012_py310.py b/docs_src/dependencies/tutorial012_py310.py
new file mode 100644
index 000000000..36ce6c711
--- /dev/null
+++ b/docs_src/dependencies/tutorial012_py310.py
@@ -0,0 +1,25 @@
+from fastapi import Depends, FastAPI, Header, HTTPException
+
+
+async def verify_token(x_token: str = Header()):
+ if x_token != "fake-super-secret-token":
+ raise HTTPException(status_code=400, detail="X-Token header invalid")
+
+
+async def verify_key(x_key: str = Header()):
+ if x_key != "fake-super-secret-key":
+ raise HTTPException(status_code=400, detail="X-Key header invalid")
+ return x_key
+
+
+app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
+
+
+@app.get("/items/")
+async def read_items():
+ return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
+
+
+@app.get("/users/")
+async def read_users():
+ return [{"username": "Rick"}, {"username": "Morty"}]
diff --git a/docs_src/dependency_testing/tutorial001_an_py39.py b/docs_src/dependency_testing/tutorial001_an_py39.py
deleted file mode 100644
index bccb0cdb1..000000000
--- a/docs_src/dependency_testing/tutorial001_an_py39.py
+++ /dev/null
@@ -1,59 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Depends, FastAPI
-from fastapi.testclient import TestClient
-
-app = FastAPI()
-
-
-async def common_parameters(
- q: Union[str, None] = None, skip: int = 0, limit: int = 100
-):
- return {"q": q, "skip": skip, "limit": limit}
-
-
-@app.get("/items/")
-async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
- return {"message": "Hello Items!", "params": commons}
-
-
-@app.get("/users/")
-async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
- return {"message": "Hello Users!", "params": commons}
-
-
-client = TestClient(app)
-
-
-async def override_dependency(q: Union[str, None] = None):
- return {"q": q, "skip": 5, "limit": 10}
-
-
-app.dependency_overrides[common_parameters] = override_dependency
-
-
-def test_override_in_items():
- response = client.get("/items/")
- assert response.status_code == 200
- assert response.json() == {
- "message": "Hello Items!",
- "params": {"q": None, "skip": 5, "limit": 10},
- }
-
-
-def test_override_in_items_with_q():
- response = client.get("/items/?q=foo")
- assert response.status_code == 200
- assert response.json() == {
- "message": "Hello Items!",
- "params": {"q": "foo", "skip": 5, "limit": 10},
- }
-
-
-def test_override_in_items_with_params():
- response = client.get("/items/?q=foo&skip=100&limit=200")
- assert response.status_code == 200
- assert response.json() == {
- "message": "Hello Items!",
- "params": {"q": "foo", "skip": 5, "limit": 10},
- }
diff --git a/docs_src/dependency_testing/tutorial001_py39.py b/docs_src/dependency_testing/tutorial001_py39.py
deleted file mode 100644
index a5fe1d9bf..000000000
--- a/docs_src/dependency_testing/tutorial001_py39.py
+++ /dev/null
@@ -1,59 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI
-from fastapi.testclient import TestClient
-
-app = FastAPI()
-
-
-async def common_parameters(
- q: Union[str, None] = None, skip: int = 0, limit: int = 100
-):
- return {"q": q, "skip": skip, "limit": limit}
-
-
-@app.get("/items/")
-async def read_items(commons: dict = Depends(common_parameters)):
- return {"message": "Hello Items!", "params": commons}
-
-
-@app.get("/users/")
-async def read_users(commons: dict = Depends(common_parameters)):
- return {"message": "Hello Users!", "params": commons}
-
-
-client = TestClient(app)
-
-
-async def override_dependency(q: Union[str, None] = None):
- return {"q": q, "skip": 5, "limit": 10}
-
-
-app.dependency_overrides[common_parameters] = override_dependency
-
-
-def test_override_in_items():
- response = client.get("/items/")
- assert response.status_code == 200
- assert response.json() == {
- "message": "Hello Items!",
- "params": {"q": None, "skip": 5, "limit": 10},
- }
-
-
-def test_override_in_items_with_q():
- response = client.get("/items/?q=foo")
- assert response.status_code == 200
- assert response.json() == {
- "message": "Hello Items!",
- "params": {"q": "foo", "skip": 5, "limit": 10},
- }
-
-
-def test_override_in_items_with_params():
- response = client.get("/items/?q=foo&skip=100&limit=200")
- assert response.status_code == 200
- assert response.json() == {
- "message": "Hello Items!",
- "params": {"q": "foo", "skip": 5, "limit": 10},
- }
diff --git a/docs_src/encoder/tutorial001_py39.py b/docs_src/encoder/tutorial001_py39.py
deleted file mode 100644
index 5f7e7061e..000000000
--- a/docs_src/encoder/tutorial001_py39.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from datetime import datetime
-from typing import Union
-
-from fastapi import FastAPI
-from fastapi.encoders import jsonable_encoder
-from pydantic import BaseModel
-
-fake_db = {}
-
-
-class Item(BaseModel):
- title: str
- timestamp: datetime
- description: Union[str, None] = None
-
-
-app = FastAPI()
-
-
-@app.put("/items/{id}")
-def update_item(id: str, item: Item):
- json_compatible_item_data = jsonable_encoder(item)
- fake_db[id] = json_compatible_item_data
diff --git a/docs_src/events/tutorial001_py310.py b/docs_src/events/tutorial001_py310.py
new file mode 100644
index 000000000..128004c9f
--- /dev/null
+++ b/docs_src/events/tutorial001_py310.py
@@ -0,0 +1,16 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+items = {}
+
+
+@app.on_event("startup")
+async def startup_event():
+ items["foo"] = {"name": "Fighters"}
+ items["bar"] = {"name": "Tenders"}
+
+
+@app.get("/items/{item_id}")
+async def read_items(item_id: str):
+ return items[item_id]
diff --git a/docs_src/events/tutorial002_py310.py b/docs_src/events/tutorial002_py310.py
new file mode 100644
index 000000000..a71fea802
--- /dev/null
+++ b/docs_src/events/tutorial002_py310.py
@@ -0,0 +1,14 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.on_event("shutdown")
+def shutdown_event():
+ with open("log.txt", mode="a") as log:
+ log.write("Application shutdown")
+
+
+@app.get("/items/")
+async def read_items():
+ return [{"name": "Foo"}]
diff --git a/docs_src/events/tutorial003_py310.py b/docs_src/events/tutorial003_py310.py
new file mode 100644
index 000000000..2b650590b
--- /dev/null
+++ b/docs_src/events/tutorial003_py310.py
@@ -0,0 +1,28 @@
+from contextlib import asynccontextmanager
+
+from fastapi import FastAPI
+
+
+def fake_answer_to_everything_ml_model(x: float):
+ return x * 42
+
+
+ml_models = {}
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ # Load the ML model
+ ml_models["answer_to_everything"] = fake_answer_to_everything_ml_model
+ yield
+ # Clean up the ML models and release the resources
+ ml_models.clear()
+
+
+app = FastAPI(lifespan=lifespan)
+
+
+@app.get("/predict")
+async def predict(x: float):
+ result = ml_models["answer_to_everything"](x)
+ return {"result": result}
diff --git a/docs_src/extending_openapi/tutorial001_py310.py b/docs_src/extending_openapi/tutorial001_py310.py
new file mode 100644
index 000000000..35e31c0e0
--- /dev/null
+++ b/docs_src/extending_openapi/tutorial001_py310.py
@@ -0,0 +1,29 @@
+from fastapi import FastAPI
+from fastapi.openapi.utils import get_openapi
+
+app = FastAPI()
+
+
+@app.get("/items/")
+async def read_items():
+ return [{"name": "Foo"}]
+
+
+def custom_openapi():
+ if app.openapi_schema:
+ return app.openapi_schema
+ openapi_schema = get_openapi(
+ title="Custom title",
+ version="2.5.0",
+ summary="This is a very custom OpenAPI schema",
+ description="Here's a longer description of the custom **OpenAPI** schema",
+ routes=app.routes,
+ )
+ openapi_schema["info"]["x-logo"] = {
+ "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png"
+ }
+ app.openapi_schema = openapi_schema
+ return app.openapi_schema
+
+
+app.openapi = custom_openapi
diff --git a/docs_src/extra_data_types/tutorial001_an_py39.py b/docs_src/extra_data_types/tutorial001_an_py39.py
deleted file mode 100644
index fa3551d66..000000000
--- a/docs_src/extra_data_types/tutorial001_an_py39.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from datetime import datetime, time, timedelta
-from typing import Annotated, Union
-from uuid import UUID
-
-from fastapi import Body, FastAPI
-
-app = FastAPI()
-
-
-@app.put("/items/{item_id}")
-async def read_items(
- item_id: UUID,
- start_datetime: Annotated[datetime, Body()],
- end_datetime: Annotated[datetime, Body()],
- process_after: Annotated[timedelta, Body()],
- repeat_at: Annotated[Union[time, None], Body()] = None,
-):
- start_process = start_datetime + process_after
- duration = end_datetime - start_process
- return {
- "item_id": item_id,
- "start_datetime": start_datetime,
- "end_datetime": end_datetime,
- "process_after": process_after,
- "repeat_at": repeat_at,
- "start_process": start_process,
- "duration": duration,
- }
diff --git a/docs_src/extra_data_types/tutorial001_py39.py b/docs_src/extra_data_types/tutorial001_py39.py
deleted file mode 100644
index 71de958ff..000000000
--- a/docs_src/extra_data_types/tutorial001_py39.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from datetime import datetime, time, timedelta
-from typing import Union
-from uuid import UUID
-
-from fastapi import Body, FastAPI
-
-app = FastAPI()
-
-
-@app.put("/items/{item_id}")
-async def read_items(
- item_id: UUID,
- start_datetime: datetime = Body(),
- end_datetime: datetime = Body(),
- process_after: timedelta = Body(),
- repeat_at: Union[time, None] = Body(default=None),
-):
- start_process = start_datetime + process_after
- duration = end_datetime - start_process
- return {
- "item_id": item_id,
- "start_datetime": start_datetime,
- "end_datetime": end_datetime,
- "process_after": process_after,
- "repeat_at": repeat_at,
- "start_process": start_process,
- "duration": duration,
- }
diff --git a/docs_src/extra_models/tutorial001_py39.py b/docs_src/extra_models/tutorial001_py39.py
deleted file mode 100644
index 327ffcdf0..000000000
--- a/docs_src/extra_models/tutorial001_py39.py
+++ /dev/null
@@ -1,43 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel, EmailStr
-
-app = FastAPI()
-
-
-class UserIn(BaseModel):
- username: str
- password: str
- email: EmailStr
- full_name: Union[str, None] = None
-
-
-class UserOut(BaseModel):
- username: str
- email: EmailStr
- full_name: Union[str, None] = None
-
-
-class UserInDB(BaseModel):
- username: str
- hashed_password: str
- email: EmailStr
- full_name: Union[str, None] = None
-
-
-def fake_password_hasher(raw_password: str):
- return "supersecret" + raw_password
-
-
-def fake_save_user(user_in: UserIn):
- hashed_password = fake_password_hasher(user_in.password)
- user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
- print("User saved! ..not really")
- return user_in_db
-
-
-@app.post("/user/", response_model=UserOut)
-async def create_user(user_in: UserIn):
- user_saved = fake_save_user(user_in)
- return user_saved
diff --git a/docs_src/extra_models/tutorial002_py39.py b/docs_src/extra_models/tutorial002_py39.py
deleted file mode 100644
index 654379601..000000000
--- a/docs_src/extra_models/tutorial002_py39.py
+++ /dev/null
@@ -1,41 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel, EmailStr
-
-app = FastAPI()
-
-
-class UserBase(BaseModel):
- username: str
- email: EmailStr
- full_name: Union[str, None] = None
-
-
-class UserIn(UserBase):
- password: str
-
-
-class UserOut(UserBase):
- pass
-
-
-class UserInDB(UserBase):
- hashed_password: str
-
-
-def fake_password_hasher(raw_password: str):
- return "supersecret" + raw_password
-
-
-def fake_save_user(user_in: UserIn):
- hashed_password = fake_password_hasher(user_in.password)
- user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
- print("User saved! ..not really")
- return user_in_db
-
-
-@app.post("/user/", response_model=UserOut)
-async def create_user(user_in: UserIn):
- user_saved = fake_save_user(user_in)
- return user_saved
diff --git a/docs_src/extra_models/tutorial003_py39.py b/docs_src/extra_models/tutorial003_py39.py
deleted file mode 100644
index 06675cbc0..000000000
--- a/docs_src/extra_models/tutorial003_py39.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class BaseItem(BaseModel):
- description: str
- type: str
-
-
-class CarItem(BaseItem):
- type: str = "car"
-
-
-class PlaneItem(BaseItem):
- type: str = "plane"
- size: int
-
-
-items = {
- "item1": {"description": "All my friends drive a low rider", "type": "car"},
- "item2": {
- "description": "Music is my aeroplane, it's my aeroplane",
- "type": "plane",
- "size": 5,
- },
-}
-
-
-@app.get("/items/{item_id}", response_model=Union[PlaneItem, CarItem])
-async def read_item(item_id: str):
- return items[item_id]
diff --git a/docs_src/extra_models/tutorial004_py310.py b/docs_src/extra_models/tutorial004_py310.py
new file mode 100644
index 000000000..28cacde4d
--- /dev/null
+++ b/docs_src/extra_models/tutorial004_py310.py
@@ -0,0 +1,20 @@
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ description: str
+
+
+items = [
+ {"name": "Foo", "description": "There comes my hero"},
+ {"name": "Red", "description": "It's my aeroplane"},
+]
+
+
+@app.get("/items/", response_model=list[Item])
+async def read_items():
+ return items
diff --git a/docs_src/extra_models/tutorial005_py310.py b/docs_src/extra_models/tutorial005_py310.py
new file mode 100644
index 000000000..9da2a0a0f
--- /dev/null
+++ b/docs_src/extra_models/tutorial005_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/keyword-weights/", response_model=dict[str, float])
+async def read_keyword_weights():
+ return {"foo": 2.3, "bar": 3.4}
diff --git a/docs_src/first_steps/tutorial001_py310.py b/docs_src/first_steps/tutorial001_py310.py
new file mode 100644
index 000000000..ee60be1f9
--- /dev/null
+++ b/docs_src/first_steps/tutorial001_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+async def root():
+ return {"message": "Hello World"}
diff --git a/docs_src/first_steps/tutorial003_py310.py b/docs_src/first_steps/tutorial003_py310.py
new file mode 100644
index 000000000..e30b827ea
--- /dev/null
+++ b/docs_src/first_steps/tutorial003_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+def root():
+ return {"message": "Hello World"}
diff --git a/docs_src/generate_clients/tutorial001_py310.py b/docs_src/generate_clients/tutorial001_py310.py
new file mode 100644
index 000000000..6a5ae2320
--- /dev/null
+++ b/docs_src/generate_clients/tutorial001_py310.py
@@ -0,0 +1,26 @@
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+
+
+class ResponseMessage(BaseModel):
+ message: str
+
+
+@app.post("/items/", response_model=ResponseMessage)
+async def create_item(item: Item):
+ return {"message": "item received"}
+
+
+@app.get("/items/", response_model=list[Item])
+async def get_items():
+ return [
+ {"name": "Plumbus", "price": 3},
+ {"name": "Portal Gun", "price": 9001},
+ ]
diff --git a/docs_src/generate_clients/tutorial002_py310.py b/docs_src/generate_clients/tutorial002_py310.py
new file mode 100644
index 000000000..83309760b
--- /dev/null
+++ b/docs_src/generate_clients/tutorial002_py310.py
@@ -0,0 +1,36 @@
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+
+
+class ResponseMessage(BaseModel):
+ message: str
+
+
+class User(BaseModel):
+ username: str
+ email: str
+
+
+@app.post("/items/", response_model=ResponseMessage, tags=["items"])
+async def create_item(item: Item):
+ return {"message": "Item received"}
+
+
+@app.get("/items/", response_model=list[Item], tags=["items"])
+async def get_items():
+ return [
+ {"name": "Plumbus", "price": 3},
+ {"name": "Portal Gun", "price": 9001},
+ ]
+
+
+@app.post("/users/", response_model=ResponseMessage, tags=["users"])
+async def create_user(user: User):
+ return {"message": "User received"}
diff --git a/docs_src/generate_clients/tutorial003_py310.py b/docs_src/generate_clients/tutorial003_py310.py
new file mode 100644
index 000000000..40722cf10
--- /dev/null
+++ b/docs_src/generate_clients/tutorial003_py310.py
@@ -0,0 +1,42 @@
+from fastapi import FastAPI
+from fastapi.routing import APIRoute
+from pydantic import BaseModel
+
+
+def custom_generate_unique_id(route: APIRoute):
+ return f"{route.tags[0]}-{route.name}"
+
+
+app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+
+
+class ResponseMessage(BaseModel):
+ message: str
+
+
+class User(BaseModel):
+ username: str
+ email: str
+
+
+@app.post("/items/", response_model=ResponseMessage, tags=["items"])
+async def create_item(item: Item):
+ return {"message": "Item received"}
+
+
+@app.get("/items/", response_model=list[Item], tags=["items"])
+async def get_items():
+ return [
+ {"name": "Plumbus", "price": 3},
+ {"name": "Portal Gun", "price": 9001},
+ ]
+
+
+@app.post("/users/", response_model=ResponseMessage, tags=["users"])
+async def create_user(user: User):
+ return {"message": "User received"}
diff --git a/docs_src/generate_clients/tutorial004_py310.py b/docs_src/generate_clients/tutorial004_py310.py
new file mode 100644
index 000000000..894dc7f8d
--- /dev/null
+++ b/docs_src/generate_clients/tutorial004_py310.py
@@ -0,0 +1,15 @@
+import json
+from pathlib import Path
+
+file_path = Path("./openapi.json")
+openapi_content = json.loads(file_path.read_text())
+
+for path_data in openapi_content["paths"].values():
+ for operation in path_data.values():
+ tag = operation["tags"][0]
+ operation_id = operation["operationId"]
+ to_remove = f"{tag}-"
+ new_operation_id = operation_id[len(to_remove) :]
+ operation["operationId"] = new_operation_id
+
+file_path.write_text(json.dumps(openapi_content))
diff --git a/docs_src/graphql_/tutorial001_py310.py b/docs_src/graphql_/tutorial001_py310.py
new file mode 100644
index 000000000..e92b2d71c
--- /dev/null
+++ b/docs_src/graphql_/tutorial001_py310.py
@@ -0,0 +1,25 @@
+import strawberry
+from fastapi import FastAPI
+from strawberry.fastapi import GraphQLRouter
+
+
+@strawberry.type
+class User:
+ name: str
+ age: int
+
+
+@strawberry.type
+class Query:
+ @strawberry.field
+ def user(self) -> User:
+ return User(name="Patrick", age=100)
+
+
+schema = strawberry.Schema(query=Query)
+
+
+graphql_app = GraphQLRouter(schema)
+
+app = FastAPI()
+app.include_router(graphql_app, prefix="/graphql")
diff --git a/docs_src/handling_errors/tutorial001_py310.py b/docs_src/handling_errors/tutorial001_py310.py
new file mode 100644
index 000000000..e5f32aac2
--- /dev/null
+++ b/docs_src/handling_errors/tutorial001_py310.py
@@ -0,0 +1,12 @@
+from fastapi import FastAPI, HTTPException
+
+app = FastAPI()
+
+items = {"foo": "The Foo Wrestlers"}
+
+
+@app.get("/items/{item_id}")
+async def read_item(item_id: str):
+ if item_id not in items:
+ raise HTTPException(status_code=404, detail="Item not found")
+ return {"item": items[item_id]}
diff --git a/docs_src/handling_errors/tutorial002_py310.py b/docs_src/handling_errors/tutorial002_py310.py
new file mode 100644
index 000000000..e48c295c9
--- /dev/null
+++ b/docs_src/handling_errors/tutorial002_py310.py
@@ -0,0 +1,16 @@
+from fastapi import FastAPI, HTTPException
+
+app = FastAPI()
+
+items = {"foo": "The Foo Wrestlers"}
+
+
+@app.get("/items-header/{item_id}")
+async def read_item_header(item_id: str):
+ if item_id not in items:
+ raise HTTPException(
+ status_code=404,
+ detail="Item not found",
+ headers={"X-Error": "There goes my error"},
+ )
+ return {"item": items[item_id]}
diff --git a/docs_src/handling_errors/tutorial003_py310.py b/docs_src/handling_errors/tutorial003_py310.py
new file mode 100644
index 000000000..791cd6838
--- /dev/null
+++ b/docs_src/handling_errors/tutorial003_py310.py
@@ -0,0 +1,25 @@
+from fastapi import FastAPI, Request
+from fastapi.responses import JSONResponse
+
+
+class UnicornException(Exception):
+ def __init__(self, name: str):
+ self.name = name
+
+
+app = FastAPI()
+
+
+@app.exception_handler(UnicornException)
+async def unicorn_exception_handler(request: Request, exc: UnicornException):
+ return JSONResponse(
+ status_code=418,
+ content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
+ )
+
+
+@app.get("/unicorns/{name}")
+async def read_unicorn(name: str):
+ if name == "yolo":
+ raise UnicornException(name=name)
+ return {"unicorn_name": name}
diff --git a/docs_src/handling_errors/tutorial004_py310.py b/docs_src/handling_errors/tutorial004_py310.py
new file mode 100644
index 000000000..ae50807e9
--- /dev/null
+++ b/docs_src/handling_errors/tutorial004_py310.py
@@ -0,0 +1,26 @@
+from fastapi import FastAPI, HTTPException
+from fastapi.exceptions import RequestValidationError
+from fastapi.responses import PlainTextResponse
+from starlette.exceptions import HTTPException as StarletteHTTPException
+
+app = FastAPI()
+
+
+@app.exception_handler(StarletteHTTPException)
+async def http_exception_handler(request, exc):
+ return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
+
+
+@app.exception_handler(RequestValidationError)
+async def validation_exception_handler(request, exc: RequestValidationError):
+ message = "Validation errors:"
+ for error in exc.errors():
+ message += f"\nField: {error['loc']}, Error: {error['msg']}"
+ return PlainTextResponse(message, status_code=400)
+
+
+@app.get("/items/{item_id}")
+async def read_item(item_id: int):
+ if item_id == 3:
+ raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
+ return {"item_id": item_id}
diff --git a/docs_src/handling_errors/tutorial005_py310.py b/docs_src/handling_errors/tutorial005_py310.py
new file mode 100644
index 000000000..0e04fa086
--- /dev/null
+++ b/docs_src/handling_errors/tutorial005_py310.py
@@ -0,0 +1,25 @@
+from fastapi import FastAPI, Request
+from fastapi.encoders import jsonable_encoder
+from fastapi.exceptions import RequestValidationError
+from fastapi.responses import JSONResponse
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+@app.exception_handler(RequestValidationError)
+async def validation_exception_handler(request: Request, exc: RequestValidationError):
+ return JSONResponse(
+ status_code=422,
+ content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
+ )
+
+
+class Item(BaseModel):
+ title: str
+ size: int
+
+
+@app.post("/items/")
+async def create_item(item: Item):
+ return item
diff --git a/docs_src/handling_errors/tutorial006_py310.py b/docs_src/handling_errors/tutorial006_py310.py
new file mode 100644
index 000000000..e05160d7e
--- /dev/null
+++ b/docs_src/handling_errors/tutorial006_py310.py
@@ -0,0 +1,28 @@
+from fastapi import FastAPI, HTTPException
+from fastapi.exception_handlers import (
+ http_exception_handler,
+ request_validation_exception_handler,
+)
+from fastapi.exceptions import RequestValidationError
+from starlette.exceptions import HTTPException as StarletteHTTPException
+
+app = FastAPI()
+
+
+@app.exception_handler(StarletteHTTPException)
+async def custom_http_exception_handler(request, exc):
+ print(f"OMG! An HTTP error!: {repr(exc)}")
+ return await http_exception_handler(request, exc)
+
+
+@app.exception_handler(RequestValidationError)
+async def validation_exception_handler(request, exc):
+ print(f"OMG! The client sent invalid data!: {exc}")
+ return await request_validation_exception_handler(request, exc)
+
+
+@app.get("/items/{item_id}")
+async def read_item(item_id: int):
+ if item_id == 3:
+ raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
+ return {"item_id": item_id}
diff --git a/docs_src/header_param_models/tutorial001_an_py39.py b/docs_src/header_param_models/tutorial001_an_py39.py
deleted file mode 100644
index 51a5f94fc..000000000
--- a/docs_src/header_param_models/tutorial001_an_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: Annotated[CommonHeaders, Header()]):
- return headers
diff --git a/docs_src/header_param_models/tutorial001_py39.py b/docs_src/header_param_models/tutorial001_py39.py
deleted file mode 100644
index 4c1137813..000000000
--- a/docs_src/header_param_models/tutorial001_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: CommonHeaders = Header()):
- return headers
diff --git a/docs_src/header_param_models/tutorial002_an_py39.py b/docs_src/header_param_models/tutorial002_an_py39.py
deleted file mode 100644
index ca5208c9d..000000000
--- a/docs_src/header_param_models/tutorial002_an_py39.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- model_config = {"extra": "forbid"}
-
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: Annotated[CommonHeaders, Header()]):
- return headers
diff --git a/docs_src/header_param_models/tutorial002_py39.py b/docs_src/header_param_models/tutorial002_py39.py
deleted file mode 100644
index f8ce559a7..000000000
--- a/docs_src/header_param_models/tutorial002_py39.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- model_config = {"extra": "forbid"}
-
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: CommonHeaders = Header()):
- return headers
diff --git a/docs_src/header_param_models/tutorial003_an_py39.py b/docs_src/header_param_models/tutorial003_an_py39.py
deleted file mode 100644
index 8be6b01d0..000000000
--- a/docs_src/header_param_models/tutorial003_an_py39.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(
- headers: Annotated[CommonHeaders, Header(convert_underscores=False)],
-):
- return headers
diff --git a/docs_src/header_param_models/tutorial003_py39.py b/docs_src/header_param_models/tutorial003_py39.py
deleted file mode 100644
index 848c34111..000000000
--- a/docs_src/header_param_models/tutorial003_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: CommonHeaders = Header(convert_underscores=False)):
- return headers
diff --git a/docs_src/header_params/tutorial001_an_py39.py b/docs_src/header_params/tutorial001_an_py39.py
deleted file mode 100644
index 1fbe3bb99..000000000
--- a/docs_src/header_params/tutorial001_an_py39.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Header
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(user_agent: Annotated[Union[str, None], Header()] = None):
- return {"User-Agent": user_agent}
diff --git a/docs_src/header_params/tutorial001_py39.py b/docs_src/header_params/tutorial001_py39.py
deleted file mode 100644
index 74429c8e2..000000000
--- a/docs_src/header_params/tutorial001_py39.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Header
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(user_agent: Union[str, None] = Header(default=None)):
- return {"User-Agent": user_agent}
diff --git a/docs_src/header_params/tutorial002_an_py39.py b/docs_src/header_params/tutorial002_an_py39.py
deleted file mode 100644
index 008e4b6e1..000000000
--- a/docs_src/header_params/tutorial002_an_py39.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Header
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- strange_header: Annotated[
- Union[str, None], Header(convert_underscores=False)
- ] = None,
-):
- return {"strange_header": strange_header}
diff --git a/docs_src/header_params/tutorial002_py39.py b/docs_src/header_params/tutorial002_py39.py
deleted file mode 100644
index 0a34f17cc..000000000
--- a/docs_src/header_params/tutorial002_py39.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Header
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- strange_header: Union[str, None] = Header(default=None, convert_underscores=False),
-):
- return {"strange_header": strange_header}
diff --git a/docs_src/header_params/tutorial003_an_py39.py b/docs_src/header_params/tutorial003_an_py39.py
deleted file mode 100644
index 5aad89407..000000000
--- a/docs_src/header_params/tutorial003_an_py39.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Header
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(x_token: Annotated[Union[list[str], None], Header()] = None):
- return {"X-Token values": x_token}
diff --git a/docs_src/header_params/tutorial003_py39.py b/docs_src/header_params/tutorial003_py39.py
deleted file mode 100644
index 34437db16..000000000
--- a/docs_src/header_params/tutorial003_py39.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Header
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(x_token: Union[list[str], None] = Header(default=None)):
- return {"X-Token values": x_token}
diff --git a/docs_src/metadata/tutorial001_1_py310.py b/docs_src/metadata/tutorial001_1_py310.py
new file mode 100644
index 000000000..419232d86
--- /dev/null
+++ b/docs_src/metadata/tutorial001_1_py310.py
@@ -0,0 +1,38 @@
+from fastapi import FastAPI
+
+description = """
+ChimichangApp API helps you do awesome stuff. 🚀
+
+## Items
+
+You can **read items**.
+
+## Users
+
+You will be able to:
+
+* **Create users** (_not implemented_).
+* **Read users** (_not implemented_).
+"""
+
+app = FastAPI(
+ title="ChimichangApp",
+ description=description,
+ summary="Deadpool's favorite app. Nuff said.",
+ version="0.0.1",
+ terms_of_service="http://example.com/terms/",
+ contact={
+ "name": "Deadpoolio the Amazing",
+ "url": "http://x-force.example.com/contact/",
+ "email": "dp@x-force.example.com",
+ },
+ license_info={
+ "name": "Apache 2.0",
+ "identifier": "Apache-2.0",
+ },
+)
+
+
+@app.get("/items/")
+async def read_items():
+ return [{"name": "Katana"}]
diff --git a/docs_src/metadata/tutorial001_py310.py b/docs_src/metadata/tutorial001_py310.py
new file mode 100644
index 000000000..76656e81b
--- /dev/null
+++ b/docs_src/metadata/tutorial001_py310.py
@@ -0,0 +1,38 @@
+from fastapi import FastAPI
+
+description = """
+ChimichangApp API helps you do awesome stuff. 🚀
+
+## Items
+
+You can **read items**.
+
+## Users
+
+You will be able to:
+
+* **Create users** (_not implemented_).
+* **Read users** (_not implemented_).
+"""
+
+app = FastAPI(
+ title="ChimichangApp",
+ description=description,
+ summary="Deadpool's favorite app. Nuff said.",
+ version="0.0.1",
+ terms_of_service="http://example.com/terms/",
+ contact={
+ "name": "Deadpoolio the Amazing",
+ "url": "http://x-force.example.com/contact/",
+ "email": "dp@x-force.example.com",
+ },
+ license_info={
+ "name": "Apache 2.0",
+ "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
+ },
+)
+
+
+@app.get("/items/")
+async def read_items():
+ return [{"name": "Katana"}]
diff --git a/docs_src/metadata/tutorial002_py310.py b/docs_src/metadata/tutorial002_py310.py
new file mode 100644
index 000000000..cf9ed7087
--- /dev/null
+++ b/docs_src/metadata/tutorial002_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI(openapi_url="/api/v1/openapi.json")
+
+
+@app.get("/items/")
+async def read_items():
+ return [{"name": "Foo"}]
diff --git a/docs_src/metadata/tutorial003_py310.py b/docs_src/metadata/tutorial003_py310.py
new file mode 100644
index 000000000..ee09c7f37
--- /dev/null
+++ b/docs_src/metadata/tutorial003_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI(docs_url="/documentation", redoc_url=None)
+
+
+@app.get("/items/")
+async def read_items():
+ return [{"name": "Foo"}]
diff --git a/docs_src/metadata/tutorial004_py310.py b/docs_src/metadata/tutorial004_py310.py
new file mode 100644
index 000000000..465bd659d
--- /dev/null
+++ b/docs_src/metadata/tutorial004_py310.py
@@ -0,0 +1,28 @@
+from fastapi import FastAPI
+
+tags_metadata = [
+ {
+ "name": "users",
+ "description": "Operations with users. The **login** logic is also here.",
+ },
+ {
+ "name": "items",
+ "description": "Manage items. So _fancy_ they have their own docs.",
+ "externalDocs": {
+ "description": "Items external docs",
+ "url": "https://fastapi.tiangolo.com/",
+ },
+ },
+]
+
+app = FastAPI(openapi_tags=tags_metadata)
+
+
+@app.get("/users/", tags=["users"])
+async def get_users():
+ return [{"name": "Harry"}, {"name": "Ron"}]
+
+
+@app.get("/items/", tags=["items"])
+async def get_items():
+ return [{"name": "wand"}, {"name": "flying broom"}]
diff --git a/docs_src/middleware/tutorial001_py310.py b/docs_src/middleware/tutorial001_py310.py
new file mode 100644
index 000000000..e65a7dade
--- /dev/null
+++ b/docs_src/middleware/tutorial001_py310.py
@@ -0,0 +1,14 @@
+import time
+
+from fastapi import FastAPI, Request
+
+app = FastAPI()
+
+
+@app.middleware("http")
+async def add_process_time_header(request: Request, call_next):
+ start_time = time.perf_counter()
+ response = await call_next(request)
+ process_time = time.perf_counter() - start_time
+ response.headers["X-Process-Time"] = str(process_time)
+ return response
diff --git a/docs_src/openapi_callbacks/tutorial001_py39.py b/docs_src/openapi_callbacks/tutorial001_py39.py
deleted file mode 100644
index 3f1bac6e2..000000000
--- a/docs_src/openapi_callbacks/tutorial001_py39.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from typing import Union
-
-from fastapi import APIRouter, FastAPI
-from pydantic import BaseModel, HttpUrl
-
-app = FastAPI()
-
-
-class Invoice(BaseModel):
- id: str
- title: Union[str, None] = None
- customer: str
- total: float
-
-
-class InvoiceEvent(BaseModel):
- description: str
- paid: bool
-
-
-class InvoiceEventReceived(BaseModel):
- ok: bool
-
-
-invoices_callback_router = APIRouter()
-
-
-@invoices_callback_router.post(
- "{$callback_url}/invoices/{$request.body.id}", response_model=InvoiceEventReceived
-)
-def invoice_notification(body: InvoiceEvent):
- pass
-
-
-@app.post("/invoices/", callbacks=invoices_callback_router.routes)
-def create_invoice(invoice: Invoice, callback_url: Union[HttpUrl, None] = None):
- """
- Create an invoice.
-
- This will (let's imagine) let the API user (some external developer) create an
- invoice.
-
- And this path operation will:
-
- * Send the invoice to the client.
- * Collect the money from the client.
- * Send a notification back to the API user (the external developer), as a callback.
- * At this point is that the API will somehow send a POST request to the
- external API with the notification of the invoice event
- (e.g. "payment successful").
- """
- # Send the invoice, collect the money, send the notification (the callback)
- return {"msg": "Invoice received"}
diff --git a/docs_src/openapi_webhooks/tutorial001_py310.py b/docs_src/openapi_webhooks/tutorial001_py310.py
new file mode 100644
index 000000000..55822bb48
--- /dev/null
+++ b/docs_src/openapi_webhooks/tutorial001_py310.py
@@ -0,0 +1,25 @@
+from datetime import datetime
+
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Subscription(BaseModel):
+ username: str
+ monthly_fee: float
+ start_date: datetime
+
+
+@app.webhooks.post("new-subscription")
+def new_subscription(body: Subscription):
+ """
+ When a new user subscribes to your service we'll send you a POST request with this
+ data to the URL that you register for the event `new-subscription` in the dashboard.
+ """
+
+
+@app.get("/users/")
+def read_users():
+ return ["Rick", "Morty"]
diff --git a/docs_src/path_operation_advanced_configuration/tutorial001_py310.py b/docs_src/path_operation_advanced_configuration/tutorial001_py310.py
new file mode 100644
index 000000000..fafa8ffb8
--- /dev/null
+++ b/docs_src/path_operation_advanced_configuration/tutorial001_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/items/", operation_id="some_specific_id_you_define")
+async def read_items():
+ return [{"item_id": "Foo"}]
diff --git a/docs_src/path_operation_advanced_configuration/tutorial002_py310.py b/docs_src/path_operation_advanced_configuration/tutorial002_py310.py
new file mode 100644
index 000000000..3aaae9b37
--- /dev/null
+++ b/docs_src/path_operation_advanced_configuration/tutorial002_py310.py
@@ -0,0 +1,24 @@
+from fastapi import FastAPI
+from fastapi.routing import APIRoute
+
+app = FastAPI()
+
+
+@app.get("/items/")
+async def read_items():
+ return [{"item_id": "Foo"}]
+
+
+def use_route_names_as_operation_ids(app: FastAPI) -> None:
+ """
+ Simplify operation IDs so that generated API clients have simpler function
+ names.
+
+ Should be called only after all routes have been added.
+ """
+ for route in app.routes:
+ if isinstance(route, APIRoute):
+ route.operation_id = route.name # in this case, 'read_items'
+
+
+use_route_names_as_operation_ids(app)
diff --git a/docs_src/path_operation_advanced_configuration/tutorial003_py310.py b/docs_src/path_operation_advanced_configuration/tutorial003_py310.py
new file mode 100644
index 000000000..dcc358e32
--- /dev/null
+++ b/docs_src/path_operation_advanced_configuration/tutorial003_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/items/", include_in_schema=False)
+async def read_items():
+ return [{"item_id": "Foo"}]
diff --git a/docs_src/path_operation_advanced_configuration/tutorial004_py39.py b/docs_src/path_operation_advanced_configuration/tutorial004_py39.py
deleted file mode 100644
index 8fabe7cb8..000000000
--- a/docs_src/path_operation_advanced_configuration/tutorial004_py39.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: set[str] = set()
-
-
-@app.post("/items/", summary="Create an item")
-async def create_item(item: Item) -> Item:
- """
- Create an item with all the information:
-
- - **name**: each item must have a name
- - **description**: a long description
- - **price**: required
- - **tax**: if the item doesn't have tax, you can omit this
- - **tags**: a set of unique tag strings for this item
- \f
- :param item: User input.
- """
- return item
diff --git a/docs_src/path_operation_advanced_configuration/tutorial005_py310.py b/docs_src/path_operation_advanced_configuration/tutorial005_py310.py
new file mode 100644
index 000000000..5837ad835
--- /dev/null
+++ b/docs_src/path_operation_advanced_configuration/tutorial005_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/items/", openapi_extra={"x-aperture-labs-portal": "blue"})
+async def read_items():
+ return [{"item_id": "portal-gun"}]
diff --git a/docs_src/path_operation_advanced_configuration/tutorial006_py310.py b/docs_src/path_operation_advanced_configuration/tutorial006_py310.py
new file mode 100644
index 000000000..403c3ee3f
--- /dev/null
+++ b/docs_src/path_operation_advanced_configuration/tutorial006_py310.py
@@ -0,0 +1,41 @@
+from fastapi import FastAPI, Request
+
+app = FastAPI()
+
+
+def magic_data_reader(raw_body: bytes):
+ return {
+ "size": len(raw_body),
+ "content": {
+ "name": "Maaaagic",
+ "price": 42,
+ "description": "Just kiddin', no magic here. ✨",
+ },
+ }
+
+
+@app.post(
+ "/items/",
+ openapi_extra={
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "price": {"type": "number"},
+ "description": {"type": "string"},
+ },
+ }
+ }
+ },
+ "required": True,
+ },
+ },
+)
+async def create_item(request: Request):
+ raw_body = await request.body()
+ data = magic_data_reader(raw_body)
+ return data
diff --git a/docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py b/docs_src/path_operation_advanced_configuration/tutorial007_py310.py
similarity index 68%
rename from docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py
rename to docs_src/path_operation_advanced_configuration/tutorial007_py310.py
index 849f648e1..ff64ef792 100644
--- a/docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py
+++ b/docs_src/path_operation_advanced_configuration/tutorial007_py310.py
@@ -1,6 +1,6 @@
import yaml
from fastapi import FastAPI, HTTPException, Request
-from pydantic.v1 import BaseModel, ValidationError
+from pydantic import BaseModel, ValidationError
app = FastAPI()
@@ -14,7 +14,7 @@ class Item(BaseModel):
"/items/",
openapi_extra={
"requestBody": {
- "content": {"application/x-yaml": {"schema": Item.schema()}},
+ "content": {"application/x-yaml": {"schema": Item.model_json_schema()}},
"required": True,
},
},
@@ -26,7 +26,7 @@ async def create_item(request: Request):
except yaml.YAMLError:
raise HTTPException(status_code=422, detail="Invalid YAML")
try:
- item = Item.parse_obj(data)
+ item = Item.model_validate(data)
except ValidationError as e:
- raise HTTPException(status_code=422, detail=e.errors())
+ raise HTTPException(status_code=422, detail=e.errors(include_url=False))
return item
diff --git a/docs_src/path_operation_configuration/tutorial001_py39.py b/docs_src/path_operation_configuration/tutorial001_py39.py
deleted file mode 100644
index 09b318282..000000000
--- a/docs_src/path_operation_configuration/tutorial001_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, status
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: set[str] = set()
-
-
-@app.post("/items/", status_code=status.HTTP_201_CREATED)
-async def create_item(item: Item) -> Item:
- return item
diff --git a/docs_src/path_operation_configuration/tutorial002_py39.py b/docs_src/path_operation_configuration/tutorial002_py39.py
deleted file mode 100644
index fca3b0de9..000000000
--- a/docs_src/path_operation_configuration/tutorial002_py39.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: set[str] = set()
-
-
-@app.post("/items/", tags=["items"])
-async def create_item(item: Item) -> Item:
- return item
-
-
-@app.get("/items/", tags=["items"])
-async def read_items():
- return [{"name": "Foo", "price": 42}]
-
-
-@app.get("/users/", tags=["users"])
-async def read_users():
- return [{"username": "johndoe"}]
diff --git a/docs_src/path_operation_configuration/tutorial002b_py310.py b/docs_src/path_operation_configuration/tutorial002b_py310.py
new file mode 100644
index 000000000..d53b4d817
--- /dev/null
+++ b/docs_src/path_operation_configuration/tutorial002b_py310.py
@@ -0,0 +1,20 @@
+from enum import Enum
+
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+class Tags(Enum):
+ items = "items"
+ users = "users"
+
+
+@app.get("/items/", tags=[Tags.items])
+async def get_items():
+ return ["Portal gun", "Plumbus"]
+
+
+@app.get("/users/", tags=[Tags.users])
+async def read_users():
+ return ["Rick", "Morty"]
diff --git a/docs_src/path_operation_configuration/tutorial003_py39.py b/docs_src/path_operation_configuration/tutorial003_py39.py
deleted file mode 100644
index a77fb34d8..000000000
--- a/docs_src/path_operation_configuration/tutorial003_py39.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: set[str] = set()
-
-
-@app.post(
- "/items/",
- summary="Create an item",
- description="Create an item with all the information, name, description, price, tax and a set of unique tags",
-)
-async def create_item(item: Item) -> Item:
- return item
diff --git a/docs_src/path_operation_configuration/tutorial004_py39.py b/docs_src/path_operation_configuration/tutorial004_py39.py
deleted file mode 100644
index 31dfbff1d..000000000
--- a/docs_src/path_operation_configuration/tutorial004_py39.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: set[str] = set()
-
-
-@app.post("/items/", summary="Create an item")
-async def create_item(item: Item) -> Item:
- """
- Create an item with all the information:
-
- - **name**: each item must have a name
- - **description**: a long description
- - **price**: required
- - **tax**: if the item doesn't have tax, you can omit this
- - **tags**: a set of unique tag strings for this item
- """
- return item
diff --git a/docs_src/path_operation_configuration/tutorial005_py39.py b/docs_src/path_operation_configuration/tutorial005_py39.py
deleted file mode 100644
index 0a53a8f2d..000000000
--- a/docs_src/path_operation_configuration/tutorial005_py39.py
+++ /dev/null
@@ -1,32 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: set[str] = set()
-
-
-@app.post(
- "/items/",
- summary="Create an item",
- response_description="The created item",
-)
-async def create_item(item: Item) -> Item:
- """
- Create an item with all the information:
-
- - **name**: each item must have a name
- - **description**: a long description
- - **price**: required
- - **tax**: if the item doesn't have tax, you can omit this
- - **tags**: a set of unique tag strings for this item
- """
- return item
diff --git a/docs_src/path_operation_configuration/tutorial006_py310.py b/docs_src/path_operation_configuration/tutorial006_py310.py
new file mode 100644
index 000000000..7c1aa9b20
--- /dev/null
+++ b/docs_src/path_operation_configuration/tutorial006_py310.py
@@ -0,0 +1,18 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/items/", tags=["items"])
+async def read_items():
+ return [{"name": "Foo", "price": 42}]
+
+
+@app.get("/users/", tags=["users"])
+async def read_users():
+ return [{"username": "johndoe"}]
+
+
+@app.get("/elements/", tags=["items"], deprecated=True)
+async def read_elements():
+ return [{"item_id": "Foo"}]
diff --git a/docs_src/path_params/tutorial001_py310.py b/docs_src/path_params/tutorial001_py310.py
new file mode 100644
index 000000000..7bbf70e6c
--- /dev/null
+++ b/docs_src/path_params/tutorial001_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+async def read_item(item_id):
+ return {"item_id": item_id}
diff --git a/docs_src/path_params/tutorial002_py310.py b/docs_src/path_params/tutorial002_py310.py
new file mode 100644
index 000000000..8272ad70d
--- /dev/null
+++ b/docs_src/path_params/tutorial002_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+async def read_item(item_id: int):
+ return {"item_id": item_id}
diff --git a/docs_src/path_params/tutorial003_py310.py b/docs_src/path_params/tutorial003_py310.py
new file mode 100644
index 000000000..5f0aa0923
--- /dev/null
+++ b/docs_src/path_params/tutorial003_py310.py
@@ -0,0 +1,13 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/users/me")
+async def read_user_me():
+ return {"user_id": "the current user"}
+
+
+@app.get("/users/{user_id}")
+async def read_user(user_id: str):
+ return {"user_id": user_id}
diff --git a/docs_src/path_params/tutorial003b_py310.py b/docs_src/path_params/tutorial003b_py310.py
new file mode 100644
index 000000000..822d37369
--- /dev/null
+++ b/docs_src/path_params/tutorial003b_py310.py
@@ -0,0 +1,13 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/users")
+async def read_users():
+ return ["Rick", "Morty"]
+
+
+@app.get("/users")
+async def read_users2():
+ return ["Bean", "Elfo"]
diff --git a/docs_src/path_params/tutorial004_py310.py b/docs_src/path_params/tutorial004_py310.py
new file mode 100644
index 000000000..2961e6178
--- /dev/null
+++ b/docs_src/path_params/tutorial004_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/files/{file_path:path}")
+async def read_file(file_path: str):
+ return {"file_path": file_path}
diff --git a/docs_src/path_params/tutorial005_py310.py b/docs_src/path_params/tutorial005_py310.py
new file mode 100644
index 000000000..9a24a4963
--- /dev/null
+++ b/docs_src/path_params/tutorial005_py310.py
@@ -0,0 +1,23 @@
+from enum import Enum
+
+from fastapi import FastAPI
+
+
+class ModelName(str, Enum):
+ alexnet = "alexnet"
+ resnet = "resnet"
+ lenet = "lenet"
+
+
+app = FastAPI()
+
+
+@app.get("/models/{model_name}")
+async def get_model(model_name: ModelName):
+ if model_name is ModelName.alexnet:
+ return {"model_name": model_name, "message": "Deep Learning FTW!"}
+
+ if model_name.value == "lenet":
+ return {"model_name": model_name, "message": "LeCNN all the images"}
+
+ return {"model_name": model_name, "message": "Have some residuals"}
diff --git a/docs_src/path_params_numeric_validations/tutorial002_an_py310.py b/docs_src/path_params_numeric_validations/tutorial002_an_py310.py
new file mode 100644
index 000000000..cd882abb2
--- /dev/null
+++ b/docs_src/path_params_numeric_validations/tutorial002_an_py310.py
@@ -0,0 +1,15 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Path
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+async def read_items(
+ q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
+):
+ results = {"item_id": item_id}
+ if q:
+ results.update({"q": q})
+ return results
diff --git a/docs_src/path_params_numeric_validations/tutorial002_py310.py b/docs_src/path_params_numeric_validations/tutorial002_py310.py
new file mode 100644
index 000000000..63ac691a8
--- /dev/null
+++ b/docs_src/path_params_numeric_validations/tutorial002_py310.py
@@ -0,0 +1,11 @@
+from fastapi import FastAPI, Path
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+async def read_items(q: str, item_id: int = Path(title="The ID of the item to get")):
+ results = {"item_id": item_id}
+ if q:
+ results.update({"q": q})
+ return results
diff --git a/docs_src/path_params_numeric_validations/tutorial003_an_py310.py b/docs_src/path_params_numeric_validations/tutorial003_an_py310.py
new file mode 100644
index 000000000..1588556e7
--- /dev/null
+++ b/docs_src/path_params_numeric_validations/tutorial003_an_py310.py
@@ -0,0 +1,15 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Path
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+async def read_items(
+ item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
+):
+ results = {"item_id": item_id}
+ if q:
+ results.update({"q": q})
+ return results
diff --git a/docs_src/path_params_numeric_validations/tutorial003_py310.py b/docs_src/path_params_numeric_validations/tutorial003_py310.py
new file mode 100644
index 000000000..8df0ffc62
--- /dev/null
+++ b/docs_src/path_params_numeric_validations/tutorial003_py310.py
@@ -0,0 +1,11 @@
+from fastapi import FastAPI, Path
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str):
+ results = {"item_id": item_id}
+ if q:
+ results.update({"q": q})
+ return results
diff --git a/docs_src/path_params_numeric_validations/tutorial004_an_py310.py b/docs_src/path_params_numeric_validations/tutorial004_an_py310.py
new file mode 100644
index 000000000..f67f6450e
--- /dev/null
+++ b/docs_src/path_params_numeric_validations/tutorial004_an_py310.py
@@ -0,0 +1,15 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Path
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+async def read_items(
+ item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str
+):
+ results = {"item_id": item_id}
+ if q:
+ results.update({"q": q})
+ return results
diff --git a/docs_src/path_params_numeric_validations/tutorial004_py310.py b/docs_src/path_params_numeric_validations/tutorial004_py310.py
new file mode 100644
index 000000000..86651d47c
--- /dev/null
+++ b/docs_src/path_params_numeric_validations/tutorial004_py310.py
@@ -0,0 +1,13 @@
+from fastapi import FastAPI, Path
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+async def read_items(
+ *, item_id: int = Path(title="The ID of the item to get", ge=1), q: str
+):
+ results = {"item_id": item_id}
+ if q:
+ results.update({"q": q})
+ return results
diff --git a/docs_src/path_params_numeric_validations/tutorial005_an_py310.py b/docs_src/path_params_numeric_validations/tutorial005_an_py310.py
new file mode 100644
index 000000000..571dd583c
--- /dev/null
+++ b/docs_src/path_params_numeric_validations/tutorial005_an_py310.py
@@ -0,0 +1,16 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Path
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+async def read_items(
+ item_id: Annotated[int, Path(title="The ID of the item to get", gt=0, le=1000)],
+ q: str,
+):
+ results = {"item_id": item_id}
+ if q:
+ results.update({"q": q})
+ return results
diff --git a/docs_src/path_params_numeric_validations/tutorial005_py310.py b/docs_src/path_params_numeric_validations/tutorial005_py310.py
new file mode 100644
index 000000000..8f12f2da0
--- /dev/null
+++ b/docs_src/path_params_numeric_validations/tutorial005_py310.py
@@ -0,0 +1,15 @@
+from fastapi import FastAPI, Path
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+async def read_items(
+ *,
+ item_id: int = Path(title="The ID of the item to get", gt=0, le=1000),
+ q: str,
+):
+ results = {"item_id": item_id}
+ if q:
+ results.update({"q": q})
+ return results
diff --git a/docs_src/path_params_numeric_validations/tutorial001_an_py39.py b/docs_src/path_params_numeric_validations/tutorial006_an_py310.py
similarity index 61%
rename from docs_src/path_params_numeric_validations/tutorial001_an_py39.py
rename to docs_src/path_params_numeric_validations/tutorial006_an_py310.py
index b36315a46..426ec3776 100644
--- a/docs_src/path_params_numeric_validations/tutorial001_an_py39.py
+++ b/docs_src/path_params_numeric_validations/tutorial006_an_py310.py
@@ -1,4 +1,4 @@
-from typing import Annotated, Union
+from typing import Annotated
from fastapi import FastAPI, Path, Query
@@ -7,10 +7,14 @@ app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
- item_id: Annotated[int, Path(title="The ID of the item to get")],
- q: Annotated[Union[str, None], Query(alias="item-query")] = None,
+ *,
+ item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
+ q: str,
+ size: Annotated[float, Query(gt=0, lt=10.5)],
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
+ if size:
+ results.update({"size": size})
return results
diff --git a/docs_src/path_params_numeric_validations/tutorial001_py39.py b/docs_src/path_params_numeric_validations/tutorial006_py310.py
similarity index 53%
rename from docs_src/path_params_numeric_validations/tutorial001_py39.py
rename to docs_src/path_params_numeric_validations/tutorial006_py310.py
index 530147028..f07629aa0 100644
--- a/docs_src/path_params_numeric_validations/tutorial001_py39.py
+++ b/docs_src/path_params_numeric_validations/tutorial006_py310.py
@@ -1,5 +1,3 @@
-from typing import Union
-
from fastapi import FastAPI, Path, Query
app = FastAPI()
@@ -7,10 +5,14 @@ app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
- item_id: int = Path(title="The ID of the item to get"),
- q: Union[str, None] = Query(default=None, alias="item-query"),
+ *,
+ item_id: int = Path(title="The ID of the item to get", ge=0, le=1000),
+ q: str,
+ size: float = Query(gt=0, lt=10.5),
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
+ if size:
+ results.update({"size": size})
return results
diff --git a/docs_src/pydantic_v1_in_v2/tutorial001_an_py39.py b/docs_src/pydantic_v1_in_v2/tutorial001_an_py39.py
deleted file mode 100644
index 62a4b2c21..000000000
--- a/docs_src/pydantic_v1_in_v2/tutorial001_an_py39.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from typing import Union
-
-from pydantic.v1 import BaseModel
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- size: float
diff --git a/docs_src/pydantic_v1_in_v2/tutorial002_an_py39.py b/docs_src/pydantic_v1_in_v2/tutorial002_an_py39.py
deleted file mode 100644
index 3c6a06080..000000000
--- a/docs_src/pydantic_v1_in_v2/tutorial002_an_py39.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic.v1 import BaseModel
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- size: float
-
-
-app = FastAPI()
-
-
-@app.post("/items/")
-async def create_item(item: Item) -> Item:
- return item
diff --git a/docs_src/pydantic_v1_in_v2/tutorial003_an_py39.py b/docs_src/pydantic_v1_in_v2/tutorial003_an_py39.py
deleted file mode 100644
index 117d6f7a4..000000000
--- a/docs_src/pydantic_v1_in_v2/tutorial003_an_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel as BaseModelV2
-from pydantic.v1 import BaseModel
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- size: float
-
-
-class ItemV2(BaseModelV2):
- name: str
- description: Union[str, None] = None
- size: float
-
-
-app = FastAPI()
-
-
-@app.post("/items/", response_model=ItemV2)
-async def create_item(item: Item):
- return item
diff --git a/docs_src/pydantic_v1_in_v2/tutorial004_an_py39.py b/docs_src/pydantic_v1_in_v2/tutorial004_an_py39.py
deleted file mode 100644
index 150ab20ae..000000000
--- a/docs_src/pydantic_v1_in_v2/tutorial004_an_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI
-from fastapi.temp_pydantic_v1_params import Body
-from pydantic.v1 import BaseModel
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- size: float
-
-
-app = FastAPI()
-
-
-@app.post("/items/")
-async def create_item(item: Annotated[Item, Body(embed=True)]) -> Item:
- return item
diff --git a/docs_src/python_types/tutorial001_py310.py b/docs_src/python_types/tutorial001_py310.py
new file mode 100644
index 000000000..09039435f
--- /dev/null
+++ b/docs_src/python_types/tutorial001_py310.py
@@ -0,0 +1,6 @@
+def get_full_name(first_name, last_name):
+ full_name = first_name.title() + " " + last_name.title()
+ return full_name
+
+
+print(get_full_name("john", "doe"))
diff --git a/docs_src/python_types/tutorial002_py310.py b/docs_src/python_types/tutorial002_py310.py
new file mode 100644
index 000000000..c0857a116
--- /dev/null
+++ b/docs_src/python_types/tutorial002_py310.py
@@ -0,0 +1,6 @@
+def get_full_name(first_name: str, last_name: str):
+ full_name = first_name.title() + " " + last_name.title()
+ return full_name
+
+
+print(get_full_name("john", "doe"))
diff --git a/docs_src/python_types/tutorial003_py310.py b/docs_src/python_types/tutorial003_py310.py
new file mode 100644
index 000000000..d021d8211
--- /dev/null
+++ b/docs_src/python_types/tutorial003_py310.py
@@ -0,0 +1,3 @@
+def get_name_with_age(name: str, age: int):
+ name_with_age = name + " is this old: " + age
+ return name_with_age
diff --git a/docs_src/python_types/tutorial004_py310.py b/docs_src/python_types/tutorial004_py310.py
new file mode 100644
index 000000000..9400269e2
--- /dev/null
+++ b/docs_src/python_types/tutorial004_py310.py
@@ -0,0 +1,3 @@
+def get_name_with_age(name: str, age: int):
+ name_with_age = name + " is this old: " + str(age)
+ return name_with_age
diff --git a/docs_src/python_types/tutorial005_py310.py b/docs_src/python_types/tutorial005_py310.py
new file mode 100644
index 000000000..6c8edb0ec
--- /dev/null
+++ b/docs_src/python_types/tutorial005_py310.py
@@ -0,0 +1,2 @@
+def get_items(item_a: str, item_b: int, item_c: float, item_d: bool, item_e: bytes):
+ return item_a, item_b, item_c, item_d, item_e
diff --git a/docs_src/python_types/tutorial006_py310.py b/docs_src/python_types/tutorial006_py310.py
new file mode 100644
index 000000000..486b67caf
--- /dev/null
+++ b/docs_src/python_types/tutorial006_py310.py
@@ -0,0 +1,3 @@
+def process_items(items: list[str]):
+ for item in items:
+ print(item)
diff --git a/docs_src/python_types/tutorial007_py310.py b/docs_src/python_types/tutorial007_py310.py
new file mode 100644
index 000000000..ea96c7964
--- /dev/null
+++ b/docs_src/python_types/tutorial007_py310.py
@@ -0,0 +1,2 @@
+def process_items(items_t: tuple[int, int, str], items_s: set[bytes]):
+ return items_t, items_s
diff --git a/docs_src/python_types/tutorial008_py310.py b/docs_src/python_types/tutorial008_py310.py
new file mode 100644
index 000000000..a393385b0
--- /dev/null
+++ b/docs_src/python_types/tutorial008_py310.py
@@ -0,0 +1,4 @@
+def process_items(prices: dict[str, float]):
+ for item_name, item_price in prices.items():
+ print(item_name)
+ print(item_price)
diff --git a/docs_src/python_types/tutorial010_py310.py b/docs_src/python_types/tutorial010_py310.py
new file mode 100644
index 000000000..468cffc2d
--- /dev/null
+++ b/docs_src/python_types/tutorial010_py310.py
@@ -0,0 +1,7 @@
+class Person:
+ def __init__(self, name: str):
+ self.name = name
+
+
+def get_person_name(one_person: Person):
+ return one_person.name
diff --git a/docs_src/python_types/tutorial011_py39.py b/docs_src/python_types/tutorial011_py39.py
deleted file mode 100644
index 4eb40b405..000000000
--- a/docs_src/python_types/tutorial011_py39.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from datetime import datetime
-from typing import Union
-
-from pydantic import BaseModel
-
-
-class User(BaseModel):
- id: int
- name: str = "John Doe"
- signup_ts: Union[datetime, None] = None
- friends: list[int] = []
-
-
-external_data = {
- "id": "123",
- "signup_ts": "2017-06-01 12:22",
- "friends": [1, "2", b"3"],
-}
-user = User(**external_data)
-print(user)
-# > User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3]
-print(user.id)
-# > 123
diff --git a/docs_src/python_types/tutorial012_py39.py b/docs_src/python_types/tutorial012_py39.py
deleted file mode 100644
index 74fa94c43..000000000
--- a/docs_src/python_types/tutorial012_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from typing import Optional
-
-from pydantic import BaseModel
-
-
-class User(BaseModel):
- name: str
- age: Optional[int]
diff --git a/docs_src/python_types/tutorial013_py310.py b/docs_src/python_types/tutorial013_py310.py
new file mode 100644
index 000000000..65a0eaa93
--- /dev/null
+++ b/docs_src/python_types/tutorial013_py310.py
@@ -0,0 +1,5 @@
+from typing import Annotated
+
+
+def say_hello(name: Annotated[str, "this is just metadata"]) -> str:
+ return f"Hello {name}"
diff --git a/docs_src/query_param_models/tutorial001_an_py39.py b/docs_src/query_param_models/tutorial001_an_py39.py
deleted file mode 100644
index 71427acae..000000000
--- a/docs_src/query_param_models/tutorial001_an_py39.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from typing import Annotated, Literal
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: Annotated[FilterParams, Query()]):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial001_py39.py b/docs_src/query_param_models/tutorial001_py39.py
deleted file mode 100644
index 3ebf9f4d7..000000000
--- a/docs_src/query_param_models/tutorial001_py39.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from typing import Literal
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: FilterParams = Query()):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial002_an_py39.py b/docs_src/query_param_models/tutorial002_an_py39.py
deleted file mode 100644
index 975956502..000000000
--- a/docs_src/query_param_models/tutorial002_an_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Annotated, Literal
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- model_config = {"extra": "forbid"}
-
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: Annotated[FilterParams, Query()]):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial002_py39.py b/docs_src/query_param_models/tutorial002_py39.py
deleted file mode 100644
index 6ec418499..000000000
--- a/docs_src/query_param_models/tutorial002_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Literal
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- model_config = {"extra": "forbid"}
-
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: FilterParams = Query()):
- return filter_query
diff --git a/docs_src/query_params/tutorial001_py310.py b/docs_src/query_params/tutorial001_py310.py
new file mode 100644
index 000000000..74e1a1760
--- /dev/null
+++ b/docs_src/query_params/tutorial001_py310.py
@@ -0,0 +1,10 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
+
+
+@app.get("/items/")
+async def read_item(skip: int = 0, limit: int = 10):
+ return fake_items_db[skip : skip + limit]
diff --git a/docs_src/query_params/tutorial002_py39.py b/docs_src/query_params/tutorial002_py39.py
deleted file mode 100644
index 8465f45ee..000000000
--- a/docs_src/query_params/tutorial002_py39.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_item(item_id: str, q: Union[str, None] = None):
- if q:
- return {"item_id": item_id, "q": q}
- return {"item_id": item_id}
diff --git a/docs_src/query_params/tutorial003_py39.py b/docs_src/query_params/tutorial003_py39.py
deleted file mode 100644
index 3362715b3..000000000
--- a/docs_src/query_params/tutorial003_py39.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_item(item_id: str, q: Union[str, None] = None, short: bool = False):
- item = {"item_id": item_id}
- if q:
- item.update({"q": q})
- if not short:
- item.update(
- {"description": "This is an amazing item that has a long description"}
- )
- return item
diff --git a/docs_src/query_params/tutorial004_py39.py b/docs_src/query_params/tutorial004_py39.py
deleted file mode 100644
index 049c3ae93..000000000
--- a/docs_src/query_params/tutorial004_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/users/{user_id}/items/{item_id}")
-async def read_user_item(
- user_id: int, item_id: str, q: Union[str, None] = None, short: bool = False
-):
- item = {"item_id": item_id, "owner_id": user_id}
- if q:
- item.update({"q": q})
- if not short:
- item.update(
- {"description": "This is an amazing item that has a long description"}
- )
- return item
diff --git a/docs_src/query_params/tutorial005_py310.py b/docs_src/query_params/tutorial005_py310.py
new file mode 100644
index 000000000..e16a40574
--- /dev/null
+++ b/docs_src/query_params/tutorial005_py310.py
@@ -0,0 +1,9 @@
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/items/{item_id}")
+async def read_user_item(item_id: str, needy: str):
+ item = {"item_id": item_id, "needy": needy}
+ return item
diff --git a/docs_src/query_params/tutorial006_py39.py b/docs_src/query_params/tutorial006_py39.py
deleted file mode 100644
index f0dbfe08f..000000000
--- a/docs_src/query_params/tutorial006_py39.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_user_item(
- item_id: str, needy: str, skip: int = 0, limit: Union[int, None] = None
-):
- item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
- return item
diff --git a/docs_src/query_params_str_validations/tutorial001_py39.py b/docs_src/query_params_str_validations/tutorial001_py39.py
deleted file mode 100644
index e38326b18..000000000
--- a/docs_src/query_params_str_validations/tutorial001_py39.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Union[str, None] = None):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial002_an_py39.py b/docs_src/query_params_str_validations/tutorial002_an_py39.py
deleted file mode 100644
index 2d8fc9798..000000000
--- a/docs_src/query_params_str_validations/tutorial002_an_py39.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[Union[str, None], Query(max_length=50)] = None):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial003_an_py39.py b/docs_src/query_params_str_validations/tutorial003_an_py39.py
deleted file mode 100644
index 3d6697793..000000000
--- a/docs_src/query_params_str_validations/tutorial003_an_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None,
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial003_py39.py b/docs_src/query_params_str_validations/tutorial003_py39.py
deleted file mode 100644
index 7d4917373..000000000
--- a/docs_src/query_params_str_validations/tutorial003_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Union[str, None] = Query(default=None, min_length=3, max_length=50),
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial004_an_py39.py b/docs_src/query_params_str_validations/tutorial004_an_py39.py
deleted file mode 100644
index de27097b3..000000000
--- a/docs_src/query_params_str_validations/tutorial004_an_py39.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Annotated[
- Union[str, None], Query(min_length=3, max_length=50, pattern="^fixedquery$")
- ] = None,
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial004_py39.py b/docs_src/query_params_str_validations/tutorial004_py39.py
deleted file mode 100644
index 64a647a16..000000000
--- a/docs_src/query_params_str_validations/tutorial004_py39.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Union[str, None] = Query(
- default=None, min_length=3, max_length=50, pattern="^fixedquery$"
- ),
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial004_regex_an_py310.py b/docs_src/query_params_str_validations/tutorial004_regex_an_py310.py
deleted file mode 100644
index 21e0d3eb8..000000000
--- a/docs_src/query_params_str_validations/tutorial004_regex_an_py310.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Annotated[
- str | None, Query(min_length=3, max_length=50, regex="^fixedquery$")
- ] = None,
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial002_py39.py b/docs_src/query_params_str_validations/tutorial005_an_py310.py
similarity index 65%
rename from docs_src/query_params_str_validations/tutorial002_py39.py
rename to docs_src/query_params_str_validations/tutorial005_an_py310.py
index 17e017b7e..b1f6046b5 100644
--- a/docs_src/query_params_str_validations/tutorial002_py39.py
+++ b/docs_src/query_params_str_validations/tutorial005_an_py310.py
@@ -1,4 +1,4 @@
-from typing import Union
+from typing import Annotated
from fastapi import FastAPI, Query
@@ -6,7 +6,7 @@ app = FastAPI()
@app.get("/items/")
-async def read_items(q: Union[str, None] = Query(default=None, max_length=50)):
+async def read_items(q: Annotated[str, Query(min_length=3)] = "fixedquery"):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
diff --git a/docs_src/query_params_str_validations/tutorial009_py39.py b/docs_src/query_params_str_validations/tutorial005_py310.py
similarity index 64%
rename from docs_src/query_params_str_validations/tutorial009_py39.py
rename to docs_src/query_params_str_validations/tutorial005_py310.py
index 8a6bfe2d9..8ab42869e 100644
--- a/docs_src/query_params_str_validations/tutorial009_py39.py
+++ b/docs_src/query_params_str_validations/tutorial005_py310.py
@@ -1,12 +1,10 @@
-from typing import Union
-
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
-async def read_items(q: Union[str, None] = Query(default=None, alias="item-query")):
+async def read_items(q: str = Query(default="fixedquery", min_length=3)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
diff --git a/docs_src/query_params_str_validations/tutorial006c_py39.py b/docs_src/query_params_str_validations/tutorial006_an_py310.py
similarity index 69%
rename from docs_src/query_params_str_validations/tutorial006c_py39.py
rename to docs_src/query_params_str_validations/tutorial006_an_py310.py
index 0a0e820da..3b4a676d2 100644
--- a/docs_src/query_params_str_validations/tutorial006c_py39.py
+++ b/docs_src/query_params_str_validations/tutorial006_an_py310.py
@@ -1,4 +1,4 @@
-from typing import Union
+from typing import Annotated
from fastapi import FastAPI, Query
@@ -6,7 +6,7 @@ app = FastAPI()
@app.get("/items/")
-async def read_items(q: Union[str, None] = Query(min_length=3)):
+async def read_items(q: Annotated[str, Query(min_length=3)]):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
diff --git a/docs_src/query_params_str_validations/tutorial006c_an_py39.py b/docs_src/query_params_str_validations/tutorial006_py310.py
similarity index 64%
rename from docs_src/query_params_str_validations/tutorial006c_an_py39.py
rename to docs_src/query_params_str_validations/tutorial006_py310.py
index 76a1cd49a..9a90eb64e 100644
--- a/docs_src/query_params_str_validations/tutorial006c_an_py39.py
+++ b/docs_src/query_params_str_validations/tutorial006_py310.py
@@ -1,12 +1,10 @@
-from typing import Annotated, Union
-
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
-async def read_items(q: Annotated[Union[str, None], Query(min_length=3)]):
+async def read_items(q: str = Query(min_length=3)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
diff --git a/docs_src/query_params_str_validations/tutorial007_an_py39.py b/docs_src/query_params_str_validations/tutorial007_an_py39.py
deleted file mode 100644
index 8d7a82c46..000000000
--- a/docs_src/query_params_str_validations/tutorial007_an_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None,
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial007_py39.py b/docs_src/query_params_str_validations/tutorial007_py39.py
deleted file mode 100644
index 27b649e14..000000000
--- a/docs_src/query_params_str_validations/tutorial007_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Union[str, None] = Query(default=None, title="Query string", min_length=3),
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial008_an_py39.py b/docs_src/query_params_str_validations/tutorial008_an_py39.py
deleted file mode 100644
index f3f2f2c0e..000000000
--- a/docs_src/query_params_str_validations/tutorial008_an_py39.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Annotated[
- Union[str, None],
- Query(
- title="Query string",
- description="Query string for the items to search in the database that have a good match",
- min_length=3,
- ),
- ] = None,
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial008_py39.py b/docs_src/query_params_str_validations/tutorial008_py39.py
deleted file mode 100644
index e3e0b50aa..000000000
--- a/docs_src/query_params_str_validations/tutorial008_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Union[str, None] = Query(
- default=None,
- title="Query string",
- description="Query string for the items to search in the database that have a good match",
- min_length=3,
- ),
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial009_an_py39.py b/docs_src/query_params_str_validations/tutorial009_an_py39.py
deleted file mode 100644
index 70a89e613..000000000
--- a/docs_src/query_params_str_validations/tutorial009_an_py39.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[Union[str, None], Query(alias="item-query")] = None):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial010_an_py39.py b/docs_src/query_params_str_validations/tutorial010_an_py39.py
deleted file mode 100644
index b126c116f..000000000
--- a/docs_src/query_params_str_validations/tutorial010_an_py39.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Annotated[
- Union[str, None],
- Query(
- alias="item-query",
- title="Query string",
- description="Query string for the items to search in the database that have a good match",
- min_length=3,
- max_length=50,
- pattern="^fixedquery$",
- deprecated=True,
- ),
- ] = None,
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial010_py39.py b/docs_src/query_params_str_validations/tutorial010_py39.py
deleted file mode 100644
index ff29176fe..000000000
--- a/docs_src/query_params_str_validations/tutorial010_py39.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Union[str, None] = Query(
- default=None,
- alias="item-query",
- title="Query string",
- description="Query string for the items to search in the database that have a good match",
- min_length=3,
- max_length=50,
- pattern="^fixedquery$",
- deprecated=True,
- ),
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial011_an_py39.py b/docs_src/query_params_str_validations/tutorial012_an_py310.py
similarity index 52%
rename from docs_src/query_params_str_validations/tutorial011_an_py39.py
rename to docs_src/query_params_str_validations/tutorial012_an_py310.py
index 416e3990d..9b5a9c2fb 100644
--- a/docs_src/query_params_str_validations/tutorial011_an_py39.py
+++ b/docs_src/query_params_str_validations/tutorial012_an_py310.py
@@ -1,4 +1,4 @@
-from typing import Annotated, Union
+from typing import Annotated
from fastapi import FastAPI, Query
@@ -6,6 +6,6 @@ app = FastAPI()
@app.get("/items/")
-async def read_items(q: Annotated[Union[list[str], None], Query()] = None):
+async def read_items(q: Annotated[list[str], Query()] = ["foo", "bar"]):
query_items = {"q": q}
return query_items
diff --git a/docs_src/query_params_str_validations/tutorial012_py310.py b/docs_src/query_params_str_validations/tutorial012_py310.py
new file mode 100644
index 000000000..070d0b04b
--- /dev/null
+++ b/docs_src/query_params_str_validations/tutorial012_py310.py
@@ -0,0 +1,9 @@
+from fastapi import FastAPI, Query
+
+app = FastAPI()
+
+
+@app.get("/items/")
+async def read_items(q: list[str] = Query(default=["foo", "bar"])):
+ query_items = {"q": q}
+ return query_items
diff --git a/docs_src/query_params_str_validations/tutorial011_py39.py b/docs_src/query_params_str_validations/tutorial013_an_py310.py
similarity index 56%
rename from docs_src/query_params_str_validations/tutorial011_py39.py
rename to docs_src/query_params_str_validations/tutorial013_an_py310.py
index 878f95c79..602734145 100644
--- a/docs_src/query_params_str_validations/tutorial011_py39.py
+++ b/docs_src/query_params_str_validations/tutorial013_an_py310.py
@@ -1,4 +1,4 @@
-from typing import Union
+from typing import Annotated
from fastapi import FastAPI, Query
@@ -6,6 +6,6 @@ app = FastAPI()
@app.get("/items/")
-async def read_items(q: Union[list[str], None] = Query(default=None)):
+async def read_items(q: Annotated[list, Query()] = []):
query_items = {"q": q}
return query_items
diff --git a/docs_src/query_params_str_validations/tutorial013_py310.py b/docs_src/query_params_str_validations/tutorial013_py310.py
new file mode 100644
index 000000000..0b0f44869
--- /dev/null
+++ b/docs_src/query_params_str_validations/tutorial013_py310.py
@@ -0,0 +1,9 @@
+from fastapi import FastAPI, Query
+
+app = FastAPI()
+
+
+@app.get("/items/")
+async def read_items(q: list = Query(default=[])):
+ query_items = {"q": q}
+ return query_items
diff --git a/docs_src/query_params_str_validations/tutorial014_an_py39.py b/docs_src/query_params_str_validations/tutorial014_an_py39.py
deleted file mode 100644
index aaf7703a5..000000000
--- a/docs_src/query_params_str_validations/tutorial014_an_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None,
-):
- if hidden_query:
- return {"hidden_query": hidden_query}
- else:
- return {"hidden_query": "Not found"}
diff --git a/docs_src/query_params_str_validations/tutorial014_py39.py b/docs_src/query_params_str_validations/tutorial014_py39.py
deleted file mode 100644
index 779db1c80..000000000
--- a/docs_src/query_params_str_validations/tutorial014_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- hidden_query: Union[str, None] = Query(default=None, include_in_schema=False),
-):
- if hidden_query:
- return {"hidden_query": hidden_query}
- else:
- return {"hidden_query": "Not found"}
diff --git a/docs_src/query_params_str_validations/tutorial015_an_py39.py b/docs_src/query_params_str_validations/tutorial015_an_py39.py
deleted file mode 100644
index 989b6d2c2..000000000
--- a/docs_src/query_params_str_validations/tutorial015_an_py39.py
+++ /dev/null
@@ -1,30 +0,0 @@
-import random
-from typing import Annotated, Union
-
-from fastapi import FastAPI
-from pydantic import AfterValidator
-
-app = FastAPI()
-
-data = {
- "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy",
- "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy",
- "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2",
-}
-
-
-def check_valid_id(id: str):
- if not id.startswith(("isbn-", "imdb-")):
- raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"')
- return id
-
-
-@app.get("/items/")
-async def read_items(
- id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None,
-):
- if id:
- item = data.get(id)
- else:
- id, item = random.choice(list(data.items()))
- return {"id": id, "name": item}
diff --git a/docs_src/request_files/tutorial001_02_an_py39.py b/docs_src/request_files/tutorial001_02_an_py39.py
deleted file mode 100644
index bb090ff6c..000000000
--- a/docs_src/request_files/tutorial001_02_an_py39.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, File, UploadFile
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(file: Annotated[Union[bytes, None], File()] = None):
- if not file:
- return {"message": "No file sent"}
- else:
- return {"file_size": len(file)}
-
-
-@app.post("/uploadfile/")
-async def create_upload_file(file: Union[UploadFile, None] = None):
- if not file:
- return {"message": "No upload file sent"}
- else:
- return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial001_02_py39.py b/docs_src/request_files/tutorial001_02_py39.py
deleted file mode 100644
index ac30be2d3..000000000
--- a/docs_src/request_files/tutorial001_02_py39.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, File, UploadFile
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(file: Union[bytes, None] = File(default=None)):
- if not file:
- return {"message": "No file sent"}
- else:
- return {"file_size": len(file)}
-
-
-@app.post("/uploadfile/")
-async def create_upload_file(file: Union[UploadFile, None] = None):
- if not file:
- return {"message": "No upload file sent"}
- else:
- return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial001_03_an_py310.py b/docs_src/request_files/tutorial001_03_an_py310.py
new file mode 100644
index 000000000..93098a677
--- /dev/null
+++ b/docs_src/request_files/tutorial001_03_an_py310.py
@@ -0,0 +1,17 @@
+from typing import Annotated
+
+from fastapi import FastAPI, File, UploadFile
+
+app = FastAPI()
+
+
+@app.post("/files/")
+async def create_file(file: Annotated[bytes, File(description="A file read as bytes")]):
+ return {"file_size": len(file)}
+
+
+@app.post("/uploadfile/")
+async def create_upload_file(
+ file: Annotated[UploadFile, File(description="A file read as UploadFile")],
+):
+ return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial001_03_py310.py b/docs_src/request_files/tutorial001_03_py310.py
new file mode 100644
index 000000000..d8005cc7d
--- /dev/null
+++ b/docs_src/request_files/tutorial001_03_py310.py
@@ -0,0 +1,15 @@
+from fastapi import FastAPI, File, UploadFile
+
+app = FastAPI()
+
+
+@app.post("/files/")
+async def create_file(file: bytes = File(description="A file read as bytes")):
+ return {"file_size": len(file)}
+
+
+@app.post("/uploadfile/")
+async def create_upload_file(
+ file: UploadFile = File(description="A file read as UploadFile"),
+):
+ return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial001_an_py310.py b/docs_src/request_files/tutorial001_an_py310.py
new file mode 100644
index 000000000..26a767221
--- /dev/null
+++ b/docs_src/request_files/tutorial001_an_py310.py
@@ -0,0 +1,15 @@
+from typing import Annotated
+
+from fastapi import FastAPI, File, UploadFile
+
+app = FastAPI()
+
+
+@app.post("/files/")
+async def create_file(file: Annotated[bytes, File()]):
+ return {"file_size": len(file)}
+
+
+@app.post("/uploadfile/")
+async def create_upload_file(file: UploadFile):
+ return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial001_py310.py b/docs_src/request_files/tutorial001_py310.py
new file mode 100644
index 000000000..2e0ea6391
--- /dev/null
+++ b/docs_src/request_files/tutorial001_py310.py
@@ -0,0 +1,13 @@
+from fastapi import FastAPI, File, UploadFile
+
+app = FastAPI()
+
+
+@app.post("/files/")
+async def create_file(file: bytes = File()):
+ return {"file_size": len(file)}
+
+
+@app.post("/uploadfile/")
+async def create_upload_file(file: UploadFile):
+ return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial002_an_py310.py b/docs_src/request_files/tutorial002_an_py310.py
new file mode 100644
index 000000000..db524ceab
--- /dev/null
+++ b/docs_src/request_files/tutorial002_an_py310.py
@@ -0,0 +1,33 @@
+from typing import Annotated
+
+from fastapi import FastAPI, File, UploadFile
+from fastapi.responses import HTMLResponse
+
+app = FastAPI()
+
+
+@app.post("/files/")
+async def create_files(files: Annotated[list[bytes], File()]):
+ return {"file_sizes": [len(file) for file in files]}
+
+
+@app.post("/uploadfiles/")
+async def create_upload_files(files: list[UploadFile]):
+ return {"filenames": [file.filename for file in files]}
+
+
+@app.get("/")
+async def main():
+ content = """
+
+
+
+
+ """
+ return HTMLResponse(content=content)
diff --git a/docs_src/request_files/tutorial002_py310.py b/docs_src/request_files/tutorial002_py310.py
new file mode 100644
index 000000000..b64cf5598
--- /dev/null
+++ b/docs_src/request_files/tutorial002_py310.py
@@ -0,0 +1,31 @@
+from fastapi import FastAPI, File, UploadFile
+from fastapi.responses import HTMLResponse
+
+app = FastAPI()
+
+
+@app.post("/files/")
+async def create_files(files: list[bytes] = File()):
+ return {"file_sizes": [len(file) for file in files]}
+
+
+@app.post("/uploadfiles/")
+async def create_upload_files(files: list[UploadFile]):
+ return {"filenames": [file.filename for file in files]}
+
+
+@app.get("/")
+async def main():
+ content = """
+
+
+
+
+ """
+ return HTMLResponse(content=content)
diff --git a/docs_src/request_files/tutorial003_an_py310.py b/docs_src/request_files/tutorial003_an_py310.py
new file mode 100644
index 000000000..5a8c5dab5
--- /dev/null
+++ b/docs_src/request_files/tutorial003_an_py310.py
@@ -0,0 +1,39 @@
+from typing import Annotated
+
+from fastapi import FastAPI, File, UploadFile
+from fastapi.responses import HTMLResponse
+
+app = FastAPI()
+
+
+@app.post("/files/")
+async def create_files(
+ files: Annotated[list[bytes], File(description="Multiple files as bytes")],
+):
+ return {"file_sizes": [len(file) for file in files]}
+
+
+@app.post("/uploadfiles/")
+async def create_upload_files(
+ files: Annotated[
+ list[UploadFile], File(description="Multiple files as UploadFile")
+ ],
+):
+ return {"filenames": [file.filename for file in files]}
+
+
+@app.get("/")
+async def main():
+ content = """
+
+
+
+
+ """
+ return HTMLResponse(content=content)
diff --git a/docs_src/request_files/tutorial003_py310.py b/docs_src/request_files/tutorial003_py310.py
new file mode 100644
index 000000000..96f5e8742
--- /dev/null
+++ b/docs_src/request_files/tutorial003_py310.py
@@ -0,0 +1,35 @@
+from fastapi import FastAPI, File, UploadFile
+from fastapi.responses import HTMLResponse
+
+app = FastAPI()
+
+
+@app.post("/files/")
+async def create_files(
+ files: list[bytes] = File(description="Multiple files as bytes"),
+):
+ return {"file_sizes": [len(file) for file in files]}
+
+
+@app.post("/uploadfiles/")
+async def create_upload_files(
+ files: list[UploadFile] = File(description="Multiple files as UploadFile"),
+):
+ return {"filenames": [file.filename for file in files]}
+
+
+@app.get("/")
+async def main():
+ content = """
+
+
+
+
+ """
+ return HTMLResponse(content=content)
diff --git a/docs_src/request_form_models/tutorial001_an_py310.py b/docs_src/request_form_models/tutorial001_an_py310.py
new file mode 100644
index 000000000..7cc81aae9
--- /dev/null
+++ b/docs_src/request_form_models/tutorial001_an_py310.py
@@ -0,0 +1,16 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
diff --git a/docs_src/request_form_models/tutorial001_py310.py b/docs_src/request_form_models/tutorial001_py310.py
new file mode 100644
index 000000000..98feff0b9
--- /dev/null
+++ b/docs_src/request_form_models/tutorial001_py310.py
@@ -0,0 +1,14 @@
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+
+
+@app.post("/login/")
+async def login(data: FormData = Form()):
+ return data
diff --git a/docs_src/request_form_models/tutorial002_an_py310.py b/docs_src/request_form_models/tutorial002_an_py310.py
new file mode 100644
index 000000000..3004e0852
--- /dev/null
+++ b/docs_src/request_form_models/tutorial002_an_py310.py
@@ -0,0 +1,17 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+ model_config = {"extra": "forbid"}
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
diff --git a/docs_src/request_form_models/tutorial002_py310.py b/docs_src/request_form_models/tutorial002_py310.py
new file mode 100644
index 000000000..59b329e8d
--- /dev/null
+++ b/docs_src/request_form_models/tutorial002_py310.py
@@ -0,0 +1,15 @@
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+ model_config = {"extra": "forbid"}
+
+
+@app.post("/login/")
+async def login(data: FormData = Form()):
+ return data
diff --git a/docs_src/request_forms/tutorial001_an_py310.py b/docs_src/request_forms/tutorial001_an_py310.py
new file mode 100644
index 000000000..8e9d2ea53
--- /dev/null
+++ b/docs_src/request_forms/tutorial001_an_py310.py
@@ -0,0 +1,10 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Form
+
+app = FastAPI()
+
+
+@app.post("/login/")
+async def login(username: Annotated[str, Form()], password: Annotated[str, Form()]):
+ return {"username": username}
diff --git a/docs_src/request_forms/tutorial001_py310.py b/docs_src/request_forms/tutorial001_py310.py
new file mode 100644
index 000000000..a53770001
--- /dev/null
+++ b/docs_src/request_forms/tutorial001_py310.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI, Form
+
+app = FastAPI()
+
+
+@app.post("/login/")
+async def login(username: str = Form(), password: str = Form()):
+ return {"username": username}
diff --git a/docs_src/request_forms_and_files/tutorial001_an_py310.py b/docs_src/request_forms_and_files/tutorial001_an_py310.py
new file mode 100644
index 000000000..12cc43e50
--- /dev/null
+++ b/docs_src/request_forms_and_files/tutorial001_an_py310.py
@@ -0,0 +1,18 @@
+from typing import Annotated
+
+from fastapi import FastAPI, File, Form, UploadFile
+
+app = FastAPI()
+
+
+@app.post("/files/")
+async def create_file(
+ file: Annotated[bytes, File()],
+ fileb: Annotated[UploadFile, File()],
+ token: Annotated[str, Form()],
+):
+ return {
+ "file_size": len(file),
+ "token": token,
+ "fileb_content_type": fileb.content_type,
+ }
diff --git a/docs_src/request_forms_and_files/tutorial001_py310.py b/docs_src/request_forms_and_files/tutorial001_py310.py
new file mode 100644
index 000000000..7b5224ce5
--- /dev/null
+++ b/docs_src/request_forms_and_files/tutorial001_py310.py
@@ -0,0 +1,14 @@
+from fastapi import FastAPI, File, Form, UploadFile
+
+app = FastAPI()
+
+
+@app.post("/files/")
+async def create_file(
+ file: bytes = File(), fileb: UploadFile = File(), token: str = Form()
+):
+ return {
+ "file_size": len(file),
+ "token": token,
+ "fileb_content_type": fileb.content_type,
+ }
diff --git a/docs_src/response_change_status_code/tutorial001_py310.py b/docs_src/response_change_status_code/tutorial001_py310.py
new file mode 100644
index 000000000..197decbfb
--- /dev/null
+++ b/docs_src/response_change_status_code/tutorial001_py310.py
@@ -0,0 +1,13 @@
+from fastapi import FastAPI, Response, status
+
+app = FastAPI()
+
+tasks = {"foo": "Listen to the Bar Fighters"}
+
+
+@app.put("/get-or-create-task/{task_id}", status_code=200)
+def get_or_create_task(task_id: str, response: Response):
+ if task_id not in tasks:
+ tasks[task_id] = "This didn't exist before"
+ response.status_code = status.HTTP_201_CREATED
+ return tasks[task_id]
diff --git a/docs_src/response_cookies/tutorial001_py310.py b/docs_src/response_cookies/tutorial001_py310.py
new file mode 100644
index 000000000..33f8e8f6e
--- /dev/null
+++ b/docs_src/response_cookies/tutorial001_py310.py
@@ -0,0 +1,12 @@
+from fastapi import FastAPI
+from fastapi.responses import JSONResponse
+
+app = FastAPI()
+
+
+@app.post("/cookie/")
+def create_cookie():
+ content = {"message": "Come to the dark side, we have cookies"}
+ response = JSONResponse(content=content)
+ response.set_cookie(key="fakesession", value="fake-cookie-session-value")
+ return response
diff --git a/docs_src/response_cookies/tutorial002_py310.py b/docs_src/response_cookies/tutorial002_py310.py
new file mode 100644
index 000000000..76c06fdb9
--- /dev/null
+++ b/docs_src/response_cookies/tutorial002_py310.py
@@ -0,0 +1,9 @@
+from fastapi import FastAPI, Response
+
+app = FastAPI()
+
+
+@app.post("/cookie-and-object/")
+def create_cookie(response: Response):
+ response.set_cookie(key="fakesession", value="fake-cookie-session-value")
+ return {"message": "Come to the dark side, we have cookies"}
diff --git a/docs_src/response_directly/tutorial001_py39.py b/docs_src/response_directly/tutorial001_py39.py
deleted file mode 100644
index 5ab655a8a..000000000
--- a/docs_src/response_directly/tutorial001_py39.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from datetime import datetime
-from typing import Union
-
-from fastapi import FastAPI
-from fastapi.encoders import jsonable_encoder
-from fastapi.responses import JSONResponse
-from pydantic import BaseModel
-
-
-class Item(BaseModel):
- title: str
- timestamp: datetime
- description: Union[str, None] = None
-
-
-app = FastAPI()
-
-
-@app.put("/items/{id}")
-def update_item(id: str, item: Item):
- json_compatible_item_data = jsonable_encoder(item)
- return JSONResponse(content=json_compatible_item_data)
diff --git a/docs_src/response_directly/tutorial002_py310.py b/docs_src/response_directly/tutorial002_py310.py
new file mode 100644
index 000000000..6643da6e6
--- /dev/null
+++ b/docs_src/response_directly/tutorial002_py310.py
@@ -0,0 +1,18 @@
+from fastapi import FastAPI, Response
+
+app = FastAPI()
+
+
+@app.get("/legacy/")
+def get_legacy_data():
+ data = """
+ WebSocket Chat
+
+
+
+
+
+
+"""
+
+
+@app.get("/")
+async def get():
+ return HTMLResponse(html)
+
+
+@app.websocket("/ws")
+async def websocket_endpoint(websocket: WebSocket):
+ await websocket.accept()
+ while True:
+ data = await websocket.receive_text()
+ await websocket.send_text(f"Message text was: {data}")
diff --git a/docs_src/websockets/tutorial002_an_py39.py b/docs_src/websockets/tutorial002_an_py39.py
deleted file mode 100644
index 606d355fe..000000000
--- a/docs_src/websockets/tutorial002_an_py39.py
+++ /dev/null
@@ -1,92 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import (
- Cookie,
- Depends,
- FastAPI,
- Query,
- WebSocket,
- WebSocketException,
- status,
-)
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-html = """
-
-
-
- WebSocket Chat
-
-
-
-
-
-
-"""
-
-
-@app.get("/")
-async def get():
- return HTMLResponse(html)
-
-
-async def get_cookie_or_token(
- websocket: WebSocket,
- session: Annotated[Union[str, None], Cookie()] = None,
- token: Annotated[Union[str, None], Query()] = None,
-):
- if session is None and token is None:
- raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
- return session or token
-
-
-@app.websocket("/items/{item_id}/ws")
-async def websocket_endpoint(
- *,
- websocket: WebSocket,
- item_id: str,
- q: Union[int, None] = None,
- cookie_or_token: Annotated[str, Depends(get_cookie_or_token)],
-):
- await websocket.accept()
- while True:
- data = await websocket.receive_text()
- await websocket.send_text(
- f"Session cookie or query token value is: {cookie_or_token}"
- )
- if q is not None:
- await websocket.send_text(f"Query parameter q is: {q}")
- await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
diff --git a/docs_src/websockets/tutorial002_py39.py b/docs_src/websockets/tutorial002_py39.py
deleted file mode 100644
index cab749e4d..000000000
--- a/docs_src/websockets/tutorial002_py39.py
+++ /dev/null
@@ -1,91 +0,0 @@
-from typing import Union
-
-from fastapi import (
- Cookie,
- Depends,
- FastAPI,
- Query,
- WebSocket,
- WebSocketException,
- status,
-)
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-html = """
-
-
-
- WebSocket Chat
-
-
-
-
-
-
-"""
-
-
-@app.get("/")
-async def get():
- return HTMLResponse(html)
-
-
-async def get_cookie_or_token(
- websocket: WebSocket,
- session: Union[str, None] = Cookie(default=None),
- token: Union[str, None] = Query(default=None),
-):
- if session is None and token is None:
- raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
- return session or token
-
-
-@app.websocket("/items/{item_id}/ws")
-async def websocket_endpoint(
- websocket: WebSocket,
- item_id: str,
- q: Union[int, None] = None,
- cookie_or_token: str = Depends(get_cookie_or_token),
-):
- await websocket.accept()
- while True:
- data = await websocket.receive_text()
- await websocket.send_text(
- f"Session cookie or query token value is: {cookie_or_token}"
- )
- if q is not None:
- await websocket.send_text(f"Query parameter q is: {q}")
- await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
diff --git a/docs_src/websockets/tutorial003_py310.py b/docs_src/websockets/tutorial003_py310.py
new file mode 100644
index 000000000..316218088
--- /dev/null
+++ b/docs_src/websockets/tutorial003_py310.py
@@ -0,0 +1,81 @@
+from fastapi import FastAPI, WebSocket, WebSocketDisconnect
+from fastapi.responses import HTMLResponse
+
+app = FastAPI()
+
+html = """
+
+
+
+ WebSocket Chat
+ Your ID:
+
+
+
+
+
+
+"""
+
+
+class ConnectionManager:
+ def __init__(self):
+ self.active_connections: list[WebSocket] = []
+
+ async def connect(self, websocket: WebSocket):
+ await websocket.accept()
+ self.active_connections.append(websocket)
+
+ def disconnect(self, websocket: WebSocket):
+ self.active_connections.remove(websocket)
+
+ async def send_personal_message(self, message: str, websocket: WebSocket):
+ await websocket.send_text(message)
+
+ async def broadcast(self, message: str):
+ for connection in self.active_connections:
+ await connection.send_text(message)
+
+
+manager = ConnectionManager()
+
+
+@app.get("/")
+async def get():
+ return HTMLResponse(html)
+
+
+@app.websocket("/ws/{client_id}")
+async def websocket_endpoint(websocket: WebSocket, client_id: int):
+ await manager.connect(websocket)
+ try:
+ while True:
+ data = await websocket.receive_text()
+ await manager.send_personal_message(f"You wrote: {data}", websocket)
+ await manager.broadcast(f"Client #{client_id} says: {data}")
+ except WebSocketDisconnect:
+ manager.disconnect(websocket)
+ await manager.broadcast(f"Client #{client_id} left the chat")
diff --git a/docs_src/wsgi/tutorial001_py310.py b/docs_src/wsgi/tutorial001_py310.py
new file mode 100644
index 000000000..8eeceb829
--- /dev/null
+++ b/docs_src/wsgi/tutorial001_py310.py
@@ -0,0 +1,23 @@
+from a2wsgi import WSGIMiddleware
+from fastapi import FastAPI
+from flask import Flask, request
+from markupsafe import escape
+
+flask_app = Flask(__name__)
+
+
+@flask_app.route("/")
+def flask_main():
+ name = request.args.get("name", "World")
+ return f"Hello, {escape(name)} from Flask!"
+
+
+app = FastAPI()
+
+
+@app.get("/v2")
+def read_main():
+ return {"message": "Hello World"}
+
+
+app.mount("/v1", WSGIMiddleware(flask_app))
diff --git a/pyproject.toml b/pyproject.toml
index e1ce30507..1e6fda3b1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -285,20 +285,205 @@ omit = [
"docs_src/dependencies/tutorial014_an_py310.py", # temporary code example?
# Pydantic v1 migration, no longer tested
"docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py",
- "docs_src/pydantic_v1_in_v2/tutorial001_an_py39.py",
"docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py",
- "docs_src/pydantic_v1_in_v2/tutorial002_an_py39.py",
"docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py",
- "docs_src/pydantic_v1_in_v2/tutorial003_an_py39.py",
"docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py",
- "docs_src/pydantic_v1_in_v2/tutorial004_an_py39.py",
- # TODO: remove when removing this file, after updating translations, Pydantic v1
- "docs_src/schema_extra_example/tutorial001_pv1_py310.py",
- "docs_src/schema_extra_example/tutorial001_pv1_py39.py",
- "docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py",
- "docs_src/settings/app03_py39/config_pv1.py",
- "docs_src/settings/app03_an_py39/config_pv1.py",
- "docs_src/settings/tutorial001_pv1_py39.py",
+ # TODO: remove all the ignores below when all translations use the new Python 3.10 files
+ "docs_src/additional_responses/tutorial001_py39.py",
+ "docs_src/additional_responses/tutorial003_py39.py",
+ "docs_src/advanced_middleware/tutorial001_py39.py",
+ "docs_src/advanced_middleware/tutorial002_py39.py",
+ "docs_src/advanced_middleware/tutorial003_py39.py",
+ "docs_src/app_testing/app_a_py39/main.py",
+ "docs_src/app_testing/app_a_py39/test_main.py",
+ "docs_src/app_testing/tutorial001_py39.py",
+ "docs_src/app_testing/tutorial002_py39.py",
+ "docs_src/app_testing/tutorial003_py39.py",
+ "docs_src/app_testing/tutorial004_py39.py",
+ "docs_src/async_tests/app_a_py39/main.py",
+ "docs_src/async_tests/app_a_py39/test_main.py",
+ "docs_src/authentication_error_status_code/tutorial001_an_py39.py",
+ "docs_src/background_tasks/tutorial001_py39.py",
+ "docs_src/behind_a_proxy/tutorial001_01_py39.py",
+ "docs_src/behind_a_proxy/tutorial001_py39.py",
+ "docs_src/behind_a_proxy/tutorial002_py39.py",
+ "docs_src/behind_a_proxy/tutorial003_py39.py",
+ "docs_src/behind_a_proxy/tutorial004_py39.py",
+ "docs_src/bigger_applications/app_an_py39/dependencies.py",
+ "docs_src/bigger_applications/app_an_py39/internal/admin.py",
+ "docs_src/bigger_applications/app_an_py39/main.py",
+ "docs_src/bigger_applications/app_an_py39/routers/items.py",
+ "docs_src/bigger_applications/app_an_py39/routers/users.py",
+ "docs_src/bigger_applications/app_py39/dependencies.py",
+ "docs_src/bigger_applications/app_py39/main.py",
+ "docs_src/body_nested_models/tutorial008_py39.py",
+ "docs_src/body_nested_models/tutorial009_py39.py",
+ "docs_src/conditional_openapi/tutorial001_py39.py",
+ "docs_src/configure_swagger_ui/tutorial001_py39.py",
+ "docs_src/configure_swagger_ui/tutorial002_py39.py",
+ "docs_src/configure_swagger_ui/tutorial003_py39.py",
+ "docs_src/cors/tutorial001_py39.py",
+ "docs_src/custom_docs_ui/tutorial001_py39.py",
+ "docs_src/custom_docs_ui/tutorial002_py39.py",
+ "docs_src/custom_response/tutorial001_py39.py",
+ "docs_src/custom_response/tutorial001b_py39.py",
+ "docs_src/custom_response/tutorial002_py39.py",
+ "docs_src/custom_response/tutorial003_py39.py",
+ "docs_src/custom_response/tutorial004_py39.py",
+ "docs_src/custom_response/tutorial005_py39.py",
+ "docs_src/custom_response/tutorial006_py39.py",
+ "docs_src/custom_response/tutorial006b_py39.py",
+ "docs_src/custom_response/tutorial006c_py39.py",
+ "docs_src/custom_response/tutorial007_py39.py",
+ "docs_src/custom_response/tutorial008_py39.py",
+ "docs_src/custom_response/tutorial009_py39.py",
+ "docs_src/custom_response/tutorial009b_py39.py",
+ "docs_src/custom_response/tutorial009c_py39.py",
+ "docs_src/custom_response/tutorial010_py39.py",
+ "docs_src/debugging/tutorial001_py39.py",
+ "docs_src/dependencies/tutorial006_an_py39.py",
+ "docs_src/dependencies/tutorial006_py39.py",
+ "docs_src/dependencies/tutorial007_py39.py",
+ "docs_src/dependencies/tutorial008_py39.py",
+ "docs_src/dependencies/tutorial008b_an_py39.py",
+ "docs_src/dependencies/tutorial008b_py39.py",
+ "docs_src/dependencies/tutorial008c_an_py39.py",
+ "docs_src/dependencies/tutorial008c_py39.py",
+ "docs_src/dependencies/tutorial008d_an_py39.py",
+ "docs_src/dependencies/tutorial008d_py39.py",
+ "docs_src/dependencies/tutorial008e_an_py39.py",
+ "docs_src/dependencies/tutorial008e_py39.py",
+ "docs_src/dependencies/tutorial010_py39.py",
+ "docs_src/dependencies/tutorial011_an_py39.py",
+ "docs_src/dependencies/tutorial011_py39.py",
+ "docs_src/dependencies/tutorial012_an_py39.py",
+ "docs_src/dependencies/tutorial012_py39.py",
+ "docs_src/events/tutorial001_py39.py",
+ "docs_src/events/tutorial002_py39.py",
+ "docs_src/events/tutorial003_py39.py",
+ "docs_src/extending_openapi/tutorial001_py39.py",
+ "docs_src/extra_models/tutorial004_py39.py",
+ "docs_src/extra_models/tutorial005_py39.py",
+ "docs_src/first_steps/tutorial001_py39.py",
+ "docs_src/first_steps/tutorial003_py39.py",
+ "docs_src/generate_clients/tutorial001_py39.py",
+ "docs_src/generate_clients/tutorial002_py39.py",
+ "docs_src/generate_clients/tutorial003_py39.py",
+ "docs_src/generate_clients/tutorial004_py39.py",
+ "docs_src/graphql_/tutorial001_py39.py",
+ "docs_src/handling_errors/tutorial001_py39.py",
+ "docs_src/handling_errors/tutorial002_py39.py",
+ "docs_src/handling_errors/tutorial003_py39.py",
+ "docs_src/handling_errors/tutorial004_py39.py",
+ "docs_src/handling_errors/tutorial005_py39.py",
+ "docs_src/handling_errors/tutorial006_py39.py",
+ "docs_src/metadata/tutorial001_1_py39.py",
+ "docs_src/metadata/tutorial001_py39.py",
+ "docs_src/metadata/tutorial002_py39.py",
+ "docs_src/metadata/tutorial003_py39.py",
+ "docs_src/metadata/tutorial004_py39.py",
+ "docs_src/middleware/tutorial001_py39.py",
+ "docs_src/openapi_webhooks/tutorial001_py39.py",
+ "docs_src/path_operation_advanced_configuration/tutorial001_py39.py",
+ "docs_src/path_operation_advanced_configuration/tutorial002_py39.py",
+ "docs_src/path_operation_advanced_configuration/tutorial003_py39.py",
+ "docs_src/path_operation_advanced_configuration/tutorial005_py39.py",
+ "docs_src/path_operation_advanced_configuration/tutorial006_py39.py",
+ "docs_src/path_operation_advanced_configuration/tutorial007_py39.py",
+ "docs_src/path_operation_configuration/tutorial002b_py39.py",
+ "docs_src/path_operation_configuration/tutorial006_py39.py",
+ "docs_src/path_params/tutorial001_py39.py",
+ "docs_src/path_params/tutorial002_py39.py",
+ "docs_src/path_params/tutorial003_py39.py",
+ "docs_src/path_params/tutorial003b_py39.py",
+ "docs_src/path_params/tutorial004_py39.py",
+ "docs_src/path_params/tutorial005_py39.py",
+ "docs_src/path_params_numeric_validations/tutorial002_an_py39.py",
+ "docs_src/path_params_numeric_validations/tutorial002_py39.py",
+ "docs_src/path_params_numeric_validations/tutorial003_an_py39.py",
+ "docs_src/path_params_numeric_validations/tutorial003_py39.py",
+ "docs_src/path_params_numeric_validations/tutorial004_an_py39.py",
+ "docs_src/path_params_numeric_validations/tutorial004_py39.py",
+ "docs_src/path_params_numeric_validations/tutorial005_an_py39.py",
+ "docs_src/path_params_numeric_validations/tutorial005_py39.py",
+ "docs_src/path_params_numeric_validations/tutorial006_an_py39.py",
+ "docs_src/path_params_numeric_validations/tutorial006_py39.py",
+ "docs_src/python_types/tutorial001_py39.py",
+ "docs_src/python_types/tutorial002_py39.py",
+ "docs_src/python_types/tutorial003_py39.py",
+ "docs_src/python_types/tutorial004_py39.py",
+ "docs_src/python_types/tutorial005_py39.py",
+ "docs_src/python_types/tutorial006_py39.py",
+ "docs_src/python_types/tutorial007_py39.py",
+ "docs_src/python_types/tutorial008_py39.py",
+ "docs_src/python_types/tutorial008b_py39.py",
+ "docs_src/python_types/tutorial009_py39.py",
+ "docs_src/python_types/tutorial009b_py39.py",
+ "docs_src/python_types/tutorial009c_py39.py",
+ "docs_src/python_types/tutorial010_py39.py",
+ "docs_src/python_types/tutorial013_py39.py",
+ "docs_src/query_params/tutorial001_py39.py",
+ "docs_src/query_params/tutorial005_py39.py",
+ "docs_src/query_params_str_validations/tutorial005_an_py39.py",
+ "docs_src/query_params_str_validations/tutorial005_py39.py",
+ "docs_src/query_params_str_validations/tutorial006_an_py39.py",
+ "docs_src/query_params_str_validations/tutorial006_py39.py",
+ "docs_src/query_params_str_validations/tutorial012_an_py39.py",
+ "docs_src/query_params_str_validations/tutorial012_py39.py",
+ "docs_src/query_params_str_validations/tutorial013_an_py39.py",
+ "docs_src/query_params_str_validations/tutorial013_py39.py",
+ "docs_src/request_files/tutorial001_03_an_py39.py",
+ "docs_src/request_files/tutorial001_03_py39.py",
+ "docs_src/request_files/tutorial001_an_py39.py",
+ "docs_src/request_files/tutorial001_py39.py",
+ "docs_src/request_files/tutorial002_an_py39.py",
+ "docs_src/request_files/tutorial002_py39.py",
+ "docs_src/request_files/tutorial003_an_py39.py",
+ "docs_src/request_files/tutorial003_py39.py",
+ "docs_src/request_form_models/tutorial001_an_py39.py",
+ "docs_src/request_form_models/tutorial001_py39.py",
+ "docs_src/request_form_models/tutorial002_an_py39.py",
+ "docs_src/request_form_models/tutorial002_py39.py",
+ "docs_src/request_forms/tutorial001_an_py39.py",
+ "docs_src/request_forms/tutorial001_py39.py",
+ "docs_src/request_forms_and_files/tutorial001_an_py39.py",
+ "docs_src/request_forms_and_files/tutorial001_py39.py",
+ "docs_src/response_change_status_code/tutorial001_py39.py",
+ "docs_src/response_cookies/tutorial001_py39.py",
+ "docs_src/response_cookies/tutorial002_py39.py",
+ "docs_src/response_directly/tutorial002_py39.py",
+ "docs_src/response_headers/tutorial001_py39.py",
+ "docs_src/response_headers/tutorial002_py39.py",
+ "docs_src/response_model/tutorial003_02_py39.py",
+ "docs_src/response_model/tutorial003_03_py39.py",
+ "docs_src/response_status_code/tutorial001_py39.py",
+ "docs_src/response_status_code/tutorial002_py39.py",
+ "docs_src/security/tutorial001_an_py39.py",
+ "docs_src/security/tutorial001_py39.py",
+ "docs_src/security/tutorial006_an_py39.py",
+ "docs_src/security/tutorial006_py39.py",
+ "docs_src/security/tutorial007_an_py39.py",
+ "docs_src/security/tutorial007_py39.py",
+ "docs_src/settings/app01_py39/config.py",
+ "docs_src/settings/app01_py39/main.py",
+ "docs_src/settings/app02_an_py39/config.py",
+ "docs_src/settings/app02_an_py39/main.py",
+ "docs_src/settings/app02_an_py39/test_main.py",
+ "docs_src/settings/app02_py39/config.py",
+ "docs_src/settings/app02_py39/main.py",
+ "docs_src/settings/app02_py39/test_main.py",
+ "docs_src/settings/app03_an_py39/config.py",
+ "docs_src/settings/app03_an_py39/main.py",
+ "docs_src/settings/app03_py39/config.py",
+ "docs_src/settings/app03_py39/main.py",
+ "docs_src/settings/tutorial001_py39.py",
+ "docs_src/static_files/tutorial001_py39.py",
+ "docs_src/sub_applications/tutorial001_py39.py",
+ "docs_src/templates/tutorial001_py39.py",
+ "docs_src/using_request_directly/tutorial001_py39.py",
+ "docs_src/websockets/tutorial001_py39.py",
+ "docs_src/websockets/tutorial003_py39.py",
+ "docs_src/wsgi/tutorial001_py39.py",
]
[tool.coverage.report]
@@ -327,32 +512,42 @@ ignore = [
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
-"docs_src/dependencies/tutorial007_py39.py" = ["F821"]
-"docs_src/dependencies/tutorial008_py39.py" = ["F821"]
-"docs_src/dependencies/tutorial009_py39.py" = ["F821"]
-"docs_src/dependencies/tutorial010_py39.py" = ["F821"]
+"docs_src/custom_request_and_route/tutorial002_an_py310.py" = ["B904"]
+"docs_src/custom_request_and_route/tutorial002_an_py39.py" = ["B904"]
+"docs_src/custom_request_and_route/tutorial002_py310.py" = ["B904"]
+"docs_src/custom_request_and_route/tutorial002_py39.py" = ["B904"]
+"docs_src/custom_response/tutorial007_py310.py" = ["B007"]
"docs_src/custom_response/tutorial007_py39.py" = ["B007"]
"docs_src/dataclasses/tutorial003_py39.py" = ["I001"]
-"docs_src/path_operation_advanced_configuration/tutorial007_py39.py" = ["B904"]
-"docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py" = ["B904"]
-"docs_src/custom_request_and_route/tutorial002_py39.py" = ["B904"]
-"docs_src/custom_request_and_route/tutorial002_py310.py" = ["B904"]
-"docs_src/custom_request_and_route/tutorial002_an_py39.py" = ["B904"]
-"docs_src/custom_request_and_route/tutorial002_an_py310.py" = ["B904"]
+"docs_src/dependencies/tutorial007_py310.py" = ["F821"]
+"docs_src/dependencies/tutorial007_py39.py" = ["F821"]
+"docs_src/dependencies/tutorial008_an_py310.py" = ["F821"]
"docs_src/dependencies/tutorial008_an_py39.py" = ["F821"]
+"docs_src/dependencies/tutorial008_py310.py" = ["F821"]
+"docs_src/dependencies/tutorial008_py39.py" = ["F821"]
+"docs_src/dependencies/tutorial008b_an_py310.py" = ["B904"]
+"docs_src/dependencies/tutorial008b_an_py39.py" = ["B904"]
+"docs_src/dependencies/tutorial008b_py310.py" = ["B904"]
+"docs_src/dependencies/tutorial008b_py39.py" = ["B904"]
+"docs_src/dependencies/tutorial009_py310.py" = ["F821"]
+"docs_src/dependencies/tutorial009_py39.py" = ["F821"]
+"docs_src/dependencies/tutorial010_py310.py" = ["F821"]
+"docs_src/dependencies/tutorial010_py39.py" = ["F821"]
+"docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py" = ["B904"]
+"docs_src/path_operation_advanced_configuration/tutorial007_py310.py" = ["B904"]
+"docs_src/path_operation_advanced_configuration/tutorial007_py39.py" = ["B904"]
+"docs_src/query_params_str_validations/tutorial012_an_py310.py" = ["B006"]
"docs_src/query_params_str_validations/tutorial012_an_py39.py" = ["B006"]
+"docs_src/query_params_str_validations/tutorial013_an_py310.py" = ["B006"]
"docs_src/query_params_str_validations/tutorial013_an_py39.py" = ["B006"]
-"docs_src/security/tutorial004_py39.py" = ["B904"]
-"docs_src/security/tutorial004_an_py39.py" = ["B904"]
"docs_src/security/tutorial004_an_py310.py" = ["B904"]
+"docs_src/security/tutorial004_an_py39.py" = ["B904"]
"docs_src/security/tutorial004_py310.py" = ["B904"]
+"docs_src/security/tutorial004_py39.py" = ["B904"]
"docs_src/security/tutorial005_an_py310.py" = ["B904"]
"docs_src/security/tutorial005_an_py39.py" = ["B904"]
"docs_src/security/tutorial005_py310.py" = ["B904"]
"docs_src/security/tutorial005_py39.py" = ["B904"]
-"docs_src/dependencies/tutorial008b_py39.py" = ["B904"]
-"docs_src/dependencies/tutorial008b_an_py39.py" = ["B904"]
-
[tool.ruff.lint.isort]
known-third-party = ["fastapi", "pydantic", "starlette"]
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial001.py b/tests/test_tutorial/test_additional_responses/test_tutorial001.py
index d8d9d4130..456070c9c 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial001.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial001.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.additional_responses.tutorial001_py39 import app
+from docs_src.additional_responses.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial002.py b/tests/test_tutorial/test_additional_responses/test_tutorial002.py
index 4fae59d22..586779e44 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial002.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial002.py
@@ -12,7 +12,6 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial003.py b/tests/test_tutorial/test_additional_responses/test_tutorial003.py
index e888819df..56eeacb60 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial003.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial003.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.additional_responses.tutorial003_py39 import app
+from docs_src.additional_responses.tutorial003_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial004.py b/tests/test_tutorial/test_additional_responses/test_tutorial004.py
index 9df326a5c..fe56fbb8b 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial004.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial004.py
@@ -12,7 +12,6 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py
index bced1f6df..f57ea2bcf 100644
--- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py
+++ b/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py
@@ -9,9 +9,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py b/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py
index f17391956..6231cf4cb 100644
--- a/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py
+++ b/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.advanced_middleware.tutorial001_py39 import app
+from docs_src.advanced_middleware.tutorial001_py310 import app
def test_middleware():
diff --git a/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py b/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py
index bae915406..fa8ac41d7 100644
--- a/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py
+++ b/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.advanced_middleware.tutorial002_py39 import app
+from docs_src.advanced_middleware.tutorial002_py310 import app
def test_middleware():
diff --git a/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py b/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py
index 66697997c..8602e1569 100644
--- a/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py
+++ b/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py
@@ -1,7 +1,7 @@
from fastapi.responses import PlainTextResponse
from fastapi.testclient import TestClient
-from docs_src.advanced_middleware.tutorial003_py39 import app
+from docs_src.advanced_middleware.tutorial003_py310 import app
@app.get("/large")
diff --git a/tests/test_tutorial/test_async_tests/test_main_a.py b/tests/test_tutorial/test_async_tests/test_main_a.py
index f29acaa9a..4e33692d0 100644
--- a/tests/test_tutorial/test_async_tests/test_main_a.py
+++ b/tests/test_tutorial/test_async_tests/test_main_a.py
@@ -1,6 +1,6 @@
import pytest
-from docs_src.async_tests.app_a_py39.test_main import test_root
+from docs_src.async_tests.app_a_py310.test_main import test_root
@pytest.mark.anyio
diff --git a/tests/test_tutorial/test_authentication_error_status_code/test_tutorial001.py b/tests/test_tutorial/test_authentication_error_status_code/test_tutorial001.py
index 6f5811631..7e1588d67 100644
--- a/tests/test_tutorial/test_authentication_error_status_code/test_tutorial001.py
+++ b/tests/test_tutorial/test_authentication_error_status_code/test_tutorial001.py
@@ -8,7 +8,7 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- "tutorial001_an_py39",
+ "tutorial001_an_py310",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial001.py b/tests/test_tutorial/test_background_tasks/test_tutorial001.py
index c0ad27a6f..100583f77 100644
--- a/tests/test_tutorial/test_background_tasks/test_tutorial001.py
+++ b/tests/test_tutorial/test_background_tasks/test_tutorial001.py
@@ -3,7 +3,7 @@ from pathlib import Path
from fastapi.testclient import TestClient
-from docs_src.background_tasks.tutorial001_py39 import app
+from docs_src.background_tasks.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002.py b/tests/test_tutorial/test_background_tasks/test_tutorial002.py
index 288a1c244..f29402c83 100644
--- a/tests/test_tutorial/test_background_tasks/test_tutorial002.py
+++ b/tests/test_tutorial/test_background_tasks/test_tutorial002.py
@@ -11,9 +11,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial002_py39",
pytest.param("tutorial002_py310", marks=needs_py310),
- "tutorial002_an_py39",
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py
index 31adaa56a..38ae460fb 100644
--- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.behind_a_proxy.tutorial001_py39 import app
+from docs_src.behind_a_proxy.tutorial001_py310 import app
client = TestClient(app, root_path="/api/v1")
diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001_01.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001_01.py
index da4acb28c..190b33c50 100644
--- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001_01.py
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001_01.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.behind_a_proxy.tutorial001_01_py39 import app
+from docs_src.behind_a_proxy.tutorial001_01_py310 import app
client = TestClient(
app,
diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py
index 56e6f2f9d..c9356a513 100644
--- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.behind_a_proxy.tutorial002_py39 import app
+from docs_src.behind_a_proxy.tutorial002_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py
index a164bb80b..d74da5b73 100644
--- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.behind_a_proxy.tutorial003_py39 import app
+from docs_src.behind_a_proxy.tutorial003_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py
index 01bba9fed..f5e27c118 100644
--- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.behind_a_proxy.tutorial004_py39 import app
+from docs_src.behind_a_proxy.tutorial004_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_bigger_applications/test_main.py b/tests/test_tutorial/test_bigger_applications/test_main.py
index 18845e470..abe008d9e 100644
--- a/tests/test_tutorial/test_bigger_applications/test_main.py
+++ b/tests/test_tutorial/test_bigger_applications/test_main.py
@@ -8,8 +8,7 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- "app_py39.main",
- "app_an_py39.main",
+ "app_an_py310.main",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_body/test_tutorial001.py b/tests/test_tutorial/test_body/test_tutorial001.py
index c1877a72e..bdabf8d68 100644
--- a/tests/test_tutorial/test_body/test_tutorial001.py
+++ b/tests/test_tutorial/test_body/test_tutorial001.py
@@ -11,7 +11,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body/test_tutorial002.py b/tests/test_tutorial/test_body/test_tutorial002.py
index 94bf213e3..f1e1236c9 100644
--- a/tests/test_tutorial/test_body/test_tutorial002.py
+++ b/tests/test_tutorial/test_body/test_tutorial002.py
@@ -1,5 +1,4 @@
import importlib
-from typing import Union
import pytest
from fastapi.testclient import TestClient
@@ -11,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
@@ -23,7 +21,7 @@ def get_client(request: pytest.FixtureRequest):
@pytest.mark.parametrize("price", ["50.5", 50.5])
-def test_post_with_tax(client: TestClient, price: Union[str, float]):
+def test_post_with_tax(client: TestClient, price: str | float):
response = client.post(
"/items/",
json={"name": "Foo", "price": price, "description": "Some Foo", "tax": 0.3},
@@ -39,7 +37,7 @@ def test_post_with_tax(client: TestClient, price: Union[str, float]):
@pytest.mark.parametrize("price", ["50.5", 50.5])
-def test_post_without_tax(client: TestClient, price: Union[str, float]):
+def test_post_without_tax(client: TestClient, price: str | float):
response = client.post(
"/items/", json={"name": "Foo", "price": price, "description": "Some Foo"}
)
diff --git a/tests/test_tutorial/test_body/test_tutorial003.py b/tests/test_tutorial/test_body/test_tutorial003.py
index 832c211f6..b4767cf28 100644
--- a/tests/test_tutorial/test_body/test_tutorial003.py
+++ b/tests/test_tutorial/test_body/test_tutorial003.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body/test_tutorial004.py b/tests/test_tutorial/test_body/test_tutorial004.py
index 1019a168c..f0a50a64c 100644
--- a/tests/test_tutorial/test_body/test_tutorial004.py
+++ b/tests/test_tutorial/test_body/test_tutorial004.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001.py b/tests/test_tutorial/test_body_fields/test_tutorial001.py
index 0116dcb09..eb94d24cd 100644
--- a/tests/test_tutorial/test_body_fields/test_tutorial001.py
+++ b/tests/test_tutorial/test_body_fields/test_tutorial001.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
index 2e8ba457b..f510f1c15 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial002.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial002.py
index 0c94e9dd1..b23402c3c 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial002.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial002.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py
index c27f3d5ba..89fabd3ba 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial003_py39",
pytest.param("tutorial003_py310", marks=needs_py310),
- "tutorial003_an_py39",
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial004.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial004.py
index 2a39f3d71..c5b4b452d 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial004.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial004.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
- pytest.param("tutorial004_an_py39"),
pytest.param("tutorial004_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial005.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial005.py
index d600e0767..b8fc98cd7 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial005.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial005.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
- pytest.param("tutorial005_an_py39"),
pytest.param("tutorial005_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial001_tutorial002_tutorial003.py b/tests/test_tutorial/test_body_nested_models/test_tutorial001_tutorial002_tutorial003.py
index 18bce279b..2e2f329f7 100644
--- a/tests/test_tutorial/test_body_nested_models/test_tutorial001_tutorial002_tutorial003.py
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial001_tutorial002_tutorial003.py
@@ -17,11 +17,8 @@ SET_OF_STR_SCHEMA = {"type": "array", "items": {"type": "string"}, "uniqueItems"
@pytest.fixture(
name="mod_name",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial004.py b/tests/test_tutorial/test_body_nested_models/test_tutorial004.py
index 6a70779b6..4605a757d 100644
--- a/tests/test_tutorial/test_body_nested_models/test_tutorial004.py
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial004.py
@@ -11,7 +11,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial005.py b/tests/test_tutorial/test_body_nested_models/test_tutorial005.py
index 2ff3d4f22..ffa02cd65 100644
--- a/tests/test_tutorial/test_body_nested_models/test_tutorial005.py
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial005.py
@@ -11,7 +11,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial006.py b/tests/test_tutorial/test_body_nested_models/test_tutorial006.py
index 229216fc5..4551a72b3 100644
--- a/tests/test_tutorial/test_body_nested_models/test_tutorial006.py
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial006.py
@@ -11,7 +11,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial006_py39"),
pytest.param("tutorial006_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial007.py b/tests/test_tutorial/test_body_nested_models/test_tutorial007.py
index 5a7763f59..5b99b41b6 100644
--- a/tests/test_tutorial/test_body_nested_models/test_tutorial007.py
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial007.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial007_py39"),
pytest.param("tutorial007_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial008.py b/tests/test_tutorial/test_body_nested_models/test_tutorial008.py
index 26f48f1d5..d038805bd 100644
--- a/tests/test_tutorial/test_body_nested_models/test_tutorial008.py
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial008.py
@@ -8,7 +8,7 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial008_py39"),
+ pytest.param("tutorial008_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py
index 492dcecd2..a747e2a64 100644
--- a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py
@@ -8,7 +8,7 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- "tutorial009_py39",
+ "tutorial009_py310",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001.py b/tests/test_tutorial/test_body_updates/test_tutorial001.py
index feb07b859..ba8d7baf3 100644
--- a/tests/test_tutorial/test_body_updates/test_tutorial001.py
+++ b/tests/test_tutorial/test_body_updates/test_tutorial001.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_body_updates/test_tutorial002.py b/tests/test_tutorial/test_body_updates/test_tutorial002.py
index a34d08b52..cf0ee7ada 100644
--- a/tests/test_tutorial/test_body_updates/test_tutorial002.py
+++ b/tests/test_tutorial/test_body_updates/test_tutorial002.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py b/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py
index 644b82ad9..a7aa9dbe2 100644
--- a/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py
+++ b/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py
@@ -5,11 +5,11 @@ from inline_snapshot import snapshot
def get_client() -> TestClient:
- from docs_src.conditional_openapi import tutorial001_py39
+ from docs_src.conditional_openapi import tutorial001_py310
- importlib.reload(tutorial001_py39)
+ importlib.reload(tutorial001_py310)
- client = TestClient(tutorial001_py39.app)
+ client = TestClient(tutorial001_py310.app)
return client
diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py
index 1fa9419a7..e2f1fbf90 100644
--- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py
+++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.configure_swagger_ui.tutorial001_py39 import app
+from docs_src.configure_swagger_ui.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py
index c218cc858..ce1cb4bac 100644
--- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py
+++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.configure_swagger_ui.tutorial002_py39 import app
+from docs_src.configure_swagger_ui.tutorial002_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py
index 8b7368549..6f28e7734 100644
--- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py
+++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.configure_swagger_ui.tutorial003_py39 import app
+from docs_src.configure_swagger_ui.tutorial003_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py
index f391c569a..c4de7ad45 100644
--- a/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py
+++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py
@@ -10,9 +10,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py
index 6583045dc..37be0f1dd 100644
--- a/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py
+++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py
@@ -10,9 +10,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=[needs_py310]),
- pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=[needs_py310]),
],
)
diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001.py b/tests/test_tutorial/test_cookie_params/test_tutorial001.py
index 4d7adf0d6..db0765ea5 100644
--- a/tests/test_tutorial/test_cookie_params/test_tutorial001.py
+++ b/tests/test_tutorial/test_cookie_params/test_tutorial001.py
@@ -11,9 +11,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="mod",
params=[
- "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_cors/test_tutorial001.py b/tests/test_tutorial/test_cors/test_tutorial001.py
index 6a733693a..428378cd4 100644
--- a/tests/test_tutorial/test_cors/test_tutorial001.py
+++ b/tests/test_tutorial/test_cors/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.cors.tutorial001_py39 import app
+from docs_src.cors.tutorial001_py310 import app
def test_cors():
diff --git a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py
index 1816e5d97..f7eb7fd97 100644
--- a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py
+++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py
@@ -10,7 +10,7 @@ def client():
static_dir: Path = Path(os.getcwd()) / "static"
print(static_dir)
static_dir.mkdir(exist_ok=True)
- from docs_src.custom_docs_ui.tutorial001_py39 import app
+ from docs_src.custom_docs_ui.tutorial001_py310 import app
with TestClient(app) as client:
yield client
diff --git a/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py
index e8b7eb7aa..28945d838 100644
--- a/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py
+++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py
@@ -10,7 +10,7 @@ def client():
static_dir: Path = Path(os.getcwd()) / "static"
print(static_dir)
static_dir.mkdir(exist_ok=True)
- from docs_src.custom_docs_ui.tutorial002_py39 import app
+ from docs_src.custom_docs_ui.tutorial002_py310 import app
with TestClient(app) as client:
yield client
diff --git a/tests/test_tutorial/test_custom_request_and_route/test_tutorial001.py b/tests/test_tutorial/test_custom_request_and_route/test_tutorial001.py
index b4ea53784..39d3bd406 100644
--- a/tests/test_tutorial/test_custom_request_and_route/test_tutorial001.py
+++ b/tests/test_tutorial/test_custom_request_and_route/test_tutorial001.py
@@ -12,9 +12,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py
index a9c7ae638..746d6c9d2 100644
--- a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py
+++ b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py
@@ -10,9 +10,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py b/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py
index 6cad7bd3f..c11ea1259 100644
--- a/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py
+++ b/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py
@@ -9,7 +9,6 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial001.py b/tests/test_tutorial/test_custom_response/test_tutorial001.py
index 20244bef4..a5fe4c8f4 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial001.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial001.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
- pytest.param("tutorial010_py39"),
+ pytest.param("tutorial001_py310"),
+ pytest.param("tutorial010_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial001b.py b/tests/test_tutorial/test_custom_response/test_tutorial001b.py
index 746801df1..32437db86 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial001b.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial001b.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.custom_response.tutorial001b_py39 import app
+from docs_src.custom_response.tutorial001b_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial002_tutorial003_tutorial004.py b/tests/test_tutorial/test_custom_response/test_tutorial002_tutorial003_tutorial004.py
index 68e046ac5..42fd85583 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial002_tutorial003_tutorial004.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial002_tutorial003_tutorial004.py
@@ -8,9 +8,9 @@ from inline_snapshot import Is, snapshot
@pytest.fixture(
name="mod_name",
params=[
- pytest.param("tutorial002_py39"),
- pytest.param("tutorial003_py39"),
- pytest.param("tutorial004_py39"),
+ pytest.param("tutorial002_py310"),
+ pytest.param("tutorial003_py310"),
+ pytest.param("tutorial004_py310"),
],
)
def get_mod_name(request: pytest.FixtureRequest) -> str:
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial005.py b/tests/test_tutorial/test_custom_response/test_tutorial005.py
index b4919af6c..297e48822 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial005.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial005.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.custom_response.tutorial005_py39 import app
+from docs_src.custom_response.tutorial005_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006.py b/tests/test_tutorial/test_custom_response/test_tutorial006.py
index ea2d366aa..4365090c2 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial006.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial006.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.custom_response.tutorial006_py39 import app
+from docs_src.custom_response.tutorial006_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006b.py b/tests/test_tutorial/test_custom_response/test_tutorial006b.py
index 133a591b1..a77618847 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial006b.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial006b.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.custom_response.tutorial006b_py39 import app
+from docs_src.custom_response.tutorial006b_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006c.py b/tests/test_tutorial/test_custom_response/test_tutorial006c.py
index 5b17d815d..f29bda2c2 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial006c.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial006c.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.custom_response.tutorial006c_py39 import app
+from docs_src.custom_response.tutorial006c_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial007.py b/tests/test_tutorial/test_custom_response/test_tutorial007.py
index a62476ec1..5f2e233f8 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial007.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial007.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.custom_response.tutorial007_py39 import app
+from docs_src.custom_response.tutorial007_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial008.py b/tests/test_tutorial/test_custom_response/test_tutorial008.py
index d9fe61f53..1be7c1a62 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial008.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial008.py
@@ -2,15 +2,15 @@ from pathlib import Path
from fastapi.testclient import TestClient
-from docs_src.custom_response import tutorial008_py39
-from docs_src.custom_response.tutorial008_py39 import app
+from docs_src.custom_response import tutorial008_py310
+from docs_src.custom_response.tutorial008_py310 import app
client = TestClient(app)
def test_get(tmp_path: Path):
file_path: Path = tmp_path / "large-video-file.mp4"
- tutorial008_py39.some_file_path = str(file_path)
+ tutorial008_py310.some_file_path = str(file_path)
test_content = b"Fake video bytes"
file_path.write_bytes(test_content)
response = client.get("/")
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial009.py b/tests/test_tutorial/test_custom_response/test_tutorial009.py
index cb6a514be..a6564d551 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial009.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial009.py
@@ -2,15 +2,15 @@ from pathlib import Path
from fastapi.testclient import TestClient
-from docs_src.custom_response import tutorial009_py39
-from docs_src.custom_response.tutorial009_py39 import app
+from docs_src.custom_response import tutorial009_py310
+from docs_src.custom_response.tutorial009_py310 import app
client = TestClient(app)
def test_get(tmp_path: Path):
file_path: Path = tmp_path / "large-video-file.mp4"
- tutorial009_py39.some_file_path = str(file_path)
+ tutorial009_py310.some_file_path = str(file_path)
test_content = b"Fake video bytes"
file_path.write_bytes(test_content)
response = client.get("/")
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial009b.py b/tests/test_tutorial/test_custom_response/test_tutorial009b.py
index 9918bdb1a..05ac62f3d 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial009b.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial009b.py
@@ -2,15 +2,15 @@ from pathlib import Path
from fastapi.testclient import TestClient
-from docs_src.custom_response import tutorial009b_py39
-from docs_src.custom_response.tutorial009b_py39 import app
+from docs_src.custom_response import tutorial009b_py310
+from docs_src.custom_response.tutorial009b_py310 import app
client = TestClient(app)
def test_get(tmp_path: Path):
file_path: Path = tmp_path / "large-video-file.mp4"
- tutorial009b_py39.some_file_path = str(file_path)
+ tutorial009b_py310.some_file_path = str(file_path)
test_content = b"Fake video bytes"
file_path.write_bytes(test_content)
response = client.get("/")
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial009c.py b/tests/test_tutorial/test_custom_response/test_tutorial009c.py
index efc3a6b4a..7a1b71307 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial009c.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial009c.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.custom_response.tutorial009c_py39 import app
+from docs_src.custom_response.tutorial009c_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial001.py b/tests/test_tutorial/test_dataclasses/test_tutorial001.py
index a3d2cf515..62de135dc 100644
--- a/tests/test_tutorial/test_dataclasses/test_tutorial001.py
+++ b/tests/test_tutorial/test_dataclasses/test_tutorial001.py
@@ -10,7 +10,6 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial002.py b/tests/test_tutorial/test_dataclasses/test_tutorial002.py
index 210d743bb..f6607c8e0 100644
--- a/tests/test_tutorial/test_dataclasses/test_tutorial002.py
+++ b/tests/test_tutorial/test_dataclasses/test_tutorial002.py
@@ -10,7 +10,6 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial003.py b/tests/test_tutorial/test_dataclasses/test_tutorial003.py
index e023271bc..5a35e5c4a 100644
--- a/tests/test_tutorial/test_dataclasses/test_tutorial003.py
+++ b/tests/test_tutorial/test_dataclasses/test_tutorial003.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_debugging/test_tutorial001.py b/tests/test_tutorial/test_debugging/test_tutorial001.py
index 1a0ca6cad..fbf2bfa02 100644
--- a/tests/test_tutorial/test_debugging/test_tutorial001.py
+++ b/tests/test_tutorial/test_debugging/test_tutorial001.py
@@ -7,7 +7,7 @@ import pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-MOD_NAME = "docs_src.debugging.tutorial001_py39"
+MOD_NAME = "docs_src.debugging.tutorial001_py310"
@pytest.fixture(name="client")
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_tutorial001_02.py b/tests/test_tutorial/test_dependencies/test_tutorial001_tutorial001_02.py
index 74f4a8f3a..11e732e6d 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial001_tutorial001_02.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial001_tutorial001_02.py
@@ -10,11 +10,8 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
- pytest.param("tutorial001_02_an_py39"),
pytest.param("tutorial001_02_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial002_tutorial003_tutorial004.py b/tests/test_tutorial/test_dependencies/test_tutorial002_tutorial003_tutorial004.py
index 6e1cea5a0..a9ddf8a52 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial002_tutorial003_tutorial004.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial002_tutorial003_tutorial004.py
@@ -10,17 +10,11 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
- pytest.param("tutorial003_an_py39"),
pytest.param("tutorial003_an_py310", marks=needs_py310),
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
- pytest.param("tutorial004_an_py39"),
pytest.param("tutorial004_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial005.py b/tests/test_tutorial/test_dependencies/test_tutorial005.py
index 31054744a..3cd083b35 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial005.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial005.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
- pytest.param("tutorial005_an_py39"),
pytest.param("tutorial005_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006.py b/tests/test_tutorial/test_dependencies/test_tutorial006.py
index 8d6cfa2d6..f6e6f8368 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial006.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial006.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial006_py39"),
- pytest.param("tutorial006_an_py39"),
+ pytest.param("tutorial006_py310"),
+ pytest.param("tutorial006_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial007.py b/tests/test_tutorial/test_dependencies/test_tutorial007.py
index 3e188abcf..c98485611 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial007.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial007.py
@@ -2,7 +2,7 @@ import asyncio
from contextlib import asynccontextmanager
from unittest.mock import Mock, patch
-from docs_src.dependencies.tutorial007_py39 import get_db
+from docs_src.dependencies.tutorial007_py310 import get_db
def test_get_db(): # Just for coverage
@@ -14,7 +14,7 @@ def test_get_db(): # Just for coverage
dbsession_moock = Mock()
with patch(
- "docs_src.dependencies.tutorial007_py39.DBSession",
+ "docs_src.dependencies.tutorial007_py310.DBSession",
return_value=dbsession_moock,
create=True,
):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008.py b/tests/test_tutorial/test_dependencies/test_tutorial008.py
index 5a2d226bf..e23ac0ac5 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial008.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial008.py
@@ -12,9 +12,9 @@ from fastapi.testclient import TestClient
@pytest.fixture(
name="module",
params=[
- "tutorial008_py39",
+ "tutorial008_py310",
pytest.param(
- "tutorial008_an_py39",
+ "tutorial008_an_py310",
marks=pytest.mark.xfail(
sys.version_info < (3, 14),
reason="Fails with `NameError: name 'DepA' is not defined`",
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b.py b/tests/test_tutorial/test_dependencies/test_tutorial008b.py
index 91e00b370..d2493d0cc 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial008b.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial008b.py
@@ -7,8 +7,8 @@ from fastapi.testclient import TestClient
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial008b_py39"),
- pytest.param("tutorial008b_an_py39"),
+ pytest.param("tutorial008b_py310"),
+ pytest.param("tutorial008b_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c.py b/tests/test_tutorial/test_dependencies/test_tutorial008c.py
index aede6f8d2..b7713c73b 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial008c.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial008c.py
@@ -9,8 +9,8 @@ from fastapi.testclient import TestClient
@pytest.fixture(
name="mod",
params=[
- pytest.param("tutorial008c_py39"),
- pytest.param("tutorial008c_an_py39"),
+ pytest.param("tutorial008c_py310"),
+ pytest.param("tutorial008c_an_py310"),
],
)
def get_mod(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d.py b/tests/test_tutorial/test_dependencies/test_tutorial008d.py
index 5477f8b95..e831c055e 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial008d.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial008d.py
@@ -8,8 +8,8 @@ from fastapi.testclient import TestClient
@pytest.fixture(
name="mod",
params=[
- pytest.param("tutorial008d_py39"),
- pytest.param("tutorial008d_an_py39"),
+ pytest.param("tutorial008d_py310"),
+ pytest.param("tutorial008d_an_py310"),
],
)
def get_mod(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008e.py b/tests/test_tutorial/test_dependencies/test_tutorial008e.py
index c433157ea..18eba9f77 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial008e.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial008e.py
@@ -7,8 +7,8 @@ from fastapi.testclient import TestClient
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial008e_py39"),
- pytest.param("tutorial008e_an_py39"),
+ pytest.param("tutorial008e_py310"),
+ pytest.param("tutorial008e_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial010.py b/tests/test_tutorial/test_dependencies/test_tutorial010.py
index 6d3815ada..954d09f20 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial010.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial010.py
@@ -4,7 +4,7 @@ from unittest.mock import Mock, patch
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
-from docs_src.dependencies.tutorial010_py39 import get_db
+from docs_src.dependencies.tutorial010_py310 import get_db
def test_get_db():
@@ -19,7 +19,7 @@ def test_get_db():
dbsession_mock = Mock()
with patch(
- "docs_src.dependencies.tutorial010_py39.DBSession",
+ "docs_src.dependencies.tutorial010_py310.DBSession",
return_value=dbsession_mock,
create=True,
):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial011.py b/tests/test_tutorial/test_dependencies/test_tutorial011.py
index 383422a7e..16167fd2e 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial011.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial011.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- "tutorial011_py39",
- pytest.param("tutorial011_an_py39"),
+ "tutorial011_py310",
+ pytest.param("tutorial011_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012.py b/tests/test_tutorial/test_dependencies/test_tutorial012.py
index a15688924..e0148e052 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial012.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial012.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial012_py39"),
- pytest.param("tutorial012_an_py39"),
+ pytest.param("tutorial012_py310"),
+ pytest.param("tutorial012_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_encoder/test_tutorial001.py b/tests/test_tutorial/test_encoder/test_tutorial001.py
index a3d672333..e8c1f3c73 100644
--- a/tests/test_tutorial/test_encoder/test_tutorial001.py
+++ b/tests/test_tutorial/test_encoder/test_tutorial001.py
@@ -11,7 +11,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="mod",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_events/test_tutorial001.py b/tests/test_tutorial/test_events/test_tutorial001.py
index 63215c00d..e392cdcc9 100644
--- a/tests/test_tutorial/test_events/test_tutorial001.py
+++ b/tests/test_tutorial/test_events/test_tutorial001.py
@@ -7,7 +7,7 @@ from inline_snapshot import snapshot
@pytest.fixture(name="app", scope="module")
def get_app():
with pytest.warns(DeprecationWarning):
- from docs_src.events.tutorial001_py39 import app
+ from docs_src.events.tutorial001_py310 import app
yield app
diff --git a/tests/test_tutorial/test_events/test_tutorial002.py b/tests/test_tutorial/test_events/test_tutorial002.py
index f98d8921f..47af7a952 100644
--- a/tests/test_tutorial/test_events/test_tutorial002.py
+++ b/tests/test_tutorial/test_events/test_tutorial002.py
@@ -7,7 +7,7 @@ from inline_snapshot import snapshot
@pytest.fixture(name="app", scope="module")
def get_app():
with pytest.warns(DeprecationWarning):
- from docs_src.events.tutorial002_py39 import app
+ from docs_src.events.tutorial002_py310 import app
yield app
diff --git a/tests/test_tutorial/test_events/test_tutorial003.py b/tests/test_tutorial/test_events/test_tutorial003.py
index 4fc848e11..3da0b2ca5 100644
--- a/tests/test_tutorial/test_events/test_tutorial003.py
+++ b/tests/test_tutorial/test_events/test_tutorial003.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.events.tutorial003_py39 import (
+from docs_src.events.tutorial003_py310 import (
app,
fake_answer_to_everything_ml_model,
ml_models,
diff --git a/tests/test_tutorial/test_extending_openapi/test_tutorial001.py b/tests/test_tutorial/test_extending_openapi/test_tutorial001.py
index bc10c888c..06c56565f 100644
--- a/tests/test_tutorial/test_extending_openapi/test_tutorial001.py
+++ b/tests/test_tutorial/test_extending_openapi/test_tutorial001.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.extending_openapi.tutorial001_py39 import app
+from docs_src.extending_openapi.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py
index 28fe68f28..2e7f0e522 100644
--- a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py
+++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_extra_models/test_tutorial001_tutorial002.py b/tests/test_tutorial/test_extra_models/test_tutorial001_tutorial002.py
index 4248878b5..4fcb7ff78 100644
--- a/tests/test_tutorial/test_extra_models/test_tutorial001_tutorial002.py
+++ b/tests/test_tutorial/test_extra_models/test_tutorial001_tutorial002.py
@@ -11,9 +11,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_extra_models/test_tutorial003.py b/tests/test_tutorial/test_extra_models/test_tutorial003.py
index 38e874158..2a2cf8afa 100644
--- a/tests/test_tutorial/test_extra_models/test_tutorial003.py
+++ b/tests/test_tutorial/test_extra_models/test_tutorial003.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_extra_models/test_tutorial004.py b/tests/test_tutorial/test_extra_models/test_tutorial004.py
index c64371e3b..3ded20959 100644
--- a/tests/test_tutorial/test_extra_models/test_tutorial004.py
+++ b/tests/test_tutorial/test_extra_models/test_tutorial004.py
@@ -8,7 +8,7 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004_py39"),
+ pytest.param("tutorial004_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_extra_models/test_tutorial005.py b/tests/test_tutorial/test_extra_models/test_tutorial005.py
index 43b8bae8e..265b76832 100644
--- a/tests/test_tutorial/test_extra_models/test_tutorial005.py
+++ b/tests/test_tutorial/test_extra_models/test_tutorial005.py
@@ -8,7 +8,7 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial005_py39"),
+ pytest.param("tutorial005_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_first_steps/test_tutorial001_tutorial002_tutorial003.py b/tests/test_tutorial/test_first_steps/test_tutorial001_tutorial002_tutorial003.py
index 5457ad132..30eab21e9 100644
--- a/tests/test_tutorial/test_first_steps/test_tutorial001_tutorial002_tutorial003.py
+++ b/tests/test_tutorial/test_first_steps/test_tutorial001_tutorial002_tutorial003.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- "tutorial001_py39",
- "tutorial003_py39",
+ "tutorial001_py310",
+ "tutorial003_py310",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_generate_clients/test_tutorial001.py b/tests/test_tutorial/test_generate_clients/test_tutorial001.py
index 62799d259..40ed3eeea 100644
--- a/tests/test_tutorial/test_generate_clients/test_tutorial001.py
+++ b/tests/test_tutorial/test_generate_clients/test_tutorial001.py
@@ -8,7 +8,7 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
+ pytest.param("tutorial001_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_generate_clients/test_tutorial002.py b/tests/test_tutorial/test_generate_clients/test_tutorial002.py
index f64f5f866..6557b8c27 100644
--- a/tests/test_tutorial/test_generate_clients/test_tutorial002.py
+++ b/tests/test_tutorial/test_generate_clients/test_tutorial002.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.generate_clients.tutorial002_py39 import app
+from docs_src.generate_clients.tutorial002_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_generate_clients/test_tutorial003.py b/tests/test_tutorial/test_generate_clients/test_tutorial003.py
index 34ede6194..cded241ae 100644
--- a/tests/test_tutorial/test_generate_clients/test_tutorial003.py
+++ b/tests/test_tutorial/test_generate_clients/test_tutorial003.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.generate_clients.tutorial003_py39 import app
+from docs_src.generate_clients.tutorial003_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_generate_clients/test_tutorial004.py b/tests/test_tutorial/test_generate_clients/test_tutorial004.py
index d04bfbfe8..1d71de869 100644
--- a/tests/test_tutorial/test_generate_clients/test_tutorial004.py
+++ b/tests/test_tutorial/test_generate_clients/test_tutorial004.py
@@ -5,16 +5,16 @@ from unittest.mock import patch
from inline_snapshot import snapshot
-from docs_src.generate_clients import tutorial003_py39
+from docs_src.generate_clients import tutorial003_py310
def test_remove_tags(tmp_path: pathlib.Path):
tmp_file = tmp_path / "openapi.json"
- openapi_json = tutorial003_py39.app.openapi()
+ openapi_json = tutorial003_py310.app.openapi()
tmp_file.write_text(json.dumps(openapi_json))
with patch("pathlib.Path", return_value=tmp_file):
- importlib.import_module("docs_src.generate_clients.tutorial004_py39")
+ importlib.import_module("docs_src.generate_clients.tutorial004_py310")
modified_openapi = json.loads(tmp_file.read_text())
assert modified_openapi == snapshot(
diff --git a/tests/test_tutorial/test_graphql/test_tutorial001.py b/tests/test_tutorial/test_graphql/test_tutorial001.py
index cc3be6a19..c93347081 100644
--- a/tests/test_tutorial/test_graphql/test_tutorial001.py
+++ b/tests/test_tutorial/test_graphql/test_tutorial001.py
@@ -10,7 +10,7 @@ warnings.filterwarnings(
category=DeprecationWarning,
)
-from docs_src.graphql_.tutorial001_py39 import app # noqa: E402
+from docs_src.graphql_.tutorial001_py310 import app # noqa: E402
@pytest.fixture(name="client")
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial001.py b/tests/test_tutorial/test_handling_errors/test_tutorial001.py
index 8283cdc73..001a02a0f 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial001.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial001.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.handling_errors.tutorial001_py39 import app
+from docs_src.handling_errors.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial002.py b/tests/test_tutorial/test_handling_errors/test_tutorial002.py
index c437693d3..0e7321ee7 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial002.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial002.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.handling_errors.tutorial002_py39 import app
+from docs_src.handling_errors.tutorial002_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial003.py b/tests/test_tutorial/test_handling_errors/test_tutorial003.py
index 959729e53..cc11985be 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial003.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial003.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.handling_errors.tutorial003_py39 import app
+from docs_src.handling_errors.tutorial003_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial004.py b/tests/test_tutorial/test_handling_errors/test_tutorial004.py
index 16165bb3d..5471cb0d8 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial004.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial004.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.handling_errors.tutorial004_py39 import app
+from docs_src.handling_errors.tutorial004_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial005.py b/tests/test_tutorial/test_handling_errors/test_tutorial005.py
index af924a9f7..c04b510c3 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial005.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial005.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.handling_errors.tutorial005_py39 import app
+from docs_src.handling_errors.tutorial005_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial006.py b/tests/test_tutorial/test_handling_errors/test_tutorial006.py
index 4c069d81e..666e44f3a 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial006.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial006.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.handling_errors.tutorial006_py39 import app
+from docs_src.handling_errors.tutorial006_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial001.py b/tests/test_tutorial/test_header_param_models/test_tutorial001.py
index 2d14c698e..8391bd119 100644
--- a/tests/test_tutorial/test_header_param_models/test_tutorial001.py
+++ b/tests/test_tutorial/test_header_param_models/test_tutorial001.py
@@ -10,9 +10,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial002.py b/tests/test_tutorial/test_header_param_models/test_tutorial002.py
index 478ac8408..3d66dca08 100644
--- a/tests/test_tutorial/test_header_param_models/test_tutorial002.py
+++ b/tests/test_tutorial/test_header_param_models/test_tutorial002.py
@@ -10,9 +10,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=[needs_py310]),
- pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=[needs_py310]),
],
)
diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial003.py b/tests/test_tutorial/test_header_param_models/test_tutorial003.py
index 00636c2b5..7d0da24fd 100644
--- a/tests/test_tutorial/test_header_param_models/test_tutorial003.py
+++ b/tests/test_tutorial/test_header_param_models/test_tutorial003.py
@@ -10,9 +10,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
- pytest.param("tutorial003_an_py39"),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_header_params/test_tutorial001.py b/tests/test_tutorial/test_header_params/test_tutorial001.py
index 2e97a8322..900d35adc 100644
--- a/tests/test_tutorial/test_header_params/test_tutorial001.py
+++ b/tests/test_tutorial/test_header_params/test_tutorial001.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_header_params/test_tutorial002.py b/tests/test_tutorial/test_header_params/test_tutorial002.py
index ba86c55bf..c756eae71 100644
--- a/tests/test_tutorial/test_header_params/test_tutorial002.py
+++ b/tests/test_tutorial/test_header_params/test_tutorial002.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_header_params/test_tutorial003.py b/tests/test_tutorial/test_header_params/test_tutorial003.py
index 30e5133c0..1f71322b6 100644
--- a/tests/test_tutorial/test_header_params/test_tutorial003.py
+++ b/tests/test_tutorial/test_header_params/test_tutorial003.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
- pytest.param("tutorial003_an_py39"),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_metadata/test_tutorial001.py b/tests/test_tutorial/test_metadata/test_tutorial001.py
index ba3c09ce4..ce0c1643a 100644
--- a/tests/test_tutorial/test_metadata/test_tutorial001.py
+++ b/tests/test_tutorial/test_metadata/test_tutorial001.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.metadata.tutorial001_py39 import app
+from docs_src.metadata.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_metadata/test_tutorial001_1.py b/tests/test_tutorial/test_metadata/test_tutorial001_1.py
index 933954973..ba9ba9dcb 100644
--- a/tests/test_tutorial/test_metadata/test_tutorial001_1.py
+++ b/tests/test_tutorial/test_metadata/test_tutorial001_1.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.metadata.tutorial001_1_py39 import app
+from docs_src.metadata.tutorial001_1_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_metadata/test_tutorial002.py b/tests/test_tutorial/test_metadata/test_tutorial002.py
index 5a252475e..979a6a7b8 100644
--- a/tests/test_tutorial/test_metadata/test_tutorial002.py
+++ b/tests/test_tutorial/test_metadata/test_tutorial002.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.metadata.tutorial002_py39 import app
+from docs_src.metadata.tutorial002_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_metadata/test_tutorial003.py b/tests/test_tutorial/test_metadata/test_tutorial003.py
index 778781e66..ee2978028 100644
--- a/tests/test_tutorial/test_metadata/test_tutorial003.py
+++ b/tests/test_tutorial/test_metadata/test_tutorial003.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.metadata.tutorial003_py39 import app
+from docs_src.metadata.tutorial003_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_metadata/test_tutorial004.py b/tests/test_tutorial/test_metadata/test_tutorial004.py
index 5c309a830..ef0533d50 100644
--- a/tests/test_tutorial/test_metadata/test_tutorial004.py
+++ b/tests/test_tutorial/test_metadata/test_tutorial004.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.metadata.tutorial004_py39 import app
+from docs_src.metadata.tutorial004_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_middleware/test_tutorial001.py b/tests/test_tutorial/test_middleware/test_tutorial001.py
index 18047f343..1fa1e5a50 100644
--- a/tests/test_tutorial/test_middleware/test_tutorial001.py
+++ b/tests/test_tutorial/test_middleware/test_tutorial001.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.middleware.tutorial001_py39 import app
+from docs_src.middleware.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py b/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py
index 1e937d0c9..62374ef27 100644
--- a/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py
+++ b/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py
@@ -11,7 +11,6 @@ from tests.utils import needs_py310
@pytest.fixture(
name="mod",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py b/tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py
index 0482c94bf..696a2bed5 100644
--- a/tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py
+++ b/tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.openapi_webhooks.tutorial001_py39 import app
+from docs_src.openapi_webhooks.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py
index 3a4f64824..ecda8a315 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_operation_advanced_configuration.tutorial001_py39 import app
+from docs_src.path_operation_advanced_configuration.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py
index c26c36030..c5067e233 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_operation_advanced_configuration.tutorial002_py39 import app
+from docs_src.path_operation_advanced_configuration.tutorial002_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py
index f060647b2..36fe21678 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_operation_advanced_configuration.tutorial003_py39 import app
+from docs_src.path_operation_advanced_configuration.tutorial003_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py
index bf7934544..894cd9749 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py
index 779e54f9e..f129ec6f4 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_operation_advanced_configuration.tutorial005_py39 import app
+from docs_src.path_operation_advanced_configuration.tutorial005_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py
index d63b5f912..f3bf2b5bf 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_operation_advanced_configuration.tutorial006_py39 import app
+from docs_src.path_operation_advanced_configuration.tutorial006_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py
index ec0c91bda..ad06e6c05 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py
@@ -8,7 +8,7 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial007_py39"),
+ pytest.param("tutorial007_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial001.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial001.py
index 500cb057c..1b81b6f86 100644
--- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial001.py
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial001.py
@@ -11,7 +11,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial002.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial002.py
index 1cc560cb9..675f3b1ae 100644
--- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial002.py
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial002.py
@@ -11,7 +11,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py
index 98319645c..f9a5ff760 100644
--- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_operation_configuration.tutorial002b_py39 import app
+from docs_src.path_operation_configuration.tutorial002b_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial003_tutorial004.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial003_tutorial004.py
index c13a3c38c..6d1afecc8 100644
--- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial003_tutorial004.py
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial003_tutorial004.py
@@ -25,9 +25,7 @@ DESCRIPTIONS = {
@pytest.fixture(
name="mod_name",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
index 07152755f..b186c0a68 100644
--- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py
index 5f56ab929..27a93f563 100644
--- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py
@@ -2,7 +2,7 @@ import pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_operation_configuration.tutorial006_py39 import app
+from docs_src.path_operation_configuration.tutorial006_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_params/test_tutorial001.py b/tests/test_tutorial/test_path_params/test_tutorial001.py
index ec598832b..75c47c855 100644
--- a/tests/test_tutorial/test_path_params/test_tutorial001.py
+++ b/tests/test_tutorial/test_path_params/test_tutorial001.py
@@ -2,7 +2,7 @@ import pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_params.tutorial001_py39 import app
+from docs_src.path_params.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_params/test_tutorial002.py b/tests/test_tutorial/test_path_params/test_tutorial002.py
index 8384ec8ef..416c70558 100644
--- a/tests/test_tutorial/test_path_params/test_tutorial002.py
+++ b/tests/test_tutorial/test_path_params/test_tutorial002.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_params.tutorial002_py39 import app
+from docs_src.path_params.tutorial002_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_params/test_tutorial003.py b/tests/test_tutorial/test_path_params/test_tutorial003.py
index 432ccde49..2c07ebbc8 100644
--- a/tests/test_tutorial/test_path_params/test_tutorial003.py
+++ b/tests/test_tutorial/test_path_params/test_tutorial003.py
@@ -2,7 +2,7 @@ import pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_params.tutorial003_py39 import app
+from docs_src.path_params.tutorial003_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_params/test_tutorial003b.py b/tests/test_tutorial/test_path_params/test_tutorial003b.py
index 1cf39eca9..debf98503 100644
--- a/tests/test_tutorial/test_path_params/test_tutorial003b.py
+++ b/tests/test_tutorial/test_path_params/test_tutorial003b.py
@@ -3,7 +3,7 @@ import asyncio
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_params.tutorial003b_py39 import app, read_users2
+from docs_src.path_params.tutorial003b_py310 import app, read_users2
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_params/test_tutorial004.py b/tests/test_tutorial/test_path_params/test_tutorial004.py
index b691e821d..2f2a72e64 100644
--- a/tests/test_tutorial/test_path_params/test_tutorial004.py
+++ b/tests/test_tutorial/test_path_params/test_tutorial004.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_params.tutorial004_py39 import app
+from docs_src.path_params.tutorial004_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_params/test_tutorial005.py b/tests/test_tutorial/test_path_params/test_tutorial005.py
index c60fee3f0..bf54b59a9 100644
--- a/tests/test_tutorial/test_path_params/test_tutorial005.py
+++ b/tests/test_tutorial/test_path_params/test_tutorial005.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.path_params.tutorial005_py39 import app
+from docs_src.path_params.tutorial005_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial001.py b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial001.py
index b43de7032..868b0ea78 100644
--- a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial001.py
+++ b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial001.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial002_tutorial003.py b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial002_tutorial003.py
index 1bb2a3ea8..55d5b418c 100644
--- a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial002_tutorial003.py
+++ b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial002_tutorial003.py
@@ -8,10 +8,10 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
- pytest.param("tutorial002_an_py39"),
- pytest.param("tutorial003_py39"),
- pytest.param("tutorial003_an_py39"),
+ pytest.param("tutorial002_py310"),
+ pytest.param("tutorial002_an_py310"),
+ pytest.param("tutorial003_py310"),
+ pytest.param("tutorial003_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
diff --git a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial004.py b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial004.py
index 37c16d295..7b1272fa1 100644
--- a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial004.py
+++ b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial004.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004_py39"),
- pytest.param("tutorial004_an_py39"),
+ pytest.param("tutorial004_py310"),
+ pytest.param("tutorial004_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
diff --git a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial005.py b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial005.py
index 0afc9dcbc..d2c9b6077 100644
--- a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial005.py
+++ b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial005.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial005_py39"),
- pytest.param("tutorial005_an_py39"),
+ pytest.param("tutorial005_py310"),
+ pytest.param("tutorial005_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
diff --git a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial006.py b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial006.py
index e0a9694c1..9fb1f8b3b 100644
--- a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial006.py
+++ b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial006.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial006_py39"),
- pytest.param("tutorial006_an_py39"),
+ pytest.param("tutorial006_py310"),
+ pytest.param("tutorial006_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
diff --git a/tests/test_tutorial/test_python_types/test_tutorial001_tutorial002.py b/tests/test_tutorial/test_python_types/test_tutorial001_tutorial002.py
index ccb096857..d7bf599fe 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial001_tutorial002.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial001_tutorial002.py
@@ -7,8 +7,8 @@ import pytest
@pytest.mark.parametrize(
"module_name",
[
- "tutorial001_py39",
- "tutorial002_py39",
+ "tutorial001_py310",
+ "tutorial002_py310",
],
)
def test_run_module(module_name: str):
diff --git a/tests/test_tutorial/test_python_types/test_tutorial003.py b/tests/test_tutorial/test_python_types/test_tutorial003.py
index 34d264917..20b1e7101 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial003.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial003.py
@@ -1,6 +1,6 @@
import pytest
-from docs_src.python_types.tutorial003_py39 import get_name_with_age
+from docs_src.python_types.tutorial003_py310 import get_name_with_age
def test_get_name_with_age_pass_int():
diff --git a/tests/test_tutorial/test_python_types/test_tutorial004.py b/tests/test_tutorial/test_python_types/test_tutorial004.py
index 24af32883..0b16c0cb4 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial004.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial004.py
@@ -1,4 +1,4 @@
-from docs_src.python_types.tutorial004_py39 import get_name_with_age
+from docs_src.python_types.tutorial004_py310 import get_name_with_age
def test_get_name_with_age_pass_int():
diff --git a/tests/test_tutorial/test_python_types/test_tutorial005.py b/tests/test_tutorial/test_python_types/test_tutorial005.py
index 6d67ec471..b5c847523 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial005.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial005.py
@@ -1,4 +1,4 @@
-from docs_src.python_types.tutorial005_py39 import get_items
+from docs_src.python_types.tutorial005_py310 import get_items
def test_get_items():
diff --git a/tests/test_tutorial/test_python_types/test_tutorial006.py b/tests/test_tutorial/test_python_types/test_tutorial006.py
index 50976926e..fbe929a76 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial006.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial006.py
@@ -1,6 +1,6 @@
from unittest.mock import patch
-from docs_src.python_types.tutorial006_py39 import process_items
+from docs_src.python_types.tutorial006_py310 import process_items
def test_process_items():
diff --git a/tests/test_tutorial/test_python_types/test_tutorial007.py b/tests/test_tutorial/test_python_types/test_tutorial007.py
index c04529465..b664d2784 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial007.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial007.py
@@ -1,4 +1,4 @@
-from docs_src.python_types.tutorial007_py39 import process_items
+from docs_src.python_types.tutorial007_py310 import process_items
def test_process_items():
diff --git a/tests/test_tutorial/test_python_types/test_tutorial008.py b/tests/test_tutorial/test_python_types/test_tutorial008.py
index 33cf6cbfb..74a4e9cac 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial008.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial008.py
@@ -1,6 +1,6 @@
from unittest.mock import patch
-from docs_src.python_types.tutorial008_py39 import process_items
+from docs_src.python_types.tutorial008_py310 import process_items
def test_process_items():
diff --git a/tests/test_tutorial/test_python_types/test_tutorial008b.py b/tests/test_tutorial/test_python_types/test_tutorial008b.py
index 1ef0d4ea1..60d7e51c1 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial008b.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial008b.py
@@ -10,7 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="module",
params=[
- pytest.param("tutorial008b_py39"),
+ pytest.param("tutorial008b_py310"),
pytest.param("tutorial008b_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_python_types/test_tutorial009_tutorial009b.py b/tests/test_tutorial/test_python_types/test_tutorial009_tutorial009b.py
index 34046c5c4..eec51b1be 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial009_tutorial009b.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial009_tutorial009b.py
@@ -10,9 +10,8 @@ from ...utils import needs_py310
@pytest.fixture(
name="module",
params=[
- pytest.param("tutorial009_py39"),
+ pytest.param("tutorial009_py310"),
pytest.param("tutorial009_py310", marks=needs_py310),
- pytest.param("tutorial009b_py39"),
],
)
def get_module(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_python_types/test_tutorial009c.py b/tests/test_tutorial/test_python_types/test_tutorial009c.py
index 7bd404911..17c4b9e0c 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial009c.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial009c.py
@@ -11,7 +11,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="module",
params=[
- pytest.param("tutorial009c_py39"),
+ pytest.param("tutorial009c_py310"),
pytest.param("tutorial009c_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_python_types/test_tutorial010.py b/tests/test_tutorial/test_python_types/test_tutorial010.py
index 9e4d2e36b..8525e6d84 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial010.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial010.py
@@ -1,4 +1,4 @@
-from docs_src.python_types.tutorial010_py39 import Person, get_person_name
+from docs_src.python_types.tutorial010_py310 import Person, get_person_name
def test_get_person_name():
diff --git a/tests/test_tutorial/test_python_types/test_tutorial011.py b/tests/test_tutorial/test_python_types/test_tutorial011.py
index a05751b97..3761eb924 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial011.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial011.py
@@ -9,7 +9,6 @@ from ...utils import needs_py310
@pytest.mark.parametrize(
"module_name",
[
- pytest.param("tutorial011_py39"),
pytest.param("tutorial011_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_python_types/test_tutorial012.py b/tests/test_tutorial/test_python_types/test_tutorial012.py
deleted file mode 100644
index e57804820..000000000
--- a/tests/test_tutorial/test_python_types/test_tutorial012.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from docs_src.python_types.tutorial012_py39 import User
-
-
-def test_user():
- user = User(name="John Doe", age=30)
- assert user.name == "John Doe"
- assert user.age == 30
diff --git a/tests/test_tutorial/test_python_types/test_tutorial013.py b/tests/test_tutorial/test_python_types/test_tutorial013.py
index 5602ef76f..d8669b485 100644
--- a/tests/test_tutorial/test_python_types/test_tutorial013.py
+++ b/tests/test_tutorial/test_python_types/test_tutorial013.py
@@ -1,4 +1,4 @@
-from docs_src.python_types.tutorial013_py39 import say_hello
+from docs_src.python_types.tutorial013_py310 import say_hello
def test_say_hello():
diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial001.py b/tests/test_tutorial/test_query_param_models/test_tutorial001.py
index 38b767154..75d1b9762 100644
--- a/tests/test_tutorial/test_query_param_models/test_tutorial001.py
+++ b/tests/test_tutorial/test_query_param_models/test_tutorial001.py
@@ -10,9 +10,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial002.py b/tests/test_tutorial/test_query_param_models/test_tutorial002.py
index b173a2df4..da2b6608a 100644
--- a/tests/test_tutorial/test_query_param_models/test_tutorial002.py
+++ b/tests/test_tutorial/test_query_param_models/test_tutorial002.py
@@ -10,9 +10,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=[needs_py310]),
- pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=[needs_py310]),
],
)
diff --git a/tests/test_tutorial/test_query_params/test_tutorial001.py b/tests/test_tutorial/test_query_params/test_tutorial001.py
index 40ada0e8e..d68702587 100644
--- a/tests/test_tutorial/test_query_params/test_tutorial001.py
+++ b/tests/test_tutorial/test_query_params/test_tutorial001.py
@@ -8,7 +8,7 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
+ pytest.param("tutorial001_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_query_params/test_tutorial002.py b/tests/test_tutorial/test_query_params/test_tutorial002.py
index 1da308a7e..9be507fba 100644
--- a/tests/test_tutorial/test_query_params/test_tutorial002.py
+++ b/tests/test_tutorial/test_query_params/test_tutorial002.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params/test_tutorial003.py b/tests/test_tutorial/test_query_params/test_tutorial003.py
index 9bb58ff9f..2951f1adf 100644
--- a/tests/test_tutorial/test_query_params/test_tutorial003.py
+++ b/tests/test_tutorial/test_query_params/test_tutorial003.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params/test_tutorial004.py b/tests/test_tutorial/test_query_params/test_tutorial004.py
index 20aadb3ac..9786f861f 100644
--- a/tests/test_tutorial/test_query_params/test_tutorial004.py
+++ b/tests/test_tutorial/test_query_params/test_tutorial004.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params/test_tutorial005.py b/tests/test_tutorial/test_query_params/test_tutorial005.py
index e023fe6d8..b21e97f0b 100644
--- a/tests/test_tutorial/test_query_params/test_tutorial005.py
+++ b/tests/test_tutorial/test_query_params/test_tutorial005.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.query_params.tutorial005_py39 import app
+from docs_src.query_params.tutorial005_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_query_params/test_tutorial006.py b/tests/test_tutorial/test_query_params/test_tutorial006.py
index b28e12655..a27f2bbb0 100644
--- a/tests/test_tutorial/test_query_params/test_tutorial006.py
+++ b/tests/test_tutorial/test_query_params/test_tutorial006.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial006_py39"),
pytest.param("tutorial006_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial001.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial001.py
index ed73b7329..1eb424e4f 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial001.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial001.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial002.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial002.py
index 3eac1f2b3..feb59f169 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial002.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial002.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial003.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial003.py
index 59d5160ac..4e1ef1da7 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial003.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial003.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
- pytest.param("tutorial003_an_py39"),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial004.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial004.py
index abf08c932..9c2d442c8 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial004.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial004.py
@@ -10,19 +10,8 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
- pytest.param("tutorial004_an_py39"),
pytest.param("tutorial004_an_py310", marks=needs_py310),
- pytest.param(
- "tutorial004_regex_an_py310",
- marks=(
- needs_py310,
- pytest.mark.filterwarnings(
- "ignore:`regex` has been deprecated, please use `pattern` instead:fastapi.exceptions.FastAPIDeprecationWarning"
- ),
- ),
- ),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial005.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial005.py
index 7b5368abc..61f07631b 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial005.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial005.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial005_py39"),
- pytest.param("tutorial005_an_py39"),
+ pytest.param("tutorial005_py310"),
+ pytest.param("tutorial005_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial006.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial006.py
index 2c1df2c08..18ee8dbdc 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial006.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial006.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial006_py39"),
- pytest.param("tutorial006_an_py39"),
+ pytest.param("tutorial006_py310"),
+ pytest.param("tutorial006_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial006c.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial006c.py
index 3df9efa83..74c10b885 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial006c.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial006c.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial006c_py39"),
pytest.param("tutorial006c_py310", marks=needs_py310),
- pytest.param("tutorial006c_an_py39"),
pytest.param("tutorial006c_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial007.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial007.py
index 874002b17..3a23ce4a4 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial007.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial007.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial007_py39"),
pytest.param("tutorial007_py310", marks=needs_py310),
- pytest.param("tutorial007_an_py39"),
pytest.param("tutorial007_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial008.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial008.py
index b9613a17b..430d1bc18 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial008.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial008.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial008_py39"),
pytest.param("tutorial008_py310", marks=needs_py310),
- pytest.param("tutorial008_an_py39"),
pytest.param("tutorial008_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial009.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial009.py
index d749d85f7..a81e1c40e 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial009.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial009.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial009_py39"),
pytest.param("tutorial009_py310", marks=needs_py310),
- pytest.param("tutorial009_an_py39"),
pytest.param("tutorial009_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py
index efe9f1fa6..bb8fbfcee 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py
@@ -11,9 +11,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial010_py39"),
pytest.param("tutorial010_py310", marks=needs_py310),
- pytest.param("tutorial010_an_py39"),
pytest.param("tutorial010_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py
index c25357fdd..8d558efec 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial011_py39"),
pytest.param("tutorial011_py310", marks=needs_py310),
- pytest.param("tutorial011_an_py39"),
pytest.param("tutorial011_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py
index c3d01e90e..5aae7fcc6 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial012_py39"),
- pytest.param("tutorial012_an_py39"),
+ pytest.param("tutorial012_py310"),
+ pytest.param("tutorial012_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
index 74efa4695..29d49a5b7 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- "tutorial013_py39",
- "tutorial013_an_py39",
+ "tutorial013_py310",
+ "tutorial013_an_py310",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py
index 6dff18b78..683e39795 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial014_py39"),
pytest.param("tutorial014_py310", marks=needs_py310),
- pytest.param("tutorial014_an_py39"),
pytest.param("tutorial014_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py
index 32a990e74..01d7c983a 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py
@@ -11,7 +11,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial015_an_py39"),
pytest.param("tutorial015_an_py310", marks=[needs_py310]),
],
)
diff --git a/tests/test_tutorial/test_request_files/test_tutorial001.py b/tests/test_tutorial/test_request_files/test_tutorial001.py
index fd5c3b055..4d3c35d65 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial001.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- "tutorial001_py39",
- "tutorial001_an_py39",
+ "tutorial001_py310",
+ "tutorial001_an_py310",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02.py b/tests/test_tutorial/test_request_files/test_tutorial001_02.py
index feeb5363e..f199b992a 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial001_02.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial001_02.py
@@ -11,9 +11,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_02_py39"),
pytest.param("tutorial001_02_py310", marks=needs_py310),
- pytest.param("tutorial001_02_an_py39"),
pytest.param("tutorial001_02_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_03.py b/tests/test_tutorial/test_request_files/test_tutorial001_03.py
index 5ef8df178..ce22c1b5c 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial001_03.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial001_03.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- "tutorial001_03_py39",
- "tutorial001_03_an_py39",
+ "tutorial001_03_py310",
+ "tutorial001_03_an_py310",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_request_files/test_tutorial002.py b/tests/test_tutorial/test_request_files/test_tutorial002.py
index 52655fd63..ebf76b3a0 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial002.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial002.py
@@ -9,8 +9,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="app",
params=[
- "tutorial002_py39",
- "tutorial002_an_py39",
+ "tutorial002_py310",
+ "tutorial002_an_py310",
],
)
def get_app(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_request_files/test_tutorial003.py b/tests/test_tutorial/test_request_files/test_tutorial003.py
index a1425ba33..f11658d27 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial003.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial003.py
@@ -9,8 +9,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="app",
params=[
- "tutorial003_py39",
- "tutorial003_an_py39",
+ "tutorial003_py310",
+ "tutorial003_an_py310",
],
)
def get_app(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001.py b/tests/test_tutorial/test_request_form_models/test_tutorial001.py
index 68fa074dc..3122e97e8 100644
--- a/tests/test_tutorial/test_request_form_models/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial001.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- "tutorial001_py39",
- "tutorial001_an_py39",
+ "tutorial001_py310",
+ "tutorial001_an_py310",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002.py b/tests/test_tutorial/test_request_form_models/test_tutorial002.py
index ed5ae109a..e5dc6e486 100644
--- a/tests/test_tutorial/test_request_form_models/test_tutorial002.py
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial002.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- "tutorial002_py39",
- "tutorial002_an_py39",
+ "tutorial002_py310",
+ "tutorial002_an_py310",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001.py b/tests/test_tutorial/test_request_forms/test_tutorial001.py
index d1596f137..ff3421aac 100644
--- a/tests/test_tutorial/test_request_forms/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_forms/test_tutorial001.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- "tutorial001_py39",
- "tutorial001_an_py39",
+ "tutorial001_py310",
+ "tutorial001_an_py310",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py
index 6e9165c42..e2462e040 100644
--- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py
@@ -9,8 +9,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="app",
params=[
- "tutorial001_py39",
- "tutorial001_an_py39",
+ "tutorial001_py310",
+ "tutorial001_an_py310",
],
)
def get_app(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_response_change_status_code/test_tutorial001.py b/tests/test_tutorial/test_response_change_status_code/test_tutorial001.py
index 05d5ca619..d046bd266 100644
--- a/tests/test_tutorial/test_response_change_status_code/test_tutorial001.py
+++ b/tests/test_tutorial/test_response_change_status_code/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_change_status_code.tutorial001_py39 import app
+from docs_src.response_change_status_code.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_cookies/test_tutorial001.py b/tests/test_tutorial/test_response_cookies/test_tutorial001.py
index 6b931c8bd..106898339 100644
--- a/tests/test_tutorial/test_response_cookies/test_tutorial001.py
+++ b/tests/test_tutorial/test_response_cookies/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_cookies.tutorial001_py39 import app
+from docs_src.response_cookies.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_cookies/test_tutorial002.py b/tests/test_tutorial/test_response_cookies/test_tutorial002.py
index 3ee5f500c..66812e480 100644
--- a/tests/test_tutorial/test_response_cookies/test_tutorial002.py
+++ b/tests/test_tutorial/test_response_cookies/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_cookies.tutorial002_py39 import app
+from docs_src.response_cookies.tutorial002_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_directly/test_tutorial001.py b/tests/test_tutorial/test_response_directly/test_tutorial001.py
index 2b034f1c9..54406684d 100644
--- a/tests/test_tutorial/test_response_directly/test_tutorial001.py
+++ b/tests/test_tutorial/test_response_directly/test_tutorial001.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_directly/test_tutorial002.py b/tests/test_tutorial/test_response_directly/test_tutorial002.py
index 047e82c14..7dcb8d292 100644
--- a/tests/test_tutorial/test_response_directly/test_tutorial002.py
+++ b/tests/test_tutorial/test_response_directly/test_tutorial002.py
@@ -8,7 +8,7 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_response_headers/test_tutorial001.py b/tests/test_tutorial/test_response_headers/test_tutorial001.py
index 6232aad23..ea182246f 100644
--- a/tests/test_tutorial/test_response_headers/test_tutorial001.py
+++ b/tests/test_tutorial/test_response_headers/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_headers.tutorial001_py39 import app
+from docs_src.response_headers.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_headers/test_tutorial002.py b/tests/test_tutorial/test_response_headers/test_tutorial002.py
index 2ac2226cb..9b90459cb 100644
--- a/tests/test_tutorial/test_response_headers/test_tutorial002.py
+++ b/tests/test_tutorial/test_response_headers/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_headers.tutorial002_py39 import app
+from docs_src.response_headers.tutorial002_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial001_tutorial001_01.py b/tests/test_tutorial/test_response_model/test_tutorial001_tutorial001_01.py
index 914f53783..bbdcc6820 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial001_tutorial001_01.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial001_tutorial001_01.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_01_py39"),
pytest.param("tutorial001_01_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial002.py b/tests/test_tutorial/test_response_model/test_tutorial002.py
index 10a4e37cd..31b465990 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial002.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial002.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003.py b/tests/test_tutorial/test_response_model/test_tutorial003.py
index a1477b7df..8178c8196 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_01.py b/tests/test_tutorial/test_response_model/test_tutorial003_01.py
index a60a14ae8..1a0c4f260 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003_01.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003_01.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_01_py39"),
pytest.param("tutorial003_01_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_02.py b/tests/test_tutorial/test_response_model/test_tutorial003_02.py
index 460c88251..a28c56be9 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003_02.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003_02.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.response_model.tutorial003_02_py39 import app
+from docs_src.response_model.tutorial003_02_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_03.py b/tests/test_tutorial/test_response_model/test_tutorial003_03.py
index c83d78c4f..65e747022 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003_03.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003_03.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.response_model.tutorial003_03_py39 import app
+from docs_src.response_model.tutorial003_03_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_04.py b/tests/test_tutorial/test_response_model/test_tutorial003_04.py
index 145af126f..44f2e504e 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003_04.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003_04.py
@@ -9,7 +9,6 @@ from ...utils import needs_py310
@pytest.mark.parametrize(
"module_name",
[
- pytest.param("tutorial003_04_py39"),
pytest.param("tutorial003_04_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_05.py b/tests/test_tutorial/test_response_model/test_tutorial003_05.py
index 187b6491f..0f0e94fda 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003_05.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003_05.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_05_py39"),
pytest.param("tutorial003_05_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial004.py b/tests/test_tutorial/test_response_model/test_tutorial004.py
index d40bce261..e7c0e79f2 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial004.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial004.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial005.py b/tests/test_tutorial/test_response_model/test_tutorial005.py
index 55b2334d4..75c8fc0ac 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial005.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial005.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial006.py b/tests/test_tutorial/test_response_model/test_tutorial006.py
index 5d6f542b5..f80ce1b28 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial006.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial006.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial006_py39"),
pytest.param("tutorial006_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_status_code/test_tutorial001_tutorial002.py b/tests/test_tutorial/test_response_status_code/test_tutorial001_tutorial002.py
index 7199ceed6..69c32f92e 100644
--- a/tests/test_tutorial/test_response_status_code/test_tutorial001_tutorial002.py
+++ b/tests/test_tutorial/test_response_status_code/test_tutorial001_tutorial002.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
- pytest.param("tutorial002_py39"),
+ pytest.param("tutorial001_py310"),
+ pytest.param("tutorial002_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py
index f19346a3a..126dfbe7d 100644
--- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py
+++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial002.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial002.py
index 8313cb14f..cac3337a2 100644
--- a/tests/test_tutorial/test_schema_extra_example/test_tutorial002.py
+++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial002.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial003.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial003.py
index 3c45a64bc..1ccca4da8 100644
--- a/tests/test_tutorial/test_schema_extra_example/test_tutorial003.py
+++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial003.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
- pytest.param("tutorial003_an_py39"),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py
index 4b8e15fa1..cffd27066 100644
--- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py
+++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
- pytest.param("tutorial004_an_py39"),
pytest.param("tutorial004_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py
index 7f8e36df2..0bc17a00e 100644
--- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py
+++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
- pytest.param("tutorial005_an_py39"),
pytest.param("tutorial005_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_security/test_tutorial001.py b/tests/test_tutorial/test_security/test_tutorial001.py
index 5742b51bf..c1a15ae00 100644
--- a/tests/test_tutorial/test_security/test_tutorial001.py
+++ b/tests/test_tutorial/test_security/test_tutorial001.py
@@ -8,8 +8,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
- pytest.param("tutorial001_an_py39"),
+ pytest.param("tutorial001_py310"),
+ pytest.param("tutorial001_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_security/test_tutorial002.py b/tests/test_tutorial/test_security/test_tutorial002.py
index 1e8c6e018..4d1202c32 100644
--- a/tests/test_tutorial/test_security/test_tutorial002.py
+++ b/tests/test_tutorial/test_security/test_tutorial002.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_security/test_tutorial003.py b/tests/test_tutorial/test_security/test_tutorial003.py
index acd910c71..45f4e57bb 100644
--- a/tests/test_tutorial/test_security/test_tutorial003.py
+++ b/tests/test_tutorial/test_security/test_tutorial003.py
@@ -10,9 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
- pytest.param("tutorial003_an_py39"),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_security/test_tutorial004.py b/tests/test_tutorial/test_security/test_tutorial004.py
index e842c92a1..e52a029bd 100644
--- a/tests/test_tutorial/test_security/test_tutorial004.py
+++ b/tests/test_tutorial/test_security/test_tutorial004.py
@@ -12,9 +12,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="mod",
params=[
- pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
- pytest.param("tutorial004_an_py39"),
pytest.param("tutorial004_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_security/test_tutorial005.py b/tests/test_tutorial/test_security/test_tutorial005.py
index 76b08860f..c6e0e78e0 100644
--- a/tests/test_tutorial/test_security/test_tutorial005.py
+++ b/tests/test_tutorial/test_security/test_tutorial005.py
@@ -11,9 +11,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="mod",
params=[
- pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
- pytest.param("tutorial005_an_py39"),
pytest.param("tutorial005_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_security/test_tutorial006.py b/tests/test_tutorial/test_security/test_tutorial006.py
index 1c96f62ae..671946d97 100644
--- a/tests/test_tutorial/test_security/test_tutorial006.py
+++ b/tests/test_tutorial/test_security/test_tutorial006.py
@@ -9,8 +9,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial006_py39"),
- pytest.param("tutorial006_an_py39"),
+ pytest.param("tutorial006_py310"),
+ pytest.param("tutorial006_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_security/test_tutorial007.py b/tests/test_tutorial/test_security/test_tutorial007.py
index 24667422f..e73545753 100644
--- a/tests/test_tutorial/test_security/test_tutorial007.py
+++ b/tests/test_tutorial/test_security/test_tutorial007.py
@@ -9,8 +9,8 @@ from inline_snapshot import snapshot
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial007_py39"),
- pytest.param("tutorial007_an_py39"),
+ pytest.param("tutorial007_py310"),
+ pytest.param("tutorial007_an_py310"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py
index 0be3b59f9..653b20c7d 100644
--- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py
+++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py
index 87c63f69e..0ef706a4d 100644
--- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py
+++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py
@@ -10,7 +10,6 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_settings/test_app01.py b/tests/test_tutorial/test_settings/test_app01.py
index 52b9b1e62..da27308e8 100644
--- a/tests/test_tutorial/test_settings/test_app01.py
+++ b/tests/test_tutorial/test_settings/test_app01.py
@@ -12,7 +12,7 @@ from pytest import MonkeyPatch
@pytest.fixture(
name="mod_name",
params=[
- pytest.param("app01_py39"),
+ pytest.param("app01_py310"),
],
)
def get_mod_name(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_settings/test_app02.py b/tests/test_tutorial/test_settings/test_app02.py
index 9cbed4fd1..20594ebb7 100644
--- a/tests/test_tutorial/test_settings/test_app02.py
+++ b/tests/test_tutorial/test_settings/test_app02.py
@@ -8,8 +8,8 @@ from pytest import MonkeyPatch
@pytest.fixture(
name="mod_path",
params=[
- pytest.param("app02_py39"),
- pytest.param("app02_an_py39"),
+ pytest.param("app02_py310"),
+ pytest.param("app02_an_py310"),
],
)
def get_mod_path(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_settings/test_app03.py b/tests/test_tutorial/test_settings/test_app03.py
index 72de49796..f4539c96d 100644
--- a/tests/test_tutorial/test_settings/test_app03.py
+++ b/tests/test_tutorial/test_settings/test_app03.py
@@ -9,8 +9,8 @@ from pytest import MonkeyPatch
@pytest.fixture(
name="mod_path",
params=[
- pytest.param("app03_py39"),
- pytest.param("app03_an_py39"),
+ pytest.param("app03_py310"),
+ pytest.param("app03_an_py310"),
],
)
def get_mod_path(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_settings/test_tutorial001.py b/tests/test_tutorial/test_settings/test_tutorial001.py
index f4576a0d2..8857c35df 100644
--- a/tests/test_tutorial/test_settings/test_tutorial001.py
+++ b/tests/test_tutorial/test_settings/test_tutorial001.py
@@ -5,7 +5,7 @@ from fastapi.testclient import TestClient
from pytest import MonkeyPatch
-@pytest.fixture(name="app", params=[pytest.param("tutorial001_py39")])
+@pytest.fixture(name="app", params=[pytest.param("tutorial001_py310")])
def get_app(request: pytest.FixtureRequest, monkeypatch: MonkeyPatch):
monkeypatch.setenv("ADMIN_EMAIL", "admin@example.com")
mod = importlib.import_module(f"docs_src.settings.{request.param}")
diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_sql_databases/test_tutorial001.py
index aec20e42e..3407ec758 100644
--- a/tests/test_tutorial/test_sql_databases/test_tutorial001.py
+++ b/tests/test_tutorial/test_sql_databases/test_tutorial001.py
@@ -22,9 +22,7 @@ def clear_sqlmodel():
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial002.py b/tests/test_tutorial/test_sql_databases/test_tutorial002.py
index 4ea7d5f64..51a36b6c7 100644
--- a/tests/test_tutorial/test_sql_databases/test_tutorial002.py
+++ b/tests/test_tutorial/test_sql_databases/test_tutorial002.py
@@ -22,9 +22,7 @@ def clear_sqlmodel():
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_static_files/test_tutorial001.py b/tests/test_tutorial/test_static_files/test_tutorial001.py
index dd93fee79..1d57310f3 100644
--- a/tests/test_tutorial/test_static_files/test_tutorial001.py
+++ b/tests/test_tutorial/test_static_files/test_tutorial001.py
@@ -12,7 +12,7 @@ def client():
static_dir.mkdir(exist_ok=True)
sample_file = static_dir / "sample.txt"
sample_file.write_text("This is a sample static file.")
- from docs_src.static_files.tutorial001_py39 import app
+ from docs_src.static_files.tutorial001_py310 import app
with TestClient(app) as client:
yield client
diff --git a/tests/test_tutorial/test_sub_applications/test_tutorial001.py b/tests/test_tutorial/test_sub_applications/test_tutorial001.py
index a8fb3dc36..63fb68fb2 100644
--- a/tests/test_tutorial/test_sub_applications/test_tutorial001.py
+++ b/tests/test_tutorial/test_sub_applications/test_tutorial001.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.sub_applications.tutorial001_py39 import app
+from docs_src.sub_applications.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_templates/test_tutorial001.py b/tests/test_tutorial/test_templates/test_tutorial001.py
index 818508037..04bc3fce8 100644
--- a/tests/test_tutorial/test_templates/test_tutorial001.py
+++ b/tests/test_tutorial/test_templates/test_tutorial001.py
@@ -11,7 +11,7 @@ def test_main():
shutil.rmtree("./templates")
shutil.copytree("./docs_src/templates/templates/", "./templates")
shutil.copytree("./docs_src/templates/static/", "./static")
- from docs_src.templates.tutorial001_py39 import app
+ from docs_src.templates.tutorial001_py310 import app
client = TestClient(app)
response = client.get("/items/foo")
diff --git a/tests/test_tutorial/test_testing/test_main_a.py b/tests/test_tutorial/test_testing/test_main_a.py
index 528488805..d071d5309 100644
--- a/tests/test_tutorial/test_testing/test_main_a.py
+++ b/tests/test_tutorial/test_testing/test_main_a.py
@@ -1,6 +1,6 @@
from inline_snapshot import snapshot
-from docs_src.app_testing.app_a_py39.test_main import client, test_read_main
+from docs_src.app_testing.app_a_py310.test_main import client, test_read_main
def test_main():
diff --git a/tests/test_tutorial/test_testing/test_main_b.py b/tests/test_tutorial/test_testing/test_main_b.py
index 3d679cd5a..2d042fd69 100644
--- a/tests/test_tutorial/test_testing/test_main_b.py
+++ b/tests/test_tutorial/test_testing/test_main_b.py
@@ -9,9 +9,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="test_module",
params=[
- "app_b_py39.test_main",
pytest.param("app_b_py310.test_main", marks=needs_py310),
- "app_b_an_py39.test_main",
pytest.param("app_b_an_py310.test_main", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_testing/test_tutorial001.py b/tests/test_tutorial/test_testing/test_tutorial001.py
index 2b501d36a..b9bb182b7 100644
--- a/tests/test_tutorial/test_testing/test_tutorial001.py
+++ b/tests/test_tutorial/test_testing/test_tutorial001.py
@@ -1,6 +1,6 @@
from inline_snapshot import snapshot
-from docs_src.app_testing.tutorial001_py39 import client, test_read_main
+from docs_src.app_testing.tutorial001_py310 import client, test_read_main
def test_main():
diff --git a/tests/test_tutorial/test_testing/test_tutorial002.py b/tests/test_tutorial/test_testing/test_tutorial002.py
index cc9b5ba27..840248dc3 100644
--- a/tests/test_tutorial/test_testing/test_tutorial002.py
+++ b/tests/test_tutorial/test_testing/test_tutorial002.py
@@ -1,4 +1,4 @@
-from docs_src.app_testing.tutorial002_py39 import test_read_main, test_websocket
+from docs_src.app_testing.tutorial002_py310 import test_read_main, test_websocket
def test_main():
diff --git a/tests/test_tutorial/test_testing/test_tutorial003.py b/tests/test_tutorial/test_testing/test_tutorial003.py
index 4faa820e9..196fc4555 100644
--- a/tests/test_tutorial/test_testing/test_tutorial003.py
+++ b/tests/test_tutorial/test_testing/test_tutorial003.py
@@ -3,5 +3,5 @@ import pytest
def test_main():
with pytest.warns(DeprecationWarning):
- from docs_src.app_testing.tutorial003_py39 import test_read_items
+ from docs_src.app_testing.tutorial003_py310 import test_read_items
test_read_items()
diff --git a/tests/test_tutorial/test_testing/test_tutorial004.py b/tests/test_tutorial/test_testing/test_tutorial004.py
index c95214ffe..d5de1bb60 100644
--- a/tests/test_tutorial/test_testing/test_tutorial004.py
+++ b/tests/test_tutorial/test_testing/test_tutorial004.py
@@ -1,4 +1,4 @@
-from docs_src.app_testing.tutorial004_py39 import test_read_items
+from docs_src.app_testing.tutorial004_py310 import test_read_items
def test_main():
diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py
index 6e9656bf5..81491276e 100644
--- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py
+++ b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py
@@ -9,9 +9,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="test_module",
params=[
- pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_using_request_directly/test_tutorial001.py b/tests/test_tutorial/test_using_request_directly/test_tutorial001.py
index cb8ae8b05..4145177e4 100644
--- a/tests/test_tutorial/test_using_request_directly/test_tutorial001.py
+++ b/tests/test_tutorial/test_using_request_directly/test_tutorial001.py
@@ -1,7 +1,7 @@
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from docs_src.using_request_directly.tutorial001_py39 import app
+from docs_src.using_request_directly.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_websockets/test_tutorial001.py b/tests/test_tutorial/test_websockets/test_tutorial001.py
index 4f8368db2..6f3bf1429 100644
--- a/tests/test_tutorial/test_websockets/test_tutorial001.py
+++ b/tests/test_tutorial/test_websockets/test_tutorial001.py
@@ -2,7 +2,7 @@ import pytest
from fastapi.testclient import TestClient
from fastapi.websockets import WebSocketDisconnect
-from docs_src.websockets.tutorial001_py39 import app
+from docs_src.websockets.tutorial001_py310 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_websockets/test_tutorial002.py b/tests/test_tutorial/test_websockets/test_tutorial002.py
index ebf1fc8e8..0509b0d0d 100644
--- a/tests/test_tutorial/test_websockets/test_tutorial002.py
+++ b/tests/test_tutorial/test_websockets/test_tutorial002.py
@@ -11,9 +11,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="app",
params=[
- pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_websockets/test_tutorial003.py b/tests/test_tutorial/test_websockets/test_tutorial003.py
index 0be1fc81d..781146371 100644
--- a/tests/test_tutorial/test_websockets/test_tutorial003.py
+++ b/tests/test_tutorial/test_websockets/test_tutorial003.py
@@ -8,7 +8,7 @@ from fastapi.testclient import TestClient
@pytest.fixture(
name="mod",
params=[
- pytest.param("tutorial003_py39"),
+ pytest.param("tutorial003_py310"),
],
)
def get_mod(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_wsgi/test_tutorial001.py b/tests/test_tutorial/test_wsgi/test_tutorial001.py
index 9fe8c2a4b..9bcd56dfc 100644
--- a/tests/test_tutorial/test_wsgi/test_tutorial001.py
+++ b/tests/test_tutorial/test_wsgi/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.wsgi.tutorial001_py39 import app
+from docs_src.wsgi.tutorial001_py310 import app
client = TestClient(app)
From 0e460654af7101866b7d0f22735ef6337fe13d0c Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
@@ -289,7 +289,7 @@
Ваш сервер(а) — это **ресурс**, который ваши программы могут потреблять или **использовать**: время вычислений на CPU и доступную оперативную память (RAM).
-Какую долю системных ресурсов вы хотите потреблять/использовать? Можно подумать «немного», но на практике вы, скорее всего, захотите потреблять **максимум без падений**.
+Какую долю системных ресурсов вы хотите потреблять/использовать? Можно подумать «немного», но на практике вы, вероятно, захотите потреблять **максимум без падений**.
Если вы платите за 3 сервера, но используете лишь малую часть их RAM и CPU, вы, вероятно, **тратите деньги впустую** 💸 и **электроэнергию серверов** 🌎 и т.п.
diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md
index 9e8562be7..791057fe5 100644
--- a/docs/ru/docs/deployment/docker.md
+++ b/docs/ru/docs/deployment/docker.md
@@ -14,7 +14,7 @@
-Если вы создаёте приложение CLI для использования в терминале вместо веб-API, посмотрите **Typer**.
+Если вы создаёте приложение CLI для использования в терминале вместо веб-API, посмотрите **Typer**.
**Typer** — младший брат FastAPI. И он задуман как **FastAPI для CLI**. ⌨️ 🚀
@@ -368,7 +368,7 @@ item: Item
* Валидацию данных:
* Автоматические и понятные ошибки, когда данные некорректны.
* Валидацию даже для глубоко вложенных объектов JSON.
-* Преобразование входных данных: из сети в данные и типы Python. Чтение из:
+* Преобразование входных данных: из сети в данные и типы Python. Чтение из:
* JSON.
* Параметров пути.
* Параметров запроса.
@@ -376,7 +376,7 @@ item: Item
* HTTP-заголовков.
* Форм.
* Файлов.
-* Преобразование выходных данных: из данных и типов Python в данные сети (например, JSON):
+* Преобразование выходных данных: из данных и типов Python в данные сети (например, JSON):
* Преобразование типов Python (`str`, `int`, `float`, `bool`, `list` и т.д.).
* Объекты `datetime`.
* Объекты `UUID`.
@@ -439,7 +439,7 @@ item: Item
* Объявление **параметров** из других источников: **HTTP-заголовки**, **cookies**, **поля формы** и **файлы**.
* Как задать **ограничения валидации** вроде `maximum_length` или `regex`.
-* Очень мощную и простую в использовании систему **внедрения зависимостей**.
+* Очень мощную и простую в использовании систему **внедрения зависимостей**.
* Безопасность и аутентификацию, включая поддержку **OAuth2** с **JWT токенами** и **HTTP Basic** аутентификацию.
* Более продвинутые (но столь же простые) приёмы объявления **глубоко вложенных JSON-моделей** (спасибо Pydantic).
* Интеграцию **GraphQL** с Strawberry и другими библиотеками.
@@ -524,7 +524,7 @@ FastAPI зависит от Pydantic и Starlette.
*
httpx — обязателен, если вы хотите использовать `TestClient`.
* jinja2 — обязателен, если вы хотите использовать конфигурацию шаблонов по умолчанию.
-* python-multipart - обязателен, если вы хотите поддерживать «парсинг» форм через `request.form()`.
+* python-multipart - обязателен, если вы хотите поддерживать «парсинг» форм через `request.form()`.
Используется FastAPI:
diff --git a/docs/ru/docs/project-generation.md b/docs/ru/docs/project-generation.md
index dbedf76fe..8155457e3 100644
--- a/docs/ru/docs/project-generation.md
+++ b/docs/ru/docs/project-generation.md
@@ -18,7 +18,7 @@
- 🤖 Автоматически сгенерированный фронтенд‑клиент.
- 🧪 [Playwright](https://playwright.dev) для End‑to‑End тестирования.
- 🦇 Поддержка тёмной темы.
-- 🐋 [Docker Compose](https://www.docker.com) для разработки и продакшна.
+- 🐋 [Docker Compose](https://www.docker.com) для разработки и продакшн.
- 🔒 Безопасное хэширование паролей по умолчанию.
- 🔑 Аутентификация по JWT‑токенам.
- 📫 Восстановление пароля по электронной почте.
diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md
index ae4a1e2b7..95153c388 100644
--- a/docs/ru/docs/python-types.md
+++ b/docs/ru/docs/python-types.md
@@ -2,7 +2,7 @@
Python поддерживает необязательные «подсказки типов» (их также называют «аннотациями типов»).
-Эти **«подсказки типов»** или аннотации — это специальный синтаксис, позволяющий объявлять тип переменной.
+Эти **«подсказки типов»** или аннотации — это специальный синтаксис, позволяющий объявлять тип переменной.
Объявляя типы для ваших переменных, редакторы кода и инструменты смогут лучше вас поддерживать.
@@ -22,7 +22,7 @@ Python поддерживает необязательные «подсказк
Давайте начнем с простого примера:
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
Вызов этой программы выводит:
@@ -34,9 +34,9 @@ John Doe
* Принимает `first_name` и `last_name`.
* Преобразует первую букву каждого значения в верхний регистр с помощью `title()`.
-* Соединяет их пробелом посередине.
+* Соединяет их пробелом посередине.
-{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
### Отредактируем пример { #edit-it }
@@ -78,7 +78,7 @@ John Doe
Это и есть «подсказки типов»:
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
Это не то же самое, что объявление значений по умолчанию, как, например:
@@ -106,7 +106,7 @@ John Doe
Посмотрите на эту функцию — у неё уже есть подсказки типов:
-{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
Так как редактор кода знает типы переменных, вы получаете не только автозавершение, но и проверки ошибок:
@@ -114,7 +114,7 @@ John Doe
Теперь вы знаете, что нужно исправить — преобразовать `age` в строку с помощью `str(age)`:
-{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
## Объявление типов { #declaring-types }
@@ -133,29 +133,32 @@ John Doe
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### Generic-типы с параметрами типов { #generic-types-with-type-parameters }
+### Модуль `typing` { #typing-module }
-Есть структуры данных, которые могут содержать другие значения, например, `dict`, `list`, `set` и `tuple`. И внутренние значения тоже могут иметь свой тип.
+Для некоторых дополнительных сценариев может понадобиться импортировать что-то из стандартного модуля `typing`. Например, когда вы хотите объявить, что что-то имеет «любой тип», можно использовать `Any` из `typing`:
-Такие типы, которые содержат внутренние типы, называют «**generic**»-типами. И их можно объявлять, в том числе с указанием внутренних типов.
+```python
+from typing import Any
-Чтобы объявлять эти типы и их внутренние типы, вы можете использовать стандартный модуль Python `typing`. Он существует специально для поддержки подсказок типов.
-#### Новые версии Python { #newer-versions-of-python }
+def some_function(data: Any):
+ print(data)
+```
-Синтаксис с использованием `typing` **совместим** со всеми версиями, от Python 3.6 до самых новых, включая Python 3.9, Python 3.10 и т.д.
+### Generic-типы { #generic-types }
-По мере развития Python **новые версии** получают улучшенную поддержку этих аннотаций типов, и во многих случаях вам даже не нужно импортировать и использовать модуль `typing`, чтобы объявлять аннотации типов.
+Некоторые типы могут принимать «параметры типов» в квадратных скобках, чтобы определить их внутренние типы. Например, «список строк» объявляется как `list[str]`.
-Если вы можете выбрать более свежую версию Python для проекта, вы получите дополнительную простоту.
+Такие типы, которые принимают параметры типов, называются **Generic-типами** или **Generics**.
-Во всей документации есть примеры, совместимые с каждой версией Python (когда есть различия).
+Вы можете использовать те же встроенные типы как generics (с квадратными скобками и типами внутри):
-Например, «**Python 3.6+**» означает совместимость с Python 3.6 и выше (включая 3.7, 3.8, 3.9, 3.10 и т.д.). А «**Python 3.9+**» — совместимость с Python 3.9 и выше (включая 3.10 и т.п.).
-
-Если вы можете использовать **последние версии Python**, используйте примеры для самой новой версии — у них будет **самый лучший и простой синтаксис**, например, «**Python 3.10+**».
+* `list`
+* `tuple`
+* `set`
+* `dict`
#### List { #list }
@@ -167,7 +170,7 @@ John Doe
Так как список — это тип, содержащий внутренние типы, укажите их в квадратных скобках:
-{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
/// info | Информация
@@ -193,7 +196,7 @@ John Doe
Аналогично вы бы объявили `tuple` и `set`:
-{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
Это означает:
@@ -208,7 +211,7 @@ John Doe
Второй параметр типа — для значений `dict`:
-{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Это означает:
@@ -220,44 +223,20 @@ John Doe
Вы можете объявить, что переменная может быть **одним из нескольких типов**, например, `int` или `str`.
-В Python 3.6 и выше (включая Python 3.10) вы можете использовать тип `Union` из `typing` и перечислить в квадратных скобках все допустимые типы.
+Чтобы это определить, используйте вертикальную черту (`|`) для разделения обоих типов.
-В Python 3.10 также появился **новый синтаксис**, где допустимые типы можно указать через вертикальную черту (`|`).
-
-//// tab | Python 3.10+
+Это называется «объединение» (union), потому что переменная может быть чем угодно из объединения этих двух множеств типов.
```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-////
-
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b_py39.py!}
-```
-
-////
-
-В обоих случаях это означает, что `item` может быть `int` или `str`.
+Это означает, что `item` может быть `int` или `str`.
#### Возможно `None` { #possibly-none }
Вы можете объявить, что значение может иметь определённый тип, например `str`, но также может быть и `None`.
-В Python 3.6 и выше (включая Python 3.10) это можно объявить, импортировав и используя `Optional` из модуля `typing`.
-
-```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-Использование `Optional[str]` вместо просто `str` позволит редактору кода помочь вам обнаружить ошибки, когда вы предполагаете, что значение всегда `str`, хотя на самом деле оно может быть и `None`.
-
-`Optional[Something]` — это на самом деле сокращение для `Union[Something, None]`, они эквивалентны.
-
-Это также означает, что в Python 3.10 вы можете использовать `Something | None`:
-
//// tab | Python 3.10+
```Python hl_lines="1"
@@ -266,96 +245,7 @@ John Doe
////
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-////
-
-//// tab | Python 3.9+ альтернативный вариант
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b_py39.py!}
-```
-
-////
-
-#### Использовать `Union` или `Optional` { #using-union-or-optional }
-
-Если вы используете версию Python ниже 3.10, вот совет с моей весьма **субъективной** точки зрения:
-
-* 🚨 Избегайте использования `Optional[SomeType]`
-* Вместо этого ✨ **используйте `Union[SomeType, None]`** ✨.
-
-Оба варианта эквивалентны и внутри одинаковы, но я бы рекомендовал `Union` вместо `Optional`, потому что слово «**optional**» («необязательный») может навести на мысль, что значение необязательное, хотя на самом деле оно означает «может быть `None`», даже если параметр не является необязательным и всё ещё обязателен.
-
-Мне кажется, `Union[SomeType, None]` более явно выражает смысл.
-
-Речь только о словах и названиях. Но эти слова могут влиять на то, как вы и ваши коллеги думаете о коде.
-
-В качестве примера возьмём эту функцию:
-
-{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
-
-Параметр `name` определён как `Optional[str]`, но он **не необязательный** — вы не можете вызвать функцию без этого параметра:
-
-```Python
-say_hi() # О нет, это вызывает ошибку! 😱
-```
-
-Параметр `name` всё ещё **обязателен** (не *optional*), потому что у него нет значения по умолчанию. При этом `name` принимает `None` как значение:
-
-```Python
-say_hi(name=None) # Это работает, None допустим 🎉
-```
-
-Хорошая новость: как только вы перейдёте на Python 3.10, об этом можно не переживать — вы сможете просто использовать `|` для объединения типов:
-
-{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
-
-И тогда вам не придётся задумываться о названиях вроде `Optional` и `Union`. 😎
-
-#### Generic-типы { #generic-types }
-
-Типы, которые принимают параметры типов в квадратных скобках, называются **Generic-типами** или **Generics**, например:
-
-//// tab | Python 3.10+
-
-Вы можете использовать те же встроенные типы как generics (с квадратными скобками и типами внутри):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-И, как и в предыдущих версиях Python, из модуля `typing`:
-
-* `Union`
-* `Optional`
-* ...и другие.
-
-В Python 3.10, как альтернативу generics `Union` и `Optional`, можно использовать вертикальную черту (`|`) для объявления объединений типов — это гораздо лучше и проще.
-
-////
-
-//// tab | Python 3.9+
-
-Вы можете использовать те же встроенные типы как generics (с квадратными скобками и типами внутри):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-И generics из модуля `typing`:
-
-* `Union`
-* `Optional`
-* ...и другие.
-
-////
+Использование `str | None` вместо просто `str` позволит редактору кода помочь вам обнаружить ошибки, когда вы предполагаете, что значение всегда `str`, хотя на самом деле оно может быть и `None`.
### Классы как типы { #classes-as-types }
@@ -363,11 +253,11 @@ say_hi(name=None) # Это работает, None допустим 🎉
Допустим, у вас есть класс `Person` с именем:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
Тогда вы можете объявить переменную типа `Person`:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
И снова вы получите полную поддержку редактора кода:
@@ -401,21 +291,15 @@ say_hi(name=None) # Это работает, None допустим 🎉
**FastAPI** целиком основан на Pydantic.
-Вы увидите намного больше всего этого на практике в [Руководстве пользователя](tutorial/index.md){.internal-link target=_blank}.
-
-/// tip | Совет
-
-У Pydantic есть особое поведение, когда вы используете `Optional` или `Union[Something, None]` без значения по умолчанию. Подробнее читайте в документации Pydantic: Required Optional fields.
-
-///
+Вы увидите намного больше всего этого на практике в [Учебник - Руководство пользователя](tutorial/index.md){.internal-link target=_blank}.
## Подсказки типов с аннотациями метаданных { #type-hints-with-metadata-annotations }
-В Python также есть возможность добавлять **дополнительные метаданные** к подсказкам типов с помощью `Annotated`.
+В Python также есть возможность добавлять **дополнительные метаданные** к подсказкам типов с помощью `Annotated`.
-Начиная с Python 3.9, `Annotated` входит в стандартную библиотеку, поэтому вы можете импортировать его из `typing`.
+Вы можете импортировать `Annotated` из `typing`.
-{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
Сам Python ничего не делает с `Annotated`. А для редакторов кода и других инструментов тип по-прежнему `str`.
@@ -453,7 +337,7 @@ say_hi(name=None) # Это работает, None допустим 🎉
* **Документирования** API с использованием OpenAPI:
* что затем используется пользовательскими интерфейсами автоматической интерактивной документации.
-Всё это может звучать абстрактно. Не волнуйтесь. Вы увидите всё это в действии в [Руководстве пользователя](tutorial/index.md){.internal-link target=_blank}.
+Всё это может звучать абстрактно. Не волнуйтесь. Вы увидите всё это в действии в [Учебник - Руководство пользователя](tutorial/index.md){.internal-link target=_blank}.
Важно то, что, используя стандартные типы Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.), **FastAPI** сделает за вас большую часть работы.
diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md
index 8d7b7442f..9fa7a8502 100644
--- a/docs/ru/docs/tutorial/background-tasks.md
+++ b/docs/ru/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@
Сначала импортируйте `BackgroundTasks` и объявите параметр в вашей функции‑обработчике пути с типом `BackgroundTasks`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI** создаст объект типа `BackgroundTasks` для вас и передаст его через этот параметр.
@@ -31,13 +31,13 @@
Так как операция записи не использует `async` и `await`, мы определим функцию как обычную `def`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
## Добавление фоновой задачи { #add-the-background-task }
Внутри вашей функции‑обработчика пути передайте функцию задачи объекту фоновых задач методом `.add_task()`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` принимает следующие аргументы:
@@ -47,7 +47,7 @@
## Встраивание зависимостей { #dependency-injection }
-Использование `BackgroundTasks` также работает с системой встраивания зависимостей, вы можете объявить параметр типа `BackgroundTasks` на нескольких уровнях: в функции‑обработчике пути, в зависимости (dependable), в подзависимости и т. д.
+Использование `BackgroundTasks` также работает с системой встраивания зависимостей, вы можете объявить параметр типа `BackgroundTasks` на нескольких уровнях: в функции‑обработчике пути, в зависимости (dependable), в подзависимости и т.д.
**FastAPI** знает, что делать в каждом случае и как переиспользовать один и тот же объект, так чтобы все фоновые задачи были объединены и затем выполнены в фоне:
@@ -73,7 +73,7 @@
## Предостережение { #caveat }
-Если вам нужно выполнять тяжелые вычисления в фоне, и при этом они не обязательно должны запускаться тем же процессом (например, вам не нужно делиться памятью, переменными и т. п.), вам могут подойти более мощные инструменты, такие как Celery.
+Если вам нужно выполнять тяжелые вычисления в фоне, и при этом они не обязательно должны запускаться тем же процессом (например, вам не нужно делиться памятью, переменными и т.п.), вам могут подойти более мощные инструменты, такие как Celery.
Они обычно требуют более сложной конфигурации, менеджера очереди сообщений/заданий (например, RabbitMQ или Redis), но позволяют запускать фоновые задачи в нескольких процессах и, что особенно важно, на нескольких серверах.
diff --git a/docs/ru/docs/tutorial/bigger-applications.md b/docs/ru/docs/tutorial/bigger-applications.md
index 76304523c..3fb36d5a2 100644
--- a/docs/ru/docs/tutorial/bigger-applications.md
+++ b/docs/ru/docs/tutorial/bigger-applications.md
@@ -85,7 +85,7 @@ from app.routers import items
Точно так же, как и в случае с классом `FastAPI`, вам нужно импортировать и создать его «экземпляр»:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
### *Операции пути* с `APIRouter` { #path-operations-with-apirouter }
@@ -93,7 +93,7 @@ from app.routers import items
Используйте его так же, как вы использовали бы класс `FastAPI`:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
Вы можете думать об `APIRouter` как об «мини-классе `FastAPI`».
@@ -117,7 +117,7 @@ from app.routers import items
Теперь мы воспользуемся простой зависимостью, чтобы прочитать кастомный HTTP-заголовок `X-Token`:
-{* ../../docs_src/bigger_applications/app_an_py39/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
/// tip | Подсказка
@@ -149,7 +149,7 @@ from app.routers import items
Таким образом, вместо того чтобы добавлять всё это в каждую *операцию пути*, мы можем добавить это в `APIRouter`.
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
Так как путь каждой *операции пути* должен начинаться с `/`, как здесь:
@@ -208,7 +208,7 @@ async def read_item(item_id: str):
Поэтому мы используем относительный импорт с `..` для зависимостей:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[3] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}
#### Как работает относительный импорт { #how-relative-imports-work }
@@ -279,7 +279,7 @@ from ...dependencies import get_token_header
Но мы всё равно можем добавить _ещё_ `tags`, которые будут применяться к конкретной *операции пути*, а также дополнительные `responses`, специфичные для этой *операции пути*:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}
/// tip | Подсказка
@@ -305,13 +305,13 @@ from ...dependencies import get_token_header
И мы даже можем объявить [глобальные зависимости](dependencies/global-dependencies.md){.internal-link target=_blank}, которые будут объединены с зависимостями для каждого `APIRouter`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[1,3,7] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
### Импорт `APIRouter` { #import-the-apirouter }
Теперь мы импортируем другие подмодули, содержащие `APIRouter`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[4:5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}
Так как файлы `app/routers/users.py` и `app/routers/items.py` являются подмодулями, входящими в один и тот же Python-пакет `app`, мы можем использовать одну точку `.` для импорта через «относительные импорты».
@@ -374,13 +374,13 @@ from .routers.users import router
Поэтому, чтобы иметь возможность использовать обе в одном файле, мы импортируем подмодули напрямую:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}
### Подключение `APIRouter` для `users` и `items` { #include-the-apirouters-for-users-and-items }
Теперь давайте подключим `router` из подмодулей `users` и `items`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[10:11] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}
/// info | Примечание
@@ -420,13 +420,13 @@ from .routers.users import router
Для этого примера всё будет очень просто. Но допустим, что поскольку он используется совместно с другими проектами в организации, мы не можем модифицировать его и добавить `prefix`, `dependencies`, `tags` и т.д. непосредственно в `APIRouter`:
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
Но мы всё равно хотим задать пользовательский `prefix` при подключении `APIRouter`, чтобы все его *операции пути* начинались с `/admin`, хотим защитить его с помощью `dependencies`, которые у нас уже есть для этого проекта, и хотим включить `tags` и `responses`.
Мы можем объявить всё это, не изменяя исходный `APIRouter`, передав эти параметры в `app.include_router()`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[14:17] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}
Таким образом исходный `APIRouter` не будет модифицирован, и мы сможем использовать файл `app/internal/admin.py` сразу в нескольких проектах организации.
@@ -447,7 +447,7 @@ from .routers.users import router
Здесь мы делаем это... просто чтобы показать, что можем 🤷:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[21:23] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}
и это будет работать корректно вместе со всеми другими *операциями пути*, добавленными через `app.include_router()`.
diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md
index 9d9400494..ddd9c6fdd 100644
--- a/docs/ru/docs/tutorial/body-multiple-params.md
+++ b/docs/ru/docs/tutorial/body-multiple-params.md
@@ -52,7 +52,7 @@
}
```
-/// note | Внимание
+/// note | Заметка
Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предполагается, что он находится внутри тела с ключом `item`.
@@ -104,12 +104,6 @@
q: str | None = None
```
-Или в Python 3.9:
-
-```Python
-q: Union[str, None] = None
-```
-
Например:
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md
index 4c914b97f..6610b209c 100644
--- a/docs/ru/docs/tutorial/body-nested-models.md
+++ b/docs/ru/docs/tutorial/body-nested-models.md
@@ -163,7 +163,7 @@ images: list[Image]
например так:
-{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
## Поддержка редактора кода везде { #editor-support-everywhere }
@@ -193,7 +193,7 @@ images: list[Image]
В этом случае вы принимаете любой `dict`, пока у него есть ключи типа `int` со значениями типа `float`:
-{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
/// tip | Совет
diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md
index 537d7ebc9..3e55607da 100644
--- a/docs/ru/docs/tutorial/body.md
+++ b/docs/ru/docs/tutorial/body.md
@@ -72,7 +72,7 @@
* Проведёт валидацию данных.
* Если данные некорректны, вернёт понятную и наглядную ошибку, указывающую, где именно и что было некорректно.
* Передаст полученные данные в параметр `item`.
- * Поскольку внутри функции вы объявили его с типом `Item`, у вас будет поддержка со стороны редактора кода (автозавершение и т. п.) для всех атрибутов и их типов.
+ * Поскольку внутри функции вы объявили его с типом `Item`, у вас будет поддержка со стороны редактора кода (автозавершение и т.п.) для всех атрибутов и их типов.
* Сгенерирует определения JSON Schema для вашей модели; вы можете использовать их и в других местах, если это имеет смысл для вашего проекта.
* Эти схемы будут частью сгенерированной схемы OpenAPI и будут использоваться автоматической документацией UIs.
@@ -148,14 +148,14 @@ JSON Schema ваших моделей будет частью сгенериро
Параметры функции будут распознаны следующим образом:
* Если параметр также объявлен в **пути**, он будет использоваться как path-параметр.
-* Если параметр имеет **скалярный тип** (например, `int`, `float`, `str`, `bool` и т. п.), он будет интерпретирован как параметр **запроса**.
+* Если параметр имеет **скалярный тип** (например, `int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**.
* Если параметр объявлен как тип **модели Pydantic**, он будет интерпретирован как **тело** запроса.
/// note | Заметка
FastAPI понимает, что значение `q` не является обязательным из-за значения по умолчанию `= None`.
-Аннотации типов `str | None` (Python 3.10+) или `Union` в `Union[str, None]` (Python 3.9+) не используются FastAPI для определения обязательности; он узнает, что параметр не обязателен, потому что у него есть значение по умолчанию `= None`.
+Аннотация типов `str | None` не используется FastAPI для определения обязательности; он узнает, что параметр не обязателен, потому что у него есть значение по умолчанию `= None`.
Но добавление аннотаций типов позволит вашему редактору кода лучше вас поддерживать и обнаруживать ошибки.
diff --git a/docs/ru/docs/tutorial/cookie-param-models.md b/docs/ru/docs/tutorial/cookie-param-models.md
index 182813afd..9b34cf030 100644
--- a/docs/ru/docs/tutorial/cookie-param-models.md
+++ b/docs/ru/docs/tutorial/cookie-param-models.md
@@ -46,7 +46,7 @@
В некоторых случаях (не особо часто встречающихся) вам может понадобиться **ограничить** cookies, которые вы хотите получать.
-Теперь ваш API сам решает, принимать ли cookies. 🤪🍪
+Теперь у вашего API есть возможность контролировать своё согласие на использование cookie. 🤪🍪
Вы можете сконфигурировать Pydantic-модель так, чтобы запретить (`forbid`) любые дополнительные (`extra`) поля:
@@ -54,9 +54,9 @@
Если клиент попробует отправить **дополнительные cookies**, то в ответ он получит **ошибку**.
-Бедные баннеры cookies, они всеми силами пытаются получить ваше согласие — и всё ради того, чтобы API его отклонил. 🍪
+Бедные баннеры cookies, они всеми силами пытаются получить ваше согласие — и всё ради того, чтобы API его отклонил. 🍪
-Например, если клиент попытается отправить cookie `santa_tracker` со значением `good-list-please`, то в ответ он получит **ошибку**, сообщающую ему, что cookie `santa_tracker` не разрешён:
+Например, если клиент попытается отправить cookie `santa_tracker` со значением `good-list-please`, то в ответ он получит **ошибку**, сообщающую ему, что `santa_tracker` cookie не разрешён:
```json
{
@@ -73,4 +73,4 @@
## Заключение { #summary }
-Вы можете использовать **Pydantic-модели** для объявления **cookies** в **FastAPI**. 😎
+Вы можете использовать **Pydantic-модели** для объявления **cookies** в **FastAPI**. 😎
diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md
index 2d2eff8d7..8dad3873e 100644
--- a/docs/ru/docs/tutorial/cookie-params.md
+++ b/docs/ru/docs/tutorial/cookie-params.md
@@ -32,11 +32,11 @@
/// info | Дополнительная информация
-Имейте в виду, что, поскольку браузеры обрабатывают cookies особым образом и «за кулисами», они не позволяют JavaScript просто так получать к ним доступ.
+Имейте в виду, что, поскольку **браузеры обрабатывают cookies** особым образом и «за кулисами», они **не** позволяют **JavaScript** просто так получать к ним доступ.
-Если вы откроете интерфейс документации API на `/docs`, вы сможете увидеть документацию по cookies для ваших операций пути.
+Если вы откроете **интерфейс документации API** на `/docs`, вы сможете увидеть **документацию** по cookies для ваших *операции пути*.
-Но даже если вы заполните данные и нажмёте «Execute», поскольку UI документации работает с JavaScript, cookies отправлены не будут, и вы увидите сообщение об ошибке, как будто вы не указали никаких значений.
+Но даже если вы **заполните данные** и нажмёте «Execute», поскольку UI документации работает с **JavaScript**, cookies отправлены не будут, и вы увидите сообщение об **ошибке**, как будто вы не указали никаких значений.
///
diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md
index d09a31e2c..feaa15968 100644
--- a/docs/ru/docs/tutorial/cors.md
+++ b/docs/ru/docs/tutorial/cors.md
@@ -46,7 +46,7 @@
* Отдельных HTTP-методов (`POST`, `PUT`) или всех вместе, используя `"*"`.
* Отдельных HTTP-заголовков или всех вместе, используя `"*"`.
-{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *}
`CORSMiddleware` использует "запрещающие" значения по умолчанию, поэтому вам нужно явным образом разрешить использование отдельных источников, методов или заголовков, чтобы браузеры могли использовать их в кросс-доменном контексте.
@@ -77,7 +77,7 @@
## Больше информации { #more-info }
-Для получения более подробной информации о CORS обратитесь к документации CORS от Mozilla.
+Для получения более подробной информации о CORS обратитесь к документации CORS от Mozilla.
/// note | Технические детали
diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md
index 51955835e..483fe8086 100644
--- a/docs/ru/docs/tutorial/debugging.md
+++ b/docs/ru/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@
В вашем FastAPI приложении, импортируйте и вызовите `uvicorn` напрямую:
-{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *}
### Описание `__name__ == "__main__"` { #about-name-main }
@@ -42,7 +42,7 @@ $ python myapp.py
то встроенная переменная `__name__`, автоматически создаваемая Python в вашем файле, будет иметь значение строкового типа `"__main__"`.
-Тогда выполнится условие и эта часть кода:
+Тогда эта часть кода:
```Python
uvicorn.run(app, host="0.0.0.0", port=8000)
@@ -59,7 +59,7 @@ $ python myapp.py
```Python
from myapp import app
-# Some more code
+# Еще немного кода
```
то автоматическая создаваемая внутри файла `myapp.py` переменная `__name__` будет иметь значение отличающееся от `"__main__"`.
@@ -99,7 +99,7 @@ from myapp import app
---
-Если используете Pycharm, вы можете выполнить следующие шаги:
+Если используете PyCharm, вы можете выполнить следующие шаги:
* Открыть "Run" меню.
* Выбрать опцию "Debug...".
diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md
index a38e885d4..9a3171e9f 100644
--- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -4,7 +4,7 @@
## `dict` из предыдущего примера { #a-dict-from-the-previous-example }
-В предыдущем примере мы возвращали `dict` из нашей зависимости:
+В предыдущем примере мы возвращали `dict` из нашей зависимости («dependable»):
{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}
@@ -67,7 +67,7 @@ fluffy = Cat(name="Mr Fluffy")
Это относится и к вызываемым объектам без параметров. Работа с ними происходит точно так же, как и для *функций-обработчиков пути* без параметров.
-Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`:
+Теперь мы можем изменить зависимость («dependable») `common_parameters`, указанную выше, на класс `CommonQueryParams`:
{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}
@@ -101,7 +101,7 @@ fluffy = Cat(name="Mr Fluffy")
Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ без Annotated
/// tip | Подсказка
@@ -137,7 +137,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
В этом случае первый `CommonQueryParams`, в:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ без Annotated
/// tip | Подсказка
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
На самом деле можно написать просто:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ без Annotated
/// tip | Подсказка
@@ -197,7 +197,7 @@ commons = Depends(CommonQueryParams)
Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ без Annotated
/// tip | Подсказка
@@ -225,7 +225,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
Вместо того чтобы писать:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ без Annotated
/// tip | Подсказка
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
...следует написать:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ без Annotated
/// tip | Подсказка
diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index ef5664448..4cfc4e699 100644
--- a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -14,7 +14,7 @@
Это должен быть `list` состоящий из `Depends()`:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*.
@@ -30,7 +30,7 @@
/// info | Примечание
-В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`.
+В этом примере мы используем выдуманные пользовательские HTTP-заголовки `X-Key` и `X-Token`.
Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}.
@@ -42,15 +42,15 @@
### Требования к зависимостям { #dependency-requirements }
-Они могут объявлять требования к запросу (например заголовки) или другие подзависимости:
+Они могут объявлять требования к запросу (например HTTP-заголовки) или другие подзависимости:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
### Вызов исключений { #raise-exceptions }
Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
### Возвращаемые значения { #return-values }
@@ -58,7 +58,7 @@
Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
## Зависимости для группы *операций путей* { #dependencies-for-a-group-of-path-operations }
diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
index dc202db61..03a7c083c 100644
--- a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,6 +1,6 @@
# Зависимости с yield { #dependencies-with-yield }
-FastAPI поддерживает зависимости, которые выполняют некоторые дополнительные шаги после завершения.
+FastAPI поддерживает зависимости, которые выполняют некоторые дополнительные шаги после завершения.
Для этого используйте `yield` вместо `return`, а дополнительные шаги (код) напишите после него.
@@ -29,15 +29,15 @@ FastAPI поддерживает зависимости, которые выпо
Перед созданием ответа будет выполнен только код до и включая оператор `yield`:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
Значение, полученное из `yield`, внедряется в *операции пути* и другие зависимости:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
Код, следующий за оператором `yield`, выполняется после ответа:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
/// tip | Подсказка
@@ -57,7 +57,7 @@ FastAPI поддерживает зависимости, которые выпо
Точно так же можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены независимо от того, было ли исключение или нет.
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
## Подзависимости с `yield` { #sub-dependencies-with-yield }
@@ -67,7 +67,7 @@ FastAPI поддерживает зависимости, которые выпо
Например, `dependency_c` может зависеть от `dependency_b`, а `dependency_b` — от `dependency_a`:
-{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *}
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
И все они могут использовать `yield`.
@@ -75,7 +75,7 @@ FastAPI поддерживает зависимости, которые выпо
И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для её кода выхода.
-{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *}
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
Точно так же можно иметь часть зависимостей с `yield`, часть — с `return`, и какие-то из них могут зависеть друг от друга.
@@ -109,7 +109,7 @@ FastAPI поддерживает зависимости, которые выпо
///
-{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *}
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
Если вы хотите перехватывать исключения и формировать на их основе пользовательский ответ, создайте [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
@@ -117,7 +117,7 @@ FastAPI поддерживает зависимости, которые выпо
Если вы ловите исключение с помощью `except` в зависимости с `yield` и не вызываете его снова (или не вызываете новое исключение), FastAPI не сможет заметить, что было исключение — так же, как это происходит в обычном Python:
-{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *}
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
В этом случае клиент получит *HTTP 500 Internal Server Error*, как и должно быть, поскольку мы не вызываем `HTTPException` или что-то подобное, но на сервере **не будет никаких логов** или других указаний на то, какая была ошибка. 😱
@@ -127,7 +127,7 @@ FastAPI поддерживает зависимости, которые выпо
Вы можете повторно вызвать то же самое исключение с помощью `raise`:
-{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *}
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
Теперь клиент получит тот же *HTTP 500 Internal Server Error*, но на сервере в логах будет наше пользовательское `InternalError`. 😎
@@ -190,7 +190,7 @@ participant tasks as Background tasks
Но если вы знаете, что не будете использовать зависимость после возврата из *функции-обработчика пути*, вы можете использовать `Depends(scope="function")`, чтобы сообщить FastAPI, что он должен закрыть зависимость после возврата из *функции-обработчика пути*, но **до того**, как **ответ будет отправлен**.
-{* ../../docs_src/dependencies/tutorial008e_an_py39.py hl[12,16] *}
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
`Depends()` принимает параметр `scope`, который может быть:
@@ -269,7 +269,7 @@ with open("./somefile.txt") as f:
Их также можно использовать внутри зависимостей **FastAPI** с `yield`, применяя операторы
`with` или `async with` внутри функции зависимости:
-{* ../../docs_src/dependencies/tutorial010_py39.py hl[1:9,13] *}
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
/// tip | Подсказка
diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md
index 2347c6dd8..f488322a9 100644
--- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md
+++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md
@@ -6,10 +6,10 @@
В этом случае они будут применяться ко всем *операциям пути* в приложении:
-{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[17] *}
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
Все способы [добавления `dependencies` (зависимостей) в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения.
## Зависимости для групп *операций пути* { #dependencies-for-groups-of-path-operations }
-Позднее, читая о том, как структурировать более крупные [приложения, содержащие много файлов](../../tutorial/bigger-applications.md){.internal-link target=_blank}, вы узнаете, как объявить один параметр `dependencies` для целой группы *операций пути*.
+Позднее, читая о том, как структурировать более крупные приложения ([приложения, содержащие много файлов](../../tutorial/bigger-applications.md){.internal-link target=_blank}), возможно, состоящие из нескольких файлов, вы узнаете, как объявить один параметр `dependencies` для целой группы *операций пути*.
diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md
index 98b0d59c6..29f735ab6 100644
--- a/docs/ru/docs/tutorial/dependencies/index.md
+++ b/docs/ru/docs/tutorial/dependencies/index.md
@@ -1,6 +1,6 @@
# Зависимости { #dependencies }
-**FastAPI** имеет очень мощную, но интуитивную систему **Инъекция зависимостей**.
+**FastAPI** имеет очень мощную, но интуитивную систему **Инъекция зависимостей**.
Она спроектирована так, чтобы быть очень простой в использовании и облегчать любому разработчику интеграцию других компонентов с **FastAPI**.
diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
index da31a6682..3c71defd8 100644
--- a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
@@ -58,11 +58,11 @@ query_extractor --> query_or_cookie_extractor --> read_query
Если одна из ваших зависимостей объявлена несколько раз для одной и той же *функции операции пути*, например, несколько зависимостей имеют общую подзависимость, **FastAPI** будет знать, что вызывать эту подзависимость нужно только один раз за запрос.
-При этом возвращаемое значение будет сохранено в "кэш" и будет передано всем "зависимым" функциям, которые нуждаются в нем внутри этого конкретного запроса, вместо того, чтобы вызывать зависимость несколько раз для одного и того же запроса.
+При этом возвращаемое значение будет сохранено в «кэш» и будет передано всем "зависимым" функциям, которые нуждаются в нем внутри этого конкретного запроса, вместо того, чтобы вызывать зависимость несколько раз для одного и того же запроса.
В расширенном сценарии, когда вы знаете, что вам нужно, чтобы зависимость вызывалась на каждом шаге (возможно, несколько раз) в одном и том же запросе, вместо использования "кэшированного" значения, вы можете установить параметр `use_cache=False` при использовании `Depends`:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python hl_lines="1"
async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
@@ -71,7 +71,7 @@ async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_ca
////
-//// tab | Python 3.9+ без Annotated
+//// tab | Python 3.10+ без Annotated
/// tip | Подсказка
diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md
index 16981f79d..28e2a49c0 100644
--- a/docs/ru/docs/tutorial/encoder.md
+++ b/docs/ru/docs/tutorial/encoder.md
@@ -10,9 +10,9 @@
Представим, что у вас есть база данных `fake_db`, которая принимает только JSON-совместимые данные.
-Например, он не принимает объекты `datetime`, так как они не совместимы с JSON.
+Например, она не принимает объекты `datetime`, так как они не совместимы с JSON.
-В таком случае объект `datetime` следует преобразовать в строку соответствующую формату ISO.
+В таком случае объект `datetime` следует преобразовать в строку, соответствующую формату ISO.
Точно так же эта база данных не может принять Pydantic-модель (объект с атрибутами), а только `dict`.
diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md
index 03156f2b4..f9b63ca70 100644
--- a/docs/ru/docs/tutorial/extra-models.md
+++ b/docs/ru/docs/tutorial/extra-models.md
@@ -190,9 +190,9 @@ some_variable: PlaneItem | CarItem
Таким же образом вы можете объявлять HTTP-ответы, возвращающие списки объектов.
-Для этого используйте стандартный `typing.List` в Python (или просто `list` в Python 3.9 и выше):
+Для этого используйте стандартный `list` в Python:
-{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *}
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
## Ответ с произвольным `dict` { #response-with-arbitrary-dict }
@@ -200,9 +200,9 @@ some_variable: PlaneItem | CarItem
Это полезно, если вы заранее не знаете корректных названий полей/атрибутов (которые будут нужны при использовании Pydantic-модели).
-В этом случае вы можете использовать `typing.Dict` (или просто `dict` в Python 3.9 и выше):
+В этом случае вы можете использовать `dict`:
-{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *}
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
## Резюме { #recap }
diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md
index 798c03d51..cee264ff4 100644
--- a/docs/ru/docs/tutorial/first-steps.md
+++ b/docs/ru/docs/tutorial/first-steps.md
@@ -2,7 +2,7 @@
Самый простой файл FastAPI может выглядеть так:
-{* ../../docs_src/first_steps/tutorial001_py39.py *}
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
Скопируйте это в файл `main.py`.
@@ -183,7 +183,7 @@ Deploying to FastAPI Cloud...
### Шаг 1: импортируйте `FastAPI` { #step-1-import-fastapi }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[1] *}
`FastAPI` — это класс на Python, который предоставляет всю функциональность для вашего API.
@@ -197,7 +197,7 @@ Deploying to FastAPI Cloud...
### Шаг 2: создайте экземпляр `FastAPI` { #step-2-create-a-fastapi-instance }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[3] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[3] *}
Здесь переменная `app` будет экземпляром класса `FastAPI`.
@@ -266,12 +266,12 @@ https://example.com/items/foo
#### Определите *декоратор операции пути (path operation decorator)* { #define-a-path-operation-decorator }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[6] *}
`@app.get("/")` сообщает **FastAPI**, что функция прямо под ним отвечает за обработку запросов, поступающих:
* по пути `/`
-* с использованием get операции
+* с использованием get операции
/// info | Информация о `@decorator`
@@ -320,7 +320,7 @@ https://example.com/items/foo
* **операция**: `get`.
* **функция**: функция ниже «декоратора» (ниже `@app.get("/")`).
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
Это функция на Python.
@@ -332,7 +332,7 @@ https://example.com/items/foo
Вы также можете определить её как обычную функцию вместо `async def`:
-{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
/// note | Примечание
@@ -342,7 +342,7 @@ https://example.com/items/foo
### Шаг 5: верните содержимое { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д.
diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md
index 2e00d7075..fbd82cf28 100644
--- a/docs/ru/docs/tutorial/handling-errors.md
+++ b/docs/ru/docs/tutorial/handling-errors.md
@@ -11,7 +11,7 @@
* Элемент, к которому клиент пытался получить доступ, не существует.
* и т.д.
-В таких случаях обычно возвращается **HTTP-код статуса ответа** в диапазоне **400** (от 400 до 499).
+В таких случаях обычно возвращают **HTTP статус-код** в диапазоне **400** (от 400 до 499).
Они похожи на двухсотые HTTP статус-коды (от 200 до 299), которые означают, что запрос обработан успешно.
@@ -25,7 +25,7 @@
### Импортируйте `HTTPException` { #import-httpexception }
-{* ../../docs_src/handling_errors/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
### Вызовите `HTTPException` в своем коде { #raise-an-httpexception-in-your-code }
@@ -39,7 +39,7 @@
В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`:
-{* ../../docs_src/handling_errors/tutorial001_py39.py hl[11] *}
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
### Возвращаемый ответ { #the-resulting-response }
@@ -71,13 +71,13 @@
## Добавление пользовательских заголовков { #add-custom-headers }
-В некоторых ситуациях полезно иметь возможность добавлять пользовательские заголовки к ошибке HTTP. Например, для некоторых типов безопасности.
+В некоторых ситуациях полезно иметь возможность добавлять пользовательские HTTP-заголовки к ошибке HTTP. Например, для некоторых типов безопасности.
Скорее всего, вам не потребуется использовать его непосредственно в коде.
Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки:
-{* ../../docs_src/handling_errors/tutorial002_py39.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
## Установка пользовательских обработчиков исключений { #install-custom-exception-handlers }
@@ -89,7 +89,7 @@
Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`:
-{* ../../docs_src/handling_errors/tutorial003_py39.py hl[5:7,13:18,24] *}
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`.
@@ -127,7 +127,7 @@
Обработчик исключения получит объект `Request` и исключение.
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[2,14:19] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с:
@@ -159,7 +159,7 @@ Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to pa
Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON:
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[3:4,9:11,25] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
/// note | Технические детали
@@ -183,7 +183,7 @@ Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to pa
Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д.
-{* ../../docs_src/handling_errors/tutorial005_py39.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
Теперь попробуйте отправить недействительный элемент, например:
@@ -239,6 +239,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`:
-{* ../../docs_src/handling_errors/tutorial006_py39.py hl[2:5,15,21] *}
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений.
diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md
index e4fe5fb54..221655aa5 100644
--- a/docs/ru/docs/tutorial/metadata.md
+++ b/docs/ru/docs/tutorial/metadata.md
@@ -18,7 +18,7 @@
Вы можете задать их следующим образом:
-{* ../../docs_src/metadata/tutorial001_py39.py hl[3:16, 19:32] *}
+{* ../../docs_src/metadata/tutorial001_py310.py hl[3:16, 19:32] *}
/// tip | Подсказка
@@ -36,7 +36,7 @@
К примеру:
-{* ../../docs_src/metadata/tutorial001_1_py39.py hl[31] *}
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
## Метаданные для тегов { #metadata-for-tags }
@@ -58,7 +58,7 @@
Создайте метаданные для ваших тегов и передайте их в параметре `openapi_tags`:
-{* ../../docs_src/metadata/tutorial004_py39.py hl[3:16,18] *}
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_).
@@ -72,7 +72,7 @@
Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги:
-{* ../../docs_src/metadata/tutorial004_py39.py hl[21,26] *}
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
/// info | Дополнительная информация
@@ -100,7 +100,7 @@
К примеру, чтобы задать её отображение по адресу `/api/v1/openapi.json`:
-{* ../../docs_src/metadata/tutorial002_py39.py hl[3] *}
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые её используют.
@@ -117,4 +117,4 @@
К примеру, чтобы задать отображение Swagger UI по адресу `/documentation` и отключить ReDoc:
-{* ../../docs_src/metadata/tutorial003_py39.py hl[3] *}
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/ru/docs/tutorial/middleware.md b/docs/ru/docs/tutorial/middleware.md
index a83d3c011..734545cd8 100644
--- a/docs/ru/docs/tutorial/middleware.md
+++ b/docs/ru/docs/tutorial/middleware.md
@@ -1,10 +1,8 @@
# Middleware (Промежуточный слой) { #middleware }
-Вы можете добавить промежуточный слой (middleware) в **FastAPI** приложение.
-
-"Middleware" это функция, которая выполняется с каждым запросом до его обработки какой-либо конкретной *операцией пути*.
-А также с каждым ответом перед его возвращением.
+Вы можете добавить middleware (промежуточный слой) в **FastAPI** приложение.
+"Middleware" - это функция, которая выполняется с каждым **запросом** до его обработки какой-либо конкретной *операцией пути*. А также с каждым **ответом** перед его возвращением.
* Она принимает каждый поступающий **запрос**.
* Может что-то сделать с этим **запросом** или выполнить любой нужный код.
@@ -23,23 +21,23 @@
## Создание middleware { #create-a-middleware }
-Для создания middleware используйте декоратор `@app.middleware("http")`.
+Для создания middleware используйте декоратор `@app.middleware("http")` поверх функции.
Функция middleware получает:
-* `request` (объект запроса).
+* `request`.
* Функцию `call_next`, которая получает `request` в качестве параметра.
* Эта функция передаёт `request` соответствующей *операции пути*.
- * Затем она возвращает ответ `response`, сгенерированный *операцией пути*.
-* Также имеется возможность видоизменить `response`, перед тем как его вернуть.
+ * Затем она возвращает `response`, сгенерированный соответствующей *операцией пути*.
+* Также имеется возможность видоизменить `response` перед тем как его вернуть.
-{* ../../docs_src/middleware/tutorial001_py39.py hl[8:9,11,14] *}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
-/// tip | Примечание
+/// tip | Совет
-Имейте в виду, что можно добавлять свои собственные заголовки при помощи префикса 'X-'.
+Имейте в виду, что можно добавлять проприетарные HTTP-заголовки с префиксом `X-`.
-Если же вы хотите добавить собственные заголовки, которые клиент сможет увидеть в браузере, то вам потребуется добавить их в настройки CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}), используя параметр `expose_headers`, см. документацию Starlette's CORS docs.
+Но если вы хотите, чтобы клиент в браузере мог видеть ваши пользовательские заголовки, необходимо добавить их в настройки CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}), используя параметр `expose_headers`, описанный в документации по CORS Starlette.
///
@@ -53,17 +51,17 @@
### До и после `response` { #before-and-after-the-response }
-Вы можете добавить код, использующий `request` до передачи его какой-либо *операции пути*.
+Вы можете добавить код, использующий `request`, до передачи его какой-либо *операции пути*.
А также после формирования `response`, до того, как вы его вернёте.
Например, вы можете добавить собственный заголовок `X-Process-Time`, содержащий время в секундах, необходимое для обработки запроса и генерации ответа:
-{* ../../docs_src/middleware/tutorial001_py39.py hl[10,12:13] *}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
-/// tip | Примечание
+/// tip | Совет
-Мы используем `time.perf_counter()` вместо `time.time()` для обеспечения большей точности наших примеров. 🤓
+Мы используем `time.perf_counter()` вместо `time.time()` для обеспечения большей точности в таких случаях. 🤓
///
@@ -94,4 +92,4 @@ app.add_middleware(MiddlewareB)
О других middleware вы можете узнать больше в разделе [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}.
-В следующем разделе вы можете прочитать, как настроить CORS с помощью middleware.
+В следующем разделе вы можете прочитать, как настроить CORS с помощью middleware.
diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md
index 112a1efca..31531c67f 100644
--- a/docs/ru/docs/tutorial/path-operation-configuration.md
+++ b/docs/ru/docs/tutorial/path-operation-configuration.md
@@ -4,7 +4,7 @@
/// warning | Внимание
-Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*.
+Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику пути*.
///
@@ -46,7 +46,7 @@
**FastAPI** поддерживает это так же, как и в случае с обычными строками:
-{* ../../docs_src/path_operation_configuration/tutorial002b_py39.py hl[1,8:10,13,18] *}
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
## Краткое и развёрнутое содержание { #summary-and-description }
@@ -56,7 +56,7 @@
## Описание из строк документации { #description-from-docstring }
-Так как описания обычно длинные и содержат много строк, вы можете объявить описание *операции пути* в функции строки документации и **FastAPI** прочитает её отсюда.
+Так как описания обычно длинные и содержат много строк, вы можете объявить описание *операции пути* в строке документации функции, и **FastAPI** прочитает её оттуда.
Вы можете использовать Markdown в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации).
@@ -90,9 +90,9 @@ OpenAPI указывает, что каждой *операции пути* не
## Обозначение *операции пути* как устаревшей { #deprecate-a-path-operation }
-Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`:
+Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`:
-{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
Он будет четко помечен как устаревший в интерактивной документации:
diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md
index f0fe78805..6c1148b60 100644
--- a/docs/ru/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md
@@ -44,7 +44,7 @@ Path-параметр всегда является обязательным, п
И если вам больше ничего не нужно указывать для этого параметра, то нет необходимости использовать `Query`.
-Но вам по-прежнему нужно использовать `Path` для path-параметра `item_id`. И если по какой-либо причине вы не хотите использовать `Annotated`, то могут возникнуть небольшие сложности.
+Но вам по-прежнему нужно использовать `Path` для path-параметра `item_id`. И по какой-либо причине вы не хотите использовать `Annotated`.
Если вы поместите параметр со значением по умолчанию перед другим параметром, у которого нет значения по умолчанию, то Python укажет на ошибку.
@@ -54,11 +54,11 @@ Path-параметр всегда является обязательным, п
Поэтому вы можете определить функцию так:
-{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете значения по умолчанию параметров функции для `Query()` или `Path()`.
-{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
## Задайте нужный вам порядок параметров, полезные приёмы { #order-the-parameters-as-you-need-tricks }
@@ -83,13 +83,13 @@ Path-параметр всегда является обязательным, п
Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
### Лучше с `Annotated` { #better-with-annotated }
Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, у вас не возникнет подобной проблемы и вам, вероятно, не придётся использовать `*`.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
## Валидация числовых данных: больше или равно { #number-validations-greater-than-or-equal }
@@ -97,7 +97,7 @@ Python не будет ничего делать с `*`, но он будет з
В этом примере при указании `ge=1`, параметр `item_id` должен быть целым числом "`g`reater than or `e`qual" — больше или равно `1`.
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
## Валидация числовых данных: больше и меньше или равно { #number-validations-greater-than-and-less-than-or-equal }
@@ -106,7 +106,7 @@ Python не будет ничего делать с `*`, но он будет з
* `gt`: больше (`g`reater `t`han)
* `le`: меньше или равно (`l`ess than or `e`qual)
-{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
## Валидация числовых данных: числа с плавающей точкой, больше и меньше { #number-validations-floats-greater-than-and-less-than }
@@ -118,7 +118,7 @@ Python не будет ничего делать с `*`, но он будет з
То же самое справедливо и для lt.
-{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
## Резюме { #recap }
diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md
index 83a7ed3ff..729569748 100644
--- a/docs/ru/docs/tutorial/path-params.md
+++ b/docs/ru/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python:
-{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`.
@@ -16,7 +16,7 @@
Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python:
-{* ../../docs_src/path_params/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
Здесь, `item_id` объявлен типом `int`.
@@ -26,7 +26,7 @@
///
-## Преобразование данных { #data-conversion }
+## Преобразование данных { #data-conversion }
Если запустите этот пример и перейдёте по адресу: http://127.0.0.1:8000/items/3, то увидите ответ:
@@ -38,7 +38,7 @@
Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
-Используя такое объявление типов, **FastAPI** выполняет автоматический "парсинг" запросов.
+Используя такое объявление типов, **FastAPI** выполняет автоматический HTTP-запрос "парсинг".
///
@@ -118,13 +118,13 @@
Поскольку *операции пути* выполняются в порядке их объявления, необходимо, чтобы путь для `/users/me` был объявлен раньше, чем путь для `/users/{user_id}`:
-{* ../../docs_src/path_params/tutorial003_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
Иначе путь для `/users/{user_id}` также будет соответствовать `/users/me`, "подразумевая", что он получает параметр `user_id` со значением `"me"`.
Аналогично, вы не можете переопределить операцию с путем:
-{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
Первый будет выполняться всегда, так как путь совпадает первым.
@@ -140,11 +140,11 @@
Затем создайте атрибуты класса с фиксированными допустимыми значениями:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
/// tip | Подсказка
-Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей Машинного обучения.
+Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей Машинного обучения.
///
@@ -152,7 +152,7 @@
Определите *параметр пути*, используя в аннотации типа класс перечисления (`ModelName`), созданный ранее:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
### Проверьте документацию { #check-the-docs }
@@ -168,13 +168,13 @@
Вы можете сравнить это значение с *элементом перечисления* класса `ModelName`:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[17] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
#### Получение *значения перечисления* { #get-the-enumeration-value }
Можно получить фактическое значение (в данном случае - `str`) с помощью `model_name.value` или в общем случае `your_enum_member.value`:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[20] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
/// tip | Подсказка
@@ -188,8 +188,8 @@
Они будут преобразованы в соответствующие значения (в данном случае - строки) перед их возвратом клиенту:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[18,21,23] *}
-Вы отправите клиенту такой JSON-ответ:
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
+На стороне клиента вы получите такой JSON-ответ:
```JSON
{
@@ -226,7 +226,7 @@ OpenAPI не поддерживает способов объявления *п
Можете использовать так:
-{* ../../docs_src/path_params/tutorial004_py39.py hl[6] *}
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
/// tip | Подсказка
@@ -241,7 +241,7 @@ OpenAPI не поддерживает способов объявления *п
Используя **FastAPI** вместе со стандартными объявлениями типов Python (короткими и интуитивно понятными), вы получаете:
* Поддержку редактора кода (проверку ошибок, автозавершение и т.п.)
-* "Парсинг" данных
+* "Парсинг" данных
* Валидацию данных
* Аннотации API и автоматическую документацию
diff --git a/docs/ru/docs/tutorial/query-param-models.md b/docs/ru/docs/tutorial/query-param-models.md
index 5ad7f1d99..7f29740ac 100644
--- a/docs/ru/docs/tutorial/query-param-models.md
+++ b/docs/ru/docs/tutorial/query-param-models.md
@@ -6,7 +6,7 @@
/// note | Заметка
-Этот функционал доступен с версии `0.115.0`. 🤓
+Это поддерживается начиная с версии FastAPI `0.115.0`. 🤓
///
diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md
index 2bc2fb22c..43cbcad03 100644
--- a/docs/ru/docs/tutorial/query-params-str-validations.md
+++ b/docs/ru/docs/tutorial/query-params-str-validations.md
@@ -47,40 +47,16 @@ FastAPI поймёт, что значение `q` не обязательно,
У нас была такая аннотация типа:
-//// tab | Python 3.10+
-
```Python
q: str | None = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Union[str, None] = None
-```
-
-////
-
Мы «обернём» это в `Annotated`, и получится:
-//// tab | Python 3.10+
-
```Python
q: Annotated[str | None] = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Annotated[Union[str, None]] = None
-```
-
-////
-
Обе версии означают одно и то же: `q` — параметр, который может быть `str` или `None`, и по умолчанию равен `None`.
А теперь к самому интересному. 🎉
@@ -109,7 +85,7 @@ q: Annotated[Union[str, None]] = None
## Альтернатива (устаревшее): `Query` как значение по умолчанию { #alternative-old-query-as-the-default-value }
-В предыдущих версиях FastAPI (до 0.95.0) требовалось использовать `Query` как значение по умолчанию для параметра вместо помещения его в `Annotated`. Скорее всего вы ещё встретите такой код, поэтому поясню.
+В предыдущих версиях FastAPI (до 0.95.0) требовалось использовать `Query` как значение по умолчанию для параметра вместо помещения его в `Annotated`. Скорее всего вы ещё встретите такой код, поэтому поясню.
/// tip | Подсказка
@@ -191,7 +167,7 @@ q: str = Query(default="rick")
## Регулярные выражения { #add-regular-expressions }
-Вы можете определить регулярное выражение `pattern`, которому должен соответствовать параметр:
+Вы можете определить регулярное выражение `pattern`, которому должен соответствовать параметр:
{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
@@ -211,7 +187,7 @@ q: str = Query(default="rick")
Допустим, вы хотите объявить, что query-параметр `q` должен иметь `min_length` равный `3` и значение по умолчанию `"fixedquery"`:
-{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial005_an_py310.py hl[9] *}
/// note | Примечание
@@ -241,7 +217,7 @@ q: Annotated[str | None, Query(min_length=3)] = None
Поэтому, когда вам нужно объявить значение как обязательное при использовании `Query`, просто не указывайте значение по умолчанию:
-{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial006_an_py310.py hl[9] *}
### Обязательный, но может быть `None` { #required-can-be-none }
@@ -292,7 +268,7 @@ http://localhost:8000/items/?q=foo&q=bar
Можно также определить значение по умолчанию как `list`, если ничего не передано:
-{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
Если вы перейдёте по адресу:
@@ -315,7 +291,7 @@ http://localhost:8000/items/
Можно использовать `list` напрямую вместо `list[str]`:
-{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
/// note | Примечание
@@ -371,7 +347,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
Предположим, этот параметр вам больше не нравится.
-Его нужно оставить на какое‑то время, так как клиенты его используют, но вы хотите, чтобы в документации он явно отображался как устаревший.
+Его нужно оставить на какое‑то время, так как клиенты его используют, но вы хотите, чтобы в документации он явно отображался как устаревший.
Тогда передайте параметр `deprecated=True` в `Query`:
@@ -401,7 +377,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
///
-Например, эта кастомная проверка убеждается, что ID элемента начинается с `isbn-` для номера книги ISBN или с `imdb-` для ID URL фильма на IMDB:
+Например, эта кастомная проверка убеждается, что ID элемента начинается с `isbn-` для номера книги ISBN или с `imdb-` для ID URL фильма на IMDB:
{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
@@ -435,7 +411,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
#### Случайный элемент { #a-random-item }
-С помощью `data.items()` мы получаем итерируемый объект с кортежами, содержащими ключ и значение для каждого элемента словаря.
+С помощью `data.items()` мы получаем итерируемый объект с кортежами, содержащими ключ и значение для каждого элемента словаря.
Мы превращаем этот итерируемый объект в обычный `list` через `list(data.items())`.
diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md
index be1c0e46e..cbacb129c 100644
--- a/docs/ru/docs/tutorial/query-params.md
+++ b/docs/ru/docs/tutorial/query-params.md
@@ -2,7 +2,7 @@
Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры.
-{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
Query-параметры представляют из себя набор пар ключ-значение, которые идут после знака `?` в URL-адресе, разделенные символами `&`.
@@ -24,7 +24,7 @@ http://127.0.0.1:8000/items/?skip=0&limit=10
Все те же правила, которые применяются к path-параметрам, также применяются и query-параметрам:
* Поддержка от редактора кода (очевидно)
-* "Парсинг" данных
+* "Парсинг" данных
* Проверка на соответствие данных (Валидация)
* Автоматическая документация
@@ -121,13 +121,13 @@ http://127.0.0.1:8000/items/foo?short=yes
## Обязательные query-параметры { #required-query-parameters }
-Когда вы объявляете значение по умолчанию для параметра, который не является path-параметром (в этом разделе, мы пока что познакомились только с path-параметрами), то он не является обязательным.
+Когда вы объявляете значение по умолчанию для параметра, который не является path-параметром (в этом разделе мы пока что рассмотрели только query-параметры), то он не является обязательным.
Если вы не хотите задавать конкретное значение, но хотите сделать параметр необязательным, вы можете установить значение по умолчанию равным `None`.
Но если вы хотите сделать query-параметр обязательным, вы можете просто не указывать значение по умолчанию:
-{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
Здесь параметр запроса `needy` является обязательным параметром с типом данных `str`.
diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md
index 9cfbd53df..41922333f 100644
--- a/docs/ru/docs/tutorial/request-files.md
+++ b/docs/ru/docs/tutorial/request-files.md
@@ -20,13 +20,13 @@ $ pip install python-multipart
Импортируйте `File` и `UploadFile` из модуля `fastapi`:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
## Определите параметры `File` { #define-file-parameters }
Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
/// info | Дополнительная информация
@@ -54,7 +54,7 @@ $ pip install python-multipart
Определите параметр файла с типом `UploadFile`:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
Использование `UploadFile` имеет ряд преимуществ перед `bytes`:
@@ -122,7 +122,7 @@ contents = myfile.file.read()
Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела.
-Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST.
+Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST.
///
@@ -144,7 +144,7 @@ contents = myfile.file.read()
Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных:
-{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
## Загрузка нескольких файлов { #multiple-file-uploads }
@@ -154,7 +154,7 @@ contents = myfile.file.read()
Для этого необходимо объявить список `bytes` или `UploadFile`:
-{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`.
@@ -170,7 +170,7 @@ contents = myfile.file.read()
Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`:
-{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
## Резюме { #recap }
diff --git a/docs/ru/docs/tutorial/request-form-models.md b/docs/ru/docs/tutorial/request-form-models.md
index f8c58356c..f4411a27b 100644
--- a/docs/ru/docs/tutorial/request-form-models.md
+++ b/docs/ru/docs/tutorial/request-form-models.md
@@ -24,7 +24,7 @@ $ pip install python-multipart
Вам просто нужно объявить **Pydantic-модель** с полями, которые вы хотите получить как **поля формы**, а затем объявить параметр как `Form`:
-{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
**FastAPI** **извлечёт** данные для **каждого поля** из **данных формы** в запросе и выдаст вам объявленную Pydantic-модель.
@@ -48,7 +48,7 @@ $ pip install python-multipart
Вы можете сконфигурировать Pydantic-модель так, чтобы запретить (`forbid`) все дополнительные (`extra`) поля:
-{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *}
+{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *}
Если клиент попробует отправить дополнительные данные, то в ответ он получит **ошибку**.
diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md
index 691dc75ba..10836d74f 100644
--- a/docs/ru/docs/tutorial/request-forms-and-files.md
+++ b/docs/ru/docs/tutorial/request-forms-and-files.md
@@ -16,13 +16,13 @@ $ pip install python-multipart
## Импортируйте `File` и `Form` { #import-file-and-form }
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[3] *}
## Определите параметры `File` и `Form` { #define-file-and-form-parameters }
Создайте параметры файла и формы таким же образом, как для `Body` или `Query`:
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[10:12] *}
Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы.
diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md
index e257652b6..01f71ac2f 100644
--- a/docs/ru/docs/tutorial/request-forms.md
+++ b/docs/ru/docs/tutorial/request-forms.md
@@ -18,17 +18,17 @@ $ pip install python-multipart
Импортируйте `Form` из `fastapi`:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[3] *}
## Определение параметров `Form` { #define-form-parameters }
Создайте параметры формы так же, как это делается для `Body` или `Query`:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[9] *}
-Например, в одном из способов использования спецификации OAuth2 (называемом «потоком пароля») требуется отправить `username` и `password` в виде полей формы.
+Например, в одном из способов использования спецификации OAuth2 (называемом «password flow» - аутентификация по паролю) требуется отправить `username` и `password` в виде полей формы.
-spec требует, чтобы поля были строго названы `username` и `password` и отправлялись как поля формы, а не JSON.
+спецификация требует, чтобы поля были строго названы `username` и `password` и отправлялись как поля формы, а не JSON.
С помощью `Form` вы можете объявить те же настройки, что и с `Body` (и `Query`, `Path`, `Cookie`), включая валидацию, примеры, псевдоним (например, `user-name` вместо `username`) и т.д.
@@ -56,7 +56,7 @@ $ pip install python-multipart
Но когда форма содержит файлы, она кодируется как `multipart/form-data`. О работе с файлами вы прочтёте в следующей главе.
-Если вы хотите узнать больше про эти кодировки и поля формы, обратитесь к MDN веб-документации для `POST`.
+Если вы хотите узнать больше про эти кодировки и поля формы, обратитесь к MDN веб-документации для `POST`.
///
diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md
index 22a811cd5..cd99ce28c 100644
--- a/docs/ru/docs/tutorial/response-model.md
+++ b/docs/ru/docs/tutorial/response-model.md
@@ -183,7 +183,7 @@ FastAPI делает несколько вещей внутри вместе с
Самый распространённый случай — [возвращать Response напрямую, как описано далее в разделах документации для продвинутых](../advanced/response-directly.md){.internal-link target=_blank}.
-{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
Этот простой случай обрабатывается FastAPI автоматически, потому что аннотация возвращаемого типа — это класс (или подкласс) `Response`.
@@ -193,7 +193,7 @@ FastAPI делает несколько вещей внутри вместе с
Вы также можете использовать подкласс `Response` в аннотации типа:
-{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
Это тоже сработает, так как `RedirectResponse` — подкласс `Response`, и FastAPI автоматически обработает этот простой случай.
@@ -201,7 +201,7 @@ FastAPI делает несколько вещей внутри вместе с
Но когда вы возвращаете произвольный объект, не являющийся валидным типом Pydantic (например, объект базы данных), и аннотируете его таким образом в функции, FastAPI попытается создать модель ответа Pydantic из этой аннотации типа и потерпит неудачу.
-То же произойдёт, если у вас будет что-то вроде union разных типов, где один или несколько не являются валидными типами Pydantic, например, это приведёт к ошибке 💥:
+То же произойдёт, если у вас будет что-то вроде union разных типов, где один или несколько не являются валидными типами Pydantic, например, это приведёт к ошибке 💥:
{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md
index 30f642b64..13d982e80 100644
--- a/docs/ru/docs/tutorial/response-status-code.md
+++ b/docs/ru/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@
* `@app.delete()`
* и других.
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
/// note | Примечание
@@ -66,7 +66,7 @@ FastAPI знает об этом и создаст документацию Open
/// tip | Подсказка
-Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с MDN документацией об HTTP статус-кодах.
+Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с MDN документацией об HTTP статус-кодах.
///
@@ -74,7 +74,7 @@ FastAPI знает об этом и создаст документацию Open
Рассмотрим предыдущий пример еще раз:
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201` – это код статуса "Создано".
@@ -82,7 +82,7 @@ FastAPI знает об этом и создаст документацию Open
Для удобства вы можете использовать переменные из `fastapi.status`.
-{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
Они содержат те же числовые значения, но позволяют использовать автозавершение редактора кода для выбора кода статуса:
@@ -90,7 +90,7 @@ FastAPI знает об этом и создаст документацию Open
/// note | Технические детали
-Вы также можете использовать `from starlette import status` вместо `from fastapi import status`.
+Вы также можете использовать `from starlette import status`.
**FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette.
diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md
index e4a97c880..c7381aae2 100644
--- a/docs/ru/docs/tutorial/schema-extra-example.md
+++ b/docs/ru/docs/tutorial/schema-extra-example.md
@@ -74,7 +74,7 @@ OpenAPI 3.1.0 (используется начиная с FastAPI 0.99.0) доб
Когда вы делаете это, примеры становятся частью внутренней **JSON Schema** для данных тела запроса.
-Тем не менее, на момент написания этого Swagger UI, инструмент, отвечающий за отображение UI документации, не поддерживает показ нескольких примеров для данных в **JSON Schema**. Но ниже есть обходной путь.
+Тем не менее, на момент написания этого Swagger UI, инструмент, отвечающий за отображение UI документации, не поддерживает показ нескольких примеров для данных в **JSON Schema**. Но ниже есть обходной путь.
### Специфические для OpenAPI `examples` { #openapi-specific-examples }
diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md
index 983e85e66..9b9673b84 100644
--- a/docs/ru/docs/tutorial/security/first-steps.md
+++ b/docs/ru/docs/tutorial/security/first-steps.md
@@ -20,7 +20,7 @@
Скопируйте пример в файл `main.py`:
-{* ../../docs_src/security/tutorial001_an_py39.py *}
+{* ../../docs_src/security/tutorial001_an_py310.py *}
## Запуск { #run-it }
@@ -132,7 +132,7 @@ OAuth2 был спроектирован так, чтобы бэкенд или
При создании экземпляра класса `OAuth2PasswordBearer` мы передаем параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `username` и `password`, чтобы получить токен.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
/// tip | Подсказка
@@ -170,7 +170,7 @@ oauth2_scheme(some, parameters)
Теперь вы можете передать `oauth2_scheme` как зависимость с `Depends`.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
Эта зависимость предоставит `str`, который будет присвоен параметру `token` *функции-обработчика пути*.
diff --git a/docs/ru/docs/tutorial/security/get-current-user.md b/docs/ru/docs/tutorial/security/get-current-user.md
index c6bc07cc1..8388b672c 100644
--- a/docs/ru/docs/tutorial/security/get-current-user.md
+++ b/docs/ru/docs/tutorial/security/get-current-user.md
@@ -2,7 +2,7 @@
В предыдущей главе система безопасности (основанная на системе внедрения зависимостей) передавала *функции-обработчику пути* `token` типа `str`:
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
Но это всё ещё не слишком полезно.
diff --git a/docs/ru/docs/tutorial/security/index.md b/docs/ru/docs/tutorial/security/index.md
index ebac013b6..bd8da824b 100644
--- a/docs/ru/docs/tutorial/security/index.md
+++ b/docs/ru/docs/tutorial/security/index.md
@@ -1,56 +1,56 @@
-# Настройка авторизации { #security }
+# Безопасность { #security }
Существует множество способов обеспечения безопасности, аутентификации и авторизации.
-Обычно эта тема является достаточно сложной и трудной.
+Обычно эта тема является достаточно сложной и «трудной».
-Во многих фреймворках и системах только работа с определением доступов к приложению и аутентификацией требует значительных затрат усилий и написания множества кода (во многих случаях его объём может составлять более 50% от всего написанного кода).
+Во многих фреймворках и системах только работа с безопасностью и аутентификацией требует значительных затрат усилий и написания множества кода (во многих случаях его объём может составлять 50% или более от всего написанного кода).
-**FastAPI** предоставляет несколько инструментов, которые помогут вам настроить **Авторизацию** легко, быстро, стандартным способом, без необходимости изучать все её тонкости.
+**FastAPI** предоставляет несколько инструментов, которые помогут вам работать с **безопасностью** легко, быстро, стандартным способом, без необходимости изучать и разбираться во всех спецификациях по безопасности.
-Но сначала давайте рассмотрим некоторые небольшие концепции.
+Но сначала давайте рассмотрим несколько небольших концепций.
-## Куда-то торопишься? { #in-a-hurry }
+## Нет времени? { #in-a-hurry }
-Если вам не нужна информация о каких-либо из следующих терминов и вам просто нужно добавить защиту с аутентификацией на основе логина и пароля *прямо сейчас*, переходите к следующим главам.
+Если вам не важны какие-либо из этих терминов и вам просто нужно добавить защиту с аутентификацией на основе имени пользователя и пароля прямо сейчас, переходите к следующим главам.
## OAuth2 { #oauth2 }
-OAuth2 - это протокол, который определяет несколько способов обработки аутентификации и авторизации.
+OAuth2 - это спецификация, которая определяет несколько способов обработки аутентификации и авторизации.
-Он довольно обширен и охватывает несколько сложных вариантов использования.
+Это довольно обширная спецификация, охватывающая несколько сложных вариантов использования.
-OAuth2 включает в себя способы аутентификации с использованием "третьей стороны".
+Она включает способы аутентификации с использованием «третьей стороны».
-Это то, что используют под собой все кнопки "вход с помощью Facebook, Google, X (Twitter), GitHub" на страницах авторизации.
+Именно это используется во всех системах с кнопками «войти с помощью Facebook, Google, X (Twitter), GitHub».
### OAuth 1 { #oauth-1 }
-Ранее использовался протокол OAuth 1, который сильно отличается от OAuth2 и является более сложным, поскольку он включал прямые описания того, как шифровать сообщение.
+Ранее использовался OAuth 1, который сильно отличается от OAuth2 и является более сложным, поскольку он включал прямые спецификации того, как шифровать обмен данными.
В настоящее время он не очень популярен и не используется.
-OAuth2 не указывает, как шифровать сообщение, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS.
+OAuth2 не указывает, как шифровать обмен данными, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS.
/// tip | Подсказка
-В разделе **Развертывание** вы увидите как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.
+В разделе о **развертывании** вы увидите, как настроить HTTPS бесплатно, используя Traefik и Let's Encrypt.
///
## OpenID Connect { #openid-connect }
-OpenID Connect - это еще один протокол, основанный на **OAuth2**.
+OpenID Connect — это ещё одна спецификация, основанная на **OAuth2**.
-Он просто расширяет OAuth2, уточняя некоторые вещи, не имеющие однозначного определения в OAuth2, в попытке сделать его более совместимым.
+Она просто расширяет OAuth2, уточняя некоторые вещи, которые относительно неоднозначны в OAuth2, стараясь сделать его более совместимым.
-Например, для входа в Google используется OpenID Connect (который под собой использует OAuth2).
+Например, для входа в Google используется OpenID Connect (который под капотом использует OAuth2).
Но вход в Facebook не поддерживает OpenID Connect. У него есть собственная вариация OAuth2.
-### OpenID (не "OpenID Connect") { #openid-not-openid-connect }
+### OpenID (не «OpenID Connect») { #openid-not-openid-connect }
-Также ранее использовался стандарт "OpenID", который пытался решить ту же проблему, что и **OpenID Connect**, но не был основан на OAuth2.
+Также ранее использовалась спецификация «OpenID», которая пыталась решить ту же задачу, что и **OpenID Connect**, но не была основана на OAuth2.
Таким образом, это была полноценная дополнительная система.
@@ -62,45 +62,45 @@ OpenAPI (ранее известный как Swagger) - это открытая
**FastAPI** основан на **OpenAPI**.
-Это то, что делает возможным наличие множества автоматических интерактивных интерфейсов документирования, сгенерированного кода и т.д.
+Это то, что делает возможными несколько автоматических интерактивных интерфейсов документации, генерацию кода и т.д.
-В OpenAPI есть способ использовать несколько "схем" безопасности.
+В OpenAPI есть способ определить несколько «схем» безопасности.
-Таким образом, вы можете воспользоваться преимуществами Всех этих стандартных инструментов, включая интерактивные системы документирования.
+Используя их, вы можете воспользоваться преимуществами всех этих инструментов, основанных на стандартах, включая интерактивные системы документирования.
-OpenAPI может использовать следующие схемы авторизации:
+OpenAPI определяет следующие схемы безопасности:
-* `apiKey`: уникальный идентификатор для приложения, который может быть получен из:
- * Параметров запроса.
- * Заголовка.
- * Cookies.
-* `http`: стандартные системы аутентификации по протоколу HTTP, включая:
- * `bearer`: заголовок `Authorization` со значением `Bearer {уникальный токен}`. Это унаследовано от OAuth2.
- * Базовая аутентификация по протоколу HTTP.
+* `apiKey`: специфичный для приложения ключ, который может поступать из:
+ * параметра запроса.
+ * HTTP-заголовка.
+ * cookie.
+* `http`: стандартные системы аутентификации по HTTP, включая:
+ * `bearer`: HTTP-заголовок `Authorization` со значением `Bearer ` плюс токен. Это унаследовано от OAuth2.
+ * Базовая аутентификация по HTTP.
* HTTP Digest и т.д.
-* `oauth2`: все способы обеспечения безопасности OAuth2 называемые "потоки" (англ. "flows").
- * Некоторые из этих "потоков" подходят для реализации аутентификации через сторонний сервис использующий OAuth 2.0 (например, Google, Facebook, X (Twitter), GitHub и т.д.):
+* `oauth2`: все способы OAuth2 для обеспечения безопасности (называются «потоками»).
+ * Несколько из этих «потоков» подходят для построения провайдера аутентификации OAuth 2.0 (например, Google, Facebook, X (Twitter), GitHub и т.д.):
* `implicit`
* `clientCredentials`
* `authorizationCode`
- * Но есть один конкретный "поток", который может быть идеально использован для обработки аутентификации непосредственно в том же приложении:
- * `password`: в некоторых следующих главах будут рассмотрены примеры этого.
-* `openIdConnect`: способ определить, как автоматически обнаруживать данные аутентификации OAuth2.
- * Это автоматическое обнаружение определено в спецификации OpenID Connect.
+ * Но есть один конкретный «поток», который можно идеально использовать для обработки аутентификации непосредственно в этом же приложении:
+ * `password`: в некоторых следующих главах будут приведены примеры.
+* `openIdConnect`: имеет способ определить, как автоматически обнаруживать данные аутентификации OAuth2.
+ * Именно это автоматическое обнаружение определено в спецификации OpenID Connect.
/// tip | Подсказка
-Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, X (Twitter), GitHub и т.д. осуществляется достаточно легко.
+Интеграция сторонних провайдеров аутентификации/авторизации, таких как Google, Facebook, X (Twitter), GitHub и т.д., также возможна и относительно проста.
-Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас.
+Самой сложной задачей является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжёлую работу за вас.
///
-## Преимущества **FastAPI** { #fastapi-utilities }
+## Инструменты **FastAPI** { #fastapi-utilities }
-Fast API предоставляет несколько инструментов для каждой из этих схем безопасности в модуле `fastapi.security`, которые упрощают использование этих механизмов безопасности.
+FastAPI предоставляет несколько инструментов для каждой из этих схем безопасности в модуле `fastapi.security`, которые упрощают использование этих механизмов безопасности.
-В следующих главах вы увидите, как обезопасить свой API, используя инструменты, предоставляемые **FastAPI**.
+В следующих главах вы увидите, как добавить безопасность в ваш API, используя инструменты, предоставляемые **FastAPI**.
-И вы также увидите, как он автоматически интегрируется в систему интерактивной документации.
+И вы также увидите, как это автоматически интегрируется в систему интерактивной документации.
diff --git a/docs/ru/docs/tutorial/security/oauth2-jwt.md b/docs/ru/docs/tutorial/security/oauth2-jwt.md
index 803491f53..7838b07df 100644
--- a/docs/ru/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/ru/docs/tutorial/security/oauth2-jwt.md
@@ -1,10 +1,10 @@
# OAuth2 с паролем (и хешированием), Bearer с JWT-токенами { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
-Теперь, когда у нас определен процесс обеспечения безопасности, давайте сделаем приложение действительно безопасным, используя токены JWT и безопасное хеширование паролей.
+Теперь, когда у нас определен процесс обеспечения безопасности, давайте сделаем приложение действительно безопасным, используя токены JWT и безопасное хеширование паролей.
Этот код можно реально использовать в своем приложении, сохранять хэши паролей в базе данных и т.д.
-Мы продолжим разбираться, начиная с того места, на котором остановились в предыдущей главе.
+Мы продолжим разбираться, начиная с того места, на котором остановились в предыдущей главе, и расширим его.
## Про JWT { #about-jwt }
@@ -43,9 +43,11 @@ $ pip install pyjwt
/// info | Дополнительная информация
+
Если вы планируете использовать алгоритмы цифровой подписи, такие как RSA или ECDSA, вам следует установить зависимость библиотеки криптографии `pyjwt[crypto]`.
Подробнее об этом можно прочитать в документации по установке PyJWT.
+
///
## Хеширование паролей { #password-hashing }
@@ -83,11 +85,13 @@ $ pip install "pwdlib[argon2]"
/// tip | Подсказка
+
С помощью `pwdlib` можно даже настроить его на чтение паролей, созданных **Django**, плагином безопасности **Flask** или многими другими библиотеками.
Таким образом, вы сможете, например, совместно использовать одни и те же данные из приложения Django в базе данных с приложением FastAPI. Или постепенно мигрировать Django-приложение, используя ту же базу данных.
При этом пользователи смогут одновременно входить в систему как из приложения Django, так и из приложения **FastAPI**.
+
///
## Хеширование и проверка паролей { #hash-and-verify-the-passwords }
@@ -97,11 +101,13 @@ $ pip install "pwdlib[argon2]"
Создайте экземпляр PasswordHash с рекомендованными настройками — он будет использоваться для хэширования и проверки паролей.
/// tip | Подсказка
+
pwdlib также поддерживает алгоритм хеширования bcrypt, но не включает устаревшие алгоритмы — для работы с устаревшими хэшами рекомендуется использовать библиотеку passlib.
Например, вы можете использовать ее для чтения и проверки паролей, сгенерированных другой системой (например, Django), но хэшировать все новые пароли другим алгоритмом, например Argon2 или Bcrypt.
И при этом быть совместимым со всеми этими системами.
+
///
Создайте служебную функцию для хэширования пароля, поступающего от пользователя.
@@ -110,10 +116,16 @@ pwdlib также поддерживает алгоритм хешировани
И еще одну — для аутентификации и возврата пользователя.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,51,58:59,62:63,72:79] *}
+
+Когда `authenticate_user` вызывается с именем пользователя, которого нет в базе данных, мы все равно запускаем `verify_password` с использованием фиктивного хэша.
+
+Это гарантирует, что эндпоинт отвечает примерно за одно и то же время вне зависимости от того, существует имя пользователя или нет, предотвращая тайминговые атаки (атака по времени), с помощью которых можно было бы перечислять существующие имена пользователей.
/// note | Технические детали
+
Если проверить новую (фальшивую) базу данных `fake_users_db`, то можно увидеть, как теперь выглядит хэшированный пароль: `"$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc"`.
+
///
## Работа с JWT токенами { #handle-jwt-tokens }
@@ -144,7 +156,7 @@ $ openssl rand -hex 32
Создайте служебную функцию для генерации нового токена доступа.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,82:90] *}
## Обновление зависимостей { #update-the-dependencies }
@@ -154,7 +166,7 @@ $ openssl rand -hex 32
Если токен недействителен, то сразу же верните HTTP-ошибку.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[93:110] *}
## Обновление *операции пути* `/token` { #update-the-token-path-operation }
@@ -162,7 +174,7 @@ $ openssl rand -hex 32
Создайте реальный токен доступа JWT и верните его
-{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[121:136] *}
### Технические подробности о JWT ключе `sub` { #technical-details-about-the-jwt-subject-sub }
@@ -202,7 +214,9 @@ Username: `johndoe`
Password: `secret`
/// check | Проверка
+
Обратите внимание, что нигде в коде не используется открытый текст пароля "`secret`", мы используем только его хэшированную версию.
+
///
@@ -225,7 +239,9 @@ Password: `secret`
/// note | Техническая информация
+
Обратите внимание на HTTP-заголовок `Authorization`, значение которого начинается с `Bearer `.
+
///
## Продвинутое использование `scopes` { #advanced-usage-with-scopes }
diff --git a/docs/ru/docs/tutorial/security/simple-oauth2.md b/docs/ru/docs/tutorial/security/simple-oauth2.md
index 36ff32c8e..4b86a4013 100644
--- a/docs/ru/docs/tutorial/security/simple-oauth2.md
+++ b/docs/ru/docs/tutorial/security/simple-oauth2.md
@@ -236,7 +236,7 @@ UserInDB(
-Если щёлкнуть на значке замка и выйти из системы, а затем попытаться выполнить ту же операцию ещё раз, будет выдана ошибка HTTP 401:
+Если щёлкнуть на значке замка и выйти из системы, а затем попробовать выполнить ту же операцию ещё раз, будет выдана ошибка HTTP 401:
```JSON
{
diff --git a/docs/ru/docs/tutorial/sql-databases.md b/docs/ru/docs/tutorial/sql-databases.md
index 1d0346533..ed67739cc 100644
--- a/docs/ru/docs/tutorial/sql-databases.md
+++ b/docs/ru/docs/tutorial/sql-databases.md
@@ -8,7 +8,7 @@
/// tip | Подсказка
-Вы можете использовать любую другую библиотеку для работы с SQL или NoSQL базами данных (иногда их называют "ORMs"), FastAPI ничего не навязывает. 😎
+Вы можете использовать любую другую библиотеку для работы с SQL или NoSQL базами данных (иногда их называют "ORMs"), FastAPI ничего не навязывает. 😎
///
@@ -344,7 +344,7 @@ $ fastapi dev main.py
-Если вы перейдёте в UI API `/docs`, вы увидите, что он обновился: теперь при создании героя он не ожидает получить `id` от клиента и т. д.
+Если вы перейдёте в UI API `/docs`, вы увидите, что он обновился: теперь при создании героя он не ожидает получить `id` от клиента и т.д.
@@ -354,4 +354,4 @@ $ fastapi dev main.py
Вы можете использовать **SQLModel** для взаимодействия с SQL базой данных и упростить код с помощью *моделей данных* и *моделей-таблиц*.
-Гораздо больше вы можете узнать в документации **SQLModel**, там есть более подробный мини-туториал по использованию SQLModel с **FastAPI**. 🚀
+Гораздо больше вы можете узнать в документации **SQLModel**, там есть более подробное мини-руководство по использованию SQLModel с **FastAPI**. 🚀
diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md
index f40cfe9b0..3b0cab831 100644
--- a/docs/ru/docs/tutorial/static-files.md
+++ b/docs/ru/docs/tutorial/static-files.md
@@ -7,7 +7,7 @@
* Импортируйте `StaticFiles`.
* "Примонтируйте" экземпляр `StaticFiles()` к определённому пути.
-{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py310.py hl[2,6] *}
/// note | Технические детали
diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md
index ab58429c5..6dd2fe579 100644
--- a/docs/ru/docs/tutorial/testing.md
+++ b/docs/ru/docs/tutorial/testing.md
@@ -30,7 +30,7 @@ $ pip install httpx
Напишите простое утверждение с `assert` дабы проверить истинность Python-выражения (это тоже стандарт `pytest`).
-{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py310.py hl[2,12,15:18] *}
/// tip | Подсказка
@@ -76,7 +76,7 @@ $ pip install httpx
В файле `main.py` находится Ваше приложение **FastAPI**:
-{* ../../docs_src/app_testing/app_a_py39/main.py *}
+{* ../../docs_src/app_testing/app_a_py310/main.py *}
### Файл тестов { #testing-file }
@@ -92,7 +92,7 @@ $ pip install httpx
Так как оба файла находятся в одной директории, для импорта объекта приложения из файла `main` в файл `test_main` Вы можете использовать относительный импорт:
-{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py310/test_main.py hl[3] *}
...и писать дальше тесты, как и раньше.
@@ -119,7 +119,7 @@ $ pip install httpx
Ещё есть операция `POST`, и она может вернуть несколько ошибок.
-Обе *операции пути* требуют наличия в запросе заголовка `X-Token`.
+Обе *операции пути* требуют наличия в запросе HTTP-заголовка `X-Token`.
{* ../../docs_src/app_testing/app_b_an_py310/main.py *}
@@ -139,7 +139,7 @@ $ pip install httpx
* Передаёте *path*-параметры или *query*-параметры, вписав их непосредственно в строку URL.
* Передаёте JSON в теле запроса, передав Python-объект (например: `dict`) через именованный параметр `json`.
* Если же Вам необходимо отправить *форму с данными* вместо JSON, то используйте параметр `data` вместо `json`.
-* Для передачи *заголовков*, передайте объект `dict` через параметр `headers`.
+* Для передачи *HTTP-заголовков*, передайте объект `dict` через параметр `headers`.
* Для передачи *cookies* также передайте `dict`, но через параметр `cookies`.
Для получения дополнительной информации о передаче данных на бэкенд с помощью `httpx` или `TestClient` ознакомьтесь с документацией HTTPX.
diff --git a/docs/ru/docs/virtual-environments.md b/docs/ru/docs/virtual-environments.md
index 43136298a..f931cc3c8 100644
--- a/docs/ru/docs/virtual-environments.md
+++ b/docs/ru/docs/virtual-environments.md
@@ -53,7 +53,7 @@ $ cd awesome-project
## Создание виртуального окружения { #create-a-virtual-environment }
-Когда вы начинаете работать над Python‑проектом **впервые**, создайте виртуальное окружение **внутри вашего проекта**.
+Когда вы начинаете работать над Python‑проектом **впервые**, создайте виртуальное окружение **внутри вашего проекта**.
/// tip | Подсказка
@@ -166,7 +166,7 @@ $ source .venv/Scripts/activate
Каждый раз, когда вы устанавливаете **новый пакет** в это окружение, **активируйте** окружение снова.
-Это гарантирует, что если вы используете **программу терминала (CLI)**, установленную этим пакетом, вы будете использовать именно ту, что из вашего виртуального окружения, а не какую‑то глобально установленную, возможно другой версии, чем вам нужна.
+Это гарантирует, что если вы используете **программу терминала (CLI)**, установленную этим пакетом, вы будете использовать именно ту, что из вашего виртуального окружения, а не какую‑то глобально установленную, возможно другой версии, чем вам нужна.
///
From 6fa573ce0bc16fe445f93db413d20146dd9ff35d Mon Sep 17 00:00:00 2001
From: "github-actions[bot]" lt
-* XWT
+* XWT
* PSGI
-### abbr bir açıklama verir { #the-abbr-gives-an-explanation }
-
-* cluster
-* Deep Learning
-
### abbr tam bir ifade ve bir açıklama verir { #the-abbr-gives-a-full-phrase-and-an-explanation }
* MDN
@@ -220,10 +215,15 @@ Burada HTML "abbr" öğeleriyle sarılmış bazı şeyler var (bazıları uydurm
Çeviriler, LLM'nin kaldırmaması gereken kendi "abbr" öğelerini ekleyebilir. Örneğin İngilizce kelimeleri açıklamak için.
-`script/translate.py` içindeki genel prompt'ta `### HTML abbr elements` bölümüne bakın.
+`scripts/translate.py` içindeki genel prompt'ta `### HTML abbr elements` bölümüne bakın.
////
+## HTML "dfn" öğeleri { #html-dfn-elements }
+
+* küme
+* Derin Öğrenme
+
## Başlıklar { #headings }
//// tab | Test
@@ -246,7 +246,7 @@ Tekrar merhaba.
Başlıklarla ilgili tek katı kural, LLM'nin süslü parantezler içindeki hash kısmını değiştirmemesidir; böylece link'ler bozulmaz.
-`script/translate.py` içindeki genel prompt'ta `### Headings` bölümüne bakın.
+`scripts/translate.py` içindeki genel prompt'ta `### Headings` bölümüne bakın.
Dile özel bazı talimatlar için örneğin `docs/de/llm-prompt.md` içindeki `### Headings` bölümüne bakın.
diff --git a/docs/tr/docs/advanced/additional-responses.md b/docs/tr/docs/advanced/additional-responses.md
index c8e372775..3a066af40 100644
--- a/docs/tr/docs/advanced/additional-responses.md
+++ b/docs/tr/docs/advanced/additional-responses.md
@@ -26,7 +26,7 @@ Bu response `dict`'lerinin her birinde, `response_model`'e benzer şekilde bir P
Örneğin, `404` status code'u ve `Message` Pydantic model'i ile başka bir response tanımlamak için şunu yazabilirsiniz:
-{* ../../docs_src/additional_responses/tutorial001_py39.py hl[18,22] *}
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
/// note | Not
@@ -203,7 +203,7 @@ Varsayılan `200` status code'unu (ya da gerekiyorsa özel bir tane) kullanarak
Ayrıca `response_model`'inizi kullanan, ancak özel bir `example` içeren `200` status code'lu bir response da tanımlayabilirsiniz:
-{* ../../docs_src/additional_responses/tutorial003_py39.py hl[20:31] *}
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
Bunların hepsi OpenAPI'nize birleştirilerek dahil edilir ve API dokümanlarında gösterilir:
diff --git a/docs/tr/docs/advanced/advanced-dependencies.md b/docs/tr/docs/advanced/advanced-dependencies.md
index 8afb544bd..8be92a6ac 100644
--- a/docs/tr/docs/advanced/advanced-dependencies.md
+++ b/docs/tr/docs/advanced/advanced-dependencies.md
@@ -18,7 +18,7 @@ Class'ın kendisini değil (zaten callable'dır), o class'ın bir instance'ını
Bunu yapmak için `__call__` adında bir method tanımlarız:
-{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *}
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
Bu durumda, ek parametreleri ve alt-dependency'leri kontrol etmek için **FastAPI**'nin kullanacağı şey bu `__call__` olacaktır; ayrıca daha sonra *path operation function* içindeki parametreye bir değer geçmek için çağrılacak olan da budur.
@@ -26,7 +26,7 @@ Bu durumda, ek parametreleri ve alt-dependency'leri kontrol etmek için **FastAP
Ve şimdi, dependency'yi "parametreleştirmek" için kullanacağımız instance parametrelerini tanımlamak üzere `__init__` kullanabiliriz:
-{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *}
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
Bu durumda **FastAPI**, `__init__` ile asla uğraşmaz veya onu önemsemez; onu doğrudan kendi kodumuzda kullanırız.
@@ -34,7 +34,7 @@ Bu durumda **FastAPI**, `__init__` ile asla uğraşmaz veya onu önemsemez; onu
Bu class'tan bir instance'ı şöyle oluşturabiliriz:
-{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *}
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
Böylece dependency'mizi "parametreleştirmiş" oluruz; artık içinde `"bar"` vardır ve bu değer `checker.fixed_content` attribute'u olarak durur.
@@ -50,7 +50,7 @@ checker(q="somequery")
...ve bunun döndürdüğü her şeyi, *path operation function* içinde `fixed_content_included` parametresine dependency değeri olarak geçirir:
-{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *}
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
/// tip | İpucu
diff --git a/docs/tr/docs/advanced/advanced-python-types.md b/docs/tr/docs/advanced/advanced-python-types.md
new file mode 100644
index 000000000..91fe1d5e0
--- /dev/null
+++ b/docs/tr/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# Gelişmiş Python Tipleri { #advanced-python-types }
+
+Python tipleriyle çalışırken işinize yarayabilecek bazı ek fikirler.
+
+## `Union` veya `Optional` Kullanımı { #using-union-or-optional }
+
+Kodunuz herhangi bir nedenle `|` kullanamıyorsa — örneğin bir tip açıklamasında (type annotation) değil de `response_model=` gibi bir yerdeyse — dikey çizgi (`|`) yerine `typing` içindeki `Union`'ı kullanabilirsiniz.
+
+Örneğin, bir şeyin `str` ya da `None` olabileceğini şöyle belirtebilirsiniz:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing`, bir şeyin `None` olabileceğini belirtmek için `Optional` ile bir kısayol da sunar.
+
+Benim oldukça öznel bakış açıma göre küçük bir ipucu:
+
+- 🚨 `Optional[SomeType]` kullanmaktan kaçının
+- Bunun yerine ✨ **`Union[SomeType, None]` kullanın** ✨.
+
+İkisi de eşdeğer ve temelde aynıdır; ancak "**optional**" kelimesi değerin isteğe bağlı olduğunu ima eder. Oysa aslında " `None` olabilir" demektir; değer isteğe bağlı olmasa ve hâlâ zorunlu olsa bile.
+
+Bence `Union[SomeType, None]` ne demek istediğini daha açık anlatır.
+
+Burada mesele sadece kelimeler ve isimler. Ancak bu kelimeler sizin ve ekip arkadaşlarınızın koda bakışını etkileyebilir.
+
+Örnek olarak şu fonksiyona bakalım:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+`name` parametresi `Optional[str]` olarak tanımlıdır; ancak isteğe bağlı değildir, parametre olmadan fonksiyonu çağıramazsınız:
+
+```Python
+say_hi() # Ah hayır, bu hata fırlatır! 😱
+```
+
+`name` parametresi varsayılan bir değeri olmadığı için hâlâ zorunludur (yani *optional* değildir). Yine de `name`, değer olarak `None` kabul eder:
+
+```Python
+say_hi(name=None) # Bu çalışır, None geçerlidir 🎉
+```
+
+İyi haber şu ki, çoğu durumda tip birliklerini (union) tanımlamak için doğrudan `|` kullanabilirsiniz:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+Dolayısıyla, normalde `Optional` ve `Union` gibi isimler için endişelenmenize gerek yok. 😎
diff --git a/docs/tr/docs/advanced/async-tests.md b/docs/tr/docs/advanced/async-tests.md
index 82349bbec..1e5b37a3d 100644
--- a/docs/tr/docs/advanced/async-tests.md
+++ b/docs/tr/docs/advanced/async-tests.md
@@ -32,11 +32,11 @@ Basit bir örnek için, [Bigger Applications](../tutorial/bigger-applications.md
`main.py` dosyası şöyle olur:
-{* ../../docs_src/async_tests/app_a_py39/main.py *}
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
`test_main.py` dosyasında `main.py` için testler yer alır, artık şöyle görünebilir:
-{* ../../docs_src/async_tests/app_a_py39/test_main.py *}
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
## Çalıştırma { #run-it }
@@ -56,7 +56,7 @@ $ pytest
`@pytest.mark.anyio` marker'ı, pytest'e bu test fonksiyonunun asenkron olarak çağrılması gerektiğini söyler:
-{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[7] *}
+{* ../../docs_src/async_tests/app_a_py310/test_main.py hl[7] *}
/// tip | İpucu
@@ -66,7 +66,7 @@ Test fonksiyonu artık `TestClient` kullanırken eskiden olduğu gibi sadece `de
Ardından app ile bir `AsyncClient` oluşturup `await` kullanarak ona async request'ler gönderebiliriz.
-{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[9:12] *}
+{* ../../docs_src/async_tests/app_a_py310/test_main.py hl[9:12] *}
Bu, şu kullanıma denktir:
diff --git a/docs/tr/docs/advanced/behind-a-proxy.md b/docs/tr/docs/advanced/behind-a-proxy.md
index e70b16960..5cf9a534d 100644
--- a/docs/tr/docs/advanced/behind-a-proxy.md
+++ b/docs/tr/docs/advanced/behind-a-proxy.md
@@ -44,7 +44,7 @@ $ fastapi run --forwarded-allow-ips="*"
Örneğin `/items/` adında bir *path operation* tanımladığınızı düşünelim:
-{* ../../docs_src/behind_a_proxy/tutorial001_01_py39.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_01_py310.py hl[6] *}
Client `/items`'a gitmeye çalışırsa, varsayılan olarak `/items/`'a redirect edilir.
@@ -115,7 +115,7 @@ Bu durumda, orijinal `/app` path'i aslında `/api/v1/app` altında servis edilir
Kodunuzun tamamı sadece `/app` varmış gibi yazılmış olsa bile.
-{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[6] *}
Proxy, request'i app server'a (muhtemelen FastAPI CLI üzerinden Uvicorn) iletmeden önce **path prefix**'i anlık olarak **"kırpar"** (strip). Böylece uygulamanız hâlâ `/app` altında servis ediliyormuş gibi davranır ve tüm kodunuzu `/api/v1` prefix'ini içerecek şekilde güncellemeniz gerekmez.
@@ -149,14 +149,14 @@ Docs UI'nin, bu API `server`'ının (proxy arkasında) `/api/v1` altında bulund
```JSON hl_lines="4-8"
{
"openapi": "3.1.0",
- // More stuff here
+ // Burada daha fazla şey var
"servers": [
{
"url": "/api/v1"
}
],
"paths": {
- // More stuff here
+ // Burada daha fazla şey var
}
}
```
@@ -193,7 +193,7 @@ Uygulamanızın her request için kullandığı mevcut `root_path` değerini ala
Burada sadece göstermek için bunu mesaja dahil ediyoruz.
-{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[8] *}
Ardından Uvicorn'u şu şekilde başlatırsanız:
@@ -220,7 +220,7 @@ Response şöyle bir şey olur:
Alternatif olarak, `--root-path` gibi bir komut satırı seçeneği (veya muadili) sağlayamıyorsanız, FastAPI uygulamanızı oluştururken `root_path` parametresini ayarlayabilirsiniz:
-{* ../../docs_src/behind_a_proxy/tutorial002_py39.py hl[3] *}
+{* ../../docs_src/behind_a_proxy/tutorial002_py310.py hl[3] *}
`FastAPI`'ye `root_path` vermek, Uvicorn veya Hypercorn'a `--root-path` komut satırı seçeneğini vermekle eşdeğerdir.
@@ -400,14 +400,14 @@ Ancak başka alternatif `servers` da sağlayabilirsiniz; örneğin *aynı* docs
Örneğin:
-{* ../../docs_src/behind_a_proxy/tutorial003_py39.py hl[4:7] *}
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
Şöyle bir OpenAPI şeması üretir:
```JSON hl_lines="5-7"
{
"openapi": "3.1.0",
- // More stuff here
+ // Burada daha fazla şey var
"servers": [
{
"url": "/api/v1"
@@ -422,7 +422,7 @@ Ancak başka alternatif `servers` da sağlayabilirsiniz; örneğin *aynı* docs
}
],
"paths": {
- // More stuff here
+ // Burada daha fazla şey var
}
}
```
@@ -455,7 +455,7 @@ OpenAPI spesifikasyonunda `servers` özelliği opsiyoneldir.
**FastAPI**'nin `root_path` kullanarak otomatik bir server eklemesini istemiyorsanız, `root_path_in_servers=False` parametresini kullanabilirsiniz:
-{* ../../docs_src/behind_a_proxy/tutorial004_py39.py hl[9] *}
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
Böylece OpenAPI şemasına dahil etmez.
diff --git a/docs/tr/docs/advanced/custom-response.md b/docs/tr/docs/advanced/custom-response.md
index c5148f428..218a5de5c 100644
--- a/docs/tr/docs/advanced/custom-response.md
+++ b/docs/tr/docs/advanced/custom-response.md
@@ -30,7 +30,7 @@ Büyük response'larda, doğrudan bir `Response` döndürmek bir dictionary dön
Ancak döndürdüğünüz içeriğin **JSON ile serialize edilebilir** olduğundan eminseniz, onu doğrudan response class’ına verebilir ve FastAPI’nin response class’ına vermeden önce dönüş içeriğinizi `jsonable_encoder` içinden geçirirken oluşturacağı ek yükten kaçınabilirsiniz.
-{* ../../docs_src/custom_response/tutorial001b_py39.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001b_py310.py hl[2,7] *}
/// info | Bilgi
@@ -55,7 +55,7 @@ Ve OpenAPI’de de bu şekilde dokümante edilir.
* `HTMLResponse` import edin.
* *path operation decorator*’ınızın `response_class` parametresi olarak `HTMLResponse` verin.
-{* ../../docs_src/custom_response/tutorial002_py39.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
/// info | Bilgi
@@ -73,7 +73,7 @@ Ve OpenAPI’de de bu şekilde dokümante edilir.
Yukarıdaki örneğin aynısı, bu sefer bir `HTMLResponse` döndürerek, şöyle görünebilir:
-{* ../../docs_src/custom_response/tutorial003_py39.py hl[2,7,19] *}
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
/// warning | Uyarı
@@ -97,7 +97,7 @@ Bu durumda `response_class` sadece OpenAPI *path operation*’ını dokümante e
Örneğin şöyle bir şey olabilir:
-{* ../../docs_src/custom_response/tutorial004_py39.py hl[7,21,23] *}
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
Bu örnekte `generate_html_response()` fonksiyonu, HTML’i bir `str` olarak döndürmek yerine zaten bir `Response` üretip döndürmektedir.
@@ -136,7 +136,7 @@ Bunu doğrudan döndürebilirsiniz.
FastAPI (aslında Starlette) otomatik olarak bir Content-Length header’ı ekler. Ayrıca `media_type`’a göre bir Content-Type header’ı ekler ve text türleri için sona bir charset ekler.
-{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
### `HTMLResponse` { #htmlresponse }
@@ -146,7 +146,7 @@ Yukarıda okuduğunuz gibi, bir miktar text veya bytes alır ve HTML response d
Bir miktar text veya bytes alır ve düz metin response döndürür.
-{* ../../docs_src/custom_response/tutorial005_py39.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
### `JSONResponse` { #jsonresponse }
@@ -180,7 +180,7 @@ Bunun için `ujson` kurulmalıdır; örneğin `pip install ujson`.
///
-{* ../../docs_src/custom_response/tutorial001_py39.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001_py310.py hl[2,7] *}
/// tip | İpucu
@@ -194,13 +194,13 @@ HTTP redirect döndürür. Varsayılan olarak 307 status code (Temporary Redirec
`RedirectResponse`’u doğrudan döndürebilirsiniz:
-{* ../../docs_src/custom_response/tutorial006_py39.py hl[2,9] *}
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
---
Veya `response_class` parametresi içinde kullanabilirsiniz:
-{* ../../docs_src/custom_response/tutorial006b_py39.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
Bunu yaparsanız, *path operation* function’ınızdan doğrudan URL döndürebilirsiniz.
@@ -210,13 +210,13 @@ Bu durumda kullanılan `status_code`, `RedirectResponse` için varsayılan olan
Ayrıca `status_code` parametresini `response_class` parametresiyle birlikte kullanabilirsiniz:
-{* ../../docs_src/custom_response/tutorial006c_py39.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
### `StreamingResponse` { #streamingresponse }
Bir async generator veya normal generator/iterator alır ve response body’yi stream eder.
-{* ../../docs_src/custom_response/tutorial007_py39.py hl[2,14] *}
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[2,14] *}
#### `StreamingResponse`’u file-like objelerle kullanma { #using-streamingresponse-with-file-like-objects }
@@ -226,7 +226,7 @@ Böylece önce hepsini memory’ye okumak zorunda kalmazsınız; bu generator fu
Buna cloud storage ile etkileşime giren, video işleyen ve benzeri birçok kütüphane dahildir.
-{* ../../docs_src/custom_response/tutorial008_py39.py hl[2,10:12,14] *}
+{* ../../docs_src/custom_response/tutorial008_py310.py hl[2,10:12,14] *}
1. Bu generator function’dır. İçinde `yield` ifadeleri olduğu için "generator function" denir.
2. Bir `with` bloğu kullanarak, generator function bittiğinde file-like objenin kapandığından emin oluruz. Yani response göndermeyi bitirdikten sonra kapanır.
@@ -255,11 +255,11 @@ Diğer response türlerine göre instantiate ederken farklı argümanlar alır:
File response'ları uygun `Content-Length`, `Last-Modified` ve `ETag` header’larını içerir.
-{* ../../docs_src/custom_response/tutorial009_py39.py hl[2,10] *}
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
`response_class` parametresini de kullanabilirsiniz:
-{* ../../docs_src/custom_response/tutorial009b_py39.py hl[2,8,10] *}
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
Bu durumda *path operation* function’ınızdan doğrudan dosya path'ini döndürebilirsiniz.
@@ -273,7 +273,7 @@ Diyelim ki girintili ve biçimlendirilmiş JSON döndürmek istiyorsunuz; bunun
Bir `CustomORJSONResponse` oluşturabilirsiniz. Burada yapmanız gereken temel şey, content’i `bytes` olarak döndüren bir `Response.render(content)` metodu yazmaktır:
-{* ../../docs_src/custom_response/tutorial009c_py39.py hl[9:14,17] *}
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
Artık şunu döndürmek yerine:
@@ -299,7 +299,7 @@ Bunu tanımlayan parametre `default_response_class`’tır.
Aşağıdaki örnekte **FastAPI**, tüm *path operations* için varsayılan olarak `JSONResponse` yerine `ORJSONResponse` kullanır.
-{* ../../docs_src/custom_response/tutorial010_py39.py hl[2,4] *}
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
/// tip | İpucu
diff --git a/docs/tr/docs/advanced/dataclasses.md b/docs/tr/docs/advanced/dataclasses.md
index 263976007..ed70a6a94 100644
--- a/docs/tr/docs/advanced/dataclasses.md
+++ b/docs/tr/docs/advanced/dataclasses.md
@@ -64,7 +64,7 @@ Bu durumda standart `dataclasses` yerine, drop-in replacement olan `pydantic.dat
6. Burada `items` içeren bir dictionary döndürüyoruz; `items` bir dataclass listesi.
- FastAPI, veriyi JSON'a serializing etmeyi yine başarır.
+ FastAPI, veriyi JSON'a serileştirmeyi yine başarır.
7. Burada `response_model`, `Author` dataclass'larından oluşan bir listenin type annotation'ını kullanıyor.
diff --git a/docs/tr/docs/advanced/events.md b/docs/tr/docs/advanced/events.md
index 257b952f9..cef8b42a5 100644
--- a/docs/tr/docs/advanced/events.md
+++ b/docs/tr/docs/advanced/events.md
@@ -30,7 +30,7 @@ Bu *startup* ve *shutdown* mantığını, `FastAPI` uygulamasının `lifespan` p
Aşağıdaki gibi `yield` kullanan async bir `lifespan()` fonksiyonu oluşturuyoruz:
-{* ../../docs_src/events/tutorial003_py39.py hl[16,19] *}
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
Burada, `yield` öncesinde (sahte) model fonksiyonunu machine learning modellerini içeren dictionary’e koyarak, modeli yükleme gibi maliyetli bir *startup* işlemini simüle ediyoruz. Bu kod, *startup* sırasında, uygulama **request almaya başlamadan önce** çalıştırılır.
@@ -48,7 +48,7 @@ Belki yeni bir sürüm başlatmanız gerekiyordur, ya da çalıştırmaktan sık
Dikkat edilmesi gereken ilk şey, `yield` içeren async bir fonksiyon tanımlıyor olmamız. Bu, `yield` kullanan Dependencies’e oldukça benzer.
-{* ../../docs_src/events/tutorial003_py39.py hl[14:19] *}
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
Fonksiyonun `yield`’den önceki kısmı, uygulama başlamadan **önce** çalışır.
@@ -60,7 +60,7 @@ Bakarsanız, fonksiyon `@asynccontextmanager` ile dekore edilmiş.
Bu da fonksiyonu "**async context manager**" denen şeye dönüştürür.
-{* ../../docs_src/events/tutorial003_py39.py hl[1,13] *}
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
Python’da **context manager**, `with` ifadesi içinde kullanabildiğiniz bir yapıdır. Örneğin `open()` bir context manager olarak kullanılabilir:
@@ -82,7 +82,7 @@ Yukarıdaki kod örneğimizde bunu doğrudan kullanmıyoruz; bunun yerine FastAP
`FastAPI` uygulamasının `lifespan` parametresi bir **async context manager** alır; dolayısıyla oluşturduğumuz yeni `lifespan` async context manager’ını buraya geçebiliriz.
-{* ../../docs_src/events/tutorial003_py39.py hl[22] *}
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
## Alternatif Events (kullanımdan kaldırıldı) { #alternative-events-deprecated }
@@ -104,7 +104,7 @@ Bu fonksiyonlar `async def` ile veya normal `def` ile tanımlanabilir.
Uygulama başlamadan önce çalıştırılacak bir fonksiyon eklemek için, `"startup"` event’i ile tanımlayın:
-{* ../../docs_src/events/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
Bu durumda `startup` event handler fonksiyonu, "database" öğesini (sadece bir `dict`) bazı değerlerle başlatır.
@@ -116,7 +116,7 @@ Ve tüm `startup` event handler’ları tamamlanmadan uygulamanız request almay
Uygulama kapanırken çalıştırılacak bir fonksiyon eklemek için, `"shutdown"` event’i ile tanımlayın:
-{* ../../docs_src/events/tutorial002_py39.py hl[6] *}
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
Burada `shutdown` event handler fonksiyonu, `log.txt` dosyasına `"Application shutdown"` satırını yazar.
@@ -150,11 +150,11 @@ Bu nedenle artık bunun yerine, yukarıda açıklandığı gibi `lifespan` kulla
Meraklı nerd’ler için küçük bir teknik detay. 🤓
-Altta, ASGI teknik spesifikasyonunda bu, Lifespan Protocol’ün bir parçasıdır ve `startup` ile `shutdown` adında event’ler tanımlar.
+Altta, ASGI teknik spesifikasyonunda bu, Lifespan Protokolü’nün bir parçasıdır ve `startup` ile `shutdown` adında event’ler tanımlar.
/// info | Bilgi
-Starlette `lifespan` handler’ları hakkında daha fazlasını Starlette's Lifespan docs içinde okuyabilirsiniz.
+Starlette `lifespan` handler’ları hakkında daha fazlasını Starlette Lifespan dokümanları içinde okuyabilirsiniz.
Ayrıca kodunuzun başka bölgelerinde de kullanılabilecek lifespan state’i nasıl yöneteceğinizi de kapsar.
diff --git a/docs/tr/docs/advanced/generate-clients.md b/docs/tr/docs/advanced/generate-clients.md
index af278f2fe..f3d6038a8 100644
--- a/docs/tr/docs/advanced/generate-clients.md
+++ b/docs/tr/docs/advanced/generate-clients.md
@@ -40,7 +40,7 @@ Bu çözümlerin bazıları açık kaynak olabilir veya ücretsiz katman sunabil
Basit bir FastAPI uygulamasıyla başlayalım:
-{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *}
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
*Path operation*'ların, request payload ve response payload için kullandıkları modelleri `Item` ve `ResponseMessage` modelleriyle tanımladıklarına dikkat edin.
@@ -98,7 +98,7 @@ Birçok durumda FastAPI uygulamanız daha büyük olacaktır ve farklı *path op
Örneğin **items** için bir bölüm, **users** için başka bir bölüm olabilir ve bunları tag'lerle ayırabilirsiniz:
-{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *}
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
### Tag'lerle TypeScript Client Üretme { #generate-a-typescript-client-with-tags }
@@ -145,7 +145,7 @@ Bu fonksiyonu özelleştirebilirsiniz. Bir `APIRoute` alır ve string döndürü
Sonrasında bu özel fonksiyonu `generate_unique_id_function` parametresiyle **FastAPI**'ye geçebilirsiniz:
-{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *}
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
### Özel Operation ID'lerle TypeScript Client Üretme { #generate-a-typescript-client-with-custom-operation-ids }
@@ -167,7 +167,7 @@ Ancak üretilen client için, client'ları üretmeden hemen önce OpenAPI operat
OpenAPI JSON'u `openapi.json` diye bir dosyaya indirip, şu tarz bir script ile **öndeki tag'i kaldırabiliriz**:
-{* ../../docs_src/generate_clients/tutorial004_py39.py *}
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
//// tab | Node.js
diff --git a/docs/tr/docs/advanced/index.md b/docs/tr/docs/advanced/index.md
index 3995109e2..ec43da6b3 100644
--- a/docs/tr/docs/advanced/index.md
+++ b/docs/tr/docs/advanced/index.md
@@ -2,7 +2,7 @@
## Ek Özellikler { #additional-features }
-Ana [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfası, **FastAPI**'ın tüm temel özelliklerini tanımanız için yeterli olmalıdır.
+Ana [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfası, **FastAPI**'nin tüm temel özelliklerini tanımanız için yeterli olmalıdır.
Sonraki bölümlerde diğer seçenekleri, konfigürasyonları ve ek özellikleri göreceksiniz.
@@ -16,6 +16,6 @@ Ve kullanım amacınıza bağlı olarak, çözüm bunlardan birinde olabilir.
## Önce Tutorial'ı Okuyun { #read-the-tutorial-first }
-Ana [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfasındaki bilgilerle **FastAPI**'nın çoğu özelliğini yine de kullanabilirsiniz.
+Ana [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfasındaki bilgilerle **FastAPI**'nin çoğu özelliğini yine de kullanabilirsiniz.
Ve sonraki bölümler, onu zaten okuduğunuzu ve bu temel fikirleri bildiğinizi varsayar.
diff --git a/docs/tr/docs/advanced/middleware.md b/docs/tr/docs/advanced/middleware.md
index a22644a09..7c1fb54f6 100644
--- a/docs/tr/docs/advanced/middleware.md
+++ b/docs/tr/docs/advanced/middleware.md
@@ -57,13 +57,13 @@ Gelen tüm request'lerin `https` veya `wss` olmasını zorunlu kılar.
`http` veya `ws` olarak gelen herhangi bir request, bunun yerine güvenli şemaya redirect edilir.
-{* ../../docs_src/advanced_middleware/tutorial001_py39.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial001_py310.py hl[2,6] *}
## `TrustedHostMiddleware` { #trustedhostmiddleware }
HTTP Host Header saldırılarına karşı korunmak için, gelen tüm request'lerde `Host` header'ının doğru ayarlanmış olmasını zorunlu kılar.
-{* ../../docs_src/advanced_middleware/tutorial002_py39.py hl[2,6:8] *}
+{* ../../docs_src/advanced_middleware/tutorial002_py310.py hl[2,6:8] *}
Aşağıdaki argümanlar desteklenir:
@@ -78,7 +78,7 @@ Gelen bir request doğru şekilde doğrulanmazsa `400` response gönderilir.
Middleware hem standart hem de streaming response'ları ele alır.
-{* ../../docs_src/advanced_middleware/tutorial003_py39.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial003_py310.py hl[2,6] *}
Aşağıdaki argümanlar desteklenir:
diff --git a/docs/tr/docs/advanced/openapi-webhooks.md b/docs/tr/docs/advanced/openapi-webhooks.md
index dd9e9bbe7..68b7e6f8d 100644
--- a/docs/tr/docs/advanced/openapi-webhooks.md
+++ b/docs/tr/docs/advanced/openapi-webhooks.md
@@ -32,7 +32,7 @@ Webhook'lar OpenAPI 3.1.0 ve üzeri sürümlerde mevcuttur; FastAPI `0.99.0` ve
Bir **FastAPI** uygulaması oluşturduğunuzda, *webhook*'ları tanımlamak için kullanabileceğiniz bir `webhooks` attribute'u vardır; *path operation* tanımlar gibi, örneğin `@app.webhooks.post()` ile.
-{* ../../docs_src/openapi_webhooks/tutorial001_py39.py hl[9:13,36:53] *}
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
Tanımladığınız webhook'lar **OpenAPI** şemasında ve otomatik **docs UI**'da yer alır.
diff --git a/docs/tr/docs/advanced/path-operation-advanced-configuration.md b/docs/tr/docs/advanced/path-operation-advanced-configuration.md
index e326842d6..ad2c46095 100644
--- a/docs/tr/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/tr/docs/advanced/path-operation-advanced-configuration.md
@@ -12,7 +12,7 @@ OpenAPI konusunda "uzman" değilseniz, muhtemelen buna ihtiyacınız yok.
Bunun her operation için benzersiz olduğundan emin olmanız gerekir.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
### operationId olarak *path operation function* adını kullanma { #using-the-path-operation-function-name-as-the-operationid }
@@ -20,7 +20,7 @@ API’lerinizin function adlarını `operationId` olarak kullanmak istiyorsanız
Bunu, tüm *path operation*’ları ekledikten sonra yapmalısınız.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py39.py hl[2, 12:21, 24] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
/// tip | İpucu
@@ -40,7 +40,7 @@ Farklı modüllerde (Python dosyalarında) olsalar bile.
Bir *path operation*’ı üretilen OpenAPI şemasından (dolayısıyla otomatik dokümantasyon sistemlerinden) hariç tutmak için `include_in_schema` parametresini kullanın ve `False` yapın:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
## Docstring’den İleri Düzey Açıklama { #advanced-description-from-docstring }
@@ -68,7 +68,7 @@ Uygulamanızda bir *path operation* tanımladığınızda, **FastAPI** OpenAPI
/// note | Teknik Detaylar
-OpenAPI spesifikasyonunda buna Operation Object denir.
+OpenAPI spesifikasyonunda buna Operation Nesnesi denir.
///
@@ -90,9 +90,9 @@ Bir *path operation* için OpenAPI şemasını `openapi_extra` parametresiyle ge
### OpenAPI Extensions { #openapi-extensions }
-Örneğin bu `openapi_extra`, [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) tanımlamak için faydalı olabilir:
+Örneğin bu `openapi_extra`, [OpenAPI Uzantıları](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) tanımlamak için faydalı olabilir:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py39.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
Otomatik API dokümanlarını açtığınızda, extension’ınız ilgili *path operation*’ın en altında görünür.
@@ -139,9 +139,9 @@ Böylece otomatik üretilen şemaya ek veri ekleyebilirsiniz.
Bunu `openapi_extra` ile yapabilirsiniz:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py39.py hl[19:36, 39:40] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
-Bu örnekte herhangi bir Pydantic model tanımlamadık. Hatta request body JSON olarak parsed bile edilmiyor; doğrudan `bytes` olarak okunuyor ve `magic_data_reader()` fonksiyonu bunu bir şekilde parse etmekten sorumlu oluyor.
+Bu örnekte herhangi bir Pydantic model tanımlamadık. Hatta request body JSON olarak ayrıştırılmıyor; doğrudan `bytes` olarak okunuyor ve `magic_data_reader()` fonksiyonu bunu bir şekilde parse etmekten sorumlu oluyor.
Buna rağmen, request body için beklenen şemayı tanımlayabiliriz.
@@ -153,7 +153,7 @@ Ve bunu, request içindeki veri tipi JSON olmasa bile yapabilirsiniz.
Örneğin bu uygulamada, FastAPI’nin Pydantic modellerinden JSON Schema çıkarmaya yönelik entegre işlevselliğini ve JSON için otomatik doğrulamayı kullanmıyoruz. Hatta request content type’ını JSON değil, YAML olarak tanımlıyoruz:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[15:20, 22] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
Buna rağmen, varsayılan entegre işlevselliği kullanmasak da, YAML olarak almak istediğimiz veri için JSON Schema’yı manuel üretmek üzere bir Pydantic model kullanmaya devam ediyoruz.
@@ -161,7 +161,7 @@ Ardından request’i doğrudan kullanıp body’yi `bytes` olarak çıkarıyoru
Sonrasında kodumuzda bu YAML içeriğini doğrudan parse ediyor, ardından YAML içeriğini doğrulamak için yine aynı Pydantic modeli kullanıyoruz:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[24:31] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
/// tip | İpucu
diff --git a/docs/tr/docs/advanced/response-change-status-code.md b/docs/tr/docs/advanced/response-change-status-code.md
index 239c0dddd..cc86cc0e3 100644
--- a/docs/tr/docs/advanced/response-change-status-code.md
+++ b/docs/tr/docs/advanced/response-change-status-code.md
@@ -20,7 +20,7 @@ Bu tür durumlarda bir `Response` parametresi kullanabilirsiniz.
Ardından bu *geçici (temporal)* `Response` nesnesi üzerinde `status_code` değerini ayarlayabilirsiniz.
-{* ../../docs_src/response_change_status_code/tutorial001_py39.py hl[1,9,12] *}
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
Sonrasında, normalde yaptığınız gibi ihtiyacınız olan herhangi bir nesneyi döndürebilirsiniz (`dict`, bir veritabanı modeli, vb.).
diff --git a/docs/tr/docs/advanced/response-cookies.md b/docs/tr/docs/advanced/response-cookies.md
index d00bfc4cd..526d6d3c6 100644
--- a/docs/tr/docs/advanced/response-cookies.md
+++ b/docs/tr/docs/advanced/response-cookies.md
@@ -6,7 +6,7 @@
Ardından bu *geçici* response nesnesi üzerinde cookie'leri set edebilirsiniz.
-{* ../../docs_src/response_cookies/tutorial002_py39.py hl[1, 8:9] *}
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
Sonrasında normalde yaptığınız gibi ihtiyaç duyduğunuz herhangi bir nesneyi döndürebilirsiniz (bir `dict`, bir veritabanı modeli vb.).
@@ -24,9 +24,9 @@ Bunu yapmak için, [Doğrudan Response Döndürme](response-directly.md){.intern
Sonra bunun içinde Cookie'leri set edin ve response'u döndürün:
-{* ../../docs_src/response_cookies/tutorial001_py39.py hl[10:12] *}
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
-/// tip | İpucu
+/// tip
`Response` parametresini kullanmak yerine doğrudan bir response döndürürseniz, FastAPI onu olduğu gibi (doğrudan) döndürür.
diff --git a/docs/tr/docs/advanced/response-directly.md b/docs/tr/docs/advanced/response-directly.md
index 332f1224f..cadefbdde 100644
--- a/docs/tr/docs/advanced/response-directly.md
+++ b/docs/tr/docs/advanced/response-directly.md
@@ -2,7 +2,7 @@
**FastAPI** ile bir *path operation* oluşturduğunuzda, normalde ondan herhangi bir veri döndürebilirsiniz: bir `dict`, bir `list`, bir Pydantic model, bir veritabanı modeli vb.
-Varsayılan olarak **FastAPI**, döndürdüğünüz bu değeri [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} bölümünde anlatılan `jsonable_encoder` ile otomatik olarak JSON'a çevirir.
+Varsayılan olarak **FastAPI**, döndürdüğünüz bu değeri [JSON Uyumlu Encoder](../tutorial/encoder.md){.internal-link target=_blank} bölümünde anlatılan `jsonable_encoder` ile otomatik olarak JSON'a çevirir.
Ardından perde arkasında, JSON-uyumlu bu veriyi (ör. bir `dict`) client'a response göndermek için kullanılacak bir `JSONResponse` içine yerleştirir.
@@ -54,12 +54,12 @@ Diyelim ki Marshmallow { #marshmallow }
-API sistemlerinin ihtiyaç duyduğu temel özelliklerden biri, koddan (Python) veriyi alıp ağ üzerinden gönderilebilecek bir şeye dönüştürmek, yani veri “dönüşüm”üdür. Örneğin, bir veritabanından gelen verileri içeren bir objeyi JSON objesine dönüştürmek, `datetime` objelerini string’e çevirmek vb.
+API sistemlerinin ihtiyaç duyduğu temel özelliklerden biri, koddan (Python) veriyi alıp ağ üzerinden gönderilebilecek bir şeye dönüştürmek, yani veri “dönüşüm”üdür. Örneğin, bir veritabanından gelen verileri içeren bir objeyi JSON objesine dönüştürmek, `datetime` objelerini string’e çevirmek vb.
API’ların ihtiyaç duyduğu bir diğer önemli özellik, veri doğrulamadır; belirli parametreler göz önüne alındığında verinin geçerli olduğundan emin olmak. Örneğin, bir alanın `int` olması ve rastgele bir metin olmaması. Bu özellikle dışarıdan gelen veriler için kullanışlıdır.
@@ -145,7 +145,7 @@ Bir veri doğrulama sistemi olmadan, tüm bu kontrolleri kod içinde el ile yapm
Marshmallow, bu özellikleri sağlamak için inşa edildi. Harika bir kütüphanedir ve geçmişte çok kullandım.
-Ancak Python tip belirteçlerinden önce yazılmıştır. Dolayısıyla her şemayı tanımlamak için Marshmallow’un sağladığı belirli yardımcılar ve sınıflar kullanılır.
+Ancak Python tip belirteçlerinden önce yazılmıştır. Dolayısıyla her şemayı tanımlamak için Marshmallow’un sağladığı belirli yardımcılar ve sınıflar kullanılır.
/// check | **FastAPI**'a ilham olan
@@ -155,7 +155,7 @@ Kodla, veri tiplerini ve doğrulamayı otomatik sağlayan “şemalar” tanıml
### Webargs { #webargs }
-API’ların ihtiyaç duyduğu bir diğer büyük özellik, gelen isteklerden veriyi ayrıştırmadır.
+API’ların ihtiyaç duyduğu bir diğer büyük özellik, gelen isteklerden veriyi ayrıştırmadır.
Webargs, Flask dahil birkaç framework’ün üzerinde bunu sağlamak için geliştirilmiş bir araçtır.
@@ -417,7 +417,7 @@ Tüm veri doğrulama, veri dönüşümü ve JSON Schema tabanlı otomatik model
### Starlette { #starlette }
-Starlette, yüksek performanslı asyncio servisleri oluşturmak için ideal, hafif bir ASGI framework’ü/araç takımıdır.
+Starlette, yüksek performanslı asyncio servisleri oluşturmak için ideal, hafif bir ASGI framework’ü/araç takımıdır.
Çok basit ve sezgiseldir. Kolayca genişletilebilir ve modüler bileşenlere sahip olacak şekilde tasarlanmıştır.
diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md
index 88fd763fc..c788d60a8 100644
--- a/docs/tr/docs/async.md
+++ b/docs/tr/docs/async.md
@@ -1,18 +1,18 @@
-# Concurrency ve async / await
+# Eşzamanlılık ve async / await { #concurrency-and-async-await }
-*path operasyon fonksiyonu* için `async def `sözdizimi, asenkron kod, eşzamanlılık ve paralellik hakkında bazı ayrıntılar.
+*path operasyon fonksiyonları* için `async def` sözdizimi hakkında detaylar ve asenkron kod, eşzamanlılık (concurrency) ve paralellik üzerine arka plan bilgisi.
-## Aceleniz mi var?
+## Aceleniz mi var? { #in-a-hurry }
-TL;DR:
+TL;DR:
-Eğer `await` ile çağrılması gerektiğini belirten üçüncü taraf kütüphaneleri kullanıyorsanız, örneğin:
+Eğer `await` ile çağırmanız gerektiğini söyleyen üçüncü taraf kütüphaneler kullanıyorsanız, örneğin:
```Python
results = await some_library()
```
-O zaman *path operasyon fonksiyonunu* `async def` ile tanımlayın örneğin:
+O zaman *path operasyon fonksiyonlarınızı* aşağıdaki gibi `async def` ile tanımlayın:
```Python hl_lines="2"
@app.get('/')
@@ -23,13 +23,13 @@ async def read_results():
/// note | Not
-Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz.
+`await` yalnızca `async def` ile oluşturulan fonksiyonların içinde kullanılabilir.
///
---
-Eğer bir veritabanı, bir API, dosya sistemi vb. ile iletişim kuran bir üçüncü taraf bir kütüphane kullanıyorsanız ve `await` kullanımını desteklemiyorsa, (bu şu anda çoğu veritabanı kütüphanesi için geçerli bir durumdur), o zaman *path operasyon fonksiyonunuzu* `def` kullanarak normal bir şekilde tanımlayın, örneğin:
+Eğer bir veritabanı, bir API, dosya sistemi vb. ile iletişim kuran ve `await` desteği olmayan bir üçüncü taraf kütüphane kullanıyorsanız (bu şu anda çoğu veritabanı kütüphanesi için geçerlidir), o zaman *path operasyon fonksiyonlarınızı* normal olarak `def` ile tanımlayın:
```Python hl_lines="2"
@app.get('/')
@@ -40,279 +40,307 @@ def results():
---
-Eğer uygulamanız (bir şekilde) başka bir şeyle iletişim kurmak ve onun cevap vermesini beklemek zorunda değilse, `async def` kullanın.
+Uygulamanız (bir şekilde) başka bir şeyle iletişim kurmak ve onun yanıtını beklemek zorunda değilse, içinde `await` kullanmanız gerekmese bile `async def` kullanın.
---
-Sadece bilmiyorsanız, normal `def` kullanın.
+Emin değilseniz, normal `def` kullanın.
---
-**Not**: *path operasyon fonksiyonlarınızda* `def` ve `async def`'i ihtiyaç duyduğunuz gibi karıştırabilir ve her birini sizin için en iyi seçeneği kullanarak tanımlayabilirsiniz. FastAPI onlarla doğru olanı yapacaktır.
+Not: *path operasyon fonksiyonlarınızda* `def` ve `async def`'i ihtiyacınız kadar karıştırabilirsiniz, her birini sizin için en iyi seçenekle tanımlayın. FastAPI onlar için doğru olanı yapacaktır.
-Her neyse, yukarıdaki durumlardan herhangi birinde, FastAPI yine de asenkron olarak çalışacak ve son derece hızlı olacaktır.
+Yukarıdaki durumların herhangi birinde FastAPI yine de asenkron olarak çalışır ve son derece hızlıdır.
-Ancak yukarıdaki adımları takip ederek, bazı performans optimizasyonları yapılabilecektir.
+Ancak yukarıdaki adımları izleyerek bazı performans optimizasyonları mümkün olur.
-## Teknik Detaylar
+## Teknik Detaylar { #technical-details }
-Python'un modern versiyonlarında **`async` ve `await`** sözdizimi ile **"coroutines"** kullanan **"asenkron kod"** desteğine sahiptir.
+Python’un modern sürümleri, **`async` ve `await`** sözdizimiyle, **"coroutines"** denilen bir yapıyı kullanarak **"asenkron kod"** desteğine sahiptir.
-Bu ifadeyi aşağıdaki bölümlerde daha da ayrıntılı açıklayalım:
+Aşağıdaki bölümlerde bu ifadeyi parça parça ele alalım:
-* **Asenkron kod**
+* **Asenkron Kod**
* **`async` ve `await`**
-* **Coroutines**
+* **Coroutine'ler**
-## Asenkron kod
+## Asenkron Kod { #asynchronous-code }
-Asenkron kod programlama dilinin 💬 bilgisayara / programa 🤖 kodun bir noktasında, *başka bir kodun* bir yerde bitmesini 🤖 beklemesi gerektiğini söylemenin bir yoludur. Bu *başka koda* "slow-file" denir 📝.
+Asenkron kod, dilin 💬 bilgisayara / programa 🤖 kodun bir noktasında, bir yerde *başka bir şeyin* bitmesini beklemesi gerektiğini söylemesinin bir yoludur. Diyelim ki bu *başka şeye* "slow-file" 📝 diyoruz.
-Böylece, bu süreçte bilgisayar "slow-file" 📝 tamamlanırken gidip başka işler yapabilir.
+Bu sırada bilgisayar, "slow-file" 📝 biterken gidip başka işler yapabilir.
-Sonra bilgisayar / program 🤖 her fırsatı olduğunda o noktada yaptığı tüm işleri 🤖 bitirene kadar geri dönücek. Ve 🤖 yapması gerekeni yaparak, beklediği görevlerden herhangi birinin bitip bitmediğini görecek.
+Sonra bilgisayar / program 🤖, ya tekrar beklediği için ya da o anda elindeki tüm işleri bitirdiğinde fırsat buldukça geri gelir. Ve beklediği görevlerden herhangi biri bittiyse, yapılması gerekenleri yapar.
-Ardından, 🤖 bitirmek için ilk görevi alır ("slow-file" 📝) ve onunla ne yapması gerekiyorsa onu devam ettirir.
+Ardından, 🤖 ilk biten görevi alır (örneğin bizim "slow-file" 📝) ve onunla yapması gerekenlere devam eder.
-Bu "başka bir şey için bekle" normalde, aşağıdakileri beklemek gibi (işlemcinin ve RAM belleğinin hızına kıyasla) nispeten "yavaş" olan I/O işlemlerine atıfta bulunur:
+Bu "başka bir şeyi beklemek" genelde işlemci ve RAM hızına kıyasla nispeten "yavaş" olan I/O işlemlerine atıfta bulunur, örneğin şunları beklemek gibi:
-* istemci tarafından ağ üzerinden veri göndermek
-* ağ üzerinden istemciye gönderilen veriler
-* sistem tarafından okunacak ve programınıza verilecek bir dosya içeriği
-* programınızın diske yazılmak üzere sisteme verdiği dosya içerikleri
+* istemciden verinin ağ üzerinden gelmesi
+* programınızın gönderdiği verinin ağ üzerinden istemciye ulaşması
+* diskteki bir dosyanın içeriğinin sistem tarafından okunup programınıza verilmesi
+* programınızın sisteme verdiği içeriğin diske yazılması
* uzak bir API işlemi
-* bir veritabanı bitirme işlemi
-* sonuçları döndürmek için bir veritabanı sorgusu
+* bir veritabanı işleminin bitmesi
+* bir veritabanı sorgusunun sonuç döndürmesi
* vb.
-Yürütme süresi çoğunlukla I/O işlemleri beklenerek tüketildiğinden bunlara "I/O bağlantılı" işlemler denir.
+Çalışma süresi çoğunlukla I/O işlemlerini beklemekle geçtiğinden, bunlara "I/O bound" işlemler denir.
-Buna "asenkron" denir, çünkü bilgisayar/program yavaş görevle "senkronize" olmak zorunda değildir, görevin tam olarak biteceği anı bekler, hiçbir şey yapmadan, görev sonucunu alabilmek ve çalışmaya devam edebilmek için .
+"Bunun" asenkron" denmesinin sebebi, bilgisayarın / programın yavaş görevle "senkronize" olmak, görev tam bittiği anda orada olup görev sonucunu almak ve işe devam etmek için hiçbir şey yapmadan beklemek zorunda olmamasıdır.
-Bunun yerine, "asenkron" bir sistem olarak, bir kez bittiğinde, bilgisayarın / programın yapması gerekeni bitirmesi için biraz (birkaç mikrosaniye) sırada bekleyebilir ve ardından sonuçları almak için geri gelebilir ve onlarla çalışmaya devam edebilir.
+Bunun yerine "asenkron" bir sistem olarak, görev bittiğinde, bilgisayarın / programın o sırada yaptığı işi bitirmesi için biraz (birkaç mikrosaniye) sırada bekleyebilir ve sonra sonuçları almak üzere geri dönüp onlarla çalışmaya devam edebilir.
-"Senkron" ("asenkron"un aksine) için genellikle "sıralı" terimini de kullanırlar, çünkü bilgisayar/program, bu adımlar beklemeyi içerse bile, farklı bir göreve geçmeden önce tüm adımları sırayla izler.
+"Senkron" (asenkronun tersi) için genelde "sıralı" terimi de kullanılır; çünkü bilgisayar / program, farklı bir göreve geçmeden önce tüm adımları sırayla izler, bu adımlar beklemeyi içerse bile.
+### Eşzamanlılık ve Burgerler { #concurrency-and-burgers }
-### Eşzamanlılık (Concurrency) ve Burgerler
+Yukarıda anlatılan **asenkron** kod fikrine bazen **"eşzamanlılık"** (concurrency) da denir. **"Paralellik"**ten (parallelism) farklıdır.
+**Eşzamanlılık** ve **paralellik**, "aynı anda az çok birden fazla şeyin olması" ile ilgilidir.
-Yukarıda açıklanan bu **asenkron** kod fikrine bazen **"eşzamanlılık"** da denir. **"Paralellikten"** farklıdır.
+Ama *eşzamanlılık* ve *paralellik* arasındaki ayrıntılar oldukça farklıdır.
-**Eşzamanlılık** ve **paralellik**, "aynı anda az ya da çok olan farklı işler" ile ilgilidir.
+Farkı görmek için burgerlerle ilgili şu hikayeyi hayal edin:
-Ancak *eşzamanlılık* ve *paralellik* arasındaki ayrıntılar oldukça farklıdır.
+### Eşzamanlı Burgerler { #concurrent-burgers }
+Aşkınla fast food almaya gidiyorsun, kasiyer senden önceki insanların siparişlerini alırken sıraya giriyorsun. 😍
-Farkı görmek için burgerlerle ilgili aşağıdaki hikayeyi hayal edin:
+
-### Eşzamanlı Burgerler
+Sonra sıra size geliyor, sen ve aşkın için 2 çok havalı burger sipariş ediyorsun. 🍔🍔
-
+
-Aşkınla beraber 😍 dışarı hamburger yemeye çıktınız 🍔, kasiyer 💁 öndeki insanlardan sipariş alırken siz sıraya girdiniz.
+Kasiyer, mutfaktaki aşçıya burgerlerini hazırlamaları gerektiğini söylüyor (o an önceki müşterilerin burgerlerini hazırlıyor olsalar bile).
-Sıra sizde ve sen aşkın 😍 ve kendin için 2 çılgın hamburger 🍔 söylüyorsun.
+
-Ödemeyi yaptın 💸.
+Ödeme yapıyorsun. 💸
-Kasiyer 💁 mutfakdaki aşçıya 👨🍳 hamburgerleri 🍔 hazırlaması gerektiğini söyler ve aşçı bunu bilir (o an önceki müşterilerin siparişlerini hazırlıyor olsa bile).
+Kasiyer sana sıra numaranı veriyor.
-Kasiyer 💁 size bir sıra numarası verir.
+
-Beklerken askınla 😍 bir masaya oturur ve uzun bir süre konuşursunuz(Burgerleriniz çok çılgın olduğundan ve hazırlanması biraz zaman alıyor ✨🍔✨).
+Beklerken aşkınla bir masa seçip oturuyorsunuz, uzun uzun sohbet ediyorsunuz (burgerler baya havalı ve hazırlanması biraz zaman alıyor).
-Hamburgeri beklerkenki zamanı 🍔, aşkının ne kadar zeki ve tatlı olduğuna hayran kalarak harcayabilirsin ✨😍✨.
+Masada aşkınla otururken, burgerleri beklerken, o zamanı aşkının ne kadar harika, tatlı ve zeki olduğuna hayran kalarak geçirebilirsin ✨😍✨.
-Aşkınla 😍 konuşurken arada sıranın size gelip gelmediğini kontrol ediyorsun.
+
-Nihayet sıra size geldi. Tezgaha gidip hamburgerleri 🍔kapıp masaya geri dönüyorsun.
+Bekler ve sohbet ederken, ara ara tezgâhtaki numaraya bakıp sıranın size gelip gelmediğini kontrol ediyorsun.
-Aşkınla hamburgerlerinizi yiyor 🍔 ve iyi vakit geçiriyorsunuz ✨.
+Bir noktada, nihayet sıra size geliyor. Tezgâha gidiyor, burgerleri alıp masaya dönüyorsun.
+
+
+
+Aşkınla burgerleri yiyip güzel vakit geçiriyorsunuz. ✨
+
+
+
+/// info | Bilgi
+
+Harika çizimler: Ketrina Thompson. 🎨
+
+///
---
-Bu hikayedeki bilgisayar / program 🤖 olduğunuzu hayal edin.
+Bu hikâyede bilgisayar / program 🤖 olduğunu hayal et.
-Sırada beklerken boştasın 😴, sıranı beklerken herhangi bir "üretim" yapmıyorsun. Ama bu sıra hızlı çünkü kasiyer sadece siparişleri alıyor (onları hazırlamıyor), burada bir sıknıtı yok.
+Sıradayken sadece boştasın 😴, sıranı bekliyorsun, çok "üretken" bir şey yapmıyorsun. Ama sorun yok, çünkü kasiyer sadece sipariş alıyor (hazırlamıyor), bu yüzden sıra hızlı ilerliyor.
-Sonra sıra size geldiğinde gerçekten "üretken" işler yapabilirsiniz 🤓, menüyü oku, ne istediğine larar ver, aşkının seçimini al 😍, öde 💸, doğru kartı çıkart, ödemeyi kontrol et, faturayı kontrol et, siparişin doğru olup olmadığını kontrol et, vb.
+Sıra sana geldiğinde gerçekten "üretken" işler yapıyorsun: menüyü işliyorsun, ne istediğine karar veriyorsun, aşkının seçimini alıyorsun, ödüyorsun, doğru para ya da kartı verdiğini kontrol ediyorsun, doğru ücretlendirildiğini kontrol ediyorsun, sipariş kalemlerinin doğru olduğunu kontrol ediyorsun, vb.
-Ama hamburgerler 🍔 hazır olmamasına rağmen Kasiyer 💁 ile işiniz "duraklıyor" ⏸, çünkü hamburgerlerin hazır olmasını bekliyoruz 🕙.
+Ama sonra, burgerlerin hâlâ gelmemiş olsa da, kasiyerle olan işin "duraklatılıyor" ⏸, çünkü burgerlerin hazır olmasını 🕙 beklemen gerekiyor.
-Ama tezgahtan uzaklaşıp sıranız gelene kadarmasanıza dönebilir 🔀 ve dikkatinizi aşkınıza 😍 verebilirsiniz vr bunun üzerine "çalışabilirsiniz" ⏯ 🤓. Artık "üretken" birşey yapıyorsunuz 🤓, sevgilinle 😍 flört eder gibi.
+Fakat tezgâhtan uzaklaşıp masada sıra numaranla oturduğun için, dikkatinizi 🔀 aşkına çevirebilir, onunla "çalışmaya" ⏯ 🤓 odaklanabilirsin. Yani yine çok "üretken" bir şey yapıyorsun, aşkınla flört etmek gibi 😍.
-Kasiyer 💁 "Hamburgerler hazır !" 🍔 dediğinde ve görüntülenen numara sizin numaranız olduğunda hemen koşup hamburgerlerinizi almaya çalışmıyorsunuz. Biliyorsunuzki kimse sizin hamburgerlerinizi 🍔 çalmayacak çünkü sıra sizin.
+Ardından kasiyer 💁, tezgâh ekranına numaranı koyarak "burgerleri bitirdim" diyor; ama numara seninki olduğunda çılgınca sıçramıyorsun. Sıra numaran sende, herkesin kendi numarası var; kimse burgerlerini çalamaz.
-Yani Aşkınızın😍 hikayeyi bitirmesini bekliyorsunuz (çalışmayı bitir ⏯ / görev işleniyor.. 🤓), nazikçe gülümseyin ve hamburger yemeye gittiğinizi söyleyin ⏸.
+Bu yüzden aşkının hikâyeyi bitirmesini (mevcut işi ⏯ / işlenen görevi 🤓 bitirmesini) bekliyor, nazikçe gülümsüyor ve burgerleri almaya gittiğini söylüyorsun ⏸.
-Ardından tezgaha 🔀, şimdi biten ilk göreve ⏯ gidin, Hamburgerleri 🍔 alın, teşekkür edin ve masaya götürün. sayacın bu adımı tamamlanır ⏹. Bu da yeni bir görev olan "hamburgerleri ye" 🔀 ⏯ görevini başlatırken "hamburgerleri al" ⏹ görevini bitirir.
+Sonra tezgâha 🔀 gidip artık bitmiş olan ilk göreve ⏯ dönüyor, burgerleri alıyor, teşekkür ediyor ve masaya getiriyorsun. Tezgâhla etkileşimin bu adımı / görevi böylece bitiyor ⏹. Bu da yeni bir görev olan "burgerleri yemek" 🔀 ⏯ görevini oluşturuyor, ama "burgerleri almak" görevi tamamlandı ⏹.
-### Parallel Hamburgerler
+### Paralel Burgerler { #parallel-burgers }
-Şimdi bunların "Eşzamanlı Hamburger" değil, "Paralel Hamburger" olduğunu düşünelim.
+Şimdi bunların "Eşzamanlı Burgerler" değil, "Paralel Burgerler" olduğunu hayal edelim.
-Hamburger 🍔 almak için 😍 aşkınla Paralel fast food'a gidiyorsun.
+Aşkınla paralel fast food almaya gidiyorsun.
-Birden fazla kasiyer varken (varsayalım 8) sıraya girdiniz👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳 ve sıranız gelene kadar bekliyorsunuz.
+Aynı anda aşçı da olan birden fazla (8 diyelim) kasiyerin, senden önceki insanların siparişlerini aldığı bir sırada bekliyorsun.
-Sizden önceki herkez ayrılmadan önce hamburgerlerinin 🍔 hazır olmasını bekliyor 🕙. Çünkü kasiyerlerin her biri bir hamburger hazırlanmadan önce bir sonraki siparişe geçmiiyor.
+Senden önceki herkes, tezgâhtan ayrılmadan önce burgerlerinin hazırlanmasını bekliyor; çünkü 8 kasiyerin her biri bir sonraki siparişe geçmeden önce burgeri hemen gidip hazırlıyor.
-Sonunda senin sıran, aşkın 😍 ve kendin için 2 hamburger 🍔 siparişi verdiniz.
+
-Ödemeyi yaptınız 💸.
+Sonunda sıra size geliyor, sen ve aşkın için 2 çok havalı burger siparişi veriyorsun.
-Kasiyer mutfağa gider 👨🍳.
+Ödüyorsun 💸.
-Sırada bekliyorsunuz 🕙, kimse sizin burgerinizi 🍔 almaya çalışmıyor çünkü sıra sizin.
+
-Sen ve aşkın 😍 sıranızı korumak ve hamburgerleri almakla o kadar meşgulsünüz ki birbirinize vakit 🕙 ayıramıyorsunuz 😞.
+Kasiyer mutfağa gidiyor.
-İşte bu "senkron" çalışmadır. Kasiyer/aşçı 👨🍳ile senkron hareket ediyorsunuz. Bu yüzden beklemek 🕙 ve kasiyer/aşçı burgeri 🍔bitirip size getirdiğinde orda olmak zorundasınız yoksa başka biri alabilir.
+Tezgâhın önünde ayakta 🕙 bekliyorsun; sıra numarası olmadığından, burgerlerini senden önce kimsenin almaması için orada durman gerekiyor.
-Sonra kasiyeri/aşçı 👨🍳 nihayet hamburgerlerinizle 🍔, uzun bir süre sonra 🕙 tezgaha geri geliyor.
+
-Burgerlerinizi 🍔 al ve aşkınla masanıza doğru ilerle 😍.
+Sen ve aşkın, kimsenin önünüze geçip burgerler gelince almaması için meşgul olduğunuzdan, aşkına dikkatini veremiyorsun. 😞
-Sadece burgerini yiyorsun 🍔 ve bitti ⏹.
+Bu "senkron" bir iştir; kasiyer/aşçı 👨🍳 ile "senkronize"sin. 🕙 Beklemen ve kasiyer/aşçı 👨🍳 burgerleri bitirip sana verdiği anda tam orada olman gerekir; yoksa bir başkası alabilir.
-Bekleyerek çok fazla zaman geçtiğinden 🕙 konuşmaya çok fazla vakit kalmadı 😞.
+
+
+Sonra kasiyer/aşçı 👨🍳, uzun süre tezgâhın önünde 🕙 bekledikten sonra nihayet burgerlerinle geri geliyor.
+
+
+
+Burgerleri alıyor ve aşkınla masaya gidiyorsun.
+
+Sadece yiyorsunuz ve iş bitiyor. ⏹
+
+
+
+Vaktin çoğu tezgâhın önünde 🕙 beklemekle geçtiğinden, pek konuşma ya da flört olmadı. 😞
+
+/// info | Bilgi
+
+Harika çizimler: Ketrina Thompson. 🎨
+
+///
---
-Paralel burger senaryosunda ise, siz iki işlemcili birer robotsunuz 🤖 (sen ve sevgilin 😍), Beklıyorsunuz 🕙 hem konuşarak güzel vakit geçirirken ⏯ hem de sıranızı bekliyorsunuz 🕙.
+Bu paralel burger senaryosunda, ikiniz (sen ve aşkın) iki işlemcili bir bilgisayar / programsınız 🤖; ikiniz de uzun süre tezgâhta "bekleme" işine 🕙 dikkat ⏯ ayırıyorsunuz.
-Mağazada ise 8 işlemci bulunuyor (Kasiyer/aşçı) 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳. Eşzamanlı burgerde yalnızca 2 kişi olabiliyordu (bir kasiyer ve bir aşçı) 💁 👨🍳.
+Fast food dükkânında 8 işlemci var (kasiyer/aşçılar). Eşzamanlı burger dükkânında yalnızca 2 kişi olabilir (bir kasiyer ve bir aşçı).
-Ama yine de bu en iyisi değil 😞.
+Ama yine de nihai deneyim pek iyi değil. 😞
---
-Bu hikaye burgerler 🍔 için paralel.
+Bu, burgerler için paralel karşılık gelen hikâye olurdu. 🍔
-Bir gerçek hayat örneği verelim. Bir banka hayal edin.
+Daha "gerçek hayat" bir örnek için, bir banka hayal edin.
-Bankaların çoğunda birkaç kasiyer 👨💼👨💼👨💼👨💼 ve uzun bir sıra var 🕙🕙🕙🕙🕙🕙🕙🕙.
+Yakın zamana kadar, bankaların çoğunda birden çok gişe memuru 👨💼👨💼👨💼👨💼 ve uzun bir sıra 🕙🕙🕙🕙🕙🕙🕙🕙 vardı.
-Tüm işi sırayla bir müşteri ile yapan tüm kasiyerler 👨💼⏯.
+Tüm gişe memurları bir müşteriyle tüm işi yapar, sonra sıradakiyle 👨💼⏯.
-Ve uzun süre kuyrukta beklemek 🕙 zorundasın yoksa sıranı kaybedersin.
+Ve sıranı kaybetmemek için uzun süre 🕙 kuyrukta beklemen gerekir.
-Muhtemelen ayak işlerı yaparken sevgilini 😍 bankaya 🏦 getirmezsin.
+Muhtemelen, bankada 🏦 işlerini hallederken aşkını 😍 yanında götürmek istemezsin.
-### Burger Sonucu
+### Burger Sonucu { #burger-conclusion }
-Bu "aşkınla fast food burgerleri" senaryosunda, çok fazla bekleme olduğu için 🕙, eşzamanlı bir sisteme sahip olmak çok daha mantıklı ⏸🔀⏯.
+"Fast food burgerleri ve aşkın" senaryosunda, çok fazla bekleme 🕙 olduğundan, eşzamanlı bir sistem ⏸🔀⏯ çok daha mantıklıdır.
-Web uygulamalarının çoğu için durum böyledir.
+Bu, çoğu web uygulaması için de geçerlidir.
-Pek çok kullanıcı var, ama sunucunuz pek de iyi olmayan bir bağlantı ile istek atmalarını bekliyor.
+Çok fazla kullanıcı vardır; ancak sunucunuz, iyi olmayan bağlantılarından gelen istekleri 🕙 bekler.
-Ve sonra yanıtların geri gelmesi için tekrar 🕙 bekliyor
+Ve sonra yanıtların geri gelmesini yine 🕙 bekler.
-Bu "bekleme" 🕙 mikrosaniye cinsinden ölçülür, yine de, hepsini toplarsak çok fazla bekleme var.
+Bu "beklemeler" 🕙 mikrosaniyelerle ölçülür; ama hepsi toplandığında sonuçta oldukça fazla bekleme olur.
-Bu nedenle, web API'leri için asenkron ⏸🔀⏯ kod kullanmak çok daha mantıklı.
+Bu yüzden web API’leri için asenkron ⏸🔀⏯ kod kullanmak çok mantıklıdır.
-Mevcut popüler Python frameworklerinin çoğu (Flask ve Django gibi), Python'daki yeni asenkron özellikler mevcut olmadan önce yazıldı. Bu nedenle, dağıtılma biçimleri paralel yürütmeyi ve yenisi kadar güçlü olmayan eski bir eşzamansız yürütme biçimini destekler.
+Bu tür asenkronluk, NodeJS’i popüler yapan şeydir (NodeJS paralel olmasa bile) ve Go dilinin gücüdür.
-Asenkron web (ASGI) özelliği, WebSockets için destek eklemek için Django'ya eklenmiş olsa da.
+Ve **FastAPI** ile elde ettiğiniz performans seviyesi de budur.
-Asenkron çalışabilme NodeJS in popüler olmasının sebebi (paralel olamasa bile) ve Go dilini güçlü yapan özelliktir.
+Ayrıca, aynı anda hem paralellik hem de asenkronluk kullanabildiğiniz için, test edilen çoğu NodeJS framework’ünden daha yüksek ve C’ye daha yakın derlenen bir dil olan Go ile başa baş performans elde edersiniz (hepsi Starlette sayesinde).
-Ve bu **FastAPI** ile elde ettiğiniz performans düzeyiyle aynıdır.
+### Eşzamanlılık paralellikten daha mı iyi? { #is-concurrency-better-than-parallelism }
-Aynı anda paralellik ve asenkronluğa sahip olabildiğiniz için, test edilen NodeJS çerçevelerinin çoğundan daha yüksek performans elde edersiniz ve C'ye daha yakın derlenmiş bir dil olan Go ile eşit bir performans elde edersiniz (bütün teşekkürler Starlette'e ).
+Hayır! Hikâyenin özü bu değil.
-### Eşzamanlılık paralellikten daha mı iyi?
+Eşzamanlılık paralellikten farklıdır. Ve çok fazla bekleme içeren **belirli** senaryolarda daha iyidir. Bu nedenle, genellikle web uygulaması geliştirme için paralellikten çok daha iyidir. Ama her şey için değil.
-Hayır! Hikayenin ahlakı bu değil.
+Bunu dengelemek için, şu kısa hikâyeyi hayal edin:
-Eşzamanlılık paralellikten farklıdır. Ve çok fazla bekleme içeren **belirli** senaryolarda daha iyidir. Bu nedenle, genellikle web uygulamaları için paralellikten çok daha iyidir. Ama her şey için değil.
+> Büyük, kirli bir evi temizlemen gerekiyor.
-Yanı, bunu aklınızda oturtmak için aşağıdaki kısa hikayeyi hayal edin:
-
-> Büyük, kirli bir evi temizlemelisin.
-
-*Evet, tüm hikaye bu*.
+*Evet, tüm hikâye bu kadar*.
---
-Beklemek yok 🕙. Hiçbir yerde. Sadece evin birden fazla yerinde yapılacak fazlasıyla iş var.
+Hiçbir yerde 🕙 bekleme yok; sadece evin birden fazla yerinde yapılacak çok iş var.
-You could have turns as in the burgers example, first the living room, then the kitchen, but as you are not waiting 🕙 for anything, just cleaning and cleaning, the turns wouldn't affect anything.
-Hamburger örneğindeki gibi dönüşleriniz olabilir, önce oturma odası, sonra mutfak, ama hiçbir şey için 🕙 beklemediğinizden, sadece temizlik, temizlik ve temizlik, dönüşler hiçbir şeyi etkilemez.
+Hamburger örneğindeki gibi dönüşlerle ilerleyebilirsin, önce salon, sonra mutfak; ama hiçbir şey 🕙 beklemediğin için, sadece temizlik yaptığından, dönüşlerin hiçbir etkisi olmaz.
-Sıralı veya sırasız (eşzamanlılık) bitirmek aynı zaman alır ve aynı miktarda işi yaparsınız.
+Dönüşlerle ya da dönüşsüz (eşzamanlılık) bitirmek aynı zaman alır ve aynı miktarda iş yapmış olursun.
-Ama bu durumda, 8 eski kasiyer/aşçı - yeni temizlikçiyi getirebilseydiniz 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳 ve her birini (artı siz) evin bir bölgesini temizlemek için görevlendirseydiniz, ekstra yardımla tüm işleri **paralel** olarak yapabilir ve çok daha erken bitirebilirdiniz.
+Ama bu durumda, 8 eski kasiyer/aşçı—yeni temizlikçiyi getirip her birine (artı sana) evin bir bölümünü versen, fazladan yardımla tüm işleri **paralel** yaparak çok daha çabuk bitirebilirdin.
-Bu senaryoda, temizlikçilerin her biri (siz dahil) birer işlemci olacak ve üzerine düşeni yapacaktır.
+Bu senaryoda, her bir temizlikçi (sen dâhil) birer işlemci olur ve kendi iş payını yapar.
-Yürütme süresinin çoğu (beklemek yerine) iş yapıldığından ve bilgisayardaki iş bir CPU tarafından yapıldığından, bu sorunlara "CPU bound" diyorlar".
+Ve yürütme süresinin çoğu gerçek işten (bekleme yerine) oluştuğu ve bilgisayardaki işi bir CPU yaptığı için, bu sorunlara "CPU bound" denir.
---
-CPU'ya bağlı işlemlerin yaygın örnekleri, karmaşık matematik işlemleri gerektiren işlerdir.
+CPU’ya bağlı işlemlerin yaygın örnekleri, karmaşık matematiksel işlem gerektiren iş yükleridir.
Örneğin:
* **Ses** veya **görüntü işleme**.
-* **Bilgisayar görüsü**: bir görüntü milyonlarca pikselden oluşur, her pikselin 3 değeri / rengi vardır, bu pikseller üzerinde aynı anda bir şeyler hesaplamayı gerektiren işleme.
-* **Makine Öğrenimi**: Çok sayıda "matris" ve "vektör" çarpımı gerektirir. Sayıları olan ve hepsini aynı anda çarpan büyük bir elektronik tablo düşünün.
-* **Derin Öğrenme**: Bu, Makine Öğreniminin bir alt alanıdır, dolayısıyla aynısı geçerlidir. Sadece çarpılacak tek bir sayı tablosu değil, büyük bir sayı kümesi vardır ve çoğu durumda bu modelleri oluşturmak ve/veya kullanmak için özel işlemciler kullanırsınız.
+* **Bilgisayar görüsü**: bir görüntü milyonlarca pikselden oluşur, her pikselin 3 değeri / rengi vardır; işleme genellikle bu pikseller üzerinde aynı anda bir şeyler hesaplamayı gerektirir.
+* **Makine Öğrenimi**: genellikle çok sayıda "matris" ve "vektör" çarpımı gerekir. Sayılar içeren devasa bir elektronik tabloyu ve hepsini aynı anda çarpmayı düşünün.
+* **Derin Öğrenme**: Makine Öğreniminin bir alt alanıdır, dolayısıyla aynısı geçerlidir. Sadece çarpılacak tek bir sayı tablosu değil, kocaman bir sayı kümesi vardır ve çoğu durumda bu modelleri kurmak ve/veya kullanmak için özel işlemciler kullanırsınız.
-### Eşzamanlılık + Paralellik: Web + Makine Öğrenimi
+### Eşzamanlılık + Paralellik: Web + Makine Öğrenimi { #concurrency-parallelism-web-machine-learning }
-**FastAPI** ile web geliştirme için çok yaygın olan eşzamanlılıktan yararlanabilirsiniz (NodeJS'in aynı çekiciliği).
+**FastAPI** ile web geliştirmede çok yaygın olan eşzamanlılıktan (NodeJS’in başlıca cazibesiyle aynı) yararlanabilirsiniz.
-Ancak, Makine Öğrenimi sistemlerindekile gibi **CPU'ya bağlı** iş yükleri için paralellik ve çoklu işlemenin (birden çok işlemin paralel olarak çalışması) avantajlarından da yararlanabilirsiniz.
+Ama ayrıca **CPU’ya bağlı** iş yükleri (Makine Öğrenimi sistemlerindeki gibi) için paralellik ve çoklu işlemden (paralel çalışan birden çok işlem) de yararlanabilirsiniz.
-Buna ek olarak Python'un **Veri Bilimi**, Makine Öğrenimi ve özellikle Derin Öğrenme için ana dil olduğu gerçeği, FastAPI'yi Veri Bilimi / Makine Öğrenimi web API'leri ve uygulamaları için çok iyi bir seçenek haline getirir.
+Buna ek olarak Python’un **Veri Bilimi**, Makine Öğrenimi ve özellikle Derin Öğrenme için ana dil olması, FastAPI’yi Veri Bilimi / Makine Öğrenimi web API’leri ve uygulamaları için çok iyi bir seçenek yapar.
-Production'da nasıl oldugunu görmek için şu bölüme bakın [Deployment](deployment/index.md){.internal-link target=_blank}.
+Production’da bu paralelliği nasıl sağlayacağınızı görmek için [Deployment](deployment/index.md){.internal-link target=_blank} bölümüne bakın.
-## `async` ve `await`
+## `async` ve `await` { #async-and-await }
-Python'un modern sürümleri, asenkron kodu tanımlamanın çok sezgisel bir yoluna sahiptir. Bu, normal "sequentıal" (sıralı) kod gibi görünmesini ve doğru anlarda sizin için "awaıt" ile bekleme yapmasını sağlar.
+Python’un modern sürümleri, asenkron kodu tanımlamak için oldukça sezgisel bir yol sunar. Bu sayede kod normal "sıralı" kod gibi görünür ve doğru anlarda sizin yerinize "beklemeyi" yapar.
-Sonuçları vermeden önce beklemeyi gerektirecek ve yeni Python özelliklerini destekleyen bir işlem olduğunda aşağıdaki gibi kodlayabilirsiniz:
+Sonuçları vermeden önce bekleme gerektiren ve bu yeni Python özelliklerini destekleyen bir işlem olduğunda, şöyle kodlayabilirsiniz:
```Python
burgers = await get_burgers(2)
```
-Buradaki `await` anahtari Python'a, sonuçları `burgers` degiskenine atamadan önce `get_burgers(2)` kodunun işini bitirmesini 🕙 beklemesi gerektiğini söyler. Bununla Python, bu ara zamanda başka bir şey 🔀 ⏯ yapabileceğini bilecektir (başka bir istek almak gibi).
+Buradaki kilit nokta `await`. Python’a, sonuçları `burgers` değişkenine koymadan önce `get_burgers(2)` çalışmasının bitmesini 🕙 beklemesi ⏸ gerektiğini söyler. Böylece Python, bu arada başka bir şey 🔀 ⏯ yapabileceğini bilir (ör. başka bir request almak gibi).
- `await`kodunun çalışması için, eşzamansızlığı destekleyen bir fonksiyonun içinde olması gerekir. Bunu da yapmak için fonksiyonu `async def` ile tanımlamamız yeterlidir:
+`await`’in çalışabilmesi için, bu asenkronluğu destekleyen bir fonksiyonun içinde olması gerekir. Bunu yapmak için fonksiyonu `async def` ile tanımlayın:
```Python hl_lines="1"
async def get_burgers(number: int):
- # burgerleri oluşturmak için asenkron birkaç iş
+ # Burgerleri yaratmak için bazı asenkron işler yap
return burgers
```
...`def` yerine:
```Python hl_lines="2"
-# bu kod asenkron değil
+# Bu asenkron değildir
def get_sequential_burgers(number: int):
- # burgerleri oluşturmak için senkron bırkaç iş
+ # Burgerleri yaratmak için bazı sıralı işler yap
return burgers
```
-`async def` ile Python, bu fonksıyonun içinde, `await` ifadelerinin farkında olması gerektiğini ve çalışma zamanı gelmeden önce bu işlevin yürütülmesini "duraklatabileceğini" ve başka bir şey yapabileceğini 🔀 bilir.
+`async def` ile Python, bu fonksiyonun içinde `await` ifadelerinin olabileceğini bilir ve bu fonksiyonun yürütülmesini "duraklatıp" ⏸ başka bir şey yapabileceğini 🔀, sonra geri dönebileceğini anlar.
-`async def` fonksiyonunu çağırmak istediğinizde, onu "awaıt" ıle kullanmanız gerekir. Yani, bu işe yaramaz:
+`async def` fonksiyonunu çağırmak istediğinizde, onu "await" etmeniz gerekir. Yani şu çalışmaz:
```Python
-# Bu işe yaramaz, çünkü get_burgers, şu şekilde tanımlandı: async def
+# Bu çalışmaz, çünkü get_burgers şöyle tanımlandı: async def
burgers = get_burgers(2)
```
---
-Bu nedenle, size onu `await` ile çağırabileceğinizi söyleyen bir kitaplık kullanıyorsanız, onu `async def` ile tanımlanan *path fonksiyonu* içerisinde kullanmanız gerekir, örneğin:
+Dolayısıyla, `await` ile çağrılabileceğini söyleyen bir kütüphane kullanıyorsanız, onu kullanan *path operasyon fonksiyonunu* `async def` ile oluşturmanız gerekir, örneğin:
```Python hl_lines="2-3"
@app.get('/burgers')
@@ -321,87 +349,96 @@ async def read_burgers():
return burgers
```
-### Daha fazla teknik detay
+### Daha teknik detaylar { #more-technical-details }
-`await` in yalnızca `async def` ile tanımlanan fonksıyonların içinde kullanılabileceğini fark etmişsinizdir.
+`await`’in yalnızca `async def` ile tanımlanan fonksiyonların içinde kullanılabildiğini fark etmiş olabilirsiniz.
-Ama aynı zamanda, `async def` ile tanımlanan fonksiyonların "await" ile beklenmesi gerekir. Bu nedenle, "`async def` içeren fonksiyonlar yalnızca "`async def` ile tanımlanan fonksiyonların içinde çağrılabilir.
+Aynı zamanda, `async def` ile tanımlanan fonksiyonların da "await" edilmesi gerekir. Yani `async def` ile tanımlanan fonksiyonlar yalnızca `async def` ile tanımlanan fonksiyonların içinde çağrılabilir.
+Peki, tavuk-yumurta meselesi: ilk `async` fonksiyon nasıl çağrılır?
-Yani yumurta mı tavukdan, tavuk mu yumurtadan gibi ilk `async` fonksiyonu nasıl çağırılır?
+**FastAPI** ile çalışıyorsanız bunu dert etmenize gerek yok; çünkü o "ilk" fonksiyon sizin *path operasyon fonksiyonunuz* olacaktır ve FastAPI doğru olanı yapmasını bilir.
-**FastAPI** ile çalışıyorsanız bunun için endişelenmenize gerek yok, çünkü bu "ilk" fonksiyon sizin *path fonksiyonunuz* olacak ve FastAPI doğru olanı nasıl yapacağını bilecek.
+Ama FastAPI olmadan da `async` / `await` kullanmak isterseniz, bunu da yapabilirsiniz.
-Ancak FastAPI olmadan `async` / `await` kullanmak istiyorsanız, resmi Python belgelerini kontrol edin.
+### Kendi async kodunuzu yazın { #write-your-own-async-code }
-### Asenkron kodun diğer biçimleri
+Starlette (ve **FastAPI**) AnyIO üzerine kuruludur; bu sayede Python standart kütüphanesindeki asyncio ve Trio ile uyumludur.
-Bu `async` ve `await` kullanimi oldukça yenidir.
+Özellikle, kendi kodunuzda daha gelişmiş desenler gerektiren ileri seviye eşzamanlılık kullanım senaryoları için doğrudan AnyIO kullanabilirsiniz.
-Ancak asenkron kodla çalışmayı çok daha kolay hale getirir.
+Hatta FastAPI kullanmıyor olsanız bile, yüksek uyumluluk ve avantajları (ör. *structured concurrency*) için AnyIO ile kendi async uygulamalarınızı yazabilirsiniz.
-Aynı sözdizimi (hemen hemen aynı) son zamanlarda JavaScript'in modern sürümlerine de dahil edildi (Tarayıcı ve NodeJS'de).
+AnyIO’nun üzerine, tür açıklamalarını biraz iyileştirmek ve daha iyi **otomatik tamamlama**, **satır içi hatalar** vb. elde etmek için ince bir katman olarak başka bir kütüphane daha oluşturdum. Ayrıca **kendi async kodunuzu** anlamanıza ve yazmanıza yardımcı olacak dostça bir giriş ve eğitim içerir: Asyncer. Özellikle **async kodu normal** (bloklayan/senkron) **kodla birleştirmeniz** gerektiğinde faydalı olacaktır.
-Ancak bundan önce, asenkron kodu işlemek oldukça karmaşık ve zordu.
+### Asenkron kodun diğer biçimleri { #other-forms-of-asynchronous-code }
-Python'un önceki sürümlerinde, threadlerı veya Gevent kullanıyor olabilirdin. Ancak kodu anlamak, hata ayıklamak ve düşünmek çok daha karmaşık olurdu.
+`async` ve `await` kullanma tarzı, dilde nispeten yenidir.
-NodeJS / Browser JavaScript'in önceki sürümlerinde, "callback" kullanırdınız. Bu da "callbacks cehennemine" yol açar.
+Ama asenkron kodla çalışmayı çok daha kolaylaştırır.
-## Coroutine'ler
+Aynı (ya da neredeyse aynı) sözdizimi yakın zamanda modern JavaScript sürümlerine (Tarayıcı ve NodeJS) de eklendi.
-**Coroutine**, bir `async def` fonksiyonu tarafından döndürülen değer için çok süslü bir terimdir. Python bunun bir fonksiyon gibi bir noktada başlayıp biteceğini bilir, ancak içinde bir `await` olduğunda dahili olarak da duraklatılabilir ⏸.
+Bundan önce, asenkron kodu ele almak oldukça daha karmaşık ve zordu.
-Ancak, `async` ve `await` ile asenkron kod kullanmanın tüm bu işlevselliği, çoğu zaman "Coroutine" kullanmak olarak adlandırılır. Go'nun ana özelliği olan "Goroutines" ile karşılaştırılabilir.
+Python’un önceki sürümlerinde thread’ler veya Gevent kullanabilirdiniz. Ama kodu anlamak, hata ayıklamak ve üzerine düşünmek çok daha zordu.
-## Sonuç
+NodeJS / Tarayıcı JavaScript’in önceki sürümlerinde "callback" kullanırdınız. Bu da "callback cehennemi"ne yol açardı.
-Aynı ifadeyi yukarıdan görelim:
+## Coroutine'ler { #coroutines }
-> Python'ın modern sürümleri, **"async" ve "await"** sözdizimi ile birlikte **"coroutines"** adlı bir özelliği kullanan **"asenkron kod"** desteğine sahiptir.
+**Coroutine**, bir `async def` fonksiyonunun döndürdüğü şeye verilen süslü isimdir. Python bunun bir fonksiyona benzer bir şey olduğunu, bir noktada başlayıp biteceğini bilir; ama içinde bir `await` olduğunda dahili olarak duraklatılabileceğini ⏸ de bilir.
-Şimdi daha mantıklı gelmeli. ✨
+`async` ve `await` ile asenkron kod kullanmanın bu işlevselliği çoğu zaman "coroutine" kullanmak olarak özetlenir. Go’nun ana kilit özelliği olan "Goroutines" ile karşılaştırılabilir.
-FastAPI'ye (Starlette aracılığıyla) güç veren ve bu kadar etkileyici bir performansa sahip olmasını sağlayan şey budur.
+## Sonuç { #conclusion }
-## Çok Teknik Detaylar
+Yukarıdaki cümleyi tekrar görelim:
-/// warning
+> Python’un modern sürümleri, **`async` ve `await`** sözdizimiyle, **"coroutines"** denilen bir yapıyı kullanarak **"asenkron kod"** desteğine sahiptir.
-Muhtemelen burayı atlayabilirsiniz.
+Artık daha anlamlı gelmeli. ✨
-Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır.
+Bunların hepsi, FastAPI’ye (Starlette aracılığıyla) güç verir ve böylesine etkileyici bir performansa sahip olmasını sağlar.
-Biraz teknik bilginiz varsa (co-routines, threads, blocking, vb)ve FastAPI'nin "async def" ile normal "def" arasındaki farkı nasıl işlediğini merak ediyorsanız, devam edin.
+## Çok Teknik Detaylar { #very-technical-details }
+
+/// warning | Uyarı
+
+Büyük ihtimalle burayı atlayabilirsiniz.
+
+Bunlar, **FastAPI**’nin altında nasıl çalıştığına dair oldukça teknik ayrıntılardır.
+
+Coroutine’ler, thread’ler, blocking vb. hakkında teknik bilginiz varsa ve FastAPI’nin `async def` ile normal `def` arasındaki farkı nasıl ele aldığını merak ediyorsanız, devam edin.
///
-### Path fonksiyonu
+### Path Operasyon Fonksiyonları { #path-operation-functions }
-"async def" yerine normal "def" ile bir *yol işlem işlevi* bildirdiğinizde, doğrudan çağrılmak yerine (sunucuyu bloke edeceğinden) daha sonra beklenen harici bir iş parçacığı havuzunda çalıştırılır.
+Bir *path operasyon fonksiyonunu* `async def` yerine normal `def` ile tanımladığınızda, (sunucuyu bloklayacağından) doğrudan çağrılmak yerine, harici bir thread pool’da çalıştırılır ve ardından beklenir.
-Yukarıda açıklanan şekilde çalışmayan başka bir asenkron framework'den geliyorsanız ve küçük bir performans kazancı (yaklaşık 100 nanosaniye) için "def" ile *path fonksiyonu* tanımlamaya alışkınsanız, **FastAPI**'de tam tersi olacağını unutmayın. Bu durumlarda, *path fonksiyonu* G/Ç engelleyen durum oluşturmadıkça "async def" kullanmak daha iyidir.
+Yukarıda açıklanan şekilde çalışmayan başka bir async framework’ten geliyorsanız ve ufak bir performans kazancı (yaklaşık 100 nanosaniye) için yalnızca hesaplama yapan basit *path operasyon fonksiyonlarını* düz `def` ile tanımlamaya alışkınsanız, **FastAPI**’de etkinin tam tersi olacağını unutmayın. Bu durumlarda, *path operasyon fonksiyonlarınız* bloklayan I/O yapan kod kullanmadıkça `async def` kullanmak daha iyidir.
-Yine de, her iki durumda da, **FastAPI**'nin önceki frameworkden [hala daha hızlı](index.md#performans){.internal-link target=_blank} (veya en azından karşılaştırılabilir) olma olasılığı vardır.
+Yine de her iki durumda da, **FastAPI**’nin önceki framework’ünüzden [hala daha hızlı](index.md#performance){.internal-link target=_blank} (ya da en azından karşılaştırılabilir) olması muhtemeldir.
-### Bagımlılıklar
+### Bağımlılıklar { #dependencies }
-Aynısı bağımlılıklar için de geçerlidir. Bir bağımlılık, "async def" yerine standart bir "def" işleviyse, harici iş parçacığı havuzunda çalıştırılır.
+Aynısı [bağımlılıklar](tutorial/dependencies/index.md){.internal-link target=_blank} için de geçerlidir. Bir bağımlılık `async def` yerine standart bir `def` fonksiyonuysa, harici thread pool’da çalıştırılır.
-### Alt-bağımlıklar
+### Alt-bağımlılıklar { #sub-dependencies }
-Birbirini gerektiren (fonksiyonlarin parametreleri olarak) birden fazla bağımlılık ve alt bağımlılıklarınız olabilir, bazıları 'async def' ve bazıları normal 'def' ile oluşturulabilir. Yine de normal 'def' ile oluşturulanlar, "await" kulanilmadan harici bir iş parçacığında (iş parçacığı havuzundan) çağrılır.
+Birbirini gerektiren birden çok bağımlılık ve [alt-bağımlılık](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} olabilir (fonksiyon tanımlarının parametreleri olarak). Bazıları `async def` ile, bazıları normal `def` ile oluşturulmuş olabilir. Yine de çalışır ve normal `def` ile oluşturulanlar "await" edilmek yerine harici bir thread’de (thread pool’dan) çağrılır.
-### Diğer yardımcı fonksiyonlar
+### Diğer yardımcı fonksiyonlar { #other-utility-functions }
-Doğrudan çağırdığınız diğer herhangi bir yardımcı fonksiyonu, normal "def" veya "async def" ile tanimlayabilirsiniz. FastAPI onu çağırma şeklinizi etkilemez.
+Doğrudan çağırdığınız diğer yardımcı fonksiyonları normal `def` veya `async def` ile tanımlayabilirsiniz ve FastAPI onları çağırma biçiminizi etkilemez.
-Bu, FastAPI'nin sizin için çağırdığı fonksiyonlarin tam tersidir: *path fonksiyonu* ve bağımlılıklar.
+Bu, FastAPI’nin sizin için çağırdığı fonksiyonların tersidir: *path operasyon fonksiyonları* ve bağımlılıklar.
-Yardımcı program fonksiyonunuz 'def' ile normal bir işlevse, bir iş parçacığı havuzunda değil doğrudan (kodunuzda yazdığınız gibi) çağrılır, işlev 'async def' ile oluşturulmuşsa çağırıldığı yerde 'await' ile beklemelisiniz.
+Yardımcı fonksiyonunuz `def` ile tanımlı normal bir fonksiyonsa, bir thread pool’da değil doğrudan (kodunuzda yazdığınız gibi) çağrılır; fonksiyon `async def` ile tanımlıysa kodunuzda çağırırken onu `await` etmelisiniz.
---
-Yeniden, bunlar, onları aramaya geldiğinizde muhtemelen işinize yarayacak çok teknik ayrıntılardır.
+Yine, bunlar muhtemelen özellikle aradığınızda işinize yarayacak çok teknik ayrıntılardır.
-Aksi takdirde, yukarıdaki bölümdeki yönergeleri iyi bilmelisiniz: Aceleniz mi var?.
+Aksi hâlde, yukarıdaki bölümdeki yönergeler yeterlidir: Aceleniz mi var?.
diff --git a/docs/tr/docs/deployment/concepts.md b/docs/tr/docs/deployment/concepts.md
index d0f568146..f5ee988c9 100644
--- a/docs/tr/docs/deployment/concepts.md
+++ b/docs/tr/docs/deployment/concepts.md
@@ -13,7 +13,7 @@ Bir **FastAPI** uygulamasını (hatta genel olarak herhangi bir web API'yi) depl
Bunların **deployment**'ları nasıl etkilediğine bakalım.
-Nihai hedef, **API client**'larınıza **güvenli** bir şekilde hizmet verebilmek, **kesintileri** önlemek ve **hesaplama kaynaklarını** (ör. uzak server'lar/sanal makineler) olabildiğince verimli kullanmaktır.
+Nihai hedef, **API client**'larınıza **güvenli** bir şekilde hizmet verebilmek, **kesintileri** önlemek ve **hesaplama kaynaklarını** (ör. uzak server'lar/sanal makineler) olabildiğince verimli kullanmaktır. 🚀
Burada bu **kavramlar** hakkında biraz daha bilgi vereceğim. Böylece, çok farklı ortamlarda—hatta bugün var olmayan **gelecekteki** ortamlarda bile—API'nizi nasıl deploy edeceğinize karar verirken ihtiyaç duyacağınız **sezgiyi** kazanmış olursunuz.
@@ -21,7 +21,7 @@ Bu kavramları dikkate alarak, **kendi API**'leriniz için en iyi deployment yak
Sonraki bölümlerde, FastAPI uygulamalarını deploy etmek için daha **somut tarifler** (recipes) paylaşacağım.
-Ama şimdilik, bu önemli **kavramsal fikirleri** inceleyelim. Bu kavramlar diğer tüm web API türleri için de geçerlidir.
+Ama şimdilik, bu önemli **kavramsal fikirleri** inceleyelim. Bu kavramlar diğer tüm web API türleri için de geçerlidir. 💡
## Güvenlik - HTTPS { #security-https }
@@ -36,16 +36,16 @@ Ve **HTTPS sertifikalarını yenilemekten** sorumlu bir şey olmalıdır; bu ayn
TLS Termination Proxy olarak kullanabileceğiniz bazı araçlar:
* Traefik
- * Sertifika yenilemelerini otomatik yönetir
+ * Sertifika yenilemelerini otomatik yönetir ✨
* Caddy
- * Sertifika yenilemelerini otomatik yönetir
+ * Sertifika yenilemelerini otomatik yönetir ✨
* Nginx
* Sertifika yenilemeleri için Certbot gibi harici bir bileşenle
* HAProxy
* Sertifika yenilemeleri için Certbot gibi harici bir bileşenle
* Nginx gibi bir Ingress Controller ile Kubernetes
* Sertifika yenilemeleri için cert-manager gibi harici bir bileşenle
-* Bir cloud provider tarafından servislerinin parçası olarak içeride yönetilmesi (aşağıyı okuyun)
+* Bir cloud provider tarafından servislerinin parçası olarak içeride yönetilmesi (aşağıyı okuyun 👇)
Bir diğer seçenek de, HTTPS kurulumunu da dahil olmak üzere işin daha büyük kısmını yapan bir **cloud service** kullanmaktır. Bunun bazı kısıtları olabilir veya daha pahalı olabilir vb. Ancak bu durumda TLS Termination Proxy'yi kendiniz kurmak zorunda kalmazsınız.
@@ -100,7 +100,7 @@ Bu yöntem çalışır ve **geliştirme sırasında** faydalıdır.
Ancak server'a olan bağlantınız koparsa, **çalışan process** muhtemelen ölür.
-Ve server yeniden başlatılırsa (örneğin update'lerden sonra ya da cloud provider'ın migration'larından sonra) bunu muhtemelen **fark etmezsiniz**. Dolayısıyla process'i manuel yeniden başlatmanız gerektiğini de bilmezsiniz. Sonuçta API'niz ölü kalır.
+Ve server yeniden başlatılırsa (örneğin update'lerden sonra ya da cloud provider'ın migration'larından sonra) bunu muhtemelen **fark etmezsiniz**. Dolayısıyla process'i manuel yeniden başlatmanız gerektiğini de bilmezsiniz. Sonuçta API'niz ölü kalır. 😱
### Startup'ta Otomatik Çalıştırma { #run-automatically-on-startup }
@@ -131,19 +131,19 @@ Uygulamanızın startup'ta çalıştığından emin olmaya benzer şekilde, hata
### Hata Yaparız { #we-make-mistakes }
-Biz insanlar sürekli **hata** yaparız. Yazılımın neredeyse *her zaman* farklı yerlerinde gizli **bug**'lar vardır.
+Biz insanlar sürekli **hata** yaparız. Yazılımın neredeyse *her zaman* farklı yerlerinde gizli **bug**'lar vardır. 🐛
-Ve biz geliştiriciler bu bug'ları buldukça ve yeni özellikler ekledikçe code'u iyileştiririz (muhtemelen yeni bug'lar da ekleyerek).
+Ve biz geliştiriciler bu bug'ları buldukça ve yeni özellikler ekledikçe code'u iyileştiririz (muhtemelen yeni bug'lar da ekleyerek 😅).
### Küçük Hatalar Otomatik Yönetilir { #small-errors-automatically-handled }
-FastAPI ile web API geliştirirken, code'umuzda bir hata olursa FastAPI genellikle bunu hatayı tetikleyen tek request ile sınırlar.
+FastAPI ile web API geliştirirken, code'umuzda bir hata olursa FastAPI genellikle bunu hatayı tetikleyen tek request ile sınırlar. 🛡
Client o request için **500 Internal Server Error** alır; ancak uygulama tamamen çöküp durmak yerine sonraki request'ler için çalışmaya devam eder.
### Daha Büyük Hatalar - Çökmeler { #bigger-errors-crashes }
-Yine de bazı durumlarda, yazdığımız bir code **tüm uygulamayı çökertip** Uvicorn ve Python'ın crash olmasına neden olabilir.
+Yine de bazı durumlarda, yazdığımız bir code **tüm uygulamayı çökertip** Uvicorn ve Python'ın crash olmasına neden olabilir. 💥
Böyle bir durumda, tek bir noktadaki hata yüzünden uygulamanın ölü kalmasını istemezsiniz; bozuk olmayan *path operations* en azından çalışmaya devam etsin istersiniz.
@@ -206,7 +206,7 @@ Ve birden fazla process normalde **belleği paylaşmaz**. Yani her çalışan pr
Örneğin code'unuz **1 GB** boyutunda bir Machine Learning modelini yüklüyorsa, API'niz tek process ile çalışırken en az 1 GB RAM tüketir. **4 process** (4 worker) başlatırsanız her biri 1 GB RAM tüketir. Yani toplamda API'niz **4 GB RAM** tüketir.
-Uzak server'ınız veya sanal makineniz yalnızca 3 GB RAM'e sahipse, 4 GB'tan fazla RAM yüklemeye çalışmak sorun çıkarır.
+Uzak server'ınız veya sanal makineniz yalnızca 3 GB RAM'e sahipse, 4 GB'tan fazla RAM yüklemeye çalışmak sorun çıkarır. 🚨
### Birden Fazla Process - Bir Örnek { #multiple-processes-an-example }
@@ -265,7 +265,7 @@ Elbette bazı durumlarda ön adımları birden fazla kez çalıştırmak sorun d
Ayrıca, kurulumunuza bağlı olarak bazı durumlarda uygulamanızı başlatmadan önce **hiç ön adıma ihtiyaç duymayabilirsiniz**.
-Bu durumda bunların hiçbirini düşünmeniz gerekmez.
+Bu durumda bunların hiçbirini düşünmeniz gerekmez. 🤷
///
@@ -291,7 +291,7 @@ Server(lar)ınız bir **kaynaktır**. Programlarınızla CPU'lardaki hesaplama z
Sistem kaynaklarının ne kadarını tüketmek/kullanmak istersiniz? "Az" demek kolaydır; ancak pratikte hedef genellikle **çökmeden mümkün olduğunca fazla** kullanmaktır.
-3 server için para ödüyor ama onların RAM ve CPU'sunun yalnızca küçük bir kısmını kullanıyorsanız, muhtemelen **para israf ediyorsunuz** ve muhtemelen **elektrik tüketimini** de gereksiz yere artırıyorsunuz vb.
+3 server için para ödüyor ama onların RAM ve CPU'sunun yalnızca küçük bir kısmını kullanıyorsanız, muhtemelen **para israf ediyorsunuz** 💸 ve muhtemelen **elektrik tüketimini** de gereksiz yere artırıyorsunuz 🌎 vb.
Bu durumda 2 server ile devam edip onların kaynaklarını (CPU, bellek, disk, ağ bant genişliği vb.) daha yüksek oranlarda kullanmak daha iyi olabilir.
@@ -316,6 +316,6 @@ Uygulamanızı nasıl deploy edeceğinize karar verirken aklınızda tutmanız g
* Bellek
* Başlatmadan önceki adımlar
-Bu fikirleri ve nasıl uygulayacağınızı anlamak, deployment'larınızı yapılandırırken ve ince ayar yaparken ihtiyaç duyacağınız sezgiyi kazanmanızı sağlamalıdır.
+Bu fikirleri ve nasıl uygulayacağınızı anlamak, deployment'larınızı yapılandırırken ve ince ayar yaparken ihtiyaç duyacağınız sezgiyi kazanmanızı sağlamalıdır. 🤓
-Sonraki bölümlerde, izleyebileceğiniz stratejilere dair daha somut örnekler paylaşacağım.
+Sonraki bölümlerde, izleyebileceğiniz stratejilere dair daha somut örnekler paylaşacağım. 🚀
diff --git a/docs/tr/docs/deployment/docker.md b/docs/tr/docs/deployment/docker.md
index 6c8f74c77..6d38a2ce1 100644
--- a/docs/tr/docs/deployment/docker.md
+++ b/docs/tr/docs/deployment/docker.md
@@ -14,7 +14,7 @@ Aceleniz var ve bunları zaten biliyor musunuz? Aşağıdaki [`Dockerfile`'a atl
-Web API yerine terminalde kullanılacak bir CLI uygulaması geliştiriyorsanız **Typer**'a göz atın.
+Web API yerine terminalde kullanılacak bir CLI uygulaması geliştiriyorsanız **Typer**'a göz atın.
**Typer**, FastAPI'ın küçük kardeşi. Ve hedefi CLI'ların **FastAPI'ı** olmak. ⌨️ 🚀
@@ -368,7 +368,7 @@ item: Item
* Verinin doğrulanması:
* Veri geçersiz olduğunda otomatik ve anlaşılır hatalar.
* Çok derin iç içe JSON nesneleri için bile doğrulama.
-* Girdi verisinin Dönüşümü: network'ten gelen veriyi Python verisine ve type'larına çevirir. Şunlardan okur:
+* Girdi verisinin Dönüşümü: network'ten gelen veriyi Python verisine ve type'larına çevirir. Şunlardan okur:
* JSON.
* Path parameter'lar.
* Query parameter'lar.
@@ -376,7 +376,7 @@ item: Item
* Header'lar.
* Form'lar.
* File'lar.
-* Çıktı verisinin Dönüşümü: Python verisini ve type'larını network verisine çevirir (JSON olarak):
+* Çıktı verisinin Dönüşümü: Python verisini ve type'larını network verisine çevirir (JSON olarak):
* Python type'larını dönüştürür (`str`, `int`, `float`, `bool`, `list`, vb.).
* `datetime` nesneleri.
* `UUID` nesneleri.
@@ -439,7 +439,7 @@ Daha fazla özellik içeren daha kapsamlı bir örnek için Dependency Injection** sistemi.
+* Çok güçlü ve kullanımı kolay bir **Bağımlılık Enjeksiyonu** sistemi.
* **JWT tokens** ve **HTTP Basic** auth ile **OAuth2** desteği dahil güvenlik ve kimlik doğrulama.
* **Çok derin iç içe JSON modelleri** tanımlamak için daha ileri (ama aynı derecede kolay) teknikler (Pydantic sayesinde).
* Strawberry ve diğer kütüphaneler ile **GraphQL** entegrasyonu.
@@ -524,7 +524,7 @@ Starlette tarafından kullanılanlar:
*
httpx - `TestClient` kullanmak istiyorsanız gereklidir.
* jinja2 - varsayılan template yapılandırmasını kullanmak istiyorsanız gereklidir.
-* python-multipart - `request.form()` ile, form "parsing" desteği istiyorsanız gereklidir.
+* python-multipart - `request.form()` ile, form "ayrıştırma" desteği istiyorsanız gereklidir.
FastAPI tarafından kullanılanlar:
@@ -534,7 +534,7 @@ FastAPI tarafından kullanılanlar:
### `standard` Bağımlılıkları Olmadan { #without-standard-dependencies }
-`standard` opsiyonel bağımlılıklarını dahil etmek istemiyorsanız, `pip install "fastapi[standard]"` yerine `pip install fastapi` ile kurabilirsiniz.
+`standard` opsiyonel bağımlılıklarını dahil etmek istemiyorsanız, `pip install fastapi` ile kurabilirsiniz.
### `fastapi-cloud-cli` Olmadan { #without-fastapi-cloud-cli }
diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md
index 01a3efe98..9477e4fab 100644
--- a/docs/tr/docs/python-types.md
+++ b/docs/tr/docs/python-types.md
@@ -2,9 +2,9 @@
Python, isteğe bağlı "type hints" (diğer adıyla "type annotations") desteğine sahiptir.
-Bu **"type hints"** veya annotations, bir değişkenin type'ını bildirmeye yarayan özel bir sözdizimidir.
+Bu **"type hints"** veya annotations, bir değişkenin tip'ini bildirmeye yarayan özel bir sözdizimidir.
-Değişkenleriniz için type bildirerek, editörler ve araçlar size daha iyi destek sağlayabilir.
+Değişkenleriniz için tip bildirerek, editörler ve araçlar size daha iyi destek sağlayabilir.
Bu, Python type hints hakkında sadece **hızlı bir eğitim / bilgi tazeleme** dokümanıdır. **FastAPI** ile kullanmak için gereken minimum bilgiyi kapsar... ki aslında bu çok azdır.
@@ -22,7 +22,7 @@ Eğer bir Python uzmanıysanız ve type hints hakkında her şeyi zaten biliyors
Basit bir örnekle başlayalım:
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
Bu programı çalıştırınca şu çıktıyı alırsınız:
@@ -34,9 +34,9 @@ Fonksiyon şunları yapar:
* `first_name` ve `last_name` değerlerini alır.
* `title()` ile her birinin ilk harfini büyük harfe çevirir.
-* Ortada bir boşluk olacak şekilde Concatenates eder.
+* Ortada bir boşluk olacak şekilde Birleştirir.
-{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
### Düzenleyelim { #edit-it }
@@ -78,7 +78,7 @@ Bu kadar.
Bunlar "type hints":
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
Bu, aşağıdaki gibi default değerler bildirmekle aynı şey değildir:
@@ -106,7 +106,7 @@ Bununla birlikte, seçenekleri görerek kaydırabilirsiniz; ta ki "tanıdık gel
Şu fonksiyona bakın, zaten type hints içeriyor:
-{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
Editör değişkenlerin tiplerini bildiği için, sadece completion değil, aynı zamanda hata kontrolleri de alırsınız:
@@ -114,9 +114,9 @@ Editör değişkenlerin tiplerini bildiği için, sadece completion değil, ayn
Artık bunu düzeltmeniz gerektiğini, `age`'i `str(age)` ile string'e çevirmeniz gerektiğini biliyorsunuz:
-{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
-## Tipleri bildirmek { #declaring-types }
+## Tipleri Bildirmek { #declaring-types }
Type hints bildirmek için ana yeri az önce gördünüz: fonksiyon parametreleri.
@@ -133,29 +133,32 @@ Sadece `str` değil, tüm standart Python tiplerini bildirebilirsiniz.
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### Tip parametreleri ile Generic tipler { #generic-types-with-type-parameters }
+### `typing` modülü { #typing-module }
-`dict`, `list`, `set` ve `tuple` gibi, başka değerler içerebilen bazı veri yapıları vardır. Ve iç değerlerin kendi tipi de olabilir.
+Bazı ek kullanım durumları için standart kütüphanedeki `typing` modülünden bazı şeyleri import etmeniz gerekebilir. Örneğin bir şeyin "herhangi bir tip" olabileceğini bildirmek istediğinizde, `typing` içindeki `Any`'yi kullanabilirsiniz:
-İç tipleri olan bu tiplere "**generic**" tipler denir. Ve bunları, iç tipleriyle birlikte bildirmek mümkündür.
+```python
+from typing import Any
-Bu tipleri ve iç tipleri bildirmek için standart Python modülü `typing`'i kullanabilirsiniz. Bu modül, özellikle bu type hints desteği için vardır.
-#### Python'un daha yeni sürümleri { #newer-versions-of-python }
+def some_function(data: Any):
+ print(data)
+```
-`typing` kullanan sözdizimi, Python 3.6'dan en yeni sürümlere kadar (Python 3.9, Python 3.10, vb. dahil) tüm sürümlerle **uyumludur**.
+### Generic tipler { #generic-types }
-Python geliştikçe, **daha yeni sürümler** bu type annotations için daha iyi destekle gelir ve çoğu durumda type annotations bildirmek için `typing` modülünü import edip kullanmanız bile gerekmez.
+Bazı tipler, köşeli parantez içinde "type parameters" alarak iç tiplerini tanımlayabilir; örneğin "string listesi" `list[str]` olarak bildirilir.
-Projeniz için daha yeni bir Python sürümü seçebiliyorsanız, bu ek sadelikten yararlanabilirsiniz.
+Bu şekilde type parameter alabilen tiplere **Generic types** veya **Generics** denir.
-Tüm dokümanlarda her Python sürümüyle uyumlu örnekler vardır (fark olduğunda).
+Aynı builtin tipleri generics olarak kullanabilirsiniz (köşeli parantez ve içinde tiplerle):
-Örneğin "**Python 3.6+**", Python 3.6 veya üstüyle (3.7, 3.8, 3.9, 3.10, vb. dahil) uyumludur. "**Python 3.9+**" ise Python 3.9 veya üstüyle (3.10 vb. dahil) uyumludur.
-
-Eğer **Python'un en güncel sürümlerini** kullanabiliyorsanız, en güncel sürüme ait örnekleri kullanın; bunlar **en iyi ve en basit sözdizimine** sahip olur, örneğin "**Python 3.10+**".
+* `list`
+* `tuple`
+* `set`
+* `dict`
#### List { #list }
@@ -163,11 +166,11 @@ Eğer **Python'un en güncel sürümlerini** kullanabiliyorsanız, en güncel s
Değişkeni, aynı iki nokta (`:`) sözdizimiyle bildirin.
-Type olarak `list` yazın.
+Tip olarak `list` yazın.
`list`, bazı iç tipleri barındıran bir tip olduğundan, bunları köşeli parantez içine yazarsınız:
-{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
/// info | Bilgi
@@ -193,7 +196,7 @@ Ve yine de editör bunun bir `str` olduğunu bilir ve buna göre destek sağlar.
`tuple`'ları ve `set`'leri bildirmek için de aynısını yaparsınız:
-{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
Bu şu anlama gelir:
@@ -208,7 +211,7 @@ Bir `dict` tanımlamak için, virgülle ayrılmış 2 type parameter verirsiniz.
İkinci type parameter, `dict`'in value'ları içindir:
-{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Bu şu anlama gelir:
@@ -220,44 +223,20 @@ Bu şu anlama gelir:
Bir değişkenin **birkaç tipten herhangi biri** olabileceğini bildirebilirsiniz; örneğin bir `int` veya bir `str`.
-Python 3.6 ve üzeri sürümlerde (Python 3.10 dahil), `typing` içinden `Union` tipini kullanabilir ve köşeli parantez içine kabul edilecek olası tipleri yazabilirsiniz.
+Bunu tanımlamak için, her iki tipi ayırmak üzere dikey çizgi (`|`) kullanırsınız.
-Python 3.10'da ayrıca, olası tipleri vertical bar (`|`) ile ayırabildiğiniz **yeni bir sözdizimi** de vardır.
-
-//// tab | Python 3.10+
+Buna "union" denir, çünkü değişken bu iki tip kümesinin birleşimindeki herhangi bir şey olabilir.
```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-////
-
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b_py39.py!}
-```
-
-////
-
-Her iki durumda da bu, `item`'ın `int` veya `str` olabileceği anlamına gelir.
+Bu, `item`'ın `int` veya `str` olabileceği anlamına gelir.
#### Muhtemelen `None` { #possibly-none }
Bir değerin `str` gibi bir tipi olabileceğini ama aynı zamanda `None` da olabileceğini bildirebilirsiniz.
-Python 3.6 ve üzeri sürümlerde (Python 3.10 dahil), `typing` modülünden `Optional` import edip kullanarak bunu bildirebilirsiniz.
-
-```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-Sadece `str` yerine `Optional[str]` kullanmak, aslında değer `None` olabilecekken her zaman `str` olduğunu varsaydığınız hataları editörün yakalamanıza yardımcı olmasını sağlar.
-
-`Optional[Something]`, aslında `Union[Something, None]` için bir kısayoldur; eşdeğerdirler.
-
-Bu aynı zamanda Python 3.10'da `Something | None` kullanabileceğiniz anlamına gelir:
-
//// tab | Python 3.10+
```Python hl_lines="1"
@@ -266,96 +245,7 @@ Bu aynı zamanda Python 3.10'da `Something | None` kullanabileceğiniz anlamına
////
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-////
-
-//// tab | Python 3.9+ alternatif
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b_py39.py!}
-```
-
-////
-
-#### `Union` veya `Optional` kullanmak { #using-union-or-optional }
-
-Python sürümünüz 3.10'un altındaysa, benim oldukça **öznel** bakış açıma göre küçük bir ipucu:
-
-* 🚨 `Optional[SomeType]` kullanmaktan kaçının
-* Bunun yerine ✨ **`Union[SomeType, None]` kullanın** ✨.
-
-İkisi eşdeğerdir ve altta aynı şeydir; ama ben `Optional` yerine `Union` önermeyi tercih ederim. Çünkü "**optional**" kelimesi değerin optional olduğunu ima ediyor gibi durur; ama gerçekte anlamı "değer `None` olabilir"dir. Değer optional olmasa ve hâlâ required olsa bile.
-
-Bence `Union[SomeType, None]` ne anlama geldiğini daha açık şekilde ifade ediyor.
-
-Bu, tamamen kelimeler ve isimlendirmelerle ilgili. Ancak bu kelimeler, sizin ve ekip arkadaşlarınızın kod hakkında nasıl düşündüğünü etkileyebilir.
-
-Örnek olarak şu fonksiyonu ele alalım:
-
-{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
-
-`name` parametresi `Optional[str]` olarak tanımlanmış, ama **optional değil**; parametre olmadan fonksiyonu çağıramazsınız:
-
-```Python
-say_hi() # Oh, no, this throws an error! 😱
-```
-
-`name` parametresi **hâlâ required**'dır (*optional* değildir) çünkü bir default değeri yoktur. Yine de `name`, değer olarak `None` kabul eder:
-
-```Python
-say_hi(name=None) # This works, None is valid 🎉
-```
-
-İyi haber şu ki, Python 3.10'a geçtiğinizde bununla uğraşmanız gerekmeyecek; çünkü tiplerin union'larını tanımlamak için doğrudan `|` kullanabileceksiniz:
-
-{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
-
-Ve böylece `Optional` ve `Union` gibi isimlerle de uğraşmanız gerekmeyecek. 😎
-
-#### Generic tipler { #generic-types }
-
-Köşeli parantez içinde type parameter alan bu tiplere **Generic types** veya **Generics** denir, örneğin:
-
-//// tab | Python 3.10+
-
-Aynı builtin tipleri generics olarak kullanabilirsiniz (köşeli parantez ve içindeki tiplerle):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-Ve önceki Python sürümlerinde olduğu gibi `typing` modülünden:
-
-* `Union`
-* `Optional`
-* ...and others.
-
-Python 3.10'da, `Union` ve `Optional` generics'lerini kullanmaya alternatif olarak, tip union'larını bildirmek için vertical bar (`|`) kullanabilirsiniz; bu çok daha iyi ve daha basittir.
-
-////
-
-//// tab | Python 3.9+
-
-Aynı builtin tipleri generics olarak kullanabilirsiniz (köşeli parantez ve içindeki tiplerle):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-Ve `typing` modülünden gelen generics:
-
-* `Union`
-* `Optional`
-* ...and others.
-
-////
+Sadece `str` yerine `str | None` kullanmak, aslında değer `None` olabilecekken her zaman `str` olduğunu varsaydığınız hataları editörün yakalamanıza yardımcı olur.
### Tip olarak sınıflar { #classes-as-types }
@@ -363,11 +253,11 @@ Bir sınıfı da bir değişkenin tipi olarak bildirebilirsiniz.
Örneğin, adı olan bir `Person` sınıfınız olsun:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
Sonra bir değişkeni `Person` tipinde olacak şekilde bildirebilirsiniz:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
Ve sonra, yine tüm editör desteğini alırsınız:
@@ -401,21 +291,15 @@ Daha fazlasını öğrenmek için Required Optional fields bölümünde okuyabilirsiniz.
-
-///
+Bunların pratikte nasıl çalıştığını [Eğitim - Kullanım Kılavuzu](tutorial/index.md){.internal-link target=_blank} içinde çok daha fazla göreceksiniz.
## Metadata Annotations ile Type Hints { #type-hints-with-metadata-annotations }
-Python'da ayrıca, `Annotated` kullanarak bu type hints içine **ek metadata** koymayı sağlayan bir özellik de vardır.
+Python'da ayrıca, `Annotated` kullanarak bu type hints içine **ek üstveri** koymayı sağlayan bir özellik de vardır.
-Python 3.9'dan itibaren `Annotated`, standart kütüphanenin bir parçasıdır; bu yüzden `typing` içinden import edebilirsiniz.
+`Annotated`'ı `typing` içinden import edebilirsiniz.
-{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
Python'un kendisi bu `Annotated` ile bir şey yapmaz. Editörler ve diğer araçlar için tip hâlâ `str`'dir.
@@ -446,14 +330,14 @@ Ayrıca kodunuzun pek çok başka Python aracı ve kütüphanesiyle çok uyumlu
...ve **FastAPI** aynı bildirimleri şunlar için de kullanır:
-* **Gereksinimleri tanımlamak**: request path parameters, query parameters, headers, bodies, dependencies, vb.
+* **Gereksinimleri tanımlamak**: request path parameters, query parameters, headers, bodies, bağımlılıklar (dependencies), vb.
* **Veriyi dönüştürmek**: request'ten gerekli tipe.
* **Veriyi doğrulamak**: her request'ten gelen veriyi:
* Veri geçersiz olduğunda client'a dönen **otomatik hatalar** üretmek.
* OpenAPI kullanarak API'yi **dokümante etmek**:
* bu, daha sonra otomatik etkileşimli dokümantasyon kullanıcı arayüzleri tarafından kullanılır.
-Bunların hepsi kulağa soyut gelebilir. Merak etmeyin. Tüm bunları [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank} içinde çalışırken göreceksiniz.
+Bunların hepsi kulağa soyut gelebilir. Merak etmeyin. Tüm bunları [Eğitim - Kullanım Kılavuzu](tutorial/index.md){.internal-link target=_blank} içinde çalışırken göreceksiniz.
Önemli olan, standart Python tiplerini tek bir yerde kullanarak (daha fazla sınıf, decorator vb. eklemek yerine), **FastAPI**'nin sizin için işin büyük kısmını yapmasıdır.
diff --git a/docs/tr/docs/translation-banner.md b/docs/tr/docs/translation-banner.md
index b52578f71..7491e61b8 100644
--- a/docs/tr/docs/translation-banner.md
+++ b/docs/tr/docs/translation-banner.md
@@ -4,7 +4,7 @@ Bu çeviri, insanlar tarafından yönlendirilen bir yapay zekâ ile oluşturuldu
Orijinal anlamın yanlış anlaşılması ya da kulağa doğal gelmeme gibi hatalar içerebilir. 🤖
-[Yapay zekâyı daha iyi yönlendirmemize yardımcı olarak](https://fastapi.tiangolo.com/tr/contributing/#translations) bu çeviriyi iyileştirebilirsiniz.
+[Yapay zekâ LLM'ini daha iyi yönlendirmemize yardımcı olarak](https://fastapi.tiangolo.com/tr/contributing/#translations) bu çeviriyi iyileştirebilirsiniz.
[İngilizce sürüm](ENGLISH_VERSION_URL)
diff --git a/docs/tr/docs/tutorial/background-tasks.md b/docs/tr/docs/tutorial/background-tasks.md
index 4cb67d822..a6dfbe5ea 100644
--- a/docs/tr/docs/tutorial/background-tasks.md
+++ b/docs/tr/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@ Bu, request’ten sonra yapılması gereken; ancak client’ın response’u alm
Önce `BackgroundTasks`’i import edin ve *path operation function*’ınızda `BackgroundTasks` tip bildirimi olan bir parametre tanımlayın:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI**, sizin için `BackgroundTasks` tipinde bir obje oluşturur ve onu ilgili parametre olarak geçirir.
@@ -31,13 +31,13 @@ Bu örnekte görev fonksiyonu bir dosyaya yazacaktır (email göndermeyi simüle
Ve yazma işlemi `async` ve `await` kullanmadığı için fonksiyonu normal `def` ile tanımlarız:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
## Arka Plan Görevini Ekleyin { #add-the-background-task }
*Path operation function*’ınızın içinde, görev fonksiyonunuzu `.add_task()` metodu ile *background tasks* objesine ekleyin:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` şu argümanları alır:
diff --git a/docs/tr/docs/tutorial/bigger-applications.md b/docs/tr/docs/tutorial/bigger-applications.md
index d8a4b8208..9dbaae601 100644
--- a/docs/tr/docs/tutorial/bigger-applications.md
+++ b/docs/tr/docs/tutorial/bigger-applications.md
@@ -85,7 +85,7 @@ Bu module için *path operation*’ları `APIRouter` kullanarak oluşturabilirsi
`FastAPI` class’ında yaptığınız gibi import edip bir "instance" oluşturursunuz:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
### `APIRouter` ile *Path Operations* { #path-operations-with-apirouter }
@@ -93,7 +93,7 @@ Sonra bunu kullanarak *path operation*’larınızı tanımlarsınız.
`FastAPI` class’ını nasıl kullanıyorsanız aynı şekilde kullanın:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
`APIRouter`’ı "mini bir `FastAPI`" class’ı gibi düşünebilirsiniz.
@@ -117,7 +117,7 @@ Bu yüzden onları ayrı bir `dependencies` module’üne koyuyoruz (`app/depend
Şimdi, özel bir `X-Token` header'ını okumak için basit bir dependency kullanalım:
-{* ../../docs_src/bigger_applications/app_an_py39/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
/// tip | İpucu
@@ -149,7 +149,7 @@ Bu module’deki tüm *path operation*’ların şu ortak özelliklere sahip old
Dolayısıyla bunları her *path operation*’a tek tek eklemek yerine `APIRouter`’a ekleyebiliriz.
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
Her *path operation*’ın path’i aşağıdaki gibi `/` ile başlamak zorunda olduğundan:
@@ -208,7 +208,7 @@ Dependency function’ını ise `app.dependencies` module’ünden, yani `app/de
Bu yüzden dependency’ler için `..` ile relative import kullanıyoruz:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[3] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}
#### Relative Import Nasıl Çalışır { #how-relative-imports-work }
@@ -279,7 +279,7 @@ Artık nasıl çalıştığını bildiğinize göre, uygulamalarınız ne kadar
Ama yine de belirli bir *path operation*’a uygulanacak _ek_ `tags` tanımlayabilir, ayrıca o *path operation*’a özel `responses` ekleyebiliriz:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}
/// tip | İpucu
@@ -305,13 +305,13 @@ Normal şekilde bir `FastAPI` class’ı oluşturursunuz.
Hatta her `APIRouter` için olan dependency’lerle birleştirilecek [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank} bile tanımlayabilirsiniz:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[1,3,7] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
### `APIRouter` Import Edin { #import-the-apirouter }
Şimdi `APIRouter` içeren diğer submodule’leri import ediyoruz:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[4:5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}
`app/routers/users.py` ve `app/routers/items.py` dosyaları aynı Python package’i olan `app`’in parçası olan submodule’ler olduğu için, onları "relative import" ile tek bir nokta `.` kullanarak import edebiliriz.
@@ -374,13 +374,13 @@ from .routers.users import router
Bu yüzden ikisini de aynı dosyada kullanabilmek için submodule’leri doğrudan import ediyoruz:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}
### `users` ve `items` için `APIRouter`’ları Dahil Edin { #include-the-apirouters-for-users-and-items }
Şimdi `users` ve `items` submodule’lerindeki `router`’ları dahil edelim:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[10:11] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}
/// info | Bilgi
@@ -420,13 +420,13 @@ Bu dosyada, kurumunuzun birden fazla proje arasında paylaştığı bazı admin
Bu örnekte çok basit olacak. Ancak kurum içinde başka projelerle paylaşıldığı için, bunu değiştirip `prefix`, `dependencies`, `tags` vs. doğrudan `APIRouter`’a ekleyemediğimizi varsayalım:
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
Yine de bu `APIRouter`’ı dahil ederken özel bir `prefix` ayarlamak istiyoruz ki tüm *path operation*’ları `/admin` ile başlasın; ayrıca bu projede hâlihazırda kullandığımız `dependencies` ile güvene almak, `tags` ve `responses` eklemek istiyoruz.
Orijinal `APIRouter`’ı değiştirmeden, bu parametreleri `app.include_router()`’a vererek hepsini tanımlayabiliriz:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[14:17] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}
Böylece orijinal `APIRouter` değişmeden kalır; yani aynı `app/internal/admin.py` dosyasını kurum içindeki diğer projelerle de paylaşmaya devam edebiliriz.
@@ -447,7 +447,7 @@ Dolayısıyla örneğin diğer projeler aynı `APIRouter`’ı farklı bir authe
Burada bunu yapıyoruz... sadece yapabildiğimizi göstermek için 🤷:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[21:23] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}
ve `app.include_router()` ile eklenen diğer tüm *path operation*’larla birlikte doğru şekilde çalışır.
diff --git a/docs/tr/docs/tutorial/body-multiple-params.md b/docs/tr/docs/tutorial/body-multiple-params.md
index 29970ca40..4cd381b86 100644
--- a/docs/tr/docs/tutorial/body-multiple-params.md
+++ b/docs/tr/docs/tutorial/body-multiple-params.md
@@ -106,12 +106,6 @@ Varsayılan olarak tekil değerler query parametresi olarak yorumlandığı içi
q: str | None = None
```
-Ya da Python 3.9'da:
-
-```Python
-q: Union[str, None] = None
-```
-
Örneğin:
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
diff --git a/docs/tr/docs/tutorial/body-nested-models.md b/docs/tr/docs/tutorial/body-nested-models.md
index b4ffef3f1..b661d175d 100644
--- a/docs/tr/docs/tutorial/body-nested-models.md
+++ b/docs/tr/docs/tutorial/body-nested-models.md
@@ -95,7 +95,7 @@ Yine, sadece bu tanımı yaparak **FastAPI** ile şunları elde edersiniz:
`str`, `int`, `float` vb. normal tekil tiplerin yanında, `str`’den türeyen daha karmaşık tekil tipleri de kullanabilirsiniz.
-Tüm seçenekleri görmek için Pydantic Type Overview sayfasına göz atın. Sonraki bölümde bazı örnekleri göreceksiniz.
+Tüm seçenekleri görmek için Pydantic Türlerine Genel Bakış sayfasına göz atın. Sonraki bölümde bazı örnekleri göreceksiniz.
Örneğin `Image` modelinde bir `url` alanımız olduğuna göre, bunu `str` yerine Pydantic’in `HttpUrl` tipinden bir instance olacak şekilde tanımlayabiliriz:
@@ -163,7 +163,7 @@ images: list[Image]
şu örnekte olduğu gibi:
-{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
## Her yerde editör desteği { #editor-support-everywhere }
@@ -193,7 +193,7 @@ Burada göreceğimiz şey de bu.
Bu durumda, `int` key’lere ve `float` value’lara sahip olduğu sürece herhangi bir `dict` kabul edersiniz:
-{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
/// tip | İpucu
diff --git a/docs/tr/docs/tutorial/body.md b/docs/tr/docs/tutorial/body.md
index 0557ef737..47fee6701 100644
--- a/docs/tr/docs/tutorial/body.md
+++ b/docs/tr/docs/tutorial/body.md
@@ -155,7 +155,7 @@ Fonksiyon parametreleri şu şekilde tanınır:
FastAPI, `q` değerinin zorunlu olmadığını `= None` default değerinden anlayacaktır.
-`str | None` (Python 3.10+) veya `Union[str, None]` (Python 3.9+) içindeki `Union`, FastAPI tarafından bu değerin zorunlu olmadığını belirlemek için kullanılmaz; FastAPI bunun zorunlu olmadığını `= None` default değeri olduğu için bilir.
+`str | None`, FastAPI tarafından bu değerin zorunlu olmadığını belirlemek için kullanılmaz; FastAPI bunun zorunlu olmadığını `= None` default değeri olduğu için bilir.
Ancak type annotation'larını eklemek, editor'ünüzün size daha iyi destek vermesini ve hataları yakalamasını sağlar.
diff --git a/docs/tr/docs/tutorial/cookie-param-models.md b/docs/tr/docs/tutorial/cookie-param-models.md
index a5bf51560..0fa399c6a 100644
--- a/docs/tr/docs/tutorial/cookie-param-models.md
+++ b/docs/tr/docs/tutorial/cookie-param-models.md
@@ -1,18 +1,18 @@
-# Cookie Parameter Models { #cookie-parameter-models }
+# Cookie Parametre Modelleri { #cookie-parameter-models }
-Birbirleriyle ilişkili bir **cookie** grubunuz varsa, bunları tanımlamak için bir **Pydantic model** oluşturabilirsiniz.
+Birbirleriyle ilişkili bir **cookie** grubunuz varsa, bunları tanımlamak için bir **Pydantic model** oluşturabilirsiniz. 🍪
-Bu sayede **model'i yeniden kullanabilir**, **birden fazla yerde** tekrar tekrar kullanabilir ve tüm parametreler için validation ve metadata'yı tek seferde tanımlayabilirsiniz.
+Bu sayede **model'i yeniden kullanabilir**, **birden fazla yerde** tekrar tekrar kullanabilir ve tüm parametreler için validation ve metadata'yı tek seferde tanımlayabilirsiniz. 😎
/// note | Not
-Bu özellik FastAPI `0.115.0` sürümünden beri desteklenmektedir.
+This is supported since FastAPI version `0.115.0`. 🤓
///
/// tip | İpucu
-Aynı teknik `Query`, `Cookie` ve `Header` için de geçerlidir.
+Aynı teknik `Query`, `Cookie` ve `Header` için de geçerlidir. 😎
///
@@ -42,11 +42,11 @@ Ancak verileri **doldurup** "Execute" düğmesine tıklasanız bile, docs UI **J
///
-## Fazladan Cookies'leri Yasaklayın { #forbid-extra-cookies }
+## Fazladan Cookie'leri Yasaklayın { #forbid-extra-cookies }
Bazı özel kullanım senaryolarında (muhtemelen çok yaygın değildir) almak istediğiniz cookie'leri **kısıtlamak** isteyebilirsiniz.
-API'niz artık kendi cookie consent'ını kontrol etme gücüne sahip.
+API'niz artık kendi cookie onayı'nı kontrol etme gücüne sahip. 🤪🍪
Pydantic'in model configuration'ını kullanarak `extra` olan herhangi bir field'ı `forbid` edebilirsiniz:
@@ -54,9 +54,9 @@ Pydantic'in model configuration'ını kullanarak `extra` olan herhangi bir field
Bir client **fazladan cookie** göndermeye çalışırsa, bir **error** response alır.
-Onayınızı almak için bunca çaba harcayan zavallı cookie banner'ları... API'nin bunu reddetmesi için.
+Onayınızı almak için bunca çaba harcayan zavallı cookie banner'ları... API'nin bunu reddetmesi için. 🍪
-Örneğin client, değeri `good-list-please` olan bir `santa_tracker` cookie'si göndermeye çalışırsa, client `santa_tracker` cookie is not allowed diyen bir **error** response alır:
+Örneğin client, değeri `good-list-please` olan bir `santa_tracker` cookie'si göndermeye çalışırsa, client `santa_tracker` cookie'ye izin verilmiyor diyen bir **error** response alır:
```json
{
@@ -73,4 +73,4 @@ Onayınızı almak için bunca çaba harcayan zavallı cookie banner'ları... **cookies** tanımlamak için **Pydantic model**'lerini kullanabilirsiniz. 😎
+**FastAPI**'de **cookie** tanımlamak için **Pydantic model**'lerini kullanabilirsiniz. 😎
diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md
index 18eedab7f..28b57fd7e 100644
--- a/docs/tr/docs/tutorial/cookie-params.md
+++ b/docs/tr/docs/tutorial/cookie-params.md
@@ -1,4 +1,4 @@
-# Çerez (Cookie) Parametreleri { #cookie-parameters }
+# Cookie (Çerez) Parametreleri { #cookie-parameters }
`Query` ve `Path` parametrelerini tanımladığınız şekilde Cookie parametreleri tanımlayabilirsiniz.
@@ -26,20 +26,20 @@ Ancak `fastapi`'dan `Query`, `Path`, `Cookie` ve diğerlerini import ettiğinizd
/// info | Bilgi
-Çerezleri tanımlamak için `Cookie` kullanmanız gerekir, aksi halde parametreler query parametreleri olarak yorumlanır.
+Cookie'leri tanımlamak için `Cookie` kullanmanız gerekir, aksi halde parametreler query parametreleri olarak yorumlanır.
///
/// info | Bilgi
-**Tarayıcılar çerezleri** özel şekillerde ve arka planda işlediği için, **JavaScript**'in onlara dokunmasına kolayca izin **vermezler**.
+**Tarayıcılar cookie'leri** özel şekillerde ve arka planda işlediği için, **JavaScript**'in onlara dokunmasına kolayca izin **vermezler**.
-`/docs` adresindeki **API docs UI**'a giderseniz, *path operation*'larınız için çerezlerin **dokümantasyonunu** görebilirsiniz.
+`/docs` adresindeki **API docs UI**'a giderseniz, *path operation*'larınız için cookie'lerin **dokümantasyonunu** görebilirsiniz.
-Ancak **veriyi doldurup** "Execute" düğmesine tıklasanız bile, docs UI **JavaScript** ile çalıştığı için çerezler gönderilmez ve herhangi bir değer yazmamışsınız gibi bir **hata** mesajı görürsünüz.
+Ancak **veriyi doldurup** "Execute" düğmesine tıklasanız bile, docs UI **JavaScript** ile çalıştığı için cookie'ler gönderilmez ve herhangi bir değer yazmamışsınız gibi bir **hata** mesajı görürsünüz.
///
## Özet { #recap }
-`Query` ve `Path` ile aynı ortak deseni kullanarak, çerezleri `Cookie` ile tanımlayın.
+`Query` ve `Path` ile aynı ortak deseni kullanarak, cookie'leri `Cookie` ile tanımlayın.
diff --git a/docs/tr/docs/tutorial/cors.md b/docs/tr/docs/tutorial/cors.md
index aae560022..c3c853fdd 100644
--- a/docs/tr/docs/tutorial/cors.md
+++ b/docs/tr/docs/tutorial/cors.md
@@ -46,7 +46,7 @@ Ayrıca backend’in şunlara izin verip vermediğini de belirtebilirsiniz:
* Belirli HTTP method’ları (`POST`, `PUT`) veya wildcard `"*"` ile hepsini.
* Belirli HTTP header’ları veya wildcard `"*"` ile hepsini.
-{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *}
`CORSMiddleware` implementasyonu tarafından kullanılan varsayılan parametreler kısıtlayıcıdır; bu nedenle tarayıcıların Cross-Domain bağlamında kullanmasına izin vermek için belirli origin’leri, method’ları veya header’ları açıkça etkinleştirmeniz gerekir.
@@ -78,7 +78,7 @@ Bu durumda middleware gelen request’i intercept eder ve uygun CORS header’la
## Daha Fazla Bilgi { #more-info }
-CORS hakkında daha fazla bilgi için Mozilla CORS dokümantasyonuna bakın.
+CORS hakkında daha fazla bilgi için Mozilla CORS dokümantasyonuna bakın.
/// note | Teknik Detaylar
diff --git a/docs/tr/docs/tutorial/debugging.md b/docs/tr/docs/tutorial/debugging.md
index 54d5c9252..839277b6d 100644
--- a/docs/tr/docs/tutorial/debugging.md
+++ b/docs/tr/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@ Visual Studio Code veya PyCharm gibi editörünüzde debugger'ı bağlayabilirsi
FastAPI uygulamanızda `uvicorn`'ı import edip doğrudan çalıştırın:
-{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *}
### `__name__ == "__main__"` Hakkında { #about-name-main }
diff --git a/docs/tr/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/tr/docs/tutorial/dependencies/classes-as-dependencies.md
index 9ee57cb29..989e93b40 100644
--- a/docs/tr/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/tr/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -101,7 +101,7 @@ Artık bu class'ı kullanarak dependency'nizi tanımlayabilirsiniz.
Yukarıdaki kodda `CommonQueryParams`'ı iki kez yazdığımıza dikkat edin:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ Annotated Olmadan
+//// tab | Python 3.10+ Annotated Olmadan
/// tip | İpucu
@@ -137,7 +137,7 @@ FastAPI tanımlanan parametreleri buradan çıkarır ve aslında çağıracağı
Bu durumda, şuradaki ilk `CommonQueryParams`:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.9+ Annotated Olmadan
+//// tab | Python 3.10+ Annotated Olmadan
/// tip | İpucu
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
Hatta şunu bile yazabilirsiniz:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ Annotated Olmadan
+//// tab | Python 3.10+ Annotated Olmadan
/// tip | İpucu
@@ -197,7 +197,7 @@ Ancak type'ı belirtmeniz önerilir; böylece editor'ünüz `commons` parametres
Ama burada bir miktar kod tekrarımız olduğunu görüyorsunuz; `CommonQueryParams`'ı iki kez yazıyoruz:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ Annotated Olmadan
+//// tab | Python 3.10+ Annotated Olmadan
/// tip | İpucu
@@ -225,7 +225,7 @@ Bu özel durumlarda şunu yapabilirsiniz:
Şunu yazmak yerine:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ Annotated Olmadan
+//// tab | Python 3.10+ Annotated Olmadan
/// tip | İpucu
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
...şunu yazarsınız:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.9+ Annotated Olmadan
+//// tab | Python 3.10+ Annotated Olmadan
/// tip | İpucu
diff --git a/docs/tr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/tr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 4903aec4a..cbb636342 100644
--- a/docs/tr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/tr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -14,7 +14,7 @@ Bu gibi durumlarda, `Depends` ile bir *path operation function* parametresi tan
Bu, `Depends()` öğelerinden oluşan bir `list` olmalıdır:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
Bu dependency'ler normal dependency'lerle aynı şekilde çalıştırılır/çözülür. Ancak (eğer bir değer döndürüyorlarsa) bu değer *path operation function*'ınıza aktarılmaz.
@@ -44,13 +44,13 @@ Normalde kullandığınız aynı dependency *function*'larını burada da kullan
Request gereksinimleri (header'lar gibi) veya başka alt dependency'ler tanımlayabilirler:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
### Exception Fırlatmak { #raise-exceptions }
Bu dependency'ler, normal dependency'lerde olduğu gibi `raise` ile exception fırlatabilir:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
### Return Değerleri { #return-values }
@@ -58,7 +58,7 @@ Ayrıca değer döndürebilirler ya da döndürmeyebilirler; dönen değer kulla
Yani başka bir yerde zaten kullandığınız, değer döndüren normal bir dependency'yi tekrar kullanabilirsiniz; değer kullanılmasa bile dependency çalıştırılacaktır:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
## Bir *Path Operation* Grubu İçin Dependency'ler { #dependencies-for-a-group-of-path-operations }
diff --git a/docs/tr/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/tr/docs/tutorial/dependencies/dependencies-with-yield.md
index bd025f799..445110ae0 100644
--- a/docs/tr/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/tr/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,12 +1,12 @@
# `yield` ile Dependency'ler { #dependencies-with-yield }
-FastAPI, işini bitirdikten sonra ek adımlar çalıştıran dependency'leri destekler.
+FastAPI, işini bitirdikten sonra ek adımlar çalıştıran dependency'leri destekler.
Bunu yapmak için `return` yerine `yield` kullanın ve ek adımları (kodu) `yield` satırından sonra yazın.
/// tip | İpucu
-Her dependency için yalnızca **bir kez** `yield` kullandığınızdan emin olun.
+Her dependency için yalnızca bir kez `yield` kullandığınızdan emin olun.
///
@@ -29,15 +29,15 @@ Hatta FastAPI bu iki decorator'ı içeride (internally) kullanır.
Response oluşturulmadan önce yalnızca `yield` satırına kadar olan (ve `yield` dahil) kod çalıştırılır:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
`yield` edilen değer, *path operation*'lara ve diğer dependency'lere enjekte edilen (injected) değerdir:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
Response'dan sonra `yield` satırını takip eden kod çalıştırılır:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
/// tip | İpucu
@@ -57,7 +57,7 @@ Dolayısıyla `except SomeException` ile dependency içinde o spesifik exception
Aynı şekilde, exception olsun ya da olmasın çıkış (exit) adımlarının çalıştırılmasını garanti etmek için `finally` kullanabilirsiniz.
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
## `yield` ile Alt Dependency'ler { #sub-dependencies-with-yield }
@@ -67,7 +67,7 @@ Her boyutta ve şekilde alt dependency'ler ve alt dependency "ağaçları" (tree
Örneğin, `dependency_c`, `dependency_b`'ye; `dependency_b` de `dependency_a`'ya bağlı olabilir:
-{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *}
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
Ve hepsi `yield` kullanabilir.
@@ -75,7 +75,7 @@ Bu durumda `dependency_c`, exit code'unu çalıştırabilmek için `dependency_b
Aynı şekilde `dependency_b` de exit code'u için `dependency_a`'dan gelen değerin (burada `dep_a`) erişilebilir olmasına ihtiyaç duyar.
-{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *}
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
Benzer şekilde, bazı dependency'ler `yield`, bazıları `return` kullanabilir ve bunların bazıları diğerlerine bağlı olabilir.
@@ -109,7 +109,7 @@ Ama ihtiyaç duyarsanız diye burada. 🤓
///
-{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *}
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
Exception yakalayıp buna göre özel bir response oluşturmak istiyorsanız bir [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} oluşturun.
@@ -117,7 +117,7 @@ Exception yakalayıp buna göre özel bir response oluşturmak istiyorsanız bir
`yield` kullanan bir dependency içinde `except` ile bir exception yakalar ve bunu tekrar fırlatmazsanız (ya da yeni bir exception fırlatmazsanız), FastAPI normal Python'da olduğu gibi bir exception olduğunu fark edemez:
-{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *}
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
Bu durumda client, biz `HTTPException` veya benzeri bir şey fırlatmadığımız için olması gerektiği gibi *HTTP 500 Internal Server Error* response'u görür; ancak server **hiç log üretmez** ve hatanın ne olduğuna dair başka bir işaret de olmaz. 😱
@@ -127,7 +127,7 @@ Bu durumda client, biz `HTTPException` veya benzeri bir şey fırlatmadığımı
Aynı exception'ı `raise` ile tekrar fırlatabilirsiniz:
-{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *}
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
Artık client yine aynı *HTTP 500 Internal Server Error* response'unu alır, ama server log'larda bizim özel `InternalError`'ımızı görür. 😎
@@ -190,7 +190,7 @@ Normalde `yield` kullanan dependency'lerin exit code'u, client'a response gönde
Ama *path operation function*'dan döndükten sonra dependency'yi kullanmayacağınızı biliyorsanız, `Depends(scope="function")` kullanarak FastAPI'ye dependency'yi *path operation function* döndükten sonra kapatmasını, ancak **response gönderilmeden önce** kapatmasını söyleyebilirsiniz.
-{* ../../docs_src/dependencies/tutorial008e_an_py39.py hl[12,16] *}
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
`Depends()` şu değerleri alabilen bir `scope` parametresi alır:
@@ -234,7 +234,6 @@ participant operation as Path Operation
`yield` kullanan dependency'ler, zaman içinde farklı kullanım senaryolarını kapsamak ve bazı sorunları düzeltmek için gelişti.
FastAPI'nin farklı sürümlerinde nelerin değiştiğini görmek isterseniz, advanced guide'da şu bölümü okuyabilirsiniz: [Advanced Dependencies - Dependencies with `yield`, `HTTPException`, `except` and Background Tasks](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks){.internal-link target=_blank}.
-
## Context Managers { #context-managers }
### "Context Managers" Nedir? { #what-are-context-managers }
@@ -269,7 +268,7 @@ Python'da Context Manager'ları, Dependency Injection** sistemine sahiptir.
+**FastAPI**, çok güçlü ama aynı zamanda sezgisel bir **Bağımlılık Enjeksiyonu** sistemine sahiptir.
Kullanımı çok basit olacak şekilde tasarlanmıştır ve herhangi bir geliştiricinin diğer bileşenleri **FastAPI** ile entegre etmesini kolaylaştırır.
diff --git a/docs/tr/docs/tutorial/dependencies/sub-dependencies.md b/docs/tr/docs/tutorial/dependencies/sub-dependencies.md
index 184db839b..ab196d829 100644
--- a/docs/tr/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/tr/docs/tutorial/dependencies/sub-dependencies.md
@@ -58,11 +58,11 @@ query_extractor --> query_or_cookie_extractor --> read_query
Bağımlılıklarınızdan biri aynı *path operation* için birden fazla kez tanımlanırsa (örneğin birden fazla bağımlılığın ortak bir alt bağımlılığı varsa), **FastAPI** o alt bağımlılığı request başına yalnızca bir kez çağıracağını bilir.
-Dönen değeri bir "cache" içinde saklar ve aynı request içinde buna ihtiyaç duyan tüm "dependant"lara aktarır; böylece aynı request için bağımlılığı tekrar tekrar çağırmaz.
+Dönen değeri bir "önbellek" içinde saklar ve aynı request içinde buna ihtiyaç duyan tüm "dependant"lara aktarır; böylece aynı request için bağımlılığı tekrar tekrar çağırmaz.
Daha ileri bir senaryoda, "cached" değeri kullanmak yerine aynı request içinde her adımda (muhtemelen birden fazla kez) bağımlılığın çağrılması gerektiğini biliyorsanız, `Depends` kullanırken `use_cache=False` parametresini ayarlayabilirsiniz:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python hl_lines="1"
async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
@@ -71,7 +71,7 @@ async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_ca
////
-//// tab | Python 3.9+ Annotated olmayan
+//// tab | Python 3.10+ Annotated olmayan
/// tip | İpucu
diff --git a/docs/tr/docs/tutorial/extra-data-types.md b/docs/tr/docs/tutorial/extra-data-types.md
index 464d3a82a..534efefc4 100644
--- a/docs/tr/docs/tutorial/extra-data-types.md
+++ b/docs/tr/docs/tutorial/extra-data-types.md
@@ -23,32 +23,32 @@ Kullanabileceğiniz ek veri tiplerinden bazıları şunlardır:
* `UUID`:
* Birçok veritabanı ve sistemde ID olarak yaygın kullanılan, standart bir "Universally Unique Identifier".
- * request ve response'larda `str` olarak temsil edilir.
+ * request'lerde ve response'larda `str` olarak temsil edilir.
* `datetime.datetime`:
* Python `datetime.datetime`.
- * request ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `2008-09-15T15:53:00+05:00`.
+ * request'lerde ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `2008-09-15T15:53:00+05:00`.
* `datetime.date`:
* Python `datetime.date`.
- * request ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `2008-09-15`.
+ * request'lerde ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `2008-09-15`.
* `datetime.time`:
* Python `datetime.time`.
- * request ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `14:23:55.003`.
+ * request'lerde ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `14:23:55.003`.
* `datetime.timedelta`:
* Python `datetime.timedelta`.
- * request ve response'larda toplam saniye sayısını ifade eden bir `float` olarak temsil edilir.
+ * request'lerde ve response'larda toplam saniye sayısını ifade eden bir `float` olarak temsil edilir.
* Pydantic, bunu ayrıca bir "ISO 8601 time diff encoding" olarak temsil etmeye de izin verir, daha fazla bilgi için dokümanlara bakın.
* `frozenset`:
- * request ve response'larda, `set` ile aynı şekilde ele alınır:
+ * request'lerde ve response'larda, `set` ile aynı şekilde ele alınır:
* request'lerde bir list okunur, tekrarlar kaldırılır ve `set`'e dönüştürülür.
* response'larda `set`, `list`'e dönüştürülür.
* Üretilen schema, `set` değerlerinin benzersiz olduğunu belirtir (JSON Schema'nın `uniqueItems` özelliğini kullanarak).
* `bytes`:
* Standart Python `bytes`.
- * request ve response'larda `str` gibi ele alınır.
+ * request'lerde ve response'larda `str` gibi ele alınır.
* Üretilen schema, bunun `binary` "format"ına sahip bir `str` olduğunu belirtir.
* `Decimal`:
* Standart Python `Decimal`.
- * request ve response'larda `float` ile aynı şekilde işlenir.
+ * request'lerde ve response'larda `float` ile aynı şekilde işlenir.
* Geçerli tüm Pydantic veri tiplerini burada görebilirsiniz: Pydantic data types.
## Örnek { #example }
diff --git a/docs/tr/docs/tutorial/extra-models.md b/docs/tr/docs/tutorial/extra-models.md
index 9aae28e05..f2bcf7a01 100644
--- a/docs/tr/docs/tutorial/extra-models.md
+++ b/docs/tr/docs/tutorial/extra-models.md
@@ -8,7 +8,7 @@ Bu durum özellikle kullanıcı modellerinde sık görülür, çünkü:
* **output modeli** `password` içermemelidir.
* **database modeli** büyük ihtimalle hash'lenmiş bir `password` tutmalıdır.
-/// danger
+/// danger | Tehlike
Kullanıcının düz metin (plaintext) `password`'ünü asla saklamayın. Her zaman sonradan doğrulayabileceğiniz "güvenli bir hash" saklayın.
@@ -132,7 +132,7 @@ UserInDB(
)
```
-/// warning
+/// warning | Uyarı
Ek destek fonksiyonları olan `fake_password_hasher` ve `fake_save_user` sadece verinin olası bir akışını göstermek içindir; elbette gerçek bir güvenlik sağlamazlar.
@@ -164,7 +164,7 @@ OpenAPI'de bu `anyOf` ile tanımlanır.
Bunu yapmak için standart Python type hint'i olan `typing.Union`'ı kullanın:
-/// note
+/// note | Not
Bir `Union` tanımlarken en spesifik type'ı önce, daha az spesifik olanı sonra ekleyin. Aşağıdaki örnekte daha spesifik olan `PlaneItem`, `Union[PlaneItem, CarItem]` içinde `CarItem`'dan önce gelir.
@@ -190,9 +190,9 @@ Ancak bunu `response_model=PlaneItem | CarItem` atamasına koyarsak hata alırı
Aynı şekilde, nesne listesi döndüren response'ları da tanımlayabilirsiniz.
-Bunun için standart Python `typing.List`'i (ya da Python 3.9 ve üzeri için sadece `list`) kullanın:
+Bunun için standart Python `list`'i kullanın:
-{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *}
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
## Rastgele `dict` ile Response { #response-with-arbitrary-dict }
@@ -200,9 +200,9 @@ Bir Pydantic modeli kullanmadan, sadece key ve value type'larını belirterek d
Bu, geçerli field/attribute adlarını (Pydantic modeli için gerekli olurdu) önceden bilmiyorsanız kullanışlıdır.
-Bu durumda `typing.Dict` (ya da Python 3.9 ve üzeri için sadece `dict`) kullanabilirsiniz:
+Bu durumda `dict` kullanabilirsiniz:
-{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *}
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
## Özet { #recap }
diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md
index 332f5c559..4b645778f 100644
--- a/docs/tr/docs/tutorial/first-steps.md
+++ b/docs/tr/docs/tutorial/first-steps.md
@@ -2,7 +2,7 @@
En sade FastAPI dosyası şu şekilde görünür:
-{* ../../docs_src/first_steps/tutorial001_py39.py *}
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
Yukarıdakini `main.py` adlı bir dosyaya kopyalayın.
@@ -183,7 +183,7 @@ Bu kadar! Artık uygulamanıza o URL üzerinden erişebilirsiniz. ✨
### Adım 1: `FastAPI` import edin { #step-1-import-fastapi }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[1] *}
`FastAPI`, API'nız için tüm işlevselliği sağlayan bir Python class'ıdır.
@@ -197,7 +197,7 @@ Bu kadar! Artık uygulamanıza o URL üzerinden erişebilirsiniz. ✨
### Adım 2: bir `FastAPI` "instance"ı oluşturun { #step-2-create-a-fastapi-instance }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[3] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[3] *}
Burada `app` değişkeni `FastAPI` class'ının bir "instance"ı olacaktır.
@@ -266,12 +266,12 @@ Biz de bunlara "**operation**" diyeceğiz.
#### Bir *path operation decorator* tanımlayın { #define-a-path-operation-decorator }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[6] *}
`@app.get("/")`, **FastAPI**'a hemen altındaki fonksiyonun şuraya giden request'leri ele almakla sorumlu olduğunu söyler:
* path `/`
-* get operation kullanarak
+* get operation kullanarak
/// info | `@decorator` Bilgisi
@@ -320,7 +320,7 @@ Bu bizim "**path operation function**"ımız:
* **operation**: `get`.
* **function**: "decorator"ün altındaki fonksiyondur (`@app.get("/")`'in altındaki).
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
Bu bir Python fonksiyonudur.
@@ -332,7 +332,7 @@ Bu durumda, bu bir `async` fonksiyondur.
Bunu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirsiniz:
-{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
/// note | Not
@@ -342,7 +342,7 @@ Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurr
### Adım 5: içeriği döndürün { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
Bir `dict`, `list`, `str`, `int` vb. tekil değerler döndürebilirsiniz.
diff --git a/docs/tr/docs/tutorial/handling-errors.md b/docs/tr/docs/tutorial/handling-errors.md
index a4d693792..a74e1a76a 100644
--- a/docs/tr/docs/tutorial/handling-errors.md
+++ b/docs/tr/docs/tutorial/handling-errors.md
@@ -25,7 +25,7 @@ Client’a hata içeren HTTP response’ları döndürmek için `HTTPException`
### `HTTPException`’ı Import Etme { #import-httpexception }
-{* ../../docs_src/handling_errors/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
### Kodunuzda Bir `HTTPException` Raise Etme { #raise-an-httpexception-in-your-code }
@@ -39,7 +39,7 @@ Bir değer döndürmek yerine exception raise etmenin faydası, Dependencies ve
Bu örnekte, client var olmayan bir ID ile bir item istediğinde, `404` status code’u ile bir exception raise edelim:
-{* ../../docs_src/handling_errors/tutorial001_py39.py hl[11] *}
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
### Ortaya Çıkan Response { #the-resulting-response }
@@ -77,7 +77,7 @@ Muhtemelen bunu doğrudan kendi kodunuzda kullanmanız gerekmeyecek.
Ama ileri seviye bir senaryo için ihtiyaç duyarsanız, özel header’lar ekleyebilirsiniz:
-{* ../../docs_src/handling_errors/tutorial002_py39.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
## Özel Exception Handler’ları Kurmak { #install-custom-exception-handlers }
@@ -89,7 +89,7 @@ Ve bu exception’ı FastAPI ile global olarak handle etmek istiyorsunuz.
`@app.exception_handler()` ile özel bir exception handler ekleyebilirsiniz:
-{* ../../docs_src/handling_errors/tutorial003_py39.py hl[5:7,13:18,24] *}
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
Burada `/unicorns/yolo` için request atarsanız, *path operation* bir `UnicornException` `raise` eder.
@@ -127,7 +127,7 @@ Override etmek için `RequestValidationError`’ı import edin ve exception hand
Exception handler, bir `Request` ve exception’ı alır.
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[2,14:19] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
Artık `/items/foo`’ya giderseniz, şu varsayılan JSON hatası yerine:
@@ -159,7 +159,7 @@ Benzer şekilde `HTTPException` handler’ını da override edebilirsiniz.
Örneğin bu hatalar için JSON yerine plain text response döndürmek isteyebilirsiniz:
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[3:4,9:11,25] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
/// note | Teknik Detaylar
@@ -183,7 +183,7 @@ Ancak bu, eğer sadece string’e çevirip bu bilgiyi doğrudan response olarak
Uygulamanızı geliştirirken body’yi log’lamak, debug etmek, kullanıcıya döndürmek vb. için bunu kullanabilirsiniz.
-{* ../../docs_src/handling_errors/tutorial005_py39.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
Şimdi şu gibi geçersiz bir item göndermeyi deneyin:
@@ -239,6 +239,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
Exception’ı, **FastAPI**’nin aynı varsayılan exception handler’larıyla birlikte kullanmak isterseniz, varsayılan exception handler’ları `fastapi.exception_handlers` içinden import edip yeniden kullanabilirsiniz:
-{* ../../docs_src/handling_errors/tutorial006_py39.py hl[2:5,15,21] *}
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
Bu örnekte sadece oldukça açıklayıcı bir mesajla hatayı yazdırıyorsunuz; ama fikir anlaşılıyor. Exception’ı kullanıp ardından varsayılan exception handler’ları olduğu gibi yeniden kullanabilirsiniz.
diff --git a/docs/tr/docs/tutorial/index.md b/docs/tr/docs/tutorial/index.md
index f672c9e20..6047e83ca 100644
--- a/docs/tr/docs/tutorial/index.md
+++ b/docs/tr/docs/tutorial/index.md
@@ -62,7 +62,7 @@ Editörünüzde kullanmak FastAPI'nin avantajlarını gerçekten gösterir: ne k
İlk adım FastAPI'yi kurmaktır.
-Bir [virtual environment](../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan emin olun, etkinleştirin ve ardından **FastAPI'yi kurun**:
+Bir [sanal ortam](../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan emin olun, etkinleştirin ve ardından **FastAPI'yi kurun**:
kwargs da denir. Default değerleri olmasa bile.
+Python bu `*` ile bir şey yapmaz; ama bundan sonraki tüm parametrelerin keyword argument (anahtar-değer çiftleri) olarak çağrılması gerektiğini bilir; buna kwargs da denir. Default değerleri olmasa bile.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
### `Annotated` ile Daha İyi { #better-with-annotated }
Şunu da unutmayın: `Annotated` kullanırsanız, fonksiyon parametresi default değerlerini kullanmadığınız için bu sorun ortaya çıkmaz ve muhtemelen `*` kullanmanız da gerekmez.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
## Sayı Doğrulamaları: Büyük Eşit { #number-validations-greater-than-or-equal }
@@ -97,7 +97,7 @@ Python bu `*` ile bir şey yapmaz; ama bundan sonraki tüm parametrelerin keywor
Burada `ge=1` ile, `item_id` değerinin `1`'den "`g`reater than or `e`qual" olacak şekilde bir tam sayı olması gerekir.
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
## Sayı Doğrulamaları: Büyük ve Küçük Eşit { #number-validations-greater-than-and-less-than-or-equal }
@@ -106,19 +106,19 @@ Aynısı şunlar için de geçerlidir:
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
## Sayı Doğrulamaları: `float` Değerler, Büyük ve Küçük { #number-validations-floats-greater-than-and-less-than }
Sayı doğrulamaları `float` değerler için de çalışır.
-Burada gt tanımlayabilmek (sadece ge değil) önemli hale gelir. Çünkü örneğin bir değerin `0`'dan büyük olmasını isteyebilirsiniz; `1`'den küçük olsa bile.
+Burada gt tanımlayabilmek (sadece ge değil) önemli hale gelir. Çünkü örneğin bir değerin `0`'dan büyük olmasını isteyebilirsiniz; `1`'den küçük olsa bile.
Bu durumda `0.5` geçerli bir değer olur. Ancak `0.0` veya `0` geçerli olmaz.
-Aynısı lt için de geçerlidir.
+Aynısı lt için de geçerlidir.
-{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
## Özet { #recap }
diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md
index db676f1ee..cbcec05d4 100644
--- a/docs/tr/docs/tutorial/path-params.md
+++ b/docs/tr/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Python string biçimlemede kullanılan sözdizimiyle path "parametreleri"ni veya "değişkenleri"ni tanımlayabilirsiniz:
-{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
Path parametresi `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır.
@@ -16,7 +16,7 @@ Yani, bu örneği çalıştırıp conversion { #data-conversion }
+## Veri dönüştürme { #data-conversion }
Bu örneği çalıştırıp tarayıcınızda http://127.0.0.1:8000/items/3 adresini açarsanız, şöyle bir response görürsünüz:
@@ -38,7 +38,7 @@ Bu örneği çalıştırıp tarayıcınızda "parsing" sağlar.
+Yani, bu tip tanımıyla birlikte **FastAPI** size otomatik request "ayrıştırma" sağlar.
///
@@ -118,13 +118,13 @@ Sonra belirli bir kullanıcı hakkında, kullanıcı ID'si ile veri almak için
*Path operation*'lar sırayla değerlendirildiği için, `/users/me` için olan path'in `/users/{user_id}` olandan önce tanımlandığından emin olmanız gerekir:
-{* ../../docs_src/path_params/tutorial003_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
Aksi halde, `/users/{user_id}` için olan path, `"me"` değerini `user_id` parametresi olarak aldığını "düşünerek" `/users/me` için de eşleşir.
Benzer şekilde, bir path operation'ı yeniden tanımlayamazsınız:
-{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
Path önce eşleştiği için her zaman ilk olan kullanılır.
@@ -140,11 +140,11 @@ Bir *path operation*'ınız *path parameter* alıyorsa ama olası geçerli *path
Sonra, kullanılabilir geçerli değerler olacak sabit değerli class attribute'ları oluşturun:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
/// tip | İpucu
-Merak ediyorsanız: "AlexNet", "ResNet" ve "LeNet", Makine Öğrenmesi modellerinin sadece isimleridir.
+Merak ediyorsanız: "AlexNet", "ResNet" ve "LeNet", Makine Öğrenmesi modellerinin sadece isimleridir.
///
@@ -152,7 +152,7 @@ Merak ediyorsanız: "AlexNet", "ResNet" ve "LeNet", Makine Öğrenmesi parsing"
+* Veri "ayrıştırma"
* Veri doğrulama
* API annotation ve otomatik dokümantasyon
diff --git a/docs/tr/docs/tutorial/query-params-str-validations.md b/docs/tr/docs/tutorial/query-params-str-validations.md
index 18f0249e5..3bdbd7aae 100644
--- a/docs/tr/docs/tutorial/query-params-str-validations.md
+++ b/docs/tr/docs/tutorial/query-params-str-validations.md
@@ -16,7 +16,7 @@ FastAPI, `q`’nun zorunlu olmadığını `= None` varsayılan değerinden anlar
///
-## Ek doğrulama { #additional-validation }
+## Ek Doğrulama { #additional-validation }
`q` opsiyonel olsa bile, verildiği durumda **uzunluğunun 50 karakteri geçmemesini** zorlayacağız.
@@ -47,40 +47,16 @@ Daha eski bir sürüm kullanıyorsanız `Annotated` kullanmaya çalışırken ha
Şu tip anotasyonuna sahiptik:
-//// tab | Python 3.10+
-
```Python
q: str | None = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Union[str, None] = None
-```
-
-////
-
Şimdi bunu `Annotated` ile saracağız; şöyle olacak:
-//// tab | Python 3.10+
-
```Python
q: Annotated[str | None] = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Annotated[Union[str, None]] = None
-```
-
-////
-
Bu iki sürüm de aynı anlama gelir: `q`, `str` veya `None` olabilen bir parametredir ve varsayılan olarak `None`’dır.
Şimdi işin eğlenceli kısmına geçelim. 🎉
@@ -109,7 +85,7 @@ FastAPI artık şunları yapacak:
## Alternatif (eski): Varsayılan değer olarak `Query` { #alternative-old-query-as-the-default-value }
-FastAPI’nin önceki sürümlerinde (0.95.0 öncesi) `Query`’yi `Annotated` içine koymak yerine, parametrenizin varsayılan değeri olarak kullanmanız gerekiyordu. Etrafta bu şekilde yazılmış kod görme ihtimaliniz yüksek; bu yüzden açıklayalım.
+FastAPI’nin önceki sürümlerinde ( 0.95.0 öncesi) `Query`’yi `Annotated` içine koymak yerine, parametrenizin varsayılan değeri olarak kullanmanız gerekiyordu. Etrafta bu şekilde yazılmış kod görme ihtimaliniz yüksek; bu yüzden açıklayalım.
/// tip | İpucu
@@ -131,6 +107,7 @@ q: str | None = Query(default=None)
...parametreyi `None` varsayılan değeriyle opsiyonel yapar; şununla aynı:
+
```Python
q: str | None = None
```
@@ -179,7 +156,7 @@ Fonksiyon parametrelerindeki varsayılan değer stiline göre **`Annotated` kull
Aynı fonksiyonu FastAPI olmadan **başka yerlerde** de **çağırabilirsiniz** ve **beklendiği gibi çalışır**. Eğer **zorunlu** bir parametre varsa (varsayılan değer yoksa) editörünüz hata ile bunu belirtir; ayrıca gerekli parametreyi vermeden çalıştırırsanız **Python** da şikayet eder.
-`Annotated` kullanmayıp bunun yerine **(eski) varsayılan değer stilini** kullanırsanız, o fonksiyonu FastAPI olmadan **başka yerlerde** çağırdığınızda doğru çalışması için argümanları geçmeniz gerektiğini **hatırlamak** zorunda kalırsınız; yoksa değerler beklediğinizden farklı olur (ör. `str` yerine `QueryInfo` veya benzeri). Üstelik editörünüz de şikayet etmez ve Python da fonksiyonu çalıştırırken şikayet etmez; ancak içerideki operasyonlar hata verince ortaya çıkar.
+`Annotated` kullanmayıp bunun yerine **(eski) varsayılan değer stilini** kullanırsanız, o fonksiyonu FastAPI olmadan **başka yerlerde** çağırdığınızda doğru çalışması için argümanları geçmeniz gerektiğini **hatırlamak** zorunda kalırsınız; yoksa değerler beklediğinizden farklı olur (ör. `QueryInfo` veya benzeri). Üstelik editörünüz de şikayet etmez ve Python da fonksiyonu çalıştırırken şikayet etmez; ancak içerideki operasyonlar hata verince ortaya çıkar.
`Annotated` birden fazla metadata anotasyonu alabildiği için, artık aynı fonksiyonu Typer gibi başka araçlarla da kullanabilirsiniz. 🚀
@@ -191,7 +168,7 @@ Aynı fonksiyonu FastAPI olmadan **başka yerlerde** de **çağırabilirsiniz**
## Regular expression ekleyin { #add-regular-expressions }
-Parametrenin eşleşmesi gereken bir `pattern` regular expression tanımlayabilirsiniz:
+Parametrenin eşleşmesi gereken bir `pattern` düzenli ifade tanımlayabilirsiniz:
{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
@@ -211,7 +188,7 @@ Elbette `None` dışında varsayılan değerler de kullanabilirsiniz.
Örneğin `q` query parametresi için `min_length` değerini `3` yapmak ve varsayılan değer olarak `"fixedquery"` vermek istediğinizi düşünelim:
-{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial005_an_py310.py hl[9] *}
/// note | Not
@@ -233,7 +210,7 @@ q: str
q: str | None = None
```
-Ancak biz artık `Query` ile tanımlıyoruz; örneğin şöyle:
+Acak biz artık `Query` ile tanımlıyoruz; örneğin şöyle:
```Python
q: Annotated[str | None, Query(min_length=3)] = None
@@ -241,7 +218,7 @@ q: Annotated[str | None, Query(min_length=3)] = None
Dolayısıyla `Query` kullanırken bir değeri zorunlu yapmak istediğinizde, varsayılan değer tanımlamamanız yeterlidir:
-{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial006_an_py310.py hl[9] *}
### Zorunlu ama `None` olabilir { #required-can-be-none }
@@ -292,7 +269,7 @@ Etkileşimli API dokümanları da buna göre güncellenir ve birden fazla değer
Hiç değer verilmezse varsayılan bir `list` de tanımlayabilirsiniz:
-{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
Şu adrese giderseniz:
@@ -315,7 +292,7 @@ http://localhost:8000/items/
`list[str]` yerine doğrudan `list` de kullanabilirsiniz:
-{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
/// note | Not
@@ -371,7 +348,7 @@ O zaman bir `alias` tanımlayabilirsiniz; bu alias, parametre değerini bulmak i
Diyelim ki artık bu parametreyi istemiyorsunuz.
-Bazı client’lar hâlâ kullandığı için bir süre tutmanız gerekiyor, ama dokümanların bunu açıkça deprecated olarak göstermesini istiyorsunuz.
+Bazı client’lar hâlâ kullandığı için bir süre tutmanız gerekiyor, ama dokümanların bunu açıkça deprecated olarak göstermesini istiyorsunuz.
O zaman `Query`’ye `deprecated=True` parametresini geçin:
@@ -401,7 +378,7 @@ Pydantic’te ISBN kitap numarası için `isbn-` ile veya IMDB film URL ID’si için `imdb-` ile başladığını kontrol eder:
+Örneğin bu custom validator, bir item ID’sinin ISBN kitap numarası için `isbn-` ile veya IMDB film URL ID’si için `imdb-` ile başladığını kontrol eder:
{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
@@ -435,9 +412,9 @@ Fark ettiniz mi? `value.startswith()` ile bir string, tuple alabilir ve tuple i
#### Rastgele Bir Item { #a-random-item }
-`data.items()` ile, her dictionary öğesi için key ve value içeren tuple’lardan oluşan bir iterable object elde ederiz.
+`data.items()` ile, her dictionary öğesi için key ve value içeren tuple’lardan oluşan bir yinelemeli nesne elde ederiz.
-Bu iterable object’i `list(data.items())` ile düzgün bir `list`’e çeviririz.
+Bu yinelemeli nesneyi `list(data.items())` ile düzgün bir `list`’e çeviririz.
Ardından `random.choice()` ile list’ten **rastgele bir değer** alırız; yani `(id, name)` içeren bir tuple elde ederiz. Şuna benzer: `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md
index 89cfa3fb3..4a9f688ca 100644
--- a/docs/tr/docs/tutorial/query-params.md
+++ b/docs/tr/docs/tutorial/query-params.md
@@ -2,7 +2,7 @@
Fonksiyonda path parametrelerinin parçası olmayan diğer parametreleri tanımladığınızda, bunlar otomatik olarak "query" parametreleri olarak yorumlanır.
-{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
Query, bir URL'de `?` işaretinden sonra gelen ve `&` karakterleriyle ayrılan anahtar-değer çiftlerinin kümesidir.
@@ -24,7 +24,7 @@ Ancak, bunları Python tipleriyle (yukarıdaki örnekte `int` olarak) tanımlad
Path parametreleri için geçerli olan aynı süreç query parametreleri için de geçerlidir:
* Editör desteği (tabii ki)
-* Veri "parsing"
+* Veri "ayrıştırma"
* Veri doğrulama
* Otomatik dokümantasyon
@@ -46,7 +46,7 @@ http://127.0.0.1:8000/items/
http://127.0.0.1:8000/items/?skip=0&limit=10
```
-Ancak örneğin şuraya giderseniz:
+Namunak örneğin şuraya giderseniz:
```
http://127.0.0.1:8000/items/?skip=20
@@ -128,7 +128,7 @@ Belirli bir değer eklemek istemiyor ama sadece opsiyonel olmasını istiyorsan
Ancak bir query parametresini zorunlu yapmak istediğinizde, herhangi bir varsayılan değer tanımlamamanız yeterlidir:
-{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
Burada query parametresi `needy`, `str` tipinde zorunlu bir query parametresidir.
diff --git a/docs/tr/docs/tutorial/request-files.md b/docs/tr/docs/tutorial/request-files.md
index 0bbc557e0..8ebef15e2 100644
--- a/docs/tr/docs/tutorial/request-files.md
+++ b/docs/tr/docs/tutorial/request-files.md
@@ -20,13 +20,13 @@ Bunun nedeni, upload edilen dosyaların "form data" olarak gönderilmesidir.
`fastapi` içinden `File` ve `UploadFile` import edin:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
## `File` Parametrelerini Tanımlayın { #define-file-parameters }
`Body` veya `Form` için yaptığınız gibi dosya parametreleri oluşturun:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
/// info | Bilgi
@@ -54,7 +54,7 @@ Ancak bazı durumlarda `UploadFile` kullanmak size fayda sağlayabilir.
Tipi `UploadFile` olan bir dosya parametresi tanımlayın:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
`UploadFile` kullanmanın `bytes`’a göre birkaç avantajı vardır:
@@ -121,7 +121,7 @@ Formlardan gelen veri, dosya içermiyorsa normalde "media type" olarak `applicat
Ancak form dosya içeriyorsa `multipart/form-data` olarak encode edilir. `File` kullanırsanız, **FastAPI** dosyaları body’nin doğru kısmından alması gerektiğini bilir.
-Bu encoding’ler ve form alanları hakkında daha fazla okumak isterseniz MDN web dokümanlarındaki POST sayfasına bakın.
+Bu encoding’ler ve form alanları hakkında daha fazla okumak isterseniz MDN web dokümanlarındaki POST sayfasına bakın.
///
@@ -143,7 +143,7 @@ Standart type annotation’ları kullanıp varsayılan değeri `None` yaparak bi
Ek metadata ayarlamak için `UploadFile` ile birlikte `File()` da kullanabilirsiniz. Örneğin:
-{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
## Birden Fazla Dosya Upload { #multiple-file-uploads }
@@ -153,7 +153,7 @@ Bu dosyalar, "form data" ile gönderilen aynı "form field" ile ilişkilendirili
Bunu kullanmak için `bytes` veya `UploadFile` listesini tanımlayın:
-{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
Tanımladığınız gibi, `bytes` veya `UploadFile`’lardan oluşan bir `list` alırsınız.
@@ -169,7 +169,7 @@ Tanımladığınız gibi, `bytes` veya `UploadFile`’lardan oluşan bir `list`
Daha önce olduğu gibi, `UploadFile` için bile ek parametreler ayarlamak amacıyla `File()` kullanabilirsiniz:
-{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
## Özet { #recap }
diff --git a/docs/tr/docs/tutorial/request-form-models.md b/docs/tr/docs/tutorial/request-form-models.md
index c35f956fc..75693190f 100644
--- a/docs/tr/docs/tutorial/request-form-models.md
+++ b/docs/tr/docs/tutorial/request-form-models.md
@@ -24,7 +24,7 @@ Bu özellik FastAPI `0.113.0` sürümünden itibaren desteklenmektedir. 🤓
Sadece, **form field** olarak almak istediğiniz alanlarla bir **Pydantic model** tanımlayın ve ardından parametreyi `Form` olarak bildirin:
-{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
**FastAPI**, request içindeki **form data**'dan **her bir field** için veriyi **çıkarır** ve size tanımladığınız Pydantic model'ini verir.
@@ -48,7 +48,7 @@ Bu özellik FastAPI `0.114.0` sürümünden itibaren desteklenmektedir. 🤓
Herhangi bir `extra` field'ı `forbid` etmek için Pydantic'in model konfigürasyonunu kullanabilirsiniz:
-{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *}
+{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *}
Bir client fazladan veri göndermeye çalışırsa, bir **error** response alır.
diff --git a/docs/tr/docs/tutorial/request-forms-and-files.md b/docs/tr/docs/tutorial/request-forms-and-files.md
index 86d26b498..69926af5e 100644
--- a/docs/tr/docs/tutorial/request-forms-and-files.md
+++ b/docs/tr/docs/tutorial/request-forms-and-files.md
@@ -16,13 +16,13 @@ $ pip install python-multipart
## `File` ve `Form` Import Edin { #import-file-and-form }
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[3] *}
## `File` ve `Form` Parametrelerini Tanımlayın { #define-file-and-form-parameters }
Dosya ve form parametrelerini, `Body` veya `Query` için yaptığınız şekilde oluşturun:
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[10:12] *}
Dosyalar ve form alanları form data olarak upload edilir ve siz de dosyaları ve form alanlarını alırsınız.
diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md
index 4608a6b79..1a5303b3e 100644
--- a/docs/tr/docs/tutorial/request-forms.md
+++ b/docs/tr/docs/tutorial/request-forms.md
@@ -18,17 +18,17 @@ $ pip install python-multipart
`Form`'u `fastapi`'den import edin:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[3] *}
## `Form` Parametrelerini Tanımlayın { #define-form-parameters }
Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[9] *}
Örneğin OAuth2 spesifikasyonunun kullanılabileceği ("password flow" olarak adlandırılan) yollardan birinde, form alanları olarak bir `username` ve `password` göndermek zorunludur.
-spec, alanların adının tam olarak `username` ve `password` olmasını ve JSON değil form alanları olarak gönderilmesini gerektirir.
+Spesifikasyon, alanların adının tam olarak `username` ve `password` olmasını ve JSON değil form alanları olarak gönderilmesini gerektirir.
`Form` ile `Body` (ve `Query`, `Path`, `Cookie`) ile yaptığınız aynı konfigürasyonları tanımlayabilirsiniz; validasyon, örnekler, alias (örn. `username` yerine `user-name`) vb. dahil.
@@ -56,13 +56,13 @@ Formlardan gelen veri normalde "media type" `application/x-www-form-urlencoded`
Ancak form dosyalar içerdiğinde `multipart/form-data` olarak encode edilir. Dosyaları ele almayı bir sonraki bölümde okuyacaksınız.
-Bu encoding'ler ve form alanları hakkında daha fazla okumak isterseniz, MDN web docs for POST sayfasına gidin.
+Bu encoding'ler ve form alanları hakkında daha fazla okumak isterseniz, MDN web docs for POST sayfasına gidin.
///
/// warning | Uyarı
-Bir *path operation* içinde birden fazla `Form` parametresi tanımlayabilirsiniz, ancak JSON olarak almayı beklediğiniz `Body` alanlarını da ayrıca tanımlayamazsınız; çünkü bu durumda request'in body'si `application/json` yerine `application/x-www-form-urlencoded` ile encode edilmiş olur.
+Bir *path operation* içinde birden fazla `Form` parametresi tanımlayabilirsiniz, ancak JSON olarak almayı beklediğiniz `Body` alanlarını da ayrıca tanımlayamazsınız; çünkü bu durumda request'in body'si `application/x-www-form-urlencoded` ile encode edilmiş olur.
Bu **FastAPI**'ın bir kısıtlaması değildir, HTTP protokolünün bir parçasıdır.
diff --git a/docs/tr/docs/tutorial/response-model.md b/docs/tr/docs/tutorial/response-model.md
index f1d1f7d15..2bf04bd9e 100644
--- a/docs/tr/docs/tutorial/response-model.md
+++ b/docs/tr/docs/tutorial/response-model.md
@@ -97,7 +97,7 @@ Artık bir browser password ile user oluşturduğunda, API response içinde ayn
Bu örnekte sorun olmayabilir; çünkü password’ü gönderen kullanıcı zaten aynı kişi.
-Ancak aynı modeli başka bir *path operation* için kullanırsak, kullanıcının password’lerini her client’a gönderiyor olabiliriz.
+Namun ancak aynı modeli başka bir *path operation* için kullanırsak, kullanıcının password’lerini her client’a gönderiyor olabiliriz.
/// danger
@@ -183,7 +183,7 @@ Bazı durumlarda Pydantic field olarak geçerli olmayan bir şey döndürebilir
En yaygın durum, [ileri seviye dokümanlarda daha sonra anlatıldığı gibi doğrudan bir Response döndürmektir](../advanced/response-directly.md){.internal-link target=_blank}.
-{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
Bu basit durum FastAPI tarafından otomatik olarak ele alınır; çünkü dönüş tipi annotation’ı `Response` class’ıdır (veya onun bir subclass’ı).
@@ -193,7 +193,7 @@ Araçlar da memnun olur; çünkü hem `RedirectResponse` hem `JSONResponse`, `Re
Type annotation içinde `Response`’un bir subclass’ını da kullanabilirsiniz:
-{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
Bu da çalışır; çünkü `RedirectResponse`, `Response`’un subclass’ıdır ve FastAPI bu basit durumu otomatik olarak yönetir.
@@ -201,7 +201,7 @@ Bu da çalışır; çünkü `RedirectResponse`, `Response`’un subclass’ıdı
Ancak geçerli bir Pydantic tipi olmayan başka rastgele bir obje (ör. bir veritabanı objesi) döndürür ve fonksiyonu da öyle annotate ederseniz, FastAPI bu type annotation’dan bir Pydantic response model oluşturmaya çalışır ve başarısız olur.
-Aynı şey, farklı tipler arasında bir union kullandığınızda ve bu tiplerden biri veya birkaçı geçerli bir Pydantic tipi değilse de olur; örneğin şu kullanım patlar 💥:
+Aynı şey, farklı tipler arasında bir birleşim kullandığınızda ve bu tiplerden biri veya birkaçı geçerli bir Pydantic tipi değilse de olur; örneğin şu kullanım patlar 💥:
{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
diff --git a/docs/tr/docs/tutorial/response-status-code.md b/docs/tr/docs/tutorial/response-status-code.md
index 57ae7bde3..d2270a334 100644
--- a/docs/tr/docs/tutorial/response-status-code.md
+++ b/docs/tr/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@ Bir response model tanımlayabildiğiniz gibi, herhangi bir *path operation* iç
* `@app.delete()`
* vb.
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
/// note | Not
@@ -66,7 +66,7 @@ Kısaca:
/// tip | İpucu
-Her bir status code hakkında daha fazla bilgi almak ve hangi kodun ne için kullanıldığını görmek için HTTP status code'lar hakkında MDN dokümantasyonuna göz atın.
+Her bir status code hakkında daha fazla bilgi almak ve hangi kodun ne için kullanıldığını görmek için MDN dokümantasyonu: HTTP status code'lar hakkında göz atın.
///
@@ -74,7 +74,7 @@ Her bir status code hakkında daha fazla bilgi almak ve hangi kodun ne için kul
Önceki örneğe tekrar bakalım:
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201`, "Created" için kullanılan status code'dur.
@@ -82,7 +82,7 @@ Ancak bu kodların her birinin ne anlama geldiğini ezberlemek zorunda değilsin
`fastapi.status` içindeki kolaylık değişkenlerini (convenience variables) kullanabilirsiniz.
-{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
Bunlar sadece kolaylık sağlar; aynı sayıyı taşırlar. Ancak bu şekilde editörün autocomplete özelliğiyle kolayca bulabilirsiniz:
diff --git a/docs/tr/docs/tutorial/schema-extra-example.md b/docs/tr/docs/tutorial/schema-extra-example.md
index a91dda892..7e29b2309 100644
--- a/docs/tr/docs/tutorial/schema-extra-example.md
+++ b/docs/tr/docs/tutorial/schema-extra-example.md
@@ -74,7 +74,7 @@ Elbette birden fazla `examples` da geçebilirsiniz:
Bunu yaptığınızda, örnekler bu body verisi için dahili **JSON Schema**’nın bir parçası olur.
-Buna rağmen, time of writing this, doküman arayüzünü gösteren araç olan Swagger UI, **JSON Schema** içindeki veriler için birden fazla örneği göstermeyi desteklemiyor. Ancak aşağıda bir çözüm yolu var.
+Buna rağmen, bu yazı yazılırken, doküman arayüzünü gösteren araç olan Swagger UI, **JSON Schema** içindeki veriler için birden fazla örneği göstermeyi desteklemiyor. Ancak aşağıda bir çözüm yolu var.
### OpenAPI’ye özel `examples` { #openapi-specific-examples }
diff --git a/docs/tr/docs/tutorial/security/first-steps.md b/docs/tr/docs/tutorial/security/first-steps.md
index 7e0a70a02..0f72d0c83 100644
--- a/docs/tr/docs/tutorial/security/first-steps.md
+++ b/docs/tr/docs/tutorial/security/first-steps.md
@@ -20,7 +20,7 @@ Güvenliği yönetmek için **FastAPI**’nin sunduğu araçları kullanalım.
Örneği `main.py` adlı bir dosyaya kopyalayın:
-{* ../../docs_src/security/tutorial001_an_py39.py *}
+{* ../../docs_src/security/tutorial001_an_py310.py *}
## Çalıştırın { #run-it }
@@ -132,7 +132,7 @@ Bu durumda bile **FastAPI**, onu oluşturabilmeniz için gereken araçları suna
`OAuth2PasswordBearer` sınıfının bir instance’ını oluştururken `tokenUrl` parametresini veririz. Bu parametre, client’ın (kullanıcının browser’ında çalışan frontend’in) token almak için `username` ve `password` göndereceği URL’yi içerir.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
/// tip | İpucu
@@ -170,7 +170,7 @@ Dolayısıyla `Depends` ile kullanılabilir.
Artık `Depends` ile bir dependency olarak `oauth2_scheme`’i geçebilirsiniz.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
Bu dependency, *path operation function* içindeki `token` parametresine atanacak bir `str` sağlar.
diff --git a/docs/tr/docs/tutorial/security/get-current-user.md b/docs/tr/docs/tutorial/security/get-current-user.md
index 9f56c7628..cc7f7a51b 100644
--- a/docs/tr/docs/tutorial/security/get-current-user.md
+++ b/docs/tr/docs/tutorial/security/get-current-user.md
@@ -2,7 +2,7 @@
Önceki bölümde güvenlik sistemi (dependency injection sistemine dayanır) *path operation function*'a `str` olarak bir `token` veriyordu:
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
Ancak bu hâlâ pek kullanışlı değil.
diff --git a/docs/tr/docs/tutorial/security/oauth2-jwt.md b/docs/tr/docs/tutorial/security/oauth2-jwt.md
index 716761157..ad991d322 100644
--- a/docs/tr/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/tr/docs/tutorial/security/oauth2-jwt.md
@@ -116,7 +116,11 @@ Sonra, alınan password'ün kayıttaki hash ile eşleşip eşleşmediğini doğr
Bir tane de kullanıcıyı authenticate edip geri döndüren bir yardımcı fonksiyon ekleyelim.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,51,58:59,62:63,72:79] *}
+
+`authenticate_user`, veritabanında var olmayan bir username ile çağrıldığında, yine de sahte (dummy) bir hash'e karşı `verify_password` çalıştırıyoruz.
+
+Bu, username geçerli olsun ya da olmasın endpoint'in yaklaşık aynı sürede yanıt vermesini sağlar; böylece mevcut username'leri saymaya yarayabilecek zamanlama saldırılarını (timing attacks) engeller.
/// note | Not
@@ -152,7 +156,7 @@ Response için token endpoint'inde kullanılacak bir Pydantic Model tanımlayın
Yeni bir access token üretmek için bir yardımcı fonksiyon oluşturun.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,82:90] *}
## Dependency'leri güncelleme { #update-the-dependencies }
@@ -162,7 +166,7 @@ Gelen token'ı decode edin, doğrulayın ve mevcut kullanıcıyı döndürün.
Token geçersizse, hemen bir HTTP hatası döndürün.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[93:110] *}
## `/token` *path operation*'ını güncelleme { #update-the-token-path-operation }
@@ -170,7 +174,7 @@ Token'ın süre sonu için bir `timedelta` oluşturun.
Gerçek bir JWT access token üretip döndürün.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[121:136] *}
### JWT "subject" `sub` Hakkında Teknik Detaylar { #technical-details-about-the-jwt-subject-sub }
diff --git a/docs/tr/docs/tutorial/sql-databases.md b/docs/tr/docs/tutorial/sql-databases.md
index e1638cb04..0a02b47ae 100644
--- a/docs/tr/docs/tutorial/sql-databases.md
+++ b/docs/tr/docs/tutorial/sql-databases.md
@@ -8,7 +8,7 @@ Burada "ORMs" olarak adlandırılır). FastAPI sizi hiçbir şeye zorlamaz.
+İstediğiniz başka bir SQL veya NoSQL veritabanı kütüphanesini kullanabilirsiniz (bazı durumlarda "ORMs" olarak adlandırılır). FastAPI sizi hiçbir şeye zorlamaz. 😎
///
@@ -49,7 +49,7 @@ $ pip install sqlmodel
Önce, tek bir **SQLModel** modeliyle uygulamanın en basit ilk sürümünü oluşturacağız.
-Aşağıda, **birden fazla model** kullanarak güvenliği ve esnekliği artırıp geliştireceğiz.
+Aşağıda, **birden fazla model** kullanarak güvenliği ve esnekliği artırıp geliştireceğiz. 🤓
### Modelleri Oluşturma { #create-models }
@@ -93,7 +93,7 @@ Sonra `SQLModel.metadata.create_all(engine)` kullanan bir fonksiyon ekleyerek t
Bir **`Session`**, **nesneleri memory’de** tutar ve verideki gerekli değişiklikleri takip eder; ardından veritabanıyla iletişim kurmak için **`engine` kullanır**.
-`yield` ile, her request için yeni bir `Session` sağlayacak bir FastAPI **dependency** oluşturacağız. Bu da her request’te tek session kullanmamızı garanti eder.
+`yield` ile, her request için yeni bir `Session` sağlayacak bir FastAPI **dependency** oluşturacağız. Bu da her request’te tek session kullanmamızı garanti eder. 🤓
Ardından bu dependency’yi kullanacak kodun geri kalanını sadeleştirmek için `Annotated` ile `SessionDep` dependency’sini oluştururuz.
@@ -107,7 +107,7 @@ Uygulama başlarken veritabanı table’larını oluşturacağız.
Burada bir uygulama startup event’inde table’ları oluşturuyoruz.
-Production’da büyük ihtimalle uygulamayı başlatmadan önce çalışan bir migration script’i kullanırsınız.
+Production’da büyük ihtimalle uygulamayı başlatmadan önce çalışan bir migration script’i kullanırsınız. 🤓
/// tip | İpucu
@@ -169,19 +169,19 @@ Sonra `/docs` arayüzüne gidin; **FastAPI**’nin API’yi **dokümante etmek**
Şimdi bu uygulamayı biraz **refactor** edelim ve **güvenliği** ile **esnekliği** artıralım.
-Önceki uygulamaya bakarsanız, UI’da şu ana kadar client’ın oluşturulacak `Hero`’nun `id` değerini belirlemesine izin verdiğini görebilirsiniz.
+Önceki uygulamaya bakarsanız, UI’da şu ana kadar client’ın oluşturulacak `Hero`’nun `id` değerini belirlemesine izin verdiğini görebilirsiniz. 😱
Buna izin vermemeliyiz; DB’de zaten atanmış bir `id`’yi ezebilirler. `id` belirlemek **client** tarafından değil, **backend** veya **veritabanı** tarafından yapılmalıdır.
-Ayrıca hero için bir `secret_name` oluşturuyoruz ama şimdiye kadar her yerde geri döndürüyoruz; bu pek de **secret** sayılmaz...
+Ayrıca hero için bir `secret_name` oluşturuyoruz ama şimdiye kadar her yerde geri döndürüyoruz; bu pek de **secret** sayılmaz... 😅
-Bunları birkaç **ek model** ekleyerek düzelteceğiz. SQLModel’in parlayacağı yer de burası.
+Bunları birkaç **ek model** ekleyerek düzelteceğiz. SQLModel’in parlayacağı yer de burası. ✨
### Birden Fazla Model Oluşturma { #create-multiple-models }
**SQLModel**’de, `table=True` olan herhangi bir model sınıfı bir **table model**’dir.
-`table=True` olmayan her model sınıfı ise bir **data model**’dir; bunlar aslında sadece Pydantic modelleridir (bazı küçük ek özelliklerle).
+`table=True` olmayan her model sınıfı ise bir **data model**’dir; bunlar aslında sadece Pydantic modelleridir (bazı küçük ek özelliklerle). 🤓
SQLModel ile **inheritance** kullanarak her durumda tüm alanları tekrar tekrar yazmaktan **kaçınabiliriz**.
@@ -216,7 +216,7 @@ Sonraki adımda `HeroPublic` modelini oluştururuz; bu model API client’ların
`HeroBase` ile aynı alanlara sahiptir; dolayısıyla `secret_name` içermez.
-Sonunda kahramanlarımızın kimliği korunmuş oldu!
+Sonunda kahramanlarımızın kimliği korunmuş oldu! 🥷
Ayrıca `id: int` alanını yeniden tanımlar. Bunu yaparak API client’larıyla bir **contract** (sözleşme) oluşturmuş oluruz; böylece `id` alanının her zaman var olacağını ve `int` olacağını (asla `None` olmayacağını) bilirler.
@@ -224,7 +224,7 @@ Ayrıca `id: int` alanını yeniden tanımlar. Bunu yaparak API client’larıyl
Return model’in bir değerin her zaman mevcut olduğunu ve her zaman `int` olduğunu (`None` değil) garanti etmesi API client’ları için çok faydalıdır; bu kesinlik sayesinde daha basit kod yazabilirler.
-Ayrıca **otomatik üretilen client**’ların arayüzleri de daha basit olur; böylece API’nizle çalışan geliştiriciler için süreç çok daha rahat olur.
+Ayrıca **otomatik üretilen client**’ların arayüzleri de daha basit olur; böylece API’nizle çalışan geliştiriciler için süreç çok daha rahat olur. 😎
///
@@ -262,13 +262,13 @@ Ayrıca password değerlerini saklamadan önce **hash** etmelisiniz; **asla plai
#### `HeroUpdate` - hero güncellemek için *data model* { #heroupdate-the-data-model-to-update-a-hero }
-Uygulamanın önceki sürümünde bir hero’yu **güncellemenin** bir yolu yoktu; ancak artık **birden fazla model** ile bunu yapabiliriz.
+Uygulamanın önceki sürümünde bir hero’yu **güncellemenin** bir yolu yoktu; ancak artık **birden fazla model** ile bunu yapabiliriz. 🎉
`HeroUpdate` *data model* biraz özeldir: yeni bir hero oluşturmak için gereken alanların **tamamına** sahiptir, ancak tüm alanlar **opsiyoneldir** (hepsinin bir default değeri vardır). Bu sayede hero güncellerken sadece güncellemek istediğiniz alanları gönderebilirsiniz.
Tüm **alanlar aslında değiştiği** için (tip artık `None` içeriyor ve default değerleri `None` oluyor), onları **yeniden tanımlamamız** gerekir.
-Aslında `HeroBase`’ten miras almamız gerekmiyor; çünkü tüm alanları yeniden tanımlıyoruz. Tutarlılık için miras almayı bırakıyorum ama bu gerekli değil. Daha çok kişisel tercih meselesi.
+Aslında `HeroBase`’ten miras almamız gerekmiyor; çünkü tüm alanları yeniden tanımlıyoruz. Tutarlılık için miras almayı bırakıyorum ama bu gerekli değil. Daha çok kişisel tercih meselesi. 🤷
`HeroUpdate` alanları:
@@ -316,7 +316,7 @@ Tek bir hero’yu **okuyabiliriz**:
Bir hero’yu **güncelleyebiliriz**. Bunun için HTTP `PATCH` operasyonu kullanırız.
-Kodda, client’ın gönderdiği tüm verilerle bir `dict` alırız; **yalnızca client’ın gönderdiği veriler**, yani sadece default değer oldukları için orada bulunan değerler hariç. Bunu yapmak için `exclude_unset=True` kullanırız. Asıl numara bu.
+Kodda, client’ın gönderdiği tüm verilerle bir `dict` alırız; **yalnızca client’ın gönderdiği veriler**, yani sadece default değer oldukları için orada bulunan değerler hariç. Bunu yapmak için `exclude_unset=True` kullanırız. Asıl numara bu. 🪄
Sonra `hero_db.sqlmodel_update(hero_data)` ile `hero_db`’yi `hero_data` içindeki verilerle güncelleriz.
@@ -326,7 +326,7 @@ Sonra `hero_db.sqlmodel_update(hero_data)` ile `hero_db`’yi `hero_data` içind
Bir hero’yu **silmek** büyük ölçüde aynı kalıyor.
-Bu örnekte her şeyi refactor etme isteğimizi bastıracağız.
+Bu örnekte her şeyi refactor etme isteğimizi bastıracağız. 😅
{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *}
@@ -354,4 +354,4 @@ $ fastapi dev main.py
Bir SQL veritabanıyla etkileşim kurmak için **SQLModel** kullanabilir ve *data model* ile *table model* yaklaşımıyla kodu sadeleştirebilirsiniz.
-**SQLModel** dokümantasyonunda çok daha fazlasını öğrenebilirsiniz; **FastAPI** ile SQLModel kullanımı için daha uzun bir mini tutorial da bulunuyor.
+**SQLModel** dokümantasyonunda çok daha fazlasını öğrenebilirsiniz; **FastAPI** ile SQLModel kullanımı için daha uzun bir mini tutorial da bulunuyor. 🚀
diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md
index d30b4389d..e49b14bd8 100644
--- a/docs/tr/docs/tutorial/static-files.md
+++ b/docs/tr/docs/tutorial/static-files.md
@@ -7,7 +7,7 @@
* `StaticFiles`'ı import edin.
* Belirli bir path'te bir `StaticFiles()` örneğini "mount" edin.
-{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py310.py hl[2,6] *}
/// note | Teknik Detaylar
@@ -23,7 +23,7 @@
Bu, bir `APIRouter` kullanmaktan farklıdır; çünkü mount edilen uygulama tamamen bağımsızdır. Ana uygulamanızın OpenAPI ve docs'ları, mount edilen uygulamadan hiçbir şey içermez, vb.
-Bununla ilgili daha fazla bilgiyi [Advanced User Guide](../advanced/index.md){.internal-link target=_blank} içinde okuyabilirsiniz.
+Bununla ilgili daha fazla bilgiyi [Gelişmiş Kullanıcı Kılavuzu](../advanced/index.md){.internal-link target=_blank} içinde okuyabilirsiniz.
## Detaylar { #details }
diff --git a/docs/tr/docs/tutorial/testing.md b/docs/tr/docs/tutorial/testing.md
index 887156606..18e0dd96c 100644
--- a/docs/tr/docs/tutorial/testing.md
+++ b/docs/tr/docs/tutorial/testing.md
@@ -12,7 +12,7 @@ Bununla birlikte **FastAPI** ile `httpx`'i kurun.
-Bir [virtual environment](../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan, onu aktifleştirdiğinizden ve sonra kurulumu yaptığınızdan emin olun; örneğin:
+Bir [Sanal Ortam](../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan, onu aktifleştirdiğinizden ve sonra kurulumu yaptığınızdan emin olun; örneğin:
```console
$ pip install httpx
@@ -30,7 +30,7 @@ Adı `test_` ile başlayan fonksiyonlar oluşturun (bu, `pytest`'in standart kon
Kontrol etmeniz gereken şeyler için standart Python ifadeleriyle basit `assert` satırları yazın (bu da `pytest` standardıdır).
-{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py310.py hl[2,12,15:18] *}
/// tip | İpucu
@@ -52,7 +52,7 @@ Bu sayede `pytest`'i ek bir karmaşıklık olmadan doğrudan kullanabilirsiniz.
/// tip | İpucu
-FastAPI uygulamanıza request göndermenin dışında testlerinizde `async` fonksiyonlar çağırmak istiyorsanız (örn. asenkron veritabanı fonksiyonları), ileri seviye bölümdeki [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} dokümanına göz atın.
+FastAPI uygulamanıza request göndermenin dışında testlerinizde `async` fonksiyonlar çağırmak istiyorsanız (örn. asenkron veritabanı fonksiyonları), ileri seviye bölümdeki [Asenkron Testler](../advanced/async-tests.md){.internal-link target=_blank} dokümanına göz atın.
///
@@ -64,7 +64,7 @@ Ayrıca **FastAPI** uygulamanız birden fazla dosya/modül vb. ile de oluşturul
### **FastAPI** Uygulama Dosyası { #fastapi-app-file }
-[Bigger Applications](bigger-applications.md){.internal-link target=_blank}'te anlatılan şekilde bir dosya yapınız olduğunu varsayalım:
+[Daha Büyük Uygulamalar](bigger-applications.md){.internal-link target=_blank}'te anlatılan şekilde bir dosya yapınız olduğunu varsayalım:
```
.
@@ -75,7 +75,7 @@ Ayrıca **FastAPI** uygulamanız birden fazla dosya/modül vb. ile de oluşturul
`main.py` dosyasında **FastAPI** uygulamanız bulunuyor olsun:
-{* ../../docs_src/app_testing/app_a_py39/main.py *}
+{* ../../docs_src/app_testing/app_a_py310/main.py *}
### Test Dosyası { #testing-file }
@@ -91,7 +91,7 @@ Sonra testlerinizin olduğu bir `test_main.py` dosyanız olabilir. Bu dosya ayn
Bu dosya aynı package içinde olduğu için, `main` modülünden (`main.py`) `app` nesnesini import etmek üzere relative import kullanabilirsiniz:
-{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py310/test_main.py hl[3] *}
...ve test kodunu da öncekiyle aynı şekilde yazabilirsiniz.
@@ -145,7 +145,7 @@ Backend'e veri geçme hakkında daha fazla bilgi için (`httpx` veya `TestClient
`TestClient`'ın Pydantic model'lerini değil, JSON'a dönüştürülebilen verileri aldığını unutmayın.
-Testinizde bir Pydantic model'iniz varsa ve test sırasında verisini uygulamaya göndermek istiyorsanız, [JSON Compatible Encoder](encoder.md){.internal-link target=_blank} içinde açıklanan `jsonable_encoder`'ı kullanabilirsiniz.
+Testinizde bir Pydantic model'iniz varsa ve test sırasında verisini uygulamaya göndermek istiyorsanız, [JSON Uyumlu Encoder](encoder.md){.internal-link target=_blank} içinde açıklanan `jsonable_encoder`'ı kullanabilirsiniz.
///
@@ -153,7 +153,7 @@ Testinizde bir Pydantic model'iniz varsa ve test sırasında verisini uygulamaya
Bundan sonra yapmanız gereken tek şey `pytest`'i kurmaktır.
-Bir [virtual environment](../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan, onu aktifleştirdiğinizden ve sonra kurulumu yaptığınızdan emin olun; örneğin:
+Bir [Sanal Ortam](../virtual-environments.md){.internal-link target=_blank} oluşturduğunuzdan, onu aktifleştirdiğinizden ve sonra kurulumu yaptığınızdan emin olun; örneğin:
-Якщо ви створюєте застосунок CLI для використання в терміналі замість веб-API, зверніть увагу на **Typer**.
+Якщо ви створюєте застосунок CLI для використання в терміналі замість веб-API, зверніть увагу на **Typer**.
**Typer** - молодший брат FastAPI. І його задумано як **FastAPI для CLI**. ⌨️ 🚀
@@ -368,7 +368,7 @@ item: Item
* Валідацію даних:
* Автоматичні та зрозумілі помилки, коли дані некоректні.
* Валідацію навіть для глибоко вкладених JSON-обʼєктів.
-* Перетворення вхідних даних: з мережі до даних і типів Python. Читання з:
+* Перетворення вхідних даних: з мережі до даних і типів Python. Читання з:
* JSON.
* Параметрів шляху.
* Параметрів запиту.
@@ -376,7 +376,7 @@ item: Item
* Headers.
* Forms.
* Files.
-* Перетворення вихідних даних: перетворення з даних і типів Python у мережеві дані (як JSON):
+* Перетворення вихідних даних: перетворення з даних і типів Python у мережеві дані (як JSON):
* Перетворення типів Python (`str`, `int`, `float`, `bool`, `list`, тощо).
* Обʼєктів `datetime`.
* Обʼєктів `UUID`.
@@ -439,7 +439,7 @@ item: Item
* Оголошення **параметрів** з інших різних місць, як-от: **headers**, **cookies**, **form fields** та **files**.
* Як встановлювати **обмеження валідації** як `maximum_length` або `regex`.
-* Дуже потужну і просту у використанні систему **Dependency Injection**.
+* Дуже потужну і просту у використанні систему **Впровадження залежностей**.
* Безпеку та автентифікацію, включно з підтримкою **OAuth2** з **JWT tokens** та **HTTP Basic** auth.
* Досконаліші (але однаково прості) техніки для оголошення **глибоко вкладених моделей JSON** (завдяки Pydantic).
* Інтеграцію **GraphQL** з Strawberry та іншими бібліотеками.
@@ -524,7 +524,7 @@ FastAPI залежить від Pydantic і Starlette.
*
httpx - потрібно, якщо ви хочете використовувати `TestClient`.
* jinja2 - потрібно, якщо ви хочете використовувати конфігурацію шаблонів за замовчуванням.
-* python-multipart - потрібно, якщо ви хочете підтримувати «parsing» форм за допомогою `request.form()`.
+* python-multipart - потрібно, якщо ви хочете підтримувати форми з «парсингом» через `request.form()`.
Використовується FastAPI:
diff --git a/docs/uk/docs/learn/index.md b/docs/uk/docs/learn/index.md
index 6e28d414a..ad468fea1 100644
--- a/docs/uk/docs/learn/index.md
+++ b/docs/uk/docs/learn/index.md
@@ -1,5 +1,5 @@
# Навчання { #learn }
-У цьому розділі надані вступні розділи та навчальні матеріали для вивчення **FastAPI**.
+У цьому розділі надані вступні розділи та навчальні посібники для вивчення **FastAPI**.
Це можна розглядати як **книгу**, **курс**, або **офіційний** та рекомендований спосіб освоїти FastAPI. 😎
diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md
index a82d13a28..deeeb2f9c 100644
--- a/docs/uk/docs/python-types.md
+++ b/docs/uk/docs/python-types.md
@@ -2,11 +2,11 @@
Python підтримує додаткові «підказки типів» (також звані «анотаціями типів»).
-Ці **«підказки типів»** або анотації — це спеціальний синтаксис, що дозволяє оголошувати тип змінної.
+Ці **«підказки типів»** або анотації — це спеціальний синтаксис, що дозволяє оголошувати тип змінної.
За допомогою оголошення типів для ваших змінних редактори та інструменти можуть надати вам кращу підтримку.
-Це лише **швидкий туторіал / нагадування** про підказки типів у Python. Він покриває лише мінімум, необхідний щоб використовувати їх з **FastAPI**... що насправді дуже мало.
+Це лише **швидкий навчальний посібник / нагадування** про підказки типів у Python. Він покриває лише мінімум, необхідний щоб використовувати їх з **FastAPI**... що насправді дуже мало.
**FastAPI** повністю базується на цих підказках типів, вони дають йому багато переваг і користі.
@@ -22,7 +22,7 @@ Python підтримує додаткові «підказки типів» (т
Давайте почнемо з простого прикладу:
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
Виклик цієї програми виводить:
@@ -34,9 +34,9 @@ John Doe
* Бере `first_name` та `last_name`.
* Перетворює першу літеру кожного з них у верхній регістр за допомогою `title()`.
-* Конкатенує їх разом із пробілом по середині.
+* Конкатенує їх разом із пробілом по середині.
-{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
### Редагуйте це { #edit-it }
@@ -78,7 +78,7 @@ John Doe
Це «підказки типів»:
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
Це не те саме, що оголошення значень за замовчуванням, як це було б з:
@@ -106,15 +106,15 @@ John Doe
Перевірте цю функцію, вона вже має підказки типів:
-{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок:
-Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у рядок за допомогою `str(age)`:
+Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку за допомогою `str(age)`:
-{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
## Оголошення типів { #declaring-types }
@@ -133,29 +133,32 @@ John Doe
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### Generic-типи з параметрами типів { #generic-types-with-type-parameters }
+### Модуль `typing` { #typing-module }
-Існують деякі структури даних, які можуть містити інші значення, наприклад `dict`, `list`, `set` та `tuple`. І внутрішні значення також можуть мати свій тип.
+Для деяких додаткових випадків використання може знадобитися імпортувати елементи зі стандартної бібліотеки, модуля `typing`. Наприклад, коли ви хочете оголосити, що щось має «будь-який тип», ви можете використати `Any` з `typing`:
-Ці типи, які мають внутрішні типи, називаються «**generic**» типами. І оголосити їх можна навіть із внутрішніми типами.
+```python
+from typing import Any
-Щоб оголосити ці типи та внутрішні типи, ви можете використовувати стандартний модуль Python `typing`. Він існує спеціально для підтримки цих підказок типів.
-#### Новіші версії Python { #newer-versions-of-python }
+def some_function(data: Any):
+ print(data)
+```
-Синтаксис із використанням `typing` **сумісний** з усіма версіями, від Python 3.6 до останніх, включаючи Python 3.9, Python 3.10 тощо.
+### Generic типи { #generic-types }
-У міру розвитку Python **новіші версії** мають покращену підтримку цих анотацій типів і в багатьох випадках вам навіть не потрібно буде імпортувати та використовувати модуль `typing` для оголошення анотацій типів.
+Деякі типи можуть приймати «параметри типів» у квадратних дужках, щоб визначити їх внутрішні типи. Наприклад, «list строк» буде оголошений як `list[str]`.
-Якщо ви можете вибрати новішу версію Python для свого проекту, ви зможете скористатися цією додатковою простотою.
+Ці типи, які можуть приймати параметри типів, називаються **generic типами** або **generics**.
-У всій документації є приклади, сумісні з кожною версією Python (коли є різниця).
+Ви можете використовувати ті самі вбудовані типи як generics (з квадратними дужками та типами всередині):
-Наприклад, «**Python 3.6+**» означає, що це сумісно з Python 3.6 або вище (включно з 3.7, 3.8, 3.9, 3.10 тощо). А «**Python 3.9+**» означає, що це сумісно з Python 3.9 або вище (включаючи 3.10 тощо).
-
-Якщо ви можете використовувати **останні версії Python**, використовуйте приклади для останньої версії — вони матимуть **найкращий і найпростіший синтаксис**, наприклад, «**Python 3.10+**».
+* `list`
+* `tuple`
+* `set`
+* `dict`
#### List { #list }
@@ -167,7 +170,7 @@ John Doe
Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
-{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
/// info | Інформація
@@ -193,7 +196,7 @@ John Doe
Ви повинні зробити те ж саме, щоб оголосити `tuple` і `set`:
-{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
Це означає:
@@ -208,56 +211,32 @@ John Doe
Другий параметр типу для значень у `dict`:
-{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Це означає:
* Змінна `prices` — це `dict`:
- * Ключі цього `dict` мають тип `str` (скажімо, назва кожного елементу).
- * Значення цього `dict` мають тип `float` (скажімо, ціна кожного елементу).
+ * Ключі цього `dict` мають тип `str` (скажімо, назва кожного предмета).
+ * Значення цього `dict` мають тип `float` (скажімо, ціна кожного предмета).
#### Union { #union }
Ви можете оголосити, що змінна може бути будь-яким із **кількох типів**, наприклад `int` або `str`.
-У Python 3.6 і вище (включаючи Python 3.10) ви можете використовувати тип `Union` з `typing` і вставляти в квадратні дужки можливі типи, які можна прийняти.
+Щоб визначити це, використовуйте вертикальну риску (`|`), щоб розділити обидва типи.
-У Python 3.10 також є **новий синтаксис**, у якому ви можете розділити можливі типи за допомогою вертикальної смуги (`|`).
-
-//// tab | Python 3.10+
+Це називається «union», тому що змінна може бути чимось із об’єднання цих двох множин типів.
```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-////
-
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b_py39.py!}
-```
-
-////
-
-В обох випадках це означає, що `item` може бути `int` або `str`.
+Це означає, що `item` може бути `int` або `str`.
#### Можливо `None` { #possibly-none }
Ви можете оголосити, що значення може мати тип, наприклад `str`, але також може бути `None`.
-У Python 3.6 і вище (включаючи Python 3.10) ви можете оголосити його, імпортувавши та використовуючи `Optional` з модуля `typing`.
-
-```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-Використання `Optional[str]` замість просто `str` дозволить редактору допомогти вам виявити помилки, коли ви могли б вважати, що значенням завжди є `str`, хоча насправді воно також може бути `None`.
-
-`Optional[Something]` насправді є скороченням для `Union[Something, None]`, вони еквівалентні.
-
-Це також означає, що в Python 3.10 ви можете використовувати `Something | None`:
-
//// tab | Python 3.10+
```Python hl_lines="1"
@@ -266,96 +245,7 @@ John Doe
////
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-////
-
-//// tab | Python 3.9+ alternative
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b_py39.py!}
-```
-
-////
-
-#### Використання `Union` або `Optional` { #using-union-or-optional }
-
-Якщо ви використовуєте версію Python нижче 3.10, ось порада з моєї дуже **суб’єктивної** точки зору:
-
-* 🚨 Уникайте використання `Optional[SomeType]`
-* Натомість ✨ **використовуйте `Union[SomeType, None]`** ✨.
-
-Обидва варіанти еквівалентні й «під капотом» це одне й те саме, але я рекомендую `Union` замість `Optional`, тому що слово «**optional**» може створювати враження, ніби значення є необов’язковим, хоча насправді це означає «воно може бути `None`», навіть якщо воно не є необов’язковим і все одно є обов’язковим.
-
-Я вважаю, що `Union[SomeType, None]` більш явно показує, що саме мається на увазі.
-
-Це лише про слова й назви. Але ці слова можуть впливати на те, як ви та ваша команда думаєте про код.
-
-Як приклад, розгляньмо цю функцію:
-
-{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
-
-Параметр `name` визначено як `Optional[str]`, але він **не є необов’язковим**, ви не можете викликати функцію без параметра:
-
-```Python
-say_hi() # Ой, ні, це викликає помилку! 😱
-```
-
-Параметр `name` **все ще є обов’язковим** (не *optional*), тому що він не має значення за замовчуванням. Водночас `name` приймає `None` як значення:
-
-```Python
-say_hi(name=None) # Це працює, None є валідним 🎉
-```
-
-Добра новина: щойно ви перейдете на Python 3.10, вам не доведеться про це хвилюватися, адже ви зможете просто використовувати `|` для визначення об’єднань типів:
-
-{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
-
-І тоді вам не доведеться хвилюватися про назви на кшталт `Optional` і `Union`. 😎
-
-#### Generic типи { #generic-types }
-
-Ці типи, які приймають параметри типу у квадратних дужках, називаються **Generic types** or **Generics**, наприклад:
-
-//// tab | Python 3.10+
-
-Ви можете використовувати ті самі вбудовані типи як generic (з квадратними дужками та типами всередині):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-І так само, як і в попередніх версіях Python, з модуля `typing`:
-
-* `Union`
-* `Optional`
-* ...та інші.
-
-У Python 3.10 як альтернативу використанню generic `Union` та `Optional` ви можете використовувати вертикальну смугу (`|`) для оголошення об’єднань типів — це значно краще й простіше.
-
-////
-
-//// tab | Python 3.9+
-
-Ви можете використовувати ті самі вбудовані типи як generic (з квадратними дужками та типами всередині):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-І generic з модуля `typing`:
-
-* `Union`
-* `Optional`
-* ...та інші.
-
-////
+Використання `str | None` замість просто `str` дозволить редактору допомогти вам виявити помилки, коли ви могли б вважати, що значенням завжди є `str`, хоча насправді воно також може бути `None`.
### Класи як типи { #classes-as-types }
@@ -363,11 +253,11 @@ say_hi(name=None) # Це працює, None є валідним 🎉
Скажімо, у вас є клас `Person` з імʼям:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
Потім ви можете оголосити змінну типу `Person`:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
І знову ж таки, ви отримуєте всю підтримку редактора:
@@ -401,21 +291,15 @@ say_hi(name=None) # Це працює, None є валідним 🎉
**FastAPI** повністю базується на Pydantic.
-Ви побачите набагато більше цього всього на практиці в [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
-
-/// tip | Порада
-
-Pydantic має спеціальну поведінку, коли ви використовуєте `Optional` або `Union[Something, None]` без значення за замовчуванням; детальніше про це можна прочитати в документації Pydantic про Required Optional fields.
-
-///
+Ви побачите набагато більше цього всього на практиці в [Навчальний посібник - Посібник користувача](tutorial/index.md){.internal-link target=_blank}.
## Підказки типів з анотаціями метаданих { #type-hints-with-metadata-annotations }
-У Python також є можливість додавати **додаткові метадані** до цих підказок типів за допомогою `Annotated`.
+У Python також є можливість додавати **додаткові метадані** до цих підказок типів за допомогою `Annotated`.
-Починаючи з Python 3.9, `Annotated` є частиною стандартної бібліотеки, тож ви можете імпортувати його з `typing`.
+Ви можете імпортувати `Annotated` з `typing`.
-{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
Сам Python нічого не робить із цим `Annotated`. А для редакторів та інших інструментів тип усе ще є `str`.
@@ -435,7 +319,7 @@ Pydantic має спеціальну поведінку, коли ви вико
///
-## Анотації типів у **FastAPI** { #type-hints-in-fastapi }
+## Підказки типів у **FastAPI** { #type-hints-in-fastapi }
**FastAPI** використовує ці підказки типів для виконання кількох речей.
@@ -453,12 +337,12 @@ Pydantic має спеціальну поведінку, коли ви вико
* **Документування** API за допомогою OpenAPI:
* який потім використовується для автоматичної інтерактивної документації користувальницьких інтерфейсів.
-Все це може здатися абстрактним. Не хвилюйтеся. Ви побачите все це в дії в [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
+Все це може здатися абстрактним. Не хвилюйтеся. Ви побачите все це в дії в [Навчальний посібник - Посібник користувача](tutorial/index.md){.internal-link target=_blank}.
Важливо те, що за допомогою стандартних типів Python в одному місці (замість того, щоб додавати більше класів, декораторів тощо), **FastAPI** зробить багато роботи за вас.
/// info | Інформація
-Якщо ви вже пройшли весь туторіал і повернулися, щоб дізнатися більше про типи, ось хороший ресурс: «шпаргалка» від `mypy`.
+Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс: «шпаргалка» від `mypy`.
///
diff --git a/docs/uk/docs/tutorial/background-tasks.md b/docs/uk/docs/tutorial/background-tasks.md
index 6d7804195..71266a8b1 100644
--- a/docs/uk/docs/tutorial/background-tasks.md
+++ b/docs/uk/docs/tutorial/background-tasks.md
@@ -1,6 +1,6 @@
# Фонові задачі { #background-tasks }
-Ви можете створювати фонові задачі, які будуть виконуватися *після* повернення відповіді.
+Ви можете створювати фонові задачі, які будуть виконуватися після повернення відповіді.
Це корисно для операцій, які потрібно виконати після обробки запиту, але клієнту не обов’язково чекати завершення цієї операції перед отриманням відповіді.
@@ -13,9 +13,9 @@
## Використання `BackgroundTasks` { #using-backgroundtasks }
-Спочатку імпортуйте `BackgroundTasks` і оголосіть параметр у вашій *функції операції шляху* з анотацією типу `BackgroundTasks`:
+Спочатку імпортуйте `BackgroundTasks` і оголосіть параметр у вашій функції операції шляху з анотацією типу `BackgroundTasks`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI** створить для вас об’єкт типу `BackgroundTasks` і передасть його як цей параметр.
@@ -31,13 +31,13 @@
І оскільки операція запису не використовує `async` та `await`, ми визначаємо функцію як звичайну `def`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
## Додавання фонової задачі { #add-the-background-task }
-Усередині вашої *функції операції шляху*, передайте функцію задачі в об'єкт *background tasks*, використовуючи метод `.add_task()`:
+Усередині вашої функції операції шляху, передайте функцію задачі в об'єкт background tasks, використовуючи метод `.add_task()`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` приймає аргументи:
@@ -47,17 +47,17 @@
## Впровадження залежностей { #dependency-injection }
-Використання `BackgroundTasks` також працює з системою впровадження залежностей. Ви можете оголосити параметр типу `BackgroundTasks` на різних рівнях: у *функції операції шляху*, у залежності (dependable), у підзалежності тощо.
+Використання `BackgroundTasks` також працює з системою впровадження залежностей. Ви можете оголосити параметр типу `BackgroundTasks` на різних рівнях: у функції операції шляху, у залежності (залежний), у підзалежності тощо.
-**FastAPI** знає, як діяти в кожному випадку і як повторно використовувати один і той самий об'єкт, щоб усі фонові задачі були об’єднані та виконувалися у фоновому режимі після завершення основного запиту:
+**FastAPI** знає, як діяти в кожному випадку і як повторно використовувати один і той самий об'єкт, щоб усі фонові задачі були об’єднані та виконувалися у фоновому режимі після завершення основного запиту:
{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
-У цьому прикладі повідомлення будуть записані у файл `log.txt` *після* того, як відповідь буде надіслана.
+У цьому прикладі повідомлення будуть записані у файл `log.txt` після того, як відповідь буде надіслана.
-Якщо у запиті був переданий query, він буде записаний у лог у фоновій задачі.
+Якщо у запиті був переданий параметр запиту, він буде записаний у лог у фоновій задачі.
-А потім інша фонова задача, згенерована у *функції операції шляху*, запише повідомлення з використанням path параметра `email`.
+А потім інша фонова задача, згенерована у функції операції шляху, запише повідомлення з використанням параметра шляху `email`.
## Технічні деталі { #technical-details }
@@ -65,7 +65,7 @@
Він імпортується/включається безпосередньо у FastAPI, щоб ви могли імпортувати його з `fastapi` і випадково не імпортували альтернативний `BackgroundTask` (без `s` в кінці) з `starlette.background`.
-Якщо використовувати лише `BackgroundTasks` (а не `BackgroundTask`), то його можна передавати як параметр у *функції операції шляху*, і **FastAPI** подбає про все інше, так само як і про використання об'єкта `Request`.
+Якщо використовувати лише `BackgroundTasks` (а не `BackgroundTask`), то його можна передавати як параметр у функції операції шляху, і **FastAPI** подбає про все інше, так само як і про використання об'єкта `Request`.
Також можна використовувати `BackgroundTask` окремо в FastAPI, але для цього вам доведеться створити об'єкт у коді та повернути Starlette `Response`, включаючи його.
@@ -81,4 +81,4 @@
## Підсумок { #recap }
-Імпортуйте та використовуйте `BackgroundTasks` як параметри у *функціях операції шляху* та залежностях, щоб додавати фонові задачі.
+Імпортуйте та використовуйте `BackgroundTasks` як параметри у функціях операції шляху та залежностях, щоб додавати фонові задачі.
diff --git a/docs/uk/docs/tutorial/body-multiple-params.md b/docs/uk/docs/tutorial/body-multiple-params.md
index f541beea7..a0db2b186 100644
--- a/docs/uk/docs/tutorial/body-multiple-params.md
+++ b/docs/uk/docs/tutorial/body-multiple-params.md
@@ -18,7 +18,7 @@
## Декілька параметрів тіла { #multiple-body-parameters }
-У попередньому прикладі *операції шляху* очікували б JSON-тіло з атрибутами `Item`, наприклад:
+У попередньому прикладi *операції шляху* очікували б JSON-тіло з атрибутами `Item`, наприклад:
```JSON
{
@@ -106,13 +106,6 @@
q: str | None = None
```
-Або в Python 3.9:
-
-```Python
-q: Union[str, None] = None
-```
-
-
Наприклад:
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
diff --git a/docs/uk/docs/tutorial/body-nested-models.md b/docs/uk/docs/tutorial/body-nested-models.md
index 6d0669358..a56ae484d 100644
--- a/docs/uk/docs/tutorial/body-nested-models.md
+++ b/docs/uk/docs/tutorial/body-nested-models.md
@@ -164,7 +164,7 @@ images: list[Image]
наприклад:
-{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
## Підтримка в редакторі всюди { #editor-support-everywhere }
@@ -194,7 +194,7 @@ images: list[Image]
У цьому випадку ви можете приймати будь-який `dict`, якщо його ключі — це `int`, а значення — `float`:
-{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
/// tip | Порада
@@ -216,6 +216,6 @@ images: list[Image]
* Підтримка в редакторі (автодоповнення всюди!)
* Конвертація даних (парсинг/сериалізація)
-* Валідацію даних
+* Валідація даних
* Документація схем
* Автоматичне створення документації
diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md
index ca1f308ab..615f0274c 100644
--- a/docs/uk/docs/tutorial/body.md
+++ b/docs/uk/docs/tutorial/body.md
@@ -8,7 +8,7 @@
Щоб оголосити тіло **запиту**, ви використовуєте Pydantic моделі з усією їх потужністю та перевагами.
-/// info | Інформація
+/// info
Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`.
@@ -73,8 +73,8 @@
* Якщо дані недійсні, він поверне гарну та чітку помилку, вказуючи, де саме і які дані були неправильними.
* Надавати отримані дані у параметрі `item`.
* Оскільки ви оголосили його у функції як тип `Item`, ви також матимете всю підтримку редактора (автозаповнення, тощо) для всіх атрибутів та їх типів.
-* Генерувати JSON Schema визначення для вашої моделі, ви також можете використовувати їх де завгодно, якщо це має сенс для вашого проекту.
-* Ці схеми будуть частиною згенерованої схеми OpenAPI і використовуватимуться автоматичною документацією UIs.
+* Генерувати визначення Схеми JSON для вашої моделі, ви також можете використовувати їх де завгодно, якщо це має сенс для вашого проекту.
+* Ці схеми будуть частиною згенерованої схеми OpenAPI і використовуватимуться автоматичною документацією UIs.
## Автоматична документація { #automatic-docs }
@@ -108,7 +108,7 @@
-/// tip | Порада
+/// tip
Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin.
@@ -151,11 +151,11 @@
* Якщо параметр має **сингулярний тип** (наприклад, `int`, `float`, `str`, `bool` тощо), він буде інтерпретуватися як параметр **запиту**.
* Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** **запиту**.
-/// note | Примітка
+/// note
FastAPI буде знати, що значення `q` не є обов'язковим через значення за замовчуванням `= None`.
-`str | None` (Python 3.10+) або `Union` у `Union[str, None]` (Python 3.9+) FastAPI не використовує, щоб визначити, що значення не є обов’язковим — він знатиме, що воно не є обов’язковим, тому що має значення за замовчуванням `= None`.
+`str | None` FastAPI не використовує, щоб визначити, що значення не є обов’язковим - він знатиме, що воно не є обов’язковим, тому що має значення за замовчуванням `= None`.
Але додавання анотацій типів дозволить вашому редактору надати вам кращу підтримку та виявляти помилки.
@@ -163,4 +163,4 @@ FastAPI буде знати, що значення `q` не є обов'язко
## Без Pydantic { #without-pydantic }
-Якщо ви не хочете використовувати моделі Pydantic, ви також можете використовувати параметри **Body**. Перегляньте документацію для [Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
+Якщо ви не хочете використовувати моделі Pydantic, ви також можете використовувати параметри **Body**. Перегляньте документацію для [Тіло - Кілька параметрів: Окремі значення в тілі](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
diff --git a/docs/uk/docs/tutorial/cookie-param-models.md b/docs/uk/docs/tutorial/cookie-param-models.md
index 3c6407716..dab57c536 100644
--- a/docs/uk/docs/tutorial/cookie-param-models.md
+++ b/docs/uk/docs/tutorial/cookie-param-models.md
@@ -1,8 +1,8 @@
# Моделі параметрів Cookie { #cookie-parameter-models }
-Якщо у Вас є група **cookies**, які пов'язані між собою, Ви можете створити **Pydantic-модель**, щоб оголосити їх. 🍪
+Якщо у вас є група **cookies**, які пов'язані між собою, ви можете створити **Pydantic-модель**, щоб оголосити їх. 🍪
-Це дозволить Вам повторно **використовувати модель** у **різних місцях**, а також оголосити валідацію та метадані для всіх параметрів одночасно. 😎
+Це дозволить вам повторно **використовувати модель** у **різних місцях**, а також оголосити валідацію та метадані для всіх параметрів одночасно. 😎
/// note | Примітка
@@ -18,11 +18,11 @@
## Cookie з Pydantic-моделлю { #cookies-with-a-pydantic-model }
-Оголосіть **cookie**-параметри, які Вам потрібні, у **Pydantic-моделі**, а потім оголосіть параметр як `Cookie`:
+Оголосіть **cookie**-параметри, які вам потрібні, у **Pydantic-моделі**, а потім оголосіть параметр як `Cookie`:
{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
-**FastAPI** буде **витягувати** дані для **кожного поля** з **cookies**, отриманих у запиті, і передавати Вам Pydantic-модель, яку Ви визначили.
+**FastAPI** буде **витягувати** дані для **кожного поля** з **cookies**, отриманих у запиті, і передавати вам Pydantic-модель, яку ви визначили.
## Перевірка у документації { #check-the-docs }
@@ -36,17 +36,17 @@
Майте на увазі, що оскільки **браузери обробляють cookies** особливим чином і «за лаштунками», вони **не** дозволяють **JavaScript** легко з ними працювати.
-Якщо Ви зайдете до **інтерфейсу документації API** за адресою `/docs`, Ви зможете побачити **документацію** для cookies у Ваших *операціях шляху*.
+Якщо ви зайдете до **інтерфейсу документації API** за адресою `/docs`, ви зможете побачити **документацію** для cookies у ваших *операціях шляху*.
-Але навіть якщо Ви заповните дані й натиснете "Execute", оскільки інтерфейс документації працює з **JavaScript**, cookies не будуть відправлені, і Ви побачите **помилку**, ніби Ви не ввели жодних значень.
+Але навіть якщо ви заповните дані й натиснете "Execute", оскільки інтерфейс документації працює з **JavaScript**, cookies не будуть відправлені, і ви побачите **помилку**, ніби ви не ввели жодних значень.
///
## Заборона додаткових cookie { #forbid-extra-cookies }
-У деяких спеціальних випадках (ймовірно, не дуже поширених) Ви можете захотіти **обмежити** cookies, які хочете отримувати.
+У деяких спеціальних випадках (ймовірно, не дуже поширених) ви можете захотіти **обмежити** cookies, які хочете отримувати.
-Ваша API тепер має можливість контролювати власну згоду на cookie. 🤪🍪
+Ваш API тепер має можливість контролювати власну згоду на cookies. 🤪🍪
Ви можете використовувати налаштування моделі Pydantic, щоб `forbid` будь-які `extra` поля:
@@ -54,9 +54,9 @@
Якщо клієнт спробує надіслати якісь **додаткові cookies**, він отримає відповідь з **помилкою**.
-Бідні банери cookie, які так старанно намагаються отримати Вашу згоду, щоб API її відхилила. 🍪
+Бідні банери cookie, які так старанно намагаються отримати вашу згоду, щоб API її відхилила. 🍪
-Наприклад, якщо клієнт спробує надіслати cookie `santa_tracker` зі значенням `good-list-please`, він отримає відповідь з помилкою, яка повідомить, що `santa_tracker` cookie не дозволено:
+Наприклад, якщо клієнт спробує надіслати cookie `santa_tracker` зі значенням `good-list-please`, він отримає відповідь з помилкою, яка повідомить, що `santa_tracker` cookie не дозволено:
```json
{
@@ -73,4 +73,4 @@
## Підсумок { #summary }
-Ви можете використовувати **Pydantic-моделі** для оголошення **cookies** у **FastAPI**. 😎
+Ви можете використовувати **Pydantic-моделі** для оголошення **cookies** у **FastAPI**. 😎
diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md
index 8a5b44e8a..3a2e6fa24 100644
--- a/docs/uk/docs/tutorial/cookie-params.md
+++ b/docs/uk/docs/tutorial/cookie-params.md
@@ -1,6 +1,6 @@
-# Параметри Cookie { #cookie-parameters }
+# Параметри кукі { #cookie-parameters }
-Ви можете визначати параметри Cookie таким же чином, як визначаються параметри `Query` і `Path`.
+Ви можете визначати параметри кукі таким же чином, як визначаються параметри `Query` і `Path`.
## Імпорт `Cookie` { #import-cookie }
@@ -10,7 +10,7 @@
## Визначення параметрів `Cookie` { #declare-cookie-parameters }
-Потім визначте параметри cookie, використовуючи таку ж конструкцію як для `Path` і `Query`.
+Потім визначте параметри кукі, використовуючи таку ж конструкцію як для `Path` і `Query`.
Ви можете визначити значення за замовчуванням, а також усі додаткові параметри валідації чи анотації:
@@ -26,20 +26,20 @@
/// info
-Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту.
+Для визначення кукі ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпретовані як параметри запиту.
///
/// info
-Майте на увазі, що оскільки **браузери обробляють cookies** спеціальним чином і за лаштунками, вони **не** дозволяють **JavaScript** легко взаємодіяти з ними.
+Майте на увазі, що оскільки **браузери обробляють кукі** спеціальним чином і за лаштунками, вони **не** дозволяють **JavaScript** легко взаємодіяти з ними.
-Якщо ви перейдете до **інтерфейсу документації API** за адресою `/docs`, ви зможете побачити **документацію** для cookies для ваших *операцій шляху*.
+Якщо ви перейдете до **інтерфейсу документації API** за адресою `/docs`, ви зможете побачити **документацію** для кукі для ваших *операцій шляху*.
-Але навіть якщо ви **заповните дані** і натиснете "Execute", оскільки інтерфейс документації працює з **JavaScript**, cookies не буде надіслано, і ви побачите повідомлення про **помилку**, ніби ви не ввели жодних значень.
+Але навіть якщо ви **заповните дані** і натиснете "Execute", оскільки інтерфейс документації працює з **JavaScript**, кукі не буде надіслано, і ви побачите повідомлення про **помилку**, ніби ви не ввели жодних значень.
///
## Підсумки { #recap }
-Визначайте cookies за допомогою `Cookie`, використовуючи той же спільний шаблон, що і `Query` та `Path`.
+Визначайте кукі за допомогою `Cookie`, використовуючи той же спільний шаблон, що і `Query` та `Path`.
diff --git a/docs/uk/docs/tutorial/cors.md b/docs/uk/docs/tutorial/cors.md
index f3ed8a7d9..5c959cef1 100644
--- a/docs/uk/docs/tutorial/cors.md
+++ b/docs/uk/docs/tutorial/cors.md
@@ -1,6 +1,6 @@
# CORS (Обмін ресурсами між різними джерелами) { #cors-cross-origin-resource-sharing }
-CORS або "Cross-Origin Resource Sharing" є ситуація, коли фронтенд, що працює в браузері, містить JavaScript-код, який взаємодіє з бекендом, розташованим в іншому "джерелі" (origin).
+CORS або «Cross-Origin Resource Sharing» є ситуація, коли фронтенд, що працює в браузері, містить JavaScript-код, який взаємодіє з бекендом, розташованим в іншому «джерелі» (origin).
## Джерело (Origin) { #origin }
@@ -13,50 +13,49 @@
* `https://localhost`
* `http://localhost:8080`
-Навіть якщо вони всі містять `localhost`, вони мають різні протоколи або порти, що робить їх окремими "джерелами".
+Навіть якщо вони всі містять `localhost`, вони мають різні протоколи або порти, що робить їх окремими «джерелами».
## Кроки { #steps }
-Припустимо, що Ваш фронтенд працює в браузері на `http://localhost:8080`, а його JavaScript намагається відправити запит до бекенду, який працює на `http://localhost` (Оскільки ми не вказуємо порт, браузер за замовчуванням припускає порт `80`).
+Припустимо, що ваш фронтенд працює в браузері на `http://localhost:8080`, а його JavaScript намагається відправити запит до бекенду, який працює на `http://localhost` (Оскільки ми не вказуємо порт, браузер за замовчуванням припускає порт `80`).
Потім браузер надішле HTTP-запит `OPTIONS` до бекенду на порту `:80`, і якщо бекенд надішле відповідні заголовки, що дозволяють комунікацію з цього іншого джерела (`http://localhost:8080`), тоді браузер на порту `:8080` дозволить JavaScript у фронтенді надіслати свій запит до бекенду на порту `:80`.
-Щоб досягти цього, бекенд на порту `:80` повинен мати список "дозволених джерел".
+Щоб досягти цього, бекенд на порту `:80` повинен мати список «дозволених джерел».
У цьому випадку список має містити `http://localhost:8080`, щоб фронтенд на порту `:8080` працював коректно.
-## Символьне підставляння { #wildcards }
+## Дикі карти { #wildcards }
-Можна також оголосити список як `"*"` ("символьне підставляння"), що означає дозвіл для всіх джерел.
+Можна також оголосити список як `"*"` (дика карта), що означає дозвіл для всіх джерел.
-Однак це дозволить лише певні типи комунікації, виключаючи все, що пов'язане з обліковими даними: Cookies, заголовки авторизації, такі як ті, що використовуються з Bearer Tokens, тощо.
+Однак це дозволить лише певні типи комунікації, виключаючи все, що пов'язане з обліковими даними: Cookies, заголовки авторизації, як-от ті, що використовуються з токенами носія, тощо.
Тому для коректної роботи краще явно вказувати дозволені джерела.
## Використання `CORSMiddleware` { #use-corsmiddleware }
-Ви можете налаштувати це у Вашому додатку **FastAPI** за допомогою `CORSMiddleware`.
+Ви можете налаштувати це у вашому додатку **FastAPI** за допомогою `CORSMiddleware`.
* Імпортуйте `CORSMiddleware`.
* Створіть список дозволених джерел (у вигляді рядків).
-* Додайте його як "middleware" у Ваш додаток **FastAPI**.
+* Додайте його як «проміжне програмне забезпечення» у ваш додаток **FastAPI**.
-
-Також можна вказати, чи дозволяє Ваш бекенд:
+Також можна вказати, чи дозволяє ваш бекенд:
* Облікові дані (заголовки авторизації, Cookies, тощо).
* Конкретні HTTP-методи (`POST`, `PUT`) або всі за допомогою `"*"`
* Конкретні HTTP-заголовки або всі за допомогою `"*"`.
-{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *}
-Параметри за замовчуванням у реалізації `CORSMiddleware` є досить обмеженими, тому Вам потрібно явно увімкнути конкретні джерела, методи або заголовки, щоб браузерам було дозволено використовувати їх у міждоменному контексті.
+Параметри за замовчуванням у реалізації `CORSMiddleware` є досить обмеженими, тому вам потрібно явно увімкнути конкретні джерела, методи або заголовки, щоб браузерам було дозволено використовувати їх у міждоменному контексті.
Підтримуються такі аргументи:
-* `allow_origins` - Список джерел, яким дозволено здійснювати міждоменні запити. Наприклад `['https://example.org', 'https://www.example.org']`. Ви можете використовувати `['*']`, щоб дозволити будь-яке джерело.
+* `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-запитів.
@@ -67,7 +66,7 @@
* `expose_headers` - Вказує, які заголовки відповіді повинні бути доступні для браузера. За замовчуванням `[]`.
* `max_age` - Встановлює максимальний час (у секундах) для кешування CORS-відповідей у браузерах. За замовчуванням `600`.
-Цей middleware обробляє два типи HTTP-запитів...
+Це проміжне програмне забезпечення обробляє два типи HTTP-запитів...
### Попередні CORS-запити { #cors-preflight-requests }
@@ -81,7 +80,7 @@
## Додаткова інформація { #more-info }
-Більше про CORS можна дізнатися в документації Mozilla про CORS.
+Більше про CORS можна дізнатися в документації Mozilla про CORS.
/// note | Технічні деталі
diff --git a/docs/uk/docs/tutorial/debugging.md b/docs/uk/docs/tutorial/debugging.md
index 0db418dcc..679018cc2 100644
--- a/docs/uk/docs/tutorial/debugging.md
+++ b/docs/uk/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@
У вашому FastAPI-додатку імпортуйте та запустіть `uvicorn` безпосередньо:
-{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *}
### Про `__name__ == "__main__"` { #about-name-main }
diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md
index 5f3750010..f03a120a0 100644
--- a/docs/uk/docs/tutorial/first-steps.md
+++ b/docs/uk/docs/tutorial/first-steps.md
@@ -2,7 +2,7 @@
Найпростіший файл FastAPI може виглядати так:
-{* ../../docs_src/first_steps/tutorial001_py39.py *}
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
Скопіюйте це до файлу `main.py`.
@@ -183,7 +183,7 @@ Deploying to FastAPI Cloud...
### Крок 1: імпортуємо `FastAPI` { #step-1-import-fastapi }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[1] *}
`FastAPI` — це клас у Python, який надає всю функціональність для вашого API.
@@ -197,7 +197,7 @@ Deploying to FastAPI Cloud...
### Крок 2: створюємо «екземпляр» `FastAPI` { #step-2-create-a-fastapi-instance }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[3] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[3] *}
Тут змінна `app` буде «екземпляром» класу `FastAPI`.
@@ -221,7 +221,7 @@ https://example.com/items/foo
/items/foo
```
-/// info | Інформація
+/// info
«Шлях» також зазвичай називають «ендпоінтом» або «маршрутом».
@@ -266,12 +266,12 @@ https://example.com/items/foo
#### Визначте *декоратор операції шляху* { #define-a-path-operation-decorator }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[6] *}
Декоратор `@app.get("/")` повідомляє **FastAPI**, що функція одразу нижче відповідає за обробку запитів, які надходять до:
* шляху `/`
-* використовуючи get операцію
+* використовуючи get операція
/// info | `@decorator` Інформація
@@ -300,7 +300,7 @@ https://example.com/items/foo
* `@app.patch()`
* `@app.trace()`
-/// tip | Порада
+/// tip
Ви можете використовувати кожну операцію (HTTP-метод) як забажаєте.
@@ -320,7 +320,7 @@ https://example.com/items/foo
* **операція**: це `get`.
* **функція**: це функція нижче «декоратора» (нижче `@app.get("/")`).
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
Це функція Python.
@@ -332,9 +332,9 @@ https://example.com/items/foo
Ви також можете визначити її як звичайну функцію замість `async def`:
-{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
-/// note | Примітка
+/// note
Якщо ви не знаєте різницю, подивіться [Асинхронність: *«Поспішаєте?»*](../async.md#in-a-hurry){.internal-link target=_blank}.
@@ -342,7 +342,7 @@ https://example.com/items/foo
### Крок 5: поверніть вміст { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int` тощо.
diff --git a/docs/uk/docs/tutorial/handling-errors.md b/docs/uk/docs/tutorial/handling-errors.md
index 53b8b12f6..28a83127f 100644
--- a/docs/uk/docs/tutorial/handling-errors.md
+++ b/docs/uk/docs/tutorial/handling-errors.md
@@ -25,7 +25,7 @@
### Імпорт `HTTPException` { #import-httpexception }
-{* ../../docs_src/handling_errors/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
### Згенеруйте `HTTPException` у своєму коді { #raise-an-httpexception-in-your-code }
@@ -39,7 +39,7 @@
У цьому прикладі, коли клієнт запитує елемент за ID, якого не існує, згенеруйте виключення зі статус-кодом `404`:
-{* ../../docs_src/handling_errors/tutorial001_py39.py hl[11] *}
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
### Отримана відповідь { #the-resulting-response }
@@ -77,7 +77,7 @@
Але якщо вам знадобиться це для складного сценарію, ви можете додати власні заголовки:
-{* ../../docs_src/handling_errors/tutorial002_py39.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
## Встановлення власних обробників виключень { #install-custom-exception-handlers }
@@ -89,7 +89,7 @@
Ви можете додати власний обробник виключень за допомогою `@app.exception_handler()`:
-{* ../../docs_src/handling_errors/tutorial003_py39.py hl[5:7,13:18,24] *}
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
Тут, якщо ви звернетеся до `/unicorns/yolo`, *операція шляху* згенерує (`raise`) `UnicornException`.
@@ -127,7 +127,7 @@
Обробник виключень отримає `Request` і саме виключення.
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[2,14:19] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
Тепер, якщо ви перейдете за посиланням `/items/foo`, замість того, щоб отримати стандартну JSON-помилку:
@@ -159,7 +159,7 @@ Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to pa
Наприклад, ви можете захотіти повернути відповідь у вигляді простого тексту замість JSON для цих помилок:
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[3:4,9:11,25] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
/// note | Технічні деталі
@@ -183,7 +183,7 @@ Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to pa
Ви можете використовувати це під час розробки свого додатка, щоб логувати тіло запиту та налагоджувати його, повертати користувачеві тощо.
-{* ../../docs_src/handling_errors/tutorial005_py39.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
Тепер спробуйте надіслати некоректний елемент, наприклад:
@@ -239,6 +239,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
Якщо ви хочете використовувати виключення разом із такими ж обробниками виключень за замовчуванням, як у **FastAPI**, ви можете імпортувати та повторно використати обробники виключень за замовчуванням із `fastapi.exception_handlers`:
-{* ../../docs_src/handling_errors/tutorial006_py39.py hl[2:5,15,21] *}
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
У цьому прикладі ви просто друкуєте помилку з дуже виразним повідомленням, але ви зрозуміли основну ідею. Ви можете використовувати виключення, а потім просто повторно використати обробники виключень за замовчуванням.
diff --git a/docs/uk/docs/tutorial/header-param-models.md b/docs/uk/docs/tutorial/header-param-models.md
index c080c19f0..dd734eaee 100644
--- a/docs/uk/docs/tutorial/header-param-models.md
+++ b/docs/uk/docs/tutorial/header-param-models.md
@@ -1,8 +1,8 @@
# Моделі параметрів заголовків { #header-parameter-models }
-Якщо у Вас є група пов’язаних **параметрів заголовків**, Ви можете створити **Pydantic модель** для їх оголошення.
+Якщо у вас є група пов’язаних **параметрів заголовків**, ви можете створити **Pydantic модель** для їх оголошення.
-Це дозволить Вам повторно **використовувати модель** в **різних місцях**, а також оголосити валідації та метадані для всіх параметрів одночасно. 😎
+Це дозволить вам повторно **використовувати модель** в **різних місцях**, а також оголосити валідації та метадані для всіх параметрів одночасно. 😎
/// note | Примітка
@@ -16,7 +16,7 @@
{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
-**FastAPI** буде **витягувати** дані для **кожного поля** з **заголовків** у запиті та передавати їх у створену Вами Pydantic модель.
+**FastAPI** буде **витягувати** дані для **кожного поля** з **заголовків** у запиті та передавати їх у створену вами Pydantic модель.
## Перевірка в документації { #check-the-docs }
@@ -28,7 +28,7 @@
## Заборонити додаткові заголовки { #forbid-extra-headers }
-У деяких особливих випадках (ймовірно, не дуже поширених) Ви можете захотіти **обмежити** заголовки, які хочете отримати.
+У деяких особливих випадках (ймовірно, не дуже поширених) ви можете захотіти **обмежити** заголовки, які хочете отримати.
Ви можете використати конфігурацію моделі Pydantic, щоб `заборонити` будь-які `додаткові` поля:
@@ -55,9 +55,9 @@
Так само, як і зі звичайними параметрами заголовків, коли у назвах параметрів є символи підкреслення, вони **автоматично перетворюються на дефіси**.
-Наприклад, якщо у коді у Вас є параметр заголовка `save_data`, очікуваний HTTP-заголовок буде `save-data`, і він так само відображатиметься в документації.
+Наприклад, якщо у коді у вас є параметр заголовка `save_data`, очікуваний HTTP-заголовок буде `save-data`, і він так само відображатиметься в документації.
-Якщо з якоїсь причини Вам потрібно вимкнути це автоматичне перетворення, Ви також можете зробити це для Pydantic моделей для параметрів заголовків.
+Якщо з якоїсь причини вам потрібно вимкнути це автоматичне перетворення, ви також можете зробити це для Pydantic моделей для параметрів заголовків.
{* ../../docs_src/header_param_models/tutorial003_an_py310.py hl[19] *}
diff --git a/docs/uk/docs/tutorial/header-params.md b/docs/uk/docs/tutorial/header-params.md
index f5a4ea18d..9e564d27a 100644
--- a/docs/uk/docs/tutorial/header-params.md
+++ b/docs/uk/docs/tutorial/header-params.md
@@ -50,7 +50,7 @@
/// warning | Попередження
-Перед тим як встановити `convert_underscores` в `False`, пам’ятайте, що деякі HTTP-проксі та сервери забороняють використання заголовків із підкресленнями.
+Перед тим як встановити `convert_underscores` в `False`, пам’ятайте, що деякі HTTP-представники та сервери забороняють використання заголовків із підкресленнями.
///
diff --git a/docs/uk/docs/tutorial/index.md b/docs/uk/docs/tutorial/index.md
index 6848090ec..ed53ac772 100644
--- a/docs/uk/docs/tutorial/index.md
+++ b/docs/uk/docs/tutorial/index.md
@@ -84,12 +84,12 @@ $ pip install "fastapi[standard]"
///
-## Розширений посібник користувача { #advanced-user-guide }
+## Просунутий посібник користувача { #advanced-user-guide }
-Існує також **Розширений посібник користувача**, який ви зможете прочитати пізніше після цього **Туторіал - Посібник користувача**.
+Існує також **Просунутий посібник користувача**, який ви зможете прочитати пізніше після цього **Туторіал - Посібник користувача**.
-**Розширений посібник користувача** засновано на цьому, використовує ті самі концепції та навчає вас деяким додатковим функціям.
+**Просунутий посібник користувача** засновано на цьому, використовує ті самі концепції та навчає вас деяким додатковим функціям.
Але вам слід спочатку прочитати **Туторіал - Посібник користувача** (те, що ви зараз читаєте).
-Він розроблений таким чином, що ви можете створити повну програму лише за допомогою **Туторіал - Посібник користувача**, а потім розширити її різними способами, залежно від ваших потреб, використовуючи деякі з додаткових ідей з **Розширеного посібника користувача**.
+Він розроблений таким чином, що ви можете створити повну програму лише за допомогою **Туторіал - Посібник користувача**, а потім розширити її різними способами, залежно від ваших потреб, використовуючи деякі з додаткових ідей з **Просунутого посібника користувача**.
diff --git a/docs/uk/docs/tutorial/metadata.md b/docs/uk/docs/tutorial/metadata.md
index cf1704562..ebe8dc40e 100644
--- a/docs/uk/docs/tutorial/metadata.md
+++ b/docs/uk/docs/tutorial/metadata.md
@@ -18,7 +18,7 @@
Ви можете налаштувати їх наступним чином:
-{* ../../docs_src/metadata/tutorial001_py39.py hl[3:16, 19:32] *}
+{* ../../docs_src/metadata/tutorial001_py310.py hl[3:16, 19:32] *}
/// tip | Порада
@@ -36,7 +36,7 @@
Наприклад:
-{* ../../docs_src/metadata/tutorial001_1_py39.py hl[31] *}
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
## Метадані для тегів { #metadata-for-tags }
@@ -58,7 +58,7 @@
Створіть метадані для своїх тегів і передайте їх у параметр `openapi_tags`:
-{* ../../docs_src/metadata/tutorial004_py39.py hl[3:16,18] *}
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
Зверніть увагу, що в описах можна використовувати Markdown, наприклад, "login" буде показано жирним шрифтом (**login**), а "fancy" буде показано курсивом (_fancy_).
@@ -72,7 +72,7 @@
Використовуйте параметр `tags` зі своїми *операціями шляху* (і `APIRouter`s), щоб призначити їх до різних тегів:
-{* ../../docs_src/metadata/tutorial004_py39.py hl[21,26] *}
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
/// info | Інформація
@@ -100,7 +100,7 @@
Наприклад, щоб налаштувати його на `/api/v1/openapi.json`:
-{* ../../docs_src/metadata/tutorial002_py39.py hl[3] *}
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
Якщо Ви хочете повністю вимкнути схему OpenAPI, Ви можете встановити `openapi_url=None`, це також вимкне інтерфейси документації, які її використовують.
@@ -117,4 +117,4 @@
Наприклад, щоб налаштувати Swagger UI на `/documentation` і вимкнути ReDoc:
-{* ../../docs_src/metadata/tutorial003_py39.py hl[3] *}
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/uk/docs/tutorial/middleware.md b/docs/uk/docs/tutorial/middleware.md
index 2d1580e49..961fb179e 100644
--- a/docs/uk/docs/tutorial/middleware.md
+++ b/docs/uk/docs/tutorial/middleware.md
@@ -31,9 +31,9 @@
* Потім вона поверне `response`, згенеровану відповідною *операцією шляху*.
* Потім ви можете додатково змінити `response` перед тим, як повернути її.
-{* ../../docs_src/middleware/tutorial001_py39.py hl[8:9,11,14] *}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
-/// tip | Порада
+/// tip
Пам’ятайте, що власні пропрієтарні заголовки можна додавати використовуючи префікс `X-`.
@@ -57,9 +57,9 @@
Наприклад, ви можете додати власний заголовок `X-Process-Time`, який міститиме час у секундах, який витратився на обробку запиту та генерацію відповіді:
-{* ../../docs_src/middleware/tutorial001_py39.py hl[10,12:13] *}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
-/// tip | Порада
+/// tip
Тут ми використовуємо `time.perf_counter()` замість `time.time()` оскільки він може бути більш точним для таких випадків. 🤓
@@ -92,4 +92,4 @@ app.add_middleware(MiddlewareB)
Ви можете пізніше прочитати більше про інші middlewares в [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}.
-Ви дізнаєтесь, як обробляти CORS за допомогою middleware в наступному розділі.
+Ви дізнаєтесь, як обробляти CORS за допомогою middleware в наступному розділі.
diff --git a/docs/uk/docs/tutorial/path-params-numeric-validations.md b/docs/uk/docs/tutorial/path-params-numeric-validations.md
index f6aa92019..9458436fd 100644
--- a/docs/uk/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/uk/docs/tutorial/path-params-numeric-validations.md
@@ -54,11 +54,11 @@ Python видасть помилку, якщо розмістити значен
Тому ви можете оголосити вашу функцію так:
-{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
Але майте на увазі, що якщо ви використовуєте `Annotated`, цієї проблеми не буде, це не матиме значення, оскільки ви не використовуєте значення за замовчуванням параметрів функції для `Query()` або `Path()`.
-{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
## Упорядковуйте параметри, як вам потрібно: хитрощі { #order-the-parameters-as-you-need-tricks }
@@ -81,15 +81,15 @@ Python видасть помилку, якщо розмістити значен
Передайте `*` як перший параметр функції.
-Python нічого не зробить із цією `*`, але розпізнає, що всі наступні параметри слід викликати як аргументи за ключовим словом (пари ключ-значення), також відомі як kwargs. Навіть якщо вони не мають значення за замовчуванням.
+Python нічого не зробить із цією `*`, але розпізнає, що всі наступні параметри слід викликати як аргументи за ключовим словом (пари ключ-значення), також відомі як kwargs. Навіть якщо вони не мають значення за замовчуванням.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
### Краще з `Annotated` { #better-with-annotated }
Майте на увазі, що якщо ви використовуєте `Annotated`, оскільки ви не використовуєте значення за замовчуванням параметрів функції, цієї проблеми не буде, і, ймовірно, вам не потрібно буде використовувати `*`.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
## Валідація числових даних: більше або дорівнює { #number-validations-greater-than-or-equal }
@@ -97,7 +97,7 @@ Python нічого не зробить із цією `*`, але розпізн
Тут, завдяки `ge=1`, `item_id` має бути цілим числом, яке "`g`reater than or `e`qual" (більше або дорівнює) `1`.
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
## Валідація числових даних: більше ніж і менше або дорівнює { #number-validations-greater-than-and-less-than-or-equal }
@@ -106,19 +106,19 @@ Python нічого не зробить із цією `*`, але розпізн
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
## Валідація числових даних: float, більше ніж і менше ніж { #number-validations-floats-greater-than-and-less-than }
Валідація чисел також працює для значень типу `float`.
-Ось де стає важливо мати можливість оголошувати gt, а не тільки ge. Це дозволяє, наприклад, вимагати, щоб значення було більше `0`, навіть якщо воно менше `1`.
+Ось де стає важливо мати можливість оголошувати gt, а не тільки ge. Це дозволяє, наприклад, вимагати, щоб значення було більше `0`, навіть якщо воно менше `1`.
Таким чином, значення `0.5` буде допустимим. Але `0.0` або `0` — ні.
-Те саме стосується lt.
+Те саме стосується lt.
-{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
## Підсумок { #recap }
diff --git a/docs/uk/docs/tutorial/path-params.md b/docs/uk/docs/tutorial/path-params.md
index 059890549..17b99cf39 100644
--- a/docs/uk/docs/tutorial/path-params.md
+++ b/docs/uk/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Ви можете оголосити «параметри» або «змінні» шляху, використовуючи той самий синтаксис, що й у форматованих рядках Python:
-{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
Значення параметра шляху `item_id` буде передано у вашу функцію як аргумент `item_id`.
@@ -16,17 +16,17 @@
Ви можете оголосити тип параметра шляху у функції, використовуючи стандартні анотації типів Python:
-{* ../../docs_src/path_params/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
У цьому випадку `item_id` оголошено як `int`.
-/// check | Примітка
+/// check | Перевірте
Це дасть вам підтримку редактора всередині функції з перевірками помилок, автодоповненням тощо.
///
-## Перетворення даних { #data-conversion }
+## Перетворення даних { #data-conversion }
Якщо ви запустите цей приклад і відкриєте у браузері http://127.0.0.1:8000/items/3, то побачите відповідь:
@@ -34,11 +34,11 @@
{"item_id":3}
```
-/// check | Примітка
+/// check | Перевірте
Зверніть увагу, що значення, яке отримала (і повернула) ваша функція, — це `3`, як Python `int`, а не рядок `"3"`.
-Отже, з таким оголошенням типу **FastAPI** надає вам автоматичний «parsing» запиту.
+Отже, з таким оголошенням типу **FastAPI** надає вам автоматичний запит «парсинг».
///
@@ -66,7 +66,7 @@
Та сама помилка з’явиться, якщо ви передасте `float` замість `int`, як у: http://127.0.0.1:8000/items/4.2
-/// check | Примітка
+/// check | Перевірте
Отже, з тим самим оголошенням типу в Python **FastAPI** надає вам валідацію даних.
@@ -82,7 +82,7 @@
-/// check | Примітка
+/// check | Перевірте
Знову ж таки, лише з тим самим оголошенням типу в Python **FastAPI** надає вам автоматичну, інтерактивну документацію (з інтеграцією Swagger UI).
@@ -118,19 +118,19 @@
Оскільки *операції шляху* оцінюються по черзі, вам потрібно переконатися, що шлях для `/users/me` оголошено перед шляхом для `/users/{user_id}`:
-{* ../../docs_src/path_params/tutorial003_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
Інакше шлях для `/users/{user_id}` також відповідатиме `/users/me`, «вважаючи», що отримує параметр `user_id` зі значенням `"me"`.
Так само ви не можете перевизначити операцію шляху:
-{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
Завжди використовуватиметься перша, оскільки шлях збігається першим.
## Попередньо визначені значення { #predefined-values }
-Якщо у вас є *операція шляху*, яка отримує *параметр шляху*, але ви хочете, щоб можливі коректні значення *параметра шляху* були попередньо визначені, ви можете використати стандартний Python `Enum`.
+Якщо у вас є *операція шляху*, яка отримує *параметр шляху*, але ви хочете, щоб можливі коректні значення *параметра шляху* були попередньо визначені, ви можете використати стандартний Python `Enum`.
### Створіть клас `Enum` { #create-an-enum-class }
@@ -140,11 +140,11 @@
Після цього створіть атрибути класу з фіксованими значеннями, які будуть доступними коректними значеннями:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
/// tip | Порада
-Якщо вам цікаво, «AlexNet», «ResNet» та «LeNet» — це просто назви Machine Learning models.
+Якщо вам цікаво, «AlexNet», «ResNet» та «LeNet» — це просто назви моделей машинного навчання моделі.
///
@@ -152,7 +152,7 @@
Потім створіть *параметр шляху* з анотацією типу, використовуючи створений вами клас enum (`ModelName`):
-{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
### Перевірте документацію { #check-the-docs }
@@ -168,13 +168,13 @@
Ви можете порівнювати його з *елементом перелічування* у створеному вами enum `ModelName`:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[17] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
#### Отримайте *значення перелічування* { #get-the-enumeration-value }
Ви можете отримати фактичне значення (у цьому випадку це `str`), використовуючи `model_name.value`, або загалом `your_enum_member.value`:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[20] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
/// tip | Порада
@@ -188,7 +188,7 @@
Вони будуть перетворені на відповідні значення (у цьому випадку рядки) перед поверненням клієнту:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[18,21,23] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
На стороні клієнта ви отримаєте відповідь у форматі JSON, наприклад:
@@ -227,7 +227,7 @@ OpenAPI не підтримує спосіб оголошення *параме
Отже, ви можете використати його так:
-{* ../../docs_src/path_params/tutorial004_py39.py hl[6] *}
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
/// tip | Порада
@@ -242,7 +242,7 @@ OpenAPI не підтримує спосіб оголошення *параме
З **FastAPI**, використовуючи короткі, інтуїтивно зрозумілі та стандартні оголошення типів Python, ви отримуєте:
* Підтримку редактора: перевірка помилок, автодоповнення тощо.
-* Перетворення даних «parsing»
+* Перетворення даних «парсинг»
* Валідацію даних
* Анотацію API та автоматичну документацію
diff --git a/docs/uk/docs/tutorial/query-param-models.md b/docs/uk/docs/tutorial/query-param-models.md
index a28bf6c27..5affc8a6c 100644
--- a/docs/uk/docs/tutorial/query-param-models.md
+++ b/docs/uk/docs/tutorial/query-param-models.md
@@ -1,6 +1,6 @@
# Моделі параметрів запиту { #query-parameter-models }
-Якщо у Вас є група **query параметрів**, які пов’язані між собою, Ви можете створити **Pydantic-модель** для їх оголошення.
+Якщо у Вас є група **параметрів запиту**, які пов’язані між собою, Ви можете створити **Pydantic-модель** для їх оголошення.
Це дозволить Вам **повторно використовувати модель** у **різних місцях**, а також оголошувати перевірки та метадані для всіх параметрів одночасно. 😎
@@ -10,13 +10,13 @@
///
-## Query параметри з Pydantic-моделлю { #query-parameters-with-a-pydantic-model }
+## Параметри запиту з Pydantic-моделлю { #query-parameters-with-a-pydantic-model }
-Оголосіть **query параметри**, які Вам потрібні, у **Pydantic-моделі**, а потім оголосіть цей параметр як `Query`:
+Оголосіть **параметри запиту**, які Вам потрібні, у **Pydantic-моделі**, а потім оголосіть цей параметр як `Query`:
{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
-**FastAPI** буде **витягувати** дані для **кожного поля** з **query параметрів** у запиті та передавати їх у визначену вами Pydantic-модель.
+**FastAPI** буде **витягувати** дані для **кожного поля** з **параметрів запиту** у запиті та передавати їх у визначену вами Pydantic-модель.
## Перевірте документацію { #check-the-docs }
@@ -26,23 +26,23 @@
POST.
+Якщо ви хочете дізнатися більше про ці типи кодування та формові поля, ознайомтеся з MDN web docs для POST.
///
@@ -143,7 +143,7 @@ contents = myfile.file.read()
Ви також можете використовувати `File()` разом із `UploadFile`, наприклад, щоб встановити додаткові метадані:
-{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
## Завантаження кількох файлів { #multiple-file-uploads }
@@ -153,7 +153,7 @@ contents = myfile.file.read()
Щоб це реалізувати, потрібно оголосити список `bytes` або `UploadFile`:
-{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
Ви отримаєте, як і було оголошено, `list` із `bytes` або `UploadFile`.
@@ -169,7 +169,7 @@ contents = myfile.file.read()
Так само як і раніше, ви можете використовувати `File()`, щоб встановити додаткові параметри навіть для `UploadFile`:
-{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
## Підсумок { #recap }
diff --git a/docs/uk/docs/tutorial/request-form-models.md b/docs/uk/docs/tutorial/request-form-models.md
index 1bfd368d6..86510be58 100644
--- a/docs/uk/docs/tutorial/request-form-models.md
+++ b/docs/uk/docs/tutorial/request-form-models.md
@@ -24,7 +24,7 @@ $ pip install python-multipart
Вам просто потрібно оголосити **Pydantic-модель** з полями, які ви хочете отримати як **поля форми**, а потім оголосити параметр як `Form`:
-{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
**FastAPI** **витягне** дані для **кожного поля** з **формових даних** у запиті та надасть вам Pydantic-модель, яку ви визначили.
@@ -48,7 +48,7 @@ $ pip install python-multipart
Ви можете використати конфігурацію Pydantic-моделі, щоб заборонити `forbid` будь-які додаткові `extra` поля:
-{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *}
+{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *}
Якщо клієнт спробує надіслати додаткові дані, він отримає **відповідь з помилкою**.
diff --git a/docs/uk/docs/tutorial/request-forms-and-files.md b/docs/uk/docs/tutorial/request-forms-and-files.md
index e809bee22..817769b71 100644
--- a/docs/uk/docs/tutorial/request-forms-and-files.md
+++ b/docs/uk/docs/tutorial/request-forms-and-files.md
@@ -6,7 +6,7 @@
Щоб отримувати завантажені файли та/або дані форми, спочатку встановіть `python-multipart`.
-Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад:
+Переконайтеся, що ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад:
```console
$ pip install python-multipart
@@ -16,15 +16,15 @@ $ pip install python-multipart
## Імпорт `File` та `Form` { #import-file-and-form }
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[3] *}
## Оголошення параметрів `File` та `Form` { #define-file-and-form-parameters }
Створіть параметри файлів та форми так само як і для `Body` або `Query`:
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[10:12] *}
-Файли та поля форми будуть завантажені як формові дані, і Ви отримаєте файли та поля форми.
+Файли та поля форми будуть завантажені як формові дані, і ви отримаєте файли та поля форми.
Ви також можете оголосити деякі файли як `bytes`, а деякі як `UploadFile`.
diff --git a/docs/uk/docs/tutorial/request-forms.md b/docs/uk/docs/tutorial/request-forms.md
index 2a22ad922..7f0c6e9bb 100644
--- a/docs/uk/docs/tutorial/request-forms.md
+++ b/docs/uk/docs/tutorial/request-forms.md
@@ -1,6 +1,6 @@
# Дані форми { #form-data }
-Якщо вам потрібно отримувати поля форми замість JSON, ви можете використовувати `Form`.
+Коли вам потрібно отримувати поля форми замість JSON, ви можете використовувати `Form`.
/// info | Інформація
@@ -18,17 +18,17 @@ $ pip install python-multipart
Імпортуйте `Form` з `fastapi`:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[3] *}
## Оголошення параметрів `Form` { #define-form-parameters }
Створюйте параметри форми так само як ви б створювали `Body` або `Query`:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[9] *}
-Наприклад, один зі способів використання специфікації OAuth2 (так званий "password flow") вимагає надсилати `username` та `password` як поля форми.
+Наприклад, один зі способів використання специфікації OAuth2 (так званий «password flow») вимагає надсилати `username` та `password` як поля форми.
-spec вимагає, щоб ці поля мали точні назви `username` і `password` та надсилалися у вигляді полів форми, а не JSON.
+специфікація вимагає, щоб ці поля мали точні назви `username` і `password` та надсилалися у вигляді полів форми, а не JSON.
З `Form` ви можете оголошувати ті ж конфігурації, що і з `Body` (та `Query`, `Path`, `Cookie`), включаючи валідацію, приклади, псевдоніми (наприклад, `user-name` замість `username`) тощо.
@@ -44,19 +44,19 @@ $ pip install python-multipart
///
-## Про "поля форми" { #about-form-fields }
+## Про «поля форми» { #about-form-fields }
-HTML-форми (``) надсилають дані на сервер у "спеціальному" кодуванні, яке відрізняється від JSON.
+HTML-форми (``) надсилають дані на сервер у «спеціальному» кодуванні, яке відрізняється від JSON.
**FastAPI** подбає про те, щоб зчитати ці дані з правильного місця, а не з JSON.
/// note | Технічні деталі
-Дані з форм зазвичай кодуються за допомогою "типу медіа" `application/x-www-form-urlencoded`.
+Дані з форм зазвичай кодуються за допомогою «типу медіа» `application/x-www-form-urlencoded`.
Але якщо форма містить файли, вона кодується як `multipart/form-data`. Ви дізнаєтеся про обробку файлів у наступному розділі.
-Якщо ви хочете дізнатися більше про ці кодування та поля форм, зверніться до MDN вебдокументації для POST.
+Якщо ви хочете дізнатися більше про ці кодування та поля форм, зверніться до MDN вебдокументації для POST.
///
diff --git a/docs/uk/docs/tutorial/response-model.md b/docs/uk/docs/tutorial/response-model.md
index 2fcad9438..fcf765c9d 100644
--- a/docs/uk/docs/tutorial/response-model.md
+++ b/docs/uk/docs/tutorial/response-model.md
@@ -81,7 +81,7 @@ FastAPI використовуватиме цей `response_model` для вик
$ pip install email-validator
```
-or with:
+або так:
```console
$ pip install "pydantic[email]"
@@ -183,7 +183,7 @@ FastAPI виконує кілька внутрішніх операцій з Pyd
Найпоширенішим випадком буде [повернення Response напряму, як пояснюється пізніше у розширеній документації](../advanced/response-directly.md){.internal-link target=_blank}.
-{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
Цей простий випадок автоматично обробляється FastAPI, тому що анотація типу повернення — це клас (або підклас) `Response`.
@@ -193,7 +193,7 @@ FastAPI виконує кілька внутрішніх операцій з Pyd
Ви також можете використати підклас `Response` в анотації типу:
-{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
Це теж працюватиме, бо `RedirectResponse` — підклас `Response`, і FastAPI автоматично обробить цей простий випадок.
@@ -201,7 +201,7 @@ FastAPI виконує кілька внутрішніх операцій з Pyd
Але коли ви повертаєте якийсь інший довільний об’єкт, що не є валідним типом Pydantic (наприклад, об’єкт бази даних), і анотуєте його так у функції, FastAPI спробує створити модель відповіді Pydantic на основі цієї анотації типу і це завершиться помилкою.
-Те саме станеться, якщо ви використаєте union між різними типами, де один або більше не є валідними типами Pydantic, наприклад, це завершиться помилкою 💥:
+Те саме станеться, якщо у вас буде об'єднання між різними типами, де один або більше не є валідними типами Pydantic, наприклад, це завершиться помилкою 💥:
{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
diff --git a/docs/uk/docs/tutorial/response-status-code.md b/docs/uk/docs/tutorial/response-status-code.md
index 5a08ee46b..c9ceb8f50 100644
--- a/docs/uk/docs/tutorial/response-status-code.md
+++ b/docs/uk/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@
* `@app.delete()`
* тощо.
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
/// note | Примітка
@@ -66,7 +66,7 @@ FastAPI знає про це і створить документацію OpenAP
/// tip | Порада
-Щоб дізнатися більше про кожен код статусу і для чого призначений кожен із них, перегляньте документацію MDN про HTTP коди статусу.
+Щоб дізнатися більше про кожен код статусу і для чого призначений кожен із них, перегляньте документацію MDN про HTTP коди статусу.
///
@@ -74,7 +74,7 @@ FastAPI знає про це і створить документацію OpenAP
Розглянемо попередній приклад ще раз:
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201` — це код статусу для «Created».
@@ -82,7 +82,7 @@ FastAPI знає про це і створить документацію OpenAP
Ви можете використовувати зручні змінні з `fastapi.status`.
-{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
Вони — просто для зручності, містять те саме число, але так ви можете скористатися автозаповненням редактора, щоб знайти їх:
diff --git a/docs/uk/docs/tutorial/schema-extra-example.md b/docs/uk/docs/tutorial/schema-extra-example.md
index 54608c2ab..38ce0eb30 100644
--- a/docs/uk/docs/tutorial/schema-extra-example.md
+++ b/docs/uk/docs/tutorial/schema-extra-example.md
@@ -40,7 +40,7 @@ OpenAPI 3.1.0 (який використовується починаючи з F
{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
-## `examples` у JSON-схемі — OpenAPI { #examples-in-json-schema-openapi }
+## `examples` у JSON-схемі - OpenAPI { #examples-in-json-schema-openapi }
При використанні будь-кого з наступного:
@@ -74,7 +74,7 @@ OpenAPI 3.1.0 (який використовується починаючи з F
Коли Ви це робите, приклади будуть частиною внутрішньої **JSON-схеми** для цих даних тіла.
-Втім, на момент написання цього (час написання цього), Swagger UI — інструмент, який відповідає за відображення UI документації — не підтримує показ кількох прикладів для даних у **JSON-схемі**. Але нижче можна прочитати про обхідний шлях.
+Втім, на час написання цього, Swagger UI — інструмент, який відповідає за відображення UI документації — не підтримує показ кількох прикладів для даних у **JSON-схемі**. Але нижче можна прочитати про обхідний шлях.
### Специфічні для OpenAPI `examples` { #openapi-specific-examples }
diff --git a/docs/uk/docs/tutorial/security/index.md b/docs/uk/docs/tutorial/security/index.md
index f1fb25178..de09c728b 100644
--- a/docs/uk/docs/tutorial/security/index.md
+++ b/docs/uk/docs/tutorial/security/index.md
@@ -73,11 +73,11 @@ OpenAPI визначає такі схеми безпеки:
* `apiKey`: специфічний для застосунку ключ, який може передаватися через:
* Параметр запиту.
* Заголовок.
- * Cookie.
+ * Кукі.
* `http`: стандартні системи HTTP-автентифікації, включаючи:
* `bearer`: заголовок `Authorization` зі значенням `Bearer ` та токеном. Це успадковано з OAuth2.
- * HTTP Basic автентифікацію.
- * HTTP Digest тощо.
+ * базову автентифікацію HTTP.
+ * HTTP дайджест тощо.
* `oauth2`: усі способи обробки безпеки за допомогою OAuth2 (так звані «потоки»).
* Декілька з цих потоків підходять для створення провайдера автентифікації OAuth 2.0 (наприклад, Google, Facebook, X (Twitter), GitHub тощо):
* `implicit`
diff --git a/docs/uk/docs/tutorial/static-files.md b/docs/uk/docs/tutorial/static-files.md
index 32ca1311d..7f45973df 100644
--- a/docs/uk/docs/tutorial/static-files.md
+++ b/docs/uk/docs/tutorial/static-files.md
@@ -7,7 +7,7 @@
* Імпортуйте `StaticFiles`.
* «Під'єднати» екземпляр `StaticFiles()` з вказанням необхідного шляху.
-{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py310.py hl[2,6] *}
/// note | Технічні деталі
diff --git a/docs/uk/docs/tutorial/testing.md b/docs/uk/docs/tutorial/testing.md
index 462592829..ff32e9fb6 100644
--- a/docs/uk/docs/tutorial/testing.md
+++ b/docs/uk/docs/tutorial/testing.md
@@ -30,7 +30,7 @@ $ pip install httpx
Записуйте прості `assert`-вирази зі стандартними виразами Python, які потрібно перевірити (це також стандарт для `pytest`).
-{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py310.py hl[2,12,15:18] *}
/// tip | Порада
@@ -76,7 +76,7 @@ $ pip install httpx
У файлі `main.py` знаходиться ваш застосунок **FastAPI**:
-{* ../../docs_src/app_testing/app_a_py39/main.py *}
+{* ../../docs_src/app_testing/app_a_py310/main.py *}
### Файл тестування { #testing-file }
@@ -90,9 +90,9 @@ $ pip install httpx
│ └── test_main.py
```
-Оскільки цей файл знаходиться в тому ж пакеті, ви можете використовувати відносний імпорт, щоб імпортувати об'єкт `app` із модуля `main` (`main.py`):
+Оскільки цей файл знаходиться в тому ж пакеті, ви можете використовувати відносний імпорт, щоб імпортувати об'єкт `app` із модуля `main` (`main.py`):
-{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py310/test_main.py hl[3] *}
...і написати код для тестів так само як і раніше.
From 54e29fbad85d7875800b86205ad47981f41b4faa Mon Sep 17 00:00:00 2001
From: "github-actions[bot]" lt
+* XWT
+* PSGI
+
+### abbr 提供了完整短语与解释 { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | 信息
+
+"abbr" 元素的 "title" 属性需要按照特定规则进行翻译。
+
+译文可以自行添加 "abbr" 元素以解释英语单词,LLM 不应删除这些元素。
+
+参见 `scripts/translate.py` 中通用提示的 `### HTML abbr elements` 部分。
+
+////
+
+## HTML "dfn" 元素 { #html-dfn-elements }
+
+* 集群
+* 深度学习
+
+## 标题 { #headings }
+
+//// tab | 测试
+
+### 开发 Web 应用——教程 { #develop-a-webapp-a-tutorial }
+
+Hello.
+
+### 类型提示与注解 { #type-hints-and-annotations }
+
+Hello again.
+
+### 超类与子类 { #super-and-subclasses }
+
+Hello again.
+
+////
+
+//// tab | 信息
+
+关于标题的唯一硬性规则是:LLM 必须保持花括号内的哈希部分不变,以确保链接不会失效。
+
+参见 `scripts/translate.py` 中通用提示的 `### Headings` 部分。
+
+语言特定的说明可参见例如 `docs/de/llm-prompt.md` 中的 `### Headings` 部分。
+
+////
+
+## 文档中使用的术语 { #terms-used-in-the-docs }
+
+//// tab | 测试
+
+* you
+* your
+
+* e.g.
+* etc.
+
+* `foo` as an `int`
+* `bar` as a `str`
+* `baz` as a `list`
+
+* the Tutorial - User guide
+* the Advanced User Guide
+* the SQLModel docs
+* the API docs
+* the automatic docs
+
+* Data Science
+* Deep Learning
+* Machine Learning
+* Dependency Injection
+* HTTP Basic authentication
+* HTTP Digest
+* ISO format
+* the JSON Schema standard
+* the JSON schema
+* the schema definition
+* Password Flow
+* Mobile
+
+* deprecated
+* designed
+* invalid
+* on the fly
+* standard
+* default
+* case-sensitive
+* case-insensitive
+
+* to serve the application
+* to serve the page
+
+* the app
+* the application
+
+* the request
+* the response
+* the error response
+
+* the path operation
+* the path operation decorator
+* the path operation function
+
+* the body
+* the request body
+* the response body
+* the JSON body
+* the form body
+* the file body
+* the function body
+
+* the parameter
+* the body parameter
+* the path parameter
+* the query parameter
+* the cookie parameter
+* the header parameter
+* the form parameter
+* the function parameter
+
+* the event
+* the startup event
+* the startup of the server
+* the shutdown event
+* the lifespan event
+
+* the handler
+* the event handler
+* the exception handler
+* to handle
+
+* the model
+* the Pydantic model
+* the data model
+* the database model
+* the form model
+* the model object
+
+* the class
+* the base class
+* the parent class
+* the subclass
+* the child class
+* the sibling class
+* the class method
+
+* the header
+* the headers
+* the authorization header
+* the `Authorization` header
+* the forwarded header
+
+* the dependency injection system
+* the dependency
+* the dependable
+* the dependant
+
+* I/O bound
+* CPU bound
+* concurrency
+* parallelism
+* multiprocessing
+
+* the env var
+* the environment variable
+* the `PATH`
+* the `PATH` variable
+
+* the authentication
+* the authentication provider
+* the authorization
+* the authorization form
+* the authorization provider
+* the user authenticates
+* the system authenticates the user
+
+* the CLI
+* the command line interface
+
+* the server
+* the client
+
+* the cloud provider
+* the cloud service
+
+* the development
+* the development stages
+
+* the dict
+* the dictionary
+* the enumeration
+* the enum
+* the enum member
+
+* the encoder
+* the decoder
+* to encode
+* to decode
+
+* the exception
+* to raise
+
+* the expression
+* the statement
+
+* the frontend
+* the backend
+
+* the GitHub discussion
+* the GitHub issue
+
+* the performance
+* the performance optimization
+
+* the return type
+* the return value
+
+* the security
+* the security scheme
+
+* the task
+* the background task
+* the task function
+
+* the template
+* the template engine
+
+* the type annotation
+* the type hint
+
+* the server worker
+* the Uvicorn worker
+* the Gunicorn Worker
+* the worker process
+* the worker class
+* the workload
+
+* the deployment
+* to deploy
+
+* the SDK
+* the software development kit
+
+* the `APIRouter`
+* the `requirements.txt`
+* the Bearer Token
+* the breaking change
+* the bug
+* the button
+* the callable
+* the code
+* the commit
+* the context manager
+* the coroutine
+* the database session
+* the disk
+* the domain
+* the engine
+* the fake X
+* the HTTP GET method
+* the item
+* the library
+* the lifespan
+* the lock
+* the middleware
+* the mobile application
+* the module
+* the mounting
+* the network
+* the origin
+* the override
+* the payload
+* the processor
+* the property
+* the proxy
+* the pull request
+* the query
+* the RAM
+* the remote machine
+* the status code
+* the string
+* the tag
+* the web framework
+* the wildcard
+* to return
+* to validate
+
+////
+
+//// tab | 信息
+
+这是一份不完整且非规范性的(主要是)技术术语清单,取自文档中常见的词汇。它可能有助于提示词设计者判断哪些术语需要对 LLM 提供额外指引。例如当它总是把一个好的译法改回次优译法,或在你的语言中对某个术语的词形变化有困难时。
+
+参见例如 `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/about/index.md b/docs/zh/docs/about/index.md
new file mode 100644
index 000000000..9b73533f7
--- /dev/null
+++ b/docs/zh/docs/about/index.md
@@ -0,0 +1,3 @@
+# 关于 { #about }
+
+关于 FastAPI、其设计、灵感等。🤓
diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md
index bc197280a..aa3d22d1c 100644
--- a/docs/zh/docs/advanced/additional-responses.md
+++ b/docs/zh/docs/advanced/additional-responses.md
@@ -26,7 +26,7 @@
例如,要声明另一个状态码为 `404` 且具有 Pydantic 模型 `Message` 的响应,你可以这样写:
-{* ../../docs_src/additional_responses/tutorial001_py39.py hl[18,22] *}
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
/// note | 注意
@@ -203,7 +203,7 @@
以及一个状态码为 `200` 的响应,它使用你的 `response_model`,但包含自定义的 `example`:
-{* ../../docs_src/additional_responses/tutorial003_py39.py hl[20:31] *}
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
所有这些都会被合并并包含到你的 OpenAPI 中,并显示在 API 文档里:
diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md
index 23ceab4e8..7eeffaf53 100644
--- a/docs/zh/docs/advanced/additional-status-codes.md
+++ b/docs/zh/docs/advanced/additional-status-codes.md
@@ -16,7 +16,7 @@
{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
-/// warning
+/// warning | 警告
当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。
@@ -26,7 +26,7 @@
///
-/// note | 技术细节
+/// note | 注意
你也可以使用 `from starlette.responses import JSONResponse`。
diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md
index 3efca8944..a547e8881 100644
--- a/docs/zh/docs/advanced/advanced-dependencies.md
+++ b/docs/zh/docs/advanced/advanced-dependencies.md
@@ -18,7 +18,7 @@
为此,声明一个 `__call__` 方法:
-{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *}
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
在这种情况下,**FastAPI** 会使用这个 `__call__` 来检查附加参数和子依赖,并且稍后会调用它,把返回值传递给你的*路径操作函数*中的参数。
@@ -26,7 +26,7 @@
现在,我们可以用 `__init__` 声明实例的参数,用来“参数化”这个依赖项:
-{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *}
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
在本例中,**FastAPI** 不会接触或关心 `__init__`,我们会在自己的代码中直接使用它。
@@ -34,7 +34,7 @@
我们可以这样创建该类的实例:
-{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *}
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
这样就把依赖项“参数化”了,现在它内部带有属性 `checker.fixed_content` 的值 `"bar"`。
@@ -50,7 +50,7 @@ checker(q="somequery")
...并将其返回值作为依赖项的值,传给我们的*路径操作函数*中的参数 `fixed_content_included`:
-{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *}
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
/// tip | 提示
diff --git a/docs/zh/docs/advanced/advanced-python-types.md b/docs/zh/docs/advanced/advanced-python-types.md
new file mode 100644
index 000000000..bbc9302e8
--- /dev/null
+++ b/docs/zh/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# 高级 Python 类型 { #advanced-python-types }
+
+这里有一些在使用 Python 类型时可能有用的额外想法。
+
+## 使用 `Union` 或 `Optional` { #using-union-or-optional }
+
+如果你的代码因为某些原因不能使用 `|`,例如它不是在类型注解里,而是在 `response_model=` 之类的参数中,那么你可以使用 `typing` 中的 `Union` 来代替竖线(`|`)。
+
+例如,你可以声明某个值可以是 `str` 或 `None`:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing` 也提供了一个声明“可能为 `None`”的快捷方式:`Optional`。
+
+从我非常主观的角度给个小建议:
+
+- 🚨 避免使用 `Optional[SomeType]`
+- 改用 ✨`Union[SomeType, None]`✨。
+
+两者是等价的,底层其实也是一样的。但我更推荐使用 `Union` 而不是 `Optional`,因为单词“optional”(可选)看起来会暗示该值是可选的,而它真正的含义是“它可以是 `None`”,即使它并不是可选的,仍然是必填的。
+
+我认为 `Union[SomeType, None]` 更能明确表达其含义。
+
+这只是关于词语和命名的问题,但这些词语会影响你和你的队友如何看待代码。
+
+举个例子,看这段函数:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+参数 `name` 被定义为 `Optional[str]`,但它并不是“可选”的,你不能不传这个参数就调用函数:
+
+```Python
+say_hi() # 哎呀,这会报错!😱
+```
+
+参数 `name` 仍然是必填的(不是“可选”),因为它没有默认值。不过,`name` 接受 `None` 作为取值:
+
+```Python
+say_hi(name=None) # 这样可以,None 是有效的 🎉
+```
+
+好消息是,在大多数情况下,你可以直接使用 `|` 来定义类型联合:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+因此,通常你不必为像 `Optional` 和 `Union` 这样的名字而操心。😎
diff --git a/docs/zh/docs/advanced/async-tests.md b/docs/zh/docs/advanced/async-tests.md
index 6803358d2..16b8a8c81 100644
--- a/docs/zh/docs/advanced/async-tests.md
+++ b/docs/zh/docs/advanced/async-tests.md
@@ -32,11 +32,11 @@
文件 `main.py` 将包含:
-{* ../../docs_src/async_tests/app_a_py39/main.py *}
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
文件 `test_main.py` 将包含针对 `main.py` 的测试,现在它可能看起来如下:
-{* ../../docs_src/async_tests/app_a_py39/test_main.py *}
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
## 运行测试 { #run-it }
@@ -56,7 +56,7 @@ $ pytest
这个标记 `@pytest.mark.anyio` 会告诉 pytest 该测试函数应该被异步调用:
-{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[7] *}
+{* ../../docs_src/async_tests/app_a_py310/test_main.py hl[7] *}
/// tip | 提示
@@ -66,7 +66,7 @@ $ pytest
我们现在可以使用应用程序创建一个 `AsyncClient` ,并使用 `await` 向其发送异步请求。
-{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[9:12] *}
+{* ../../docs_src/async_tests/app_a_py310/test_main.py hl[9:12] *}
这相当于:
@@ -74,7 +74,7 @@ $ pytest
response = client.get('/')
```
-我们曾经通过它向 `TestClient` 发出请求。
+...我们曾经通过它向 `TestClient` 发出请求。
/// tip | 提示
diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md
index b44b0b5ac..3ccc65f29 100644
--- a/docs/zh/docs/advanced/behind-a-proxy.md
+++ b/docs/zh/docs/advanced/behind-a-proxy.md
@@ -44,7 +44,7 @@ $ fastapi run --forwarded-allow-ips="*"
例如,假设你定义了一个*路径操作* `/items/`:
-{* ../../docs_src/behind_a_proxy/tutorial001_01_py39.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_01_py310.py hl[6] *}
如果客户端尝试访问 `/items`,默认会被重定向到 `/items/`。
@@ -115,7 +115,7 @@ sequenceDiagram
即使你的所有代码都假设只有 `/app`。
-{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[6] *}
代理会在将请求传递给应用服务器(可能是通过 FastAPI CLI 运行的 Uvicorn)之前,实时**“移除”**这个**路径前缀**,让你的应用认为它是在 `/app` 被服务,这样你就不需要更新所有代码去包含 `/api/v1` 前缀。
@@ -193,7 +193,7 @@ ASGI 规范为这种用例定义了 `root_path`。
这里我们把它包含在响应消息中仅用于演示。
-{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[8] *}
然后,如果你这样启动 Uvicorn:
@@ -220,7 +220,7 @@ $ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
或者,如果你无法提供类似 `--root-path` 的命令行选项,你可以在创建 FastAPI 应用时设置参数 `root_path`:
-{* ../../docs_src/behind_a_proxy/tutorial002_py39.py hl[3] *}
+{* ../../docs_src/behind_a_proxy/tutorial002_py310.py hl[3] *}
把 `root_path` 传给 `FastAPI` 等同于把命令行选项 `--root-path` 传给 Uvicorn 或 Hypercorn。
@@ -400,7 +400,7 @@ $ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
例如:
-{* ../../docs_src/behind_a_proxy/tutorial003_py39.py hl[4:7] *}
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
会生成如下的 OpenAPI 模式:
@@ -455,7 +455,7 @@ OpenAPI 规范中的 `servers` 属性是可选的。
如果你不希望 **FastAPI** 包含一个使用 `root_path` 的自动服务器,可以使用参数 `root_path_in_servers=False`:
-{* ../../docs_src/behind_a_proxy/tutorial004_py39.py hl[9] *}
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
这样它就不会被包含到 OpenAPI 模式中。
diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md
index f5bec5fdc..7c19b73fb 100644
--- a/docs/zh/docs/advanced/custom-response.md
+++ b/docs/zh/docs/advanced/custom-response.md
@@ -30,7 +30,7 @@
但如果你确定你返回的内容是「可以用 JSON 序列化」的,你可以将它直接传给响应类,从而避免在传给响应类之前先通过 `jsonable_encoder` 带来的额外开销。
-{* ../../docs_src/custom_response/tutorial001b_py39.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001b_py310.py hl[2,7] *}
/// info | 信息
@@ -55,7 +55,7 @@
* 导入 `HTMLResponse`。
* 将 `HTMLResponse` 作为你的 *路径操作* 的 `response_class` 参数传入。
-{* ../../docs_src/custom_response/tutorial002_py39.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
/// info | 信息
@@ -73,7 +73,7 @@
和上面一样的例子,返回一个 `HTMLResponse` 看起来可能是这样:
-{* ../../docs_src/custom_response/tutorial003_py39.py hl[2,7,19] *}
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
/// warning | 警告
@@ -97,7 +97,7 @@
比如像这样:
-{* ../../docs_src/custom_response/tutorial004_py39.py hl[7,21,23] *}
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
在这个例子中,函数 `generate_html_response()` 已经生成并返回 `Response` 对象而不是在 `str` 中返回 HTML。
@@ -136,7 +136,7 @@
FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它还将包含一个基于 `media_type` 的 Content-Type 头,并为文本类型附加一个字符集。
-{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
### `HTMLResponse` { #htmlresponse }
@@ -146,7 +146,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
接受文本或字节并返回纯文本响应。
-{* ../../docs_src/custom_response/tutorial005_py39.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
### `JSONResponse` { #jsonresponse }
@@ -180,7 +180,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
///
-{* ../../docs_src/custom_response/tutorial001_py39.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001_py310.py hl[2,7] *}
/// tip | 提示
@@ -194,13 +194,13 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
你可以直接返回一个 `RedirectResponse`:
-{* ../../docs_src/custom_response/tutorial006_py39.py hl[2,9] *}
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
---
或者你可以把它用于 `response_class` 参数:
-{* ../../docs_src/custom_response/tutorial006b_py39.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
如果你这么做,那么你可以在 *路径操作* 函数中直接返回 URL。
@@ -210,13 +210,13 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
你也可以将 `status_code` 参数和 `response_class` 参数结合使用:
-{* ../../docs_src/custom_response/tutorial006c_py39.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
### `StreamingResponse` { #streamingresponse }
采用异步生成器或普通生成器/迭代器,然后流式传输响应主体。
-{* ../../docs_src/custom_response/tutorial007_py39.py hl[2,14] *}
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[2,14] *}
#### 对类似文件的对象使用 `StreamingResponse` { #using-streamingresponse-with-file-like-objects }
@@ -226,7 +226,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
这也包括许多与云存储、视频处理等交互的库。
-{* ../../docs_src/custom_response/tutorial008_py39.py hl[2,10:12,14] *}
+{* ../../docs_src/custom_response/tutorial008_py310.py hl[2,10:12,14] *}
1. 这是生成器函数。之所以是「生成器函数」,是因为它内部包含 `yield` 语句。
2. 通过使用 `with` 代码块,我们可以确保在生成器函数完成后关闭类文件对象。因此,在它完成发送响应之后会被关闭。
@@ -255,11 +255,11 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
文件响应将包含适当的 `Content-Length`、`Last-Modified` 和 `ETag` 响应头。
-{* ../../docs_src/custom_response/tutorial009_py39.py hl[2,10] *}
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
你也可以使用 `response_class` 参数:
-{* ../../docs_src/custom_response/tutorial009b_py39.py hl[2,8,10] *}
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
在这种情况下,你可以在 *路径操作* 函数中直接返回文件路径。
@@ -273,7 +273,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
你可以创建一个 `CustomORJSONResponse`。你需要做的主要事情是实现一个返回 `bytes` 的 `Response.render(content)` 方法:
-{* ../../docs_src/custom_response/tutorial009c_py39.py hl[9:14,17] *}
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
现在,不再是返回:
@@ -281,7 +281,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
{"message": "Hello World"}
```
-…这个响应将返回:
+...这个响应将返回:
```json
{
@@ -299,7 +299,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
在下面的示例中,**FastAPI** 会在所有 *路径操作* 中默认使用 `ORJSONResponse`,而不是 `JSONResponse`。
-{* ../../docs_src/custom_response/tutorial010_py39.py hl[2,4] *}
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
/// tip | 提示
diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md
index d62aef8f3..f552d779f 100644
--- a/docs/zh/docs/advanced/dataclasses.md
+++ b/docs/zh/docs/advanced/dataclasses.md
@@ -59,7 +59,7 @@ FastAPI 基于 **Pydantic** 构建,我已经向你展示过如何使用 Pydant
在本例中,它是一个 `Item` 数据类列表。
6. 这里我们返回一个字典,里面的 `items` 是一个数据类列表。
- FastAPI 仍然能够将数据序列化为 JSON。
+ FastAPI 仍然能够将数据序列化为 JSON。
7. 这里的 `response_model` 使用了 “`Author` 数据类列表” 的类型注解。
同样,你可以将 `dataclasses` 与标准类型注解组合使用。
diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md
index 7b49931a4..71ad1ae38 100644
--- a/docs/zh/docs/advanced/events.md
+++ b/docs/zh/docs/advanced/events.md
@@ -30,7 +30,7 @@
我们使用 `yield` 创建了一个异步函数 `lifespan()` 像这样:
-{* ../../docs_src/events/tutorial003_py39.py hl[16,19] *}
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
在这里,我们在 `yield` 之前将(虚拟的)模型函数放入机器学习模型的字典中,以此模拟加载模型的耗时**启动**操作。这段代码将在应用程序**开始处理请求之前**执行,即**启动**期间。
@@ -48,7 +48,7 @@
首先要注意的是,我们定义了一个带有 `yield` 的异步函数。这与带有 `yield` 的依赖项非常相似。
-{* ../../docs_src/events/tutorial003_py39.py hl[14:19] *}
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
这个函数在 `yield` 之前的部分,会在应用启动前执行。
@@ -60,7 +60,7 @@
它将函数转化为所谓的“**异步上下文管理器**”。
-{* ../../docs_src/events/tutorial003_py39.py hl[1,13] *}
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
在 Python 中,**上下文管理器**是一个你可以在 `with` 语句中使用的东西,例如,`open()` 可以作为上下文管理器使用。
@@ -82,7 +82,7 @@ async with lifespan(app):
`FastAPI` 的 `lifespan` 参数接受一个**异步上下文管理器**,所以我们可以把我们新定义的异步上下文管理器 `lifespan` 传给它。
-{* ../../docs_src/events/tutorial003_py39.py hl[22] *}
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
## 替代事件(弃用) { #alternative-events-deprecated }
@@ -104,7 +104,7 @@ async with lifespan(app):
使用事件 `"startup"` 声明一个在应用启动前运行的函数:
-{* ../../docs_src/events/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
本例中,`startup` 事件处理器函数为项目“数据库”(只是一个 `dict`)提供了一些初始值。
@@ -116,7 +116,7 @@ async with lifespan(app):
使用事件 `"shutdown"` 声明一个在应用关闭时运行的函数:
-{* ../../docs_src/events/tutorial002_py39.py hl[6] *}
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
此处,`shutdown` 事件处理器函数会向文件 `log.txt` 写入一行文本 `"Application shutdown"`。
diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md
index 48a4ba07a..e8a3b2055 100644
--- a/docs/zh/docs/advanced/generate-clients.md
+++ b/docs/zh/docs/advanced/generate-clients.md
@@ -40,7 +40,7 @@ FastAPI 会自动生成 **OpenAPI 3.1** 规范,因此你使用的任何工具
先从一个简单的 FastAPI 应用开始:
-{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *}
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
请注意,这些*路径操作*使用 `Item` 和 `ResponseMessage` 模型来定义它们的请求载荷和响应载荷。
@@ -98,7 +98,7 @@ npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
例如,你可以有一个 **items** 相关的部分和另一个 **users** 相关的部分,它们可以用标签来分隔:
-{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *}
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
### 生成带标签的 TypeScript 客户端 { #generate-a-typescript-client-with-tags }
@@ -121,7 +121,7 @@ npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
```
-……这是因为客户端生成器会把每个*路径操作*的 OpenAPI 内部**操作 ID(operation ID)**用作方法名的一部分。
+...这是因为客户端生成器会把每个*路径操作*的 OpenAPI 内部**操作 ID(operation ID)**用作方法名的一部分。
OpenAPI 要求每个操作 ID 在所有*路径操作*中都是唯一的,因此 FastAPI 会使用**函数名**、**路径**和**HTTP 方法/操作**来生成操作 ID,以确保其唯一性。
@@ -145,7 +145,7 @@ FastAPI 为每个*路径操作*使用一个**唯一 ID**,它既用于**操作
然后你可以把这个自定义函数通过 `generate_unique_id_function` 参数传给 **FastAPI**:
-{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *}
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
### 使用自定义操作 ID 生成 TypeScript 客户端 { #generate-a-typescript-client-with-custom-operation-ids }
@@ -167,7 +167,7 @@ FastAPI 为每个*路径操作*使用一个**唯一 ID**,它既用于**操作
我们可以把 OpenAPI JSON 下载到 `openapi.json` 文件中,然后用如下脚本**移除这个标签前缀**:
-{* ../../docs_src/generate_clients/tutorial004_py39.py *}
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
//// tab | Node.js
diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md
index 108bbbb5c..de4a3fcb1 100644
--- a/docs/zh/docs/advanced/middleware.md
+++ b/docs/zh/docs/advanced/middleware.md
@@ -43,7 +43,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
**FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。
-/// note | 注意
+/// note | 技术细节
以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。
@@ -57,13 +57,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
任何传向 `http` 或 `ws` 的请求都会被重定向至安全方案。
-{* ../../docs_src/advanced_middleware/tutorial001_py39.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial001_py310.py hl[2,6] *}
## `TrustedHostMiddleware` { #trustedhostmiddleware }
强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。
-{* ../../docs_src/advanced_middleware/tutorial002_py39.py hl[2,6:8] *}
+{* ../../docs_src/advanced_middleware/tutorial002_py310.py hl[2,6:8] *}
支持以下参数:
@@ -78,7 +78,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
中间件会处理标准响应与流响应。
-{* ../../docs_src/advanced_middleware/tutorial003_py39.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial003_py310.py hl[2,6] *}
支持以下参数:
diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md
index 6e8df68ae..cc9f5c28e 100644
--- a/docs/zh/docs/advanced/openapi-callbacks.md
+++ b/docs/zh/docs/advanced/openapi-callbacks.md
@@ -179,7 +179,7 @@ JSON 请求体包含如下内容:
### 查看文档 { #check-the-docs }
-现在,使用 Uvicorn 启动应用,打开 http://127.0.0.1:8000/docs。
+现在,启动应用并打开 http://127.0.0.1:8000/docs。
就能看到文档的*路径操作*已经包含了**回调**的内容以及*外部 API*:
diff --git a/docs/zh/docs/advanced/openapi-webhooks.md b/docs/zh/docs/advanced/openapi-webhooks.md
index 9e64ed4e3..d23fbcf88 100644
--- a/docs/zh/docs/advanced/openapi-webhooks.md
+++ b/docs/zh/docs/advanced/openapi-webhooks.md
@@ -32,7 +32,7 @@
当您创建一个 **FastAPI** 应用程序时,有一个 `webhooks` 属性可以用来定义网络钩子,方式与您定义*路径操作*的时候相同,例如使用 `@app.webhooks.post()` 。
-{* ../../docs_src/openapi_webhooks/tutorial001_py39.py hl[9:13,36:53] *}
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
您定义的网络钩子将被包含在 `OpenAPI` 的架构中,并出现在自动生成的**文档 UI** 中。
diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md
index 6c9928ffc..588d4f09c 100644
--- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md
@@ -12,7 +12,7 @@
务必确保每个操作的 `operation_id` 都是唯一的。
-{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
### 使用 *路径操作函数* 的函数名作为 operationId { #using-the-path-operation-function-name-as-the-operationid }
@@ -20,7 +20,7 @@
你应该在添加了所有 *路径操作* 之后执行此操作。
-{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py39.py hl[2, 12:21, 24] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
/// tip
@@ -40,7 +40,7 @@
使用参数 `include_in_schema` 并将其设置为 `False`,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了):
-{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
## 来自 docstring 的高级描述 { #advanced-description-from-docstring }
@@ -92,7 +92,7 @@
例如,这个 `openapi_extra` 可用于声明 [OpenAPI 扩展](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
-{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py39.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
当你打开自动 API 文档时,你的扩展会显示在该 *路径操作* 的底部。
@@ -139,9 +139,9 @@
你可以用 `openapi_extra` 来做到:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py39.py hl[19:36, 39:40] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
-在这个示例中,我们没有声明任何 Pydantic 模型。事实上,请求体甚至没有被 解析 为 JSON,而是直接以 `bytes` 读取,并由函数 `magic_data_reader()` 以某种方式负责解析。
+在这个示例中,我们没有声明任何 Pydantic 模型。事实上,请求体甚至没有被 解析 为 JSON,而是直接以 `bytes` 读取,并由函数 `magic_data_reader()` 以某种方式负责解析。
尽管如此,我们仍然可以声明请求体的预期方案。
@@ -153,7 +153,7 @@
例如,在这个应用中我们不使用 FastAPI 集成的从 Pydantic 模型提取 JSON Schema 的功能,也不使用对 JSON 的自动校验。实际上,我们将请求的内容类型声明为 YAML,而不是 JSON:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[15:20, 22] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
尽管我们没有使用默认的集成功能,我们仍然使用 Pydantic 模型手动生成我们想以 YAML 接收的数据的 JSON Schema。
@@ -161,7 +161,7 @@
接着在我们的代码中,我们直接解析该 YAML 内容,然后再次使用同一个 Pydantic 模型来验证该 YAML 内容:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[24:31] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
/// tip
diff --git a/docs/zh/docs/advanced/response-change-status-code.md b/docs/zh/docs/advanced/response-change-status-code.md
index cdcd39f50..0b004bf4e 100644
--- a/docs/zh/docs/advanced/response-change-status-code.md
+++ b/docs/zh/docs/advanced/response-change-status-code.md
@@ -20,9 +20,11 @@
然后你可以在这个*临时*响应对象中设置`status_code`。
-{* ../../docs_src/response_change_status_code/tutorial001_py39.py hl[1,9,12] *}
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
-然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。
+然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。
+
+如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。
**FastAPI**将使用这个*临时*响应来提取状态码(也包括cookies和头部),并将它们放入包含你返回的值的最终响应中,该响应由任何`response_model`过滤。
diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md
index cc311a270..c618cd0f0 100644
--- a/docs/zh/docs/advanced/response-cookies.md
+++ b/docs/zh/docs/advanced/response-cookies.md
@@ -4,7 +4,7 @@
你可以在 *路径操作函数* 中定义一个类型为 `Response` 的参数,这样你就可以在这个临时响应对象中设置cookie了。
-{* ../../docs_src/response_cookies/tutorial002_py39.py hl[1, 8:9] *}
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。
@@ -22,9 +22,9 @@
然后设置Cookies,并返回:
-{* ../../docs_src/response_cookies/tutorial001_py39.py hl[10:12] *}
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
-/// tip
+/// tip | 提示
需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。
diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md
index 8a9cf6ab8..a97992d24 100644
--- a/docs/zh/docs/advanced/response-directly.md
+++ b/docs/zh/docs/advanced/response-directly.md
@@ -36,7 +36,7 @@
{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
-/// note | 注意
+/// note | 技术细节
你也可以使用 `from starlette.responses import JSONResponse`。
@@ -54,7 +54,7 @@
你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回:
-{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
## 说明 { #notes }
diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md
index fa02f53be..01bde56d2 100644
--- a/docs/zh/docs/advanced/response-headers.md
+++ b/docs/zh/docs/advanced/response-headers.md
@@ -6,13 +6,13 @@
然后你可以在这个*临时*响应对象中设置头部。
-{* ../../docs_src/response_headers/tutorial002_py39.py hl[1, 7:8] *}
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
然后你可以像平常一样返回任何你需要的对象(例如一个 `dict` 或者一个数据库模型)。
如果你声明了一个 `response_model`,它仍然会被用来过滤和转换你返回的对象。
-**FastAPI** 将使用这个临时响应来提取头部(也包括 cookies 和状态码),并将它们放入包含你返回的值的最终响应中,该响应由任何 `response_model` 过滤。
+**FastAPI** 将使用这个*临时*响应来提取头部(也包括 cookies 和状态码),并将它们放入包含你返回的值的最终响应中,该响应由任何 `response_model` 过滤。
你也可以在依赖项中声明 `Response` 参数,并在其中设置头部(和 cookies)。
@@ -22,7 +22,7 @@
按照[直接返回响应](response-directly.md){.internal-link target=_blank}中所述创建响应,并将头部作为附加参数传递:
-{* ../../docs_src/response_headers/tutorial001_py39.py hl[10:12] *}
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
/// note | 技术细节
diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md
index 55479d8e3..9128a4975 100644
--- a/docs/zh/docs/advanced/security/http-basic-auth.md
+++ b/docs/zh/docs/advanced/security/http-basic-auth.md
@@ -20,7 +20,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。
* 返回类型为 `HTTPBasicCredentials` 的对象:
* 包含发送的 `username` 与 `password`
-{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *}
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码:
@@ -40,7 +40,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。
然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。
-{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *}
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
这类似于:
@@ -104,4 +104,4 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加响应头 `WWW-Authenticate`,让浏览器再次显示登录提示:
-{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *}
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md
index adf264491..b4def73eb 100644
--- a/docs/zh/docs/advanced/settings.md
+++ b/docs/zh/docs/advanced/settings.md
@@ -54,7 +54,7 @@ $ pip install "fastapi[all]"
你可以使用与 Pydantic 模型相同的验证功能和工具,例如不同的数据类型,以及使用 `Field()` 进行附加验证。
-{* ../../docs_src/settings/tutorial001_py39.py hl[2,5:8,11] *}
+{* ../../docs_src/settings/tutorial001_py310.py hl[2,5:8,11] *}
/// tip | 提示
@@ -70,7 +70,7 @@ $ pip install "fastapi[all]"
然后你可以在应用中使用新的 `settings` 对象:
-{* ../../docs_src/settings/tutorial001_py39.py hl[18:20] *}
+{* ../../docs_src/settings/tutorial001_py310.py hl[18:20] *}
### 运行服务器 { #run-the-server }
@@ -100,19 +100,19 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.p
## 在另一个模块中放置设置 { #settings-in-another-module }
-你可以把这些设置放在另一个模块文件中,就像你在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。
+你可以把这些设置放在另一个模块文件中,就像你在[更大的应用 - 多个文件](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。
例如,可以有一个 `config.py` 文件:
-{* ../../docs_src/settings/app01_py39/config.py *}
+{* ../../docs_src/settings/app01_py310/config.py *}
然后在 `main.py` 文件中使用它:
-{* ../../docs_src/settings/app01_py39/main.py hl[3,11:13] *}
+{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}
/// tip | 提示
-你还需要一个 `__init__.py` 文件,就像你在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。
+你还需要一个 `__init__.py` 文件,就像你在[更大的应用 - 多个文件](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。
///
@@ -126,7 +126,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.p
延续上一个示例,你的 `config.py` 文件可能如下所示:
-{* ../../docs_src/settings/app02_an_py39/config.py hl[10] *}
+{* ../../docs_src/settings/app02_an_py310/config.py hl[10] *}
注意,现在我们不再创建默认实例 `settings = Settings()`。
@@ -134,7 +134,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.p
现在我们创建一个依赖项,返回一个新的 `config.Settings()`。
-{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *}
+{* ../../docs_src/settings/app02_an_py310/main.py hl[6,12:13] *}
/// tip | 提示
@@ -144,15 +144,15 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.p
///
-然后我们可以在“路径操作函数”中将其作为依赖项引入,并在需要的任何地方使用它。
+然后我们可以在路径操作函数中将其作为依赖项引入,并在需要的任何地方使用它。
-{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *}
+{* ../../docs_src/settings/app02_an_py310/main.py hl[17,19:21] *}
### 设置与测试 { #settings-and-testing }
接着,在测试期间,通过为 `get_settings` 创建依赖项覆盖,就可以很容易地提供一个不同的设置对象:
-{* ../../docs_src/settings/app02_an_py39/test_main.py hl[9:10,13,21] *}
+{* ../../docs_src/settings/app02_an_py310/test_main.py hl[9:10,13,21] *}
在依赖项覆盖中,我们在创建新的 `Settings` 对象时为 `admin_email` 设置了一个新值,然后返回该新对象。
@@ -193,7 +193,7 @@ APP_NAME="ChimichangApp"
然后更新 `config.py`:
-{* ../../docs_src/settings/app03_an_py39/config.py hl[9] *}
+{* ../../docs_src/settings/app03_an_py310/config.py hl[9] *}
/// tip | 提示
@@ -226,7 +226,7 @@ def get_settings():
但由于我们在顶部使用了 `@lru_cache` 装饰器,`Settings` 对象只会在第一次调用时创建一次。 ✔️
-{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *}
+{* ../../docs_src/settings/app03_an_py310/main.py hl[1,11] *}
接着,对于后续请求中依赖项里对 `get_settings()` 的任何调用,它不会再次执行 `get_settings()` 的内部代码并创建新的 `Settings` 对象,而是会一遍又一遍地返回第一次调用时返回的那个相同对象。
diff --git a/docs/zh/docs/advanced/sub-applications.md b/docs/zh/docs/advanced/sub-applications.md
index fe1fcd121..3e61610a3 100644
--- a/docs/zh/docs/advanced/sub-applications.md
+++ b/docs/zh/docs/advanced/sub-applications.md
@@ -10,7 +10,7 @@
首先,创建主(顶层)**FastAPI** 应用及其*路径操作*:
-{* ../../docs_src/sub_applications/tutorial001_py39.py hl[3, 6:8] *}
+{* ../../docs_src/sub_applications/tutorial001_py310.py hl[3, 6:8] *}
### 子应用 { #sub-application }
@@ -18,7 +18,7 @@
子应用只是另一个标准 FastAPI 应用,但这个应用是被**挂载**的应用:
-{* ../../docs_src/sub_applications/tutorial001_py39.py hl[11, 14:16] *}
+{* ../../docs_src/sub_applications/tutorial001_py310.py hl[11, 14:16] *}
### 挂载子应用 { #mount-the-sub-application }
@@ -26,7 +26,7 @@
本例的子应用挂载在 `/subapi` 路径下:
-{* ../../docs_src/sub_applications/tutorial001_py39.py hl[11, 19] *}
+{* ../../docs_src/sub_applications/tutorial001_py310.py hl[11, 19] *}
### 查看自动 API 文档 { #check-the-automatic-api-docs }
diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md
index f2e5c21cf..37575aff2 100644
--- a/docs/zh/docs/advanced/templates.md
+++ b/docs/zh/docs/advanced/templates.md
@@ -27,7 +27,7 @@ $ pip install jinja2
* 在返回模板的*路径操作*中声明 `Request` 参数
* 使用 `templates` 渲染并返回 `TemplateResponse`,传递模板的名称、request 对象以及一个包含多个键值对(用于 Jinja2 模板)的 "context" 字典。
-{* ../../docs_src/templates/tutorial001_py39.py hl[4,11,15:18] *}
+{* ../../docs_src/templates/tutorial001_py310.py hl[4,11,15:18] *}
/// note
diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md
index db0b39483..3291cfc25 100644
--- a/docs/zh/docs/advanced/testing-dependencies.md
+++ b/docs/zh/docs/advanced/testing-dependencies.md
@@ -46,7 +46,6 @@ FastAPI 可以覆盖这些位置的依赖项。
app.dependency_overrides = {}
```
-
/// tip | 提示
如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。
diff --git a/docs/zh/docs/advanced/testing-events.md b/docs/zh/docs/advanced/testing-events.md
index 221984e90..90cbbda13 100644
--- a/docs/zh/docs/advanced/testing-events.md
+++ b/docs/zh/docs/advanced/testing-events.md
@@ -2,10 +2,10 @@
当你需要在测试中运行 `lifespan` 时,可以将 `TestClient` 与 `with` 语句一起使用:
-{* ../../docs_src/app_testing/tutorial004_py39.py hl[9:15,18,27:28,30:32,41:43] *}
+{* ../../docs_src/app_testing/tutorial004_py310.py hl[9:15,18,27:28,30:32,41:43] *}
你可以在[官方 Starlette 文档站点的“在测试中运行 lifespan”](https://www.starlette.dev/lifespan/#running-lifespan-in-tests)阅读更多细节。
对于已弃用的 `startup` 和 `shutdown` 事件,可以按如下方式使用 `TestClient`:
-{* ../../docs_src/app_testing/tutorial003_py39.py hl[9:12,20:24] *}
+{* ../../docs_src/app_testing/tutorial003_py310.py hl[9:12,20:24] *}
diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md
index 64e1d3005..e435e41e2 100644
--- a/docs/zh/docs/advanced/testing-websockets.md
+++ b/docs/zh/docs/advanced/testing-websockets.md
@@ -4,7 +4,7 @@
为此,在 `with` 语句中使用 `TestClient` 连接到 WebSocket:
-{* ../../docs_src/app_testing/tutorial002_py39.py hl[27:31] *}
+{* ../../docs_src/app_testing/tutorial002_py310.py hl[27:31] *}
/// note | 注意
diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md
index 64ba8da1b..8cfad4203 100644
--- a/docs/zh/docs/advanced/using-request-directly.md
+++ b/docs/zh/docs/advanced/using-request-directly.md
@@ -29,7 +29,7 @@
此时,需要直接访问请求。
-{* ../../docs_src/using_request_directly/tutorial001_py39.py hl[1,7:8] *}
+{* ../../docs_src/using_request_directly/tutorial001_py310.py hl[1,7:8] *}
把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。
diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md
index 4486a2e69..513e1aaec 100644
--- a/docs/zh/docs/advanced/websockets.md
+++ b/docs/zh/docs/advanced/websockets.md
@@ -38,13 +38,13 @@ $ pip install websockets
但这是一种专注于 WebSockets 的服务器端并提供一个工作示例的最简单方式:
-{* ../../docs_src/websockets/tutorial001_py39.py hl[2,6:38,41:43] *}
+{* ../../docs_src/websockets/tutorial001_py310.py hl[2,6:38,41:43] *}
## 创建 `websocket` { #create-a-websocket }
在您的 **FastAPI** 应用程序中,创建一个 `websocket`:
-{* ../../docs_src/websockets/tutorial001_py39.py hl[1,46:47] *}
+{* ../../docs_src/websockets/tutorial001_py310.py hl[1,46:47] *}
/// note | 技术细节
@@ -58,7 +58,7 @@ $ pip install websockets
在您的 WebSocket 路由中,您可以使用 `await` 等待消息并发送消息。
-{* ../../docs_src/websockets/tutorial001_py39.py hl[48:52] *}
+{* ../../docs_src/websockets/tutorial001_py310.py hl[48:52] *}
您可以接收和发送二进制、文本和 JSON 数据。
@@ -154,7 +154,7 @@ $ fastapi dev main.py
当 WebSocket 连接关闭时,`await websocket.receive_text()` 将引发 `WebSocketDisconnect` 异常,您可以捕获并处理该异常,就像本示例中的示例一样。
-{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *}
+{* ../../docs_src/websockets/tutorial003_py310.py hl[79:81] *}
尝试以下操作:
diff --git a/docs/zh/docs/advanced/wsgi.md b/docs/zh/docs/advanced/wsgi.md
index 73fcb3219..487fbf8dd 100644
--- a/docs/zh/docs/advanced/wsgi.md
+++ b/docs/zh/docs/advanced/wsgi.md
@@ -18,7 +18,7 @@
之后将其挂载到某一个路径下。
-{* ../../docs_src/wsgi/tutorial001_py39.py hl[1,3,23] *}
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
/// note | 注意
diff --git a/docs/zh/docs/alternatives.md b/docs/zh/docs/alternatives.md
new file mode 100644
index 000000000..8a552c91d
--- /dev/null
+++ b/docs/zh/docs/alternatives.md
@@ -0,0 +1,482 @@
+# 替代方案、灵感与对比 { #alternatives-inspiration-and-comparisons }
+
+是什么启发了 **FastAPI**,它与替代方案的比较,以及它从中学到的东西。
+
+## 介绍 { #intro }
+
+没有前人的工作,就不会有 **FastAPI**。
+
+在它诞生之前,已经有许多工具为其提供了灵感。
+
+我曾经多年避免创建一个新框架。起初,我尝试用许多不同的框架、插件和工具来解决 **FastAPI** 所覆盖的全部功能。
+
+但在某个时刻,除了创造一个能提供所有这些功能的东西之外,别无选择;它要吸收以往工具的最佳理念,并以尽可能好的方式组合起来,利用之前都不存在的语言特性(Python 3.6+ 类型提示)。
+
+## 先前的工具 { #previous-tools }
+
+### Django { #django }
+
+它是最流行且被广泛信任的 Python 框架。被用于构建 Instagram 等系统。
+
+它与关系型数据库(如 MySQL、PostgreSQL)耦合相对紧密,因此若要以 NoSQL 数据库(如 Couchbase、MongoDB、Cassandra 等)作为主要存储引擎并不容易。
+
+它最初用于在后端生成 HTML,而不是创建由现代前端(如 React、Vue.js、Angular)或与之通信的其他系统(如 IoT 设备)使用的 API。
+
+### Django REST Framework { #django-rest-framework }
+
+Django REST framework 作为一个灵活工具箱而创建,用于在底层使用 Django 构建 Web API,从而增强其 API 能力。
+
+它被包括 Mozilla、Red Hat、Eventbrite 在内的许多公司使用。
+
+它是最早的“自动 API 文档”的范例之一,这正是启发“寻找” **FastAPI** 的最初想法之一。
+
+/// note | 注意
+
+Django REST Framework 由 Tom Christie 创建。他也是 Starlette 和 Uvicorn 的作者,**FastAPI** 就是基于它们构建的。
+
+///
+
+/// check | 启发 **FastAPI**:
+
+提供自动化的 API 文档 Web 界面。
+
+///
+
+### Flask { #flask }
+
+Flask 是一个“微框架”,它不包含数据库集成,也没有像 Django 那样的许多默认内建功能。
+
+这种简单与灵活使得可以将 NoSQL 数据库作为主要的数据存储系统。
+
+由于非常简单,它相对直观易学,尽管文档在某些部分略显偏技术。
+
+它也常用于不一定需要数据库、用户管理,或任何 Django 预构建功能的应用;当然,许多这类功能可以通过插件添加。
+
+这种组件解耦、可按需扩展的“微框架”特性,是我想保留的关键点。
+
+鉴于 Flask 的简洁,它似乎非常适合构建 API。接下来要找的,就是 Flask 版的 “Django REST Framework”。
+
+/// check | 启发 **FastAPI**:
+
+- 成为微框架,便于按需组合所需的工具与组件。
+- 提供简单易用的路由系统。
+
+///
+
+### Requests { #requests }
+
+**FastAPI** 实际上不是 **Requests** 的替代品。它们的作用范围完全不同。
+
+在 FastAPI 应用程序内部使用 Requests 其实非常常见。
+
+尽管如此,FastAPI 依然从 Requests 中获得了不少灵感。
+
+**Requests** 是一个用于与 API 交互(作为客户端)的库,而 **FastAPI** 是一个用于构建 API(作为服务端)的库。
+
+它们处在某种意义上的“对立端”,彼此互补。
+
+Requests 设计非常简单直观,易于使用,且有合理的默认值。同时它也非常强大、可定制。
+
+这就是为什么,正如其官网所说:
+
+> Requests 是有史以来下载量最高的 Python 包之一
+
+它的用法非常简单。例如,进行一次 `GET` 请求,你会这样写:
+
+```Python
+response = requests.get("http://example.com/some/url")
+```
+
+对应地,FastAPI 的 API 路径操作可能看起来是这样的:
+
+```Python hl_lines="1"
+@app.get("/some/url")
+def read_url():
+ return {"message": "Hello World"}
+```
+
+可以看到 `requests.get(...)` 与 `@app.get(...)` 的相似之处。
+
+/// check | 启发 **FastAPI**:
+
+- 提供简单直观的 API。
+- 直接、自然地使用 HTTP 方法名(操作)。
+- 具备合理默认值,同时支持强大定制能力。
+
+///
+
+### Swagger / OpenAPI { #swagger-openapi }
+
+我想从 Django REST Framework 得到的主要特性之一是自动 API 文档。
+
+随后我发现有一个用于用 JSON(或 YAML,JSON 的扩展)来描述 API 的标准,称为 Swagger。
+
+并且已经有了用于 Swagger API 的 Web 用户界面。因此,只要能为 API 生成 Swagger 文档,就能自动使用这个 Web 界面。
+
+后来,Swagger 交由 Linux 基金会管理,并更名为 OpenAPI。
+
+因此,在谈到 2.0 版本时人们常说 “Swagger”,而 3+ 版本则称为 “OpenAPI”。
+
+/// check | 启发 **FastAPI**:
+
+采用并使用开放的 API 规范标准,而非自定义模式。
+
+并集成基于标准的用户界面工具:
+
+- Swagger UI
+- ReDoc
+
+选择这两者是因为它们相当流行且稳定;但稍作搜索,你就能找到数十种 OpenAPI 的替代用户界面(都可以与 **FastAPI** 搭配使用)。
+
+///
+
+### Flask REST 框架 { #flask-rest-frameworks }
+
+有若干基于 Flask 的 REST 框架,但在投入时间精力深入调研后,我发现许多已停止维护或被弃用,并存在多处未解决问题,不太适合采用。
+
+### Marshmallow { #marshmallow }
+
+API 系统所需的主要特性之一是数据“序列化”,即将代码(Python)中的数据转换为可通过网络发送的形式。例如,将包含数据库数据的对象转换为 JSON 对象、将 `datetime` 对象转换为字符串等。
+
+API 的另一个重要特性是数据校验,确保数据在给定约束下是有效的。例如,某个字段必须是 `int` 而不是任意字符串。这对传入数据尤其有用。
+
+没有数据校验系统的话,你就得在代码里手写所有检查。
+
+这些正是 Marshmallow 要提供的功能。它是个很棒的库,我之前大量使用过。
+
+但它诞生于 Python 类型提示出现之前。因此,定义每个模式都需要使用 Marshmallow 提供的特定工具和类。
+
+/// check | 启发 **FastAPI**:
+
+使用代码定义“模式”,自动提供数据类型与校验。
+
+///
+
+### Webargs { #webargs }
+
+API 的另一个重要需求是从传入请求中解析数据。
+
+Webargs 是一个在多个框架(包括 Flask)之上提供该功能的工具。
+
+它在底层使用 Marshmallow 进行数据校验,并且由相同的开发者创建。
+
+在拥有 **FastAPI** 之前,我也大量使用过它,这是个很棒的工具。
+
+/// info | 信息
+
+Webargs 由与 Marshmallow 相同的开发者创建。
+
+///
+
+/// check | 启发 **FastAPI**:
+
+对传入请求数据进行自动校验。
+
+///
+
+### APISpec { #apispec }
+
+Marshmallow 与 Webargs 通过插件提供了校验、解析与序列化。
+
+但文档仍然缺失,于是出现了 APISpec。
+
+它为许多框架提供插件(Starlette 也有插件)。
+
+它的工作方式是:你在处理路由的每个函数的文档字符串里,用 YAML 格式编写模式定义。
+
+然后它会生成 OpenAPI 模式。
+
+这正是它在 Flask、Starlette、Responder 等框架里的工作方式。
+
+但这样我们又回到了在 Python 字符串中维护一套“微语法”(一大段 YAML)的问题上。
+
+编辑器很难为此提供帮助;而且如果我们修改了参数或 Marshmallow 模式,却忘了同步更新那个 YAML 文档字符串,生成的模式就会过时。
+
+/// info | 信息
+
+APISpec 由与 Marshmallow 相同的开发者创建。
+
+///
+
+/// check | 启发 **FastAPI**:
+
+支持开放的 API 标准 OpenAPI。
+
+///
+
+### Flask-apispec { #flask-apispec }
+
+这是一个 Flask 插件,将 Webargs、Marshmallow 与 APISpec 结合在一起。
+
+它利用 Webargs 与 Marshmallow 的信息,通过 APISpec 自动生成 OpenAPI 模式。
+
+这是个很棒却被低估的工具;它理应比许多 Flask 插件更流行。或许是因为它的文档过于简洁与抽象。
+
+这解决了在 Python 文档字符串里书写 YAML(另一套语法)的问题。
+
+在构建 **FastAPI** 之前,Flask + Flask-apispec + Marshmallow + Webargs 的组合是我最喜欢的后端技术栈。
+
+使用它促成了若干 Flask 全栈脚手架的诞生。以下是我(以及若干外部团队)至今使用的主要技术栈:
+
+* https://github.com/tiangolo/full-stack
+* https://github.com/tiangolo/full-stack-flask-couchbase
+* https://github.com/tiangolo/full-stack-flask-couchdb
+
+这些全栈脚手架也成为了[**FastAPI** 项目脚手架](project-generation.md){.internal-link target=_blank}的基础。
+
+/// info | 信息
+
+Flask-apispec 由与 Marshmallow 相同的开发者创建。
+
+///
+
+/// check | 启发 **FastAPI**:
+
+从定义序列化与校验的同一份代码自动生成 OpenAPI 模式。
+
+///
+
+### NestJS(以及 Angular) { #nestjs-and-angular }
+
+这甚至不是 Python。NestJS 是一个 JavaScript(TypeScript)的 NodeJS 框架,受 Angular 启发。
+
+它实现了与 Flask-apispec 有些类似的效果。
+
+它集成了受 Angular 2 启发的依赖注入系统。与我所知的其他依赖注入系统一样,需要预先注册“可注入项”,因此会增加冗长与重复。
+
+由于参数用 TypeScript 类型描述(类似 Python 类型提示),编辑器支持相当好。
+
+但由于 TypeScript 的类型在编译为 JavaScript 后不会保留,无法只依赖这些类型同时定义校验、序列化与文档。受此以及一些设计决策影响,为了获得校验、序列化与自动 schema 生成,需要在许多位置添加装饰器,因此代码会相当冗长。
+
+它对嵌套模型的支持并不好。如果请求的 JSON 体是包含嵌套 JSON 对象的 JSON 对象,则无法被正确文档化和校验。
+
+/// check | 启发 **FastAPI**:
+
+使用 Python 类型以获得出色的编辑器支持。
+
+拥有强大的依赖注入系统,并设法尽量减少代码重复。
+
+///
+
+### Sanic { #sanic }
+
+它是最早的一批基于 `asyncio` 的极速 Python 框架之一,且做得与 Flask 很相似。
+
+/// note | 技术细节
+
+它使用了 `uvloop` 来替代 Python 默认的 `asyncio` 循环。这正是它如此之快的原因。
+
+它显然启发了 Uvicorn 和 Starlette;在公开的基准测试中,它们目前比 Sanic 更快。
+
+///
+
+/// check | 启发 **FastAPI**:
+
+找到实现疯狂性能的路径。
+
+这就是 **FastAPI** 基于 Starlette 的原因,因为它是目前可用的最快框架(由第三方基准测试验证)。
+
+///
+
+### Falcon { #falcon }
+
+Falcon 是另一个高性能 Python 框架,它被设计为精简且可作为 Hug 等其他框架的基础。
+
+它设计为接收两个参数的函数:一个“request”和一个“response”。然后从 request 中“读取”,向 response 中“写入”。由于这种设计,无法用标准的 Python 类型提示将请求参数和请求体声明为函数形参。
+
+因此,数据校验、序列化与文档要么需要手写完成,无法自动化;要么需要在 Falcon 之上实现一个框架,例如 Hug。其他受 Falcon 设计启发、采用“一个 request 对象 + 一个 response 对象作为参数”的框架也有同样的区别。
+
+/// check | 启发 **FastAPI**:
+
+寻找获得卓越性能的方法。
+
+与 Hug(Hug 基于 Falcon)一起,启发 **FastAPI** 在函数中声明一个 `response` 参数。尽管在 FastAPI 中它是可选的,主要用于设置 headers、cookies 和可选的状态码。
+
+///
+
+### Molten { #molten }
+
+我在构建 **FastAPI** 的早期阶段发现了 Molten。它有不少相似的想法:
+
+* 基于 Python 类型提示。
+* 从这些类型获得校验与文档。
+* 依赖注入系统。
+
+它没有使用像 Pydantic 这样的第三方数据校验、序列化与文档库,而是有自己的实现。因此这些数据类型定义不太容易在其他地方复用。
+
+它需要稍微冗长一些的配置。并且由于基于 WSGI(而非 ASGI),它并未设计为充分利用 Uvicorn、Starlette、Sanic 等工具所提供的高性能。
+
+其依赖注入系统需要预先注册依赖,且依赖根据声明的类型来解析。因此无法为同一类型声明多于一个“组件”。
+
+路由在一个地方集中声明,使用在其他地方声明的函数(而不是使用可以直接放在处理端点函数之上的装饰器)。这更接近 Django 的做法,而不是 Flask(和 Starlette)。它在代码中割裂了相对紧耦合的内容。
+
+/// check | 启发 **FastAPI**:
+
+通过模型属性的“默认值”为数据类型定义额外校验。这提升了编辑器支持,而这在当时的 Pydantic 中尚不可用。
+
+这实际上促成了对 Pydantic 的部分更新,以支持这种校验声明风格(这些功能现已在 Pydantic 中可用)。
+
+///
+
+### Hug { #hug }
+
+Hug 是最早使用 Python 类型提示来声明 API 参数类型的框架之一。这一绝妙想法也启发了其他工具。
+
+它在声明中使用自定义类型而不是标准的 Python 类型,但这依然是巨大的进步。
+
+它也是最早生成一个自定义 JSON 模式来声明整个 API 的框架之一。
+
+它并不基于 OpenAPI 与 JSON Schema 这类标准。因此与其他工具(如 Swagger UI)的集成并非一帆风顺。但它仍是非常有创新性的想法。
+
+它有一个有趣且少见的特性:使用同一框架,可以同时创建 API 与 CLI。
+
+由于基于同步 Python Web 框架的上一代标准(WSGI),它无法处理 WebSocket 等,尽管它的性能仍然很高。
+
+/// info | 信息
+
+Hug 由 Timothy Crosley 创建,他也是 `isort` 的作者,这是一个能自动排序 Python 文件中导入的优秀工具。
+
+///
+
+/// check | 启发 **FastAPI** 的想法:
+
+Hug 启发了 APIStar 的部分设计,也是我当时最看好的工具之一,与 APIStar 并列。
+
+Hug 促使 **FastAPI** 使用 Python 类型提示来声明参数,并自动生成定义整个 API 的模式。
+
+Hug 启发 **FastAPI** 在函数中声明 `response` 参数,用于设置 headers 与 cookies。
+
+///
+
+### APIStar (<= 0.5) { #apistar-0-5 }
+
+就在决定动手构建 **FastAPI** 之前,我找到了 **APIStar** 服务器。它几乎具备我想要的一切,设计也很出色。
+
+在我见过的框架中,它是最早使用 Python 类型提示来声明参数和请求的实现之一(早于 NestJS 与 Molten)。我与 Hug 几乎同时发现了它。但 APIStar 使用了 OpenAPI 标准。
+
+它基于相同的类型提示,在多处自动进行数据校验、序列化并生成 OpenAPI 模式。
+
+请求体模式定义并未使用与 Pydantic 相同的 Python 类型提示,它更接近 Marshmallow,因此编辑器支持不如 Pydantic 好,但即便如此,APIStar 仍是当时可用的最佳选择。
+
+它在当时拥有最好的性能基准(仅被 Starlette 超越)。
+
+起初它没有自动 API 文档 Web 界面,但我知道我可以把 Swagger UI 加进去。
+
+它有一个依赖注入系统。与上文提到的其他工具一样,需要预先注册组件。但这依然是很棒的特性。
+
+我从未在完整项目中使用过它,因为它没有安全集成,因此我无法用它替代基于 Flask-apispec 的全栈脚手架所具备的全部功能。我曾把“提交一个增加该功能的 PR”放在了待办里。
+
+但随后,项目的重心发生了变化。
+
+它不再是一个 API Web 框架,因为作者需要专注于 Starlette。
+
+现在 APIStar 是一组用于校验 OpenAPI 规范的工具,而不是 Web 框架。
+
+/// info | 信息
+
+APIStar 由 Tom Christie 创建。他还创建了:
+
+* Django REST Framework
+* Starlette(**FastAPI** 基于其之上)
+* Uvicorn(被 Starlette 与 **FastAPI** 使用)
+
+///
+
+/// check | 启发 **FastAPI**:
+
+诞生。
+
+用同一套 Python 类型同时声明多件事(数据校验、序列化与文档),并且还能提供出色的编辑器支持——我认为这是个极其巧妙的想法。
+
+在长时间寻找与测试多种替代之后,APIStar 是当时最好的选择。
+
+随后 APIStar 不再作为服务器存在,而 Starlette 出现,成为实现该体系的更佳基础。这成为构建 **FastAPI** 的最终灵感来源。
+
+我把 **FastAPI** 视为 APIStar 的“精神续作”,并在此基础上,结合前述工具的经验,改进并增强了功能、类型系统及其他各方面。
+
+///
+
+## **FastAPI** 所使用的组件 { #used-by-fastapi }
+
+### Pydantic { #pydantic }
+
+Pydantic 是一个基于 Python 类型提示来定义数据校验、序列化与文档(使用 JSON Schema)的库。
+
+这使得它极其直观。
+
+它可与 Marshmallow 类比。尽管在基准测试中它比 Marshmallow 更快。并且由于同样基于 Python 类型提示,编辑器支持优秀。
+
+/// check | **FastAPI** 用它来:
+
+处理所有数据校验、数据序列化与自动模型文档(基于 JSON Schema)。
+
+随后 **FastAPI** 会把这些 JSON Schema 数据纳入 OpenAPI(以及完成其他所有工作)。
+
+///
+
+### Starlette { #starlette }
+
+Starlette 是一个轻量级的 ASGI 框架/工具集,非常适合构建高性能的 asyncio 服务。
+
+它非常简单直观。被设计为易于扩展,且具有模块化组件。
+
+它具备:
+
+* 性能极其出色。
+* 支持 WebSocket。
+* 进程内后台任务。
+* 启动与停止事件。
+* 基于 HTTPX 的测试客户端。
+* CORS、GZip、静态文件、流式响应。
+* 会话与 Cookie 支持。
+* 100% 测试覆盖率。
+* 100% 类型注解的代码库。
+* 极少的强依赖。
+
+Starlette 目前是测试中最快的 Python 框架。仅次于 Uvicorn,它不是框架,而是服务器。
+
+Starlette 提供了 Web 微框架的全部基础能力。
+
+但它不提供自动的数据校验、序列化或文档。
+
+这正是 **FastAPI** 在其之上增加的主要内容之一,全部基于 Python 类型提示(通过 Pydantic)。此外还有依赖注入系统、安全工具、OpenAPI 模式生成等。
+
+/// note | 技术细节
+
+ASGI 是由 Django 核心团队成员推动的新“标准”。它尚不是正式的“Python 标准”(PEP),尽管正朝此方向推进。
+
+尽管如此,已有多种工具将其作为“标准”使用。这极大提升了互操作性:你可以把 Uvicorn 换成其他 ASGI 服务器(如 Daphne 或 Hypercorn),或添加 ASGI 兼容的工具,如 `python-socketio`。
+
+///
+
+/// check | **FastAPI** 用它来:
+
+处理所有核心 Web 部分,并在其之上扩展功能。
+
+`FastAPI` 类本身直接继承自 `Starlette`。
+
+因此,凡是你能用 Starlette 完成的事,也能直接用 **FastAPI** 完成;可以把它看作“加速版”的 Starlette。
+
+///
+
+### Uvicorn { #uvicorn }
+
+Uvicorn 是一个基于 uvloop 与 httptools 构建的极速 ASGI 服务器。
+
+它不是 Web 框架,而是服务器。例如它不提供按路径路由的工具——这是 Starlette(或 **FastAPI**)这类框架在其之上提供的功能。
+
+它是 Starlette 与 **FastAPI** 推荐的服务器。
+
+/// check | **FastAPI** 推荐将其作为:
+
+运行 **FastAPI** 应用的主要 Web 服务器。
+
+你也可以使用 `--workers` 命令行选项以获得异步的多进程服务器。
+
+更多细节见[部署](deployment/index.md){.internal-link target=_blank}一节。
+
+///
+
+## 基准与速度 { #benchmarks-and-speed }
+
+要理解、比较并查看 Uvicorn、Starlette 与 FastAPI 之间的差异,请查看[基准](benchmarks.md){.internal-link target=_blank}一节。
diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md
index c94c90787..36d875f51 100644
--- a/docs/zh/docs/async.md
+++ b/docs/zh/docs/async.md
@@ -298,7 +298,7 @@ CPU 密集型操作的常见示例是需要复杂的数学处理。
这一点,再加上 Python 是**数据科学**、机器学习(尤其是深度学习)的主要语言这一简单事实,使得 **FastAPI** 与数据科学/机器学习 Web API 和应用程序(以及其他许多应用程序)非常匹配。
-了解如何在生产环境中实现这种并行性,可查看此文 [Deployment](deployment/index.md){.internal-link target=_blank}。
+了解如何在生产环境中实现这种并行性,可查看此文 [部署](deployment/index.md){.internal-link target=_blank}。
## `async` 和 `await` { #async-and-await }
@@ -369,7 +369,7 @@ Starlette (和 **FastAPI**) 是基于 AnyIO 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。
-我(指原作者 —— 译者注)基于 AnyIO 新建了一个库,作为一个轻量级的封装层,用来优化类型注解,同时提供了更好的**自动补全**、**内联错误提示**等功能。这个库还附带了一个友好的入门指南和教程,能帮助你**理解**并编写**自己的异步代码**:Asyncer。如果你有**结合使用异步代码和常规**(阻塞/同步)代码的需求,这个库会特别有用。
+我基于 AnyIO 新建了一个库,作为一个轻量级的封装层,用来优化类型注解,同时提供了更好的**自动补全**、**内联错误提示**等功能。这个库还附带了一个友好的入门指南和教程,能帮助你**理解**并编写**自己的异步代码**:Asyncer。如果你有**结合使用异步代码和常规**(阻塞/同步)代码的需求,这个库会特别有用。
### 其他形式的异步代码 { #other-forms-of-asynchronous-code }
diff --git a/docs/zh/docs/benchmarks.md b/docs/zh/docs/benchmarks.md
index 1a4b4a3de..a6e706dfa 100644
--- a/docs/zh/docs/benchmarks.md
+++ b/docs/zh/docs/benchmarks.md
@@ -23,7 +23,7 @@
* 你不会直接在 Uvicorn 中编写应用程序。这意味着你的代码至少必须包含 Starlette(或 **FastAPI**)提供的代码。如果你这样做了(即直接在 Uvicorn 中编写应用程序),最终的应用程序会和使用了框架并且最小化了应用代码和 bug 的情况具有相同的性能损耗。
* 如果你要对比 Uvicorn,请将其与 Daphne,Hypercorn,uWSGI 等应用服务器进行比较。
* **Starlette**:
- * 在 Uvicorn 后使用 Starlette,性能会略有下降。实际上,Starlette 使用 Uvicorn 运行。因此,由于必须执行更多的代码,它只会比 Uvicorn 更慢。
+ * 性能仅次于 Uvicorn。实际上,Starlette 使用 Uvicorn 运行。因此,由于必须执行更多的代码,它只会比 Uvicorn 更慢。
* 但它为你提供了构建简单的网络程序的工具,并具有基于路径的路由等功能。
* 如果想对比与 Starlette 对标的开发框架,请将其与 Sanic,Flask,Django 等网络框架(或微框架)进行比较。
* **FastAPI**:
diff --git a/docs/zh/docs/deployment/concepts.md b/docs/zh/docs/deployment/concepts.md
index 66d32629c..76e967d7d 100644
--- a/docs/zh/docs/deployment/concepts.md
+++ b/docs/zh/docs/deployment/concepts.md
@@ -190,7 +190,7 @@
### 工作进程和端口 { #worker-processes-and-ports }
-还记得文档 [About HTTPS](https.md){.internal-link target=_blank} 中只有一个进程可以侦听服务器中的端口和 IP 地址的一种组合吗?
+还记得文档 [关于 HTTPS](https.md){.internal-link target=_blank} 中只有一个进程可以侦听服务器中的端口和 IP 地址的一种组合吗?
现在仍然是对的。
diff --git a/docs/zh/docs/deployment/docker.md b/docs/zh/docs/deployment/docker.md
index 3d0c19903..4e7410587 100644
--- a/docs/zh/docs/deployment/docker.md
+++ b/docs/zh/docs/deployment/docker.md
@@ -14,7 +14,7 @@
diff --git a/docs/zh/docs/how-to/general.md b/docs/zh/docs/how-to/general.md
index e75ad6c79..2c9f78179 100644
--- a/docs/zh/docs/how-to/general.md
+++ b/docs/zh/docs/how-to/general.md
@@ -36,4 +36,4 @@
## OpenAPI 文档 URL { #openapi-docs-urls }
-要更改用于自动生成文档的 URL,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}。
+要更改自动生成的文档用户界面所使用的 URL,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}。
diff --git a/docs/zh/docs/how-to/graphql.md b/docs/zh/docs/how-to/graphql.md
new file mode 100644
index 000000000..5384f1513
--- /dev/null
+++ b/docs/zh/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+由于 **FastAPI** 基于 **ASGI** 标准,因此很容易集成任何也兼容 ASGI 的 **GraphQL** 库。
+
+你可以在同一个应用中将常规的 FastAPI 路径操作与 GraphQL 结合使用。
+
+/// tip | 提示
+
+**GraphQL** 解决一些非常特定的用例。
+
+与常见的 **Web API** 相比,它有各自的**优点**和**缺点**。
+
+请确保评估在你的用例中,这些**好处**是否足以弥补这些**缺点**。 🤓
+
+///
+
+## GraphQL 库 { #graphql-libraries }
+
+以下是一些支持 **ASGI** 的 **GraphQL** 库。你可以将它们与 **FastAPI** 一起使用:
+
+* Strawberry 🍓
+ * 提供 面向 FastAPI 的文档
+* Ariadne
+ * 提供 面向 FastAPI 的文档
+* Tartiflette
+ * 提供用于 ASGI 集成的 Tartiflette ASGI
+* Graphene
+ * 可配合 starlette-graphene3 使用
+
+## 使用 Strawberry 的 GraphQL { #graphql-with-strawberry }
+
+如果你需要或想要使用 **GraphQL**,**Strawberry** 是**推荐**的库,因为它的设计与 **FastAPI** 最为接近,全部基于**类型注解**。
+
+根据你的用例,你可能会更喜欢其他库,但如果你问我,我大概率会建议你先试试 **Strawberry**。
+
+下面是一个将 Strawberry 与 FastAPI 集成的小预览:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+你可以在 Strawberry 文档中了解更多信息。
+
+还有关于 将 Strawberry 与 FastAPI 结合使用的文档。
+
+## Starlette 中较早的 `GraphQLApp` { #older-graphqlapp-from-starlette }
+
+早期版本的 Starlette 包含一个 `GraphQLApp` 类,用于与 Graphene 集成。
+
+它已在 Starlette 中被弃用,但如果你的代码使用了它,你可以轻松**迁移**到 starlette-graphene3,它覆盖相同的用例,且接口**几乎完全一致**。
+
+/// tip | 提示
+
+如果你需要 GraphQL,我仍然建议看看 Strawberry,因为它基于类型注解而不是自定义类和类型。
+
+///
+
+## 了解更多 { #learn-more }
+
+你可以在 GraphQL 官方文档中了解更多关于 **GraphQL** 的内容。
+
+你也可以通过上面的链接阅读各个库的更多信息。
diff --git a/docs/zh/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/zh/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 000000000..2e5445200
--- /dev/null
+++ b/docs/zh/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# 从 Pydantic v1 迁移到 Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+如果你有一个较旧的 FastAPI 应用,可能在使用 Pydantic v1。
+
+FastAPI 0.100.0 同时支持 Pydantic v1 和 v2,会使用你已安装的任一版本。
+
+FastAPI 0.119.0 引入了在 Pydantic v2 内部以 `pydantic.v1` 形式对 Pydantic v1 的部分支持,以便于迁移到 v2。
+
+FastAPI 0.126.0 移除了对 Pydantic v1 的支持,但在一段时间内仍支持 `pydantic.v1`。
+
+/// warning | 警告
+
+从 Python 3.14 开始,Pydantic 团队不再为最新的 Python 版本提供 Pydantic v1 的支持。
+
+这也包括 `pydantic.v1`,在 Python 3.14 及更高版本中不再受支持。
+
+如果你想使用 Python 的最新特性,需要确保使用 Pydantic v2。
+
+///
+
+如果你的旧 FastAPI 应用在用 Pydantic v1,这里将向你展示如何迁移到 Pydantic v2,以及 FastAPI 0.119.0 中可帮助你渐进式迁移的功能。
+
+## 官方指南 { #official-guide }
+
+Pydantic 有一份从 v1 迁移到 v2 的官方 迁移指南。
+
+其中包含变更内容、校验如何更准确更严格、可能的注意事项等。
+
+你可以阅读以更好地了解变更。
+
+## 测试 { #tests }
+
+请确保你的应用有[测试](../tutorial/testing.md){.internal-link target=_blank},并在持续集成(CI)中运行它们。
+
+这样你就可以升级并确保一切仍按预期工作。
+
+## `bump-pydantic` { #bump-pydantic }
+
+在很多情况下,如果你使用的是未做自定义的常规 Pydantic 模型,可以将从 Pydantic v1 迁移到 v2 的大部分过程自动化。
+
+你可以使用同一 Pydantic 团队提供的 `bump-pydantic`。
+
+该工具会帮助你自动修改大部分需要变更的代码。
+
+之后运行测试检查是否一切正常。如果正常,你就完成了。😎
+
+## v2 中的 Pydantic v1 { #pydantic-v1-in-v2 }
+
+Pydantic v2 以子模块 `pydantic.v1` 的形式包含了 Pydantic v1 的全部内容。但在 Python 3.13 以上的版本中不再受支持。
+
+这意味着你可以安装最新的 Pydantic v2,并从该子模块导入并使用旧的 Pydantic v1 组件,就像安装了旧版 Pydantic v1 一样。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### FastAPI 对 v2 中 Pydantic v1 的支持 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+自 FastAPI 0.119.0 起,FastAPI 也对 Pydantic v2 内的 Pydantic v1 提供了部分支持,以便迁移到 v2。
+
+因此,你可以将 Pydantic 升级到最新的 v2,并将导入改为使用 `pydantic.v1` 子模块,在很多情况下就能直接工作。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | 警告
+
+请注意,由于 Pydantic 团队自 Python 3.14 起不再在较新的 Python 版本中支持 Pydantic v1,使用 `pydantic.v1` 在 Python 3.14 及更高版本中也不受支持。
+
+///
+
+### 同一应用中同时使用 Pydantic v1 与 v2 { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic 不支持在一个 Pydantic v2 模型的字段中定义 Pydantic v1 模型,反之亦然。
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...但是,你可以在同一个应用中分别使用 Pydantic v1 和 v2 的独立模型。
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+在某些情况下,甚至可以在 FastAPI 应用的同一个路径操作中同时使用 Pydantic v1 和 v2 模型:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+在上面的示例中,输入模型是 Pydantic v1 模型,输出模型(在 `response_model=ItemV2` 中定义)是 Pydantic v2 模型。
+
+### Pydantic v1 参数 { #pydantic-v1-parameters }
+
+如果你需要在 Pydantic v1 模型中使用 FastAPI 特有的参数工具,如 `Body`、`Query`、`Form` 等,在完成向 Pydantic v2 的迁移前,可以从 `fastapi.temp_pydantic_v1_params` 导入它们:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### 分步迁移 { #migrate-in-steps }
+
+/// tip | 提示
+
+优先尝试 `bump-pydantic`,如果测试通过且可行,那么你就用一个命令完成了。✨
+
+///
+
+如果 `bump-pydantic` 不适用于你的场景,你可以在同一应用中同时支持 Pydantic v1 和 v2 模型,逐步迁移到 Pydantic v2。
+
+你可以首先将 Pydantic 升级到最新的 v2,并将所有模型的导入改为使用 `pydantic.v1`。
+
+然后按模块或分组,逐步把模型从 Pydantic v1 迁移到 v2。🚶
diff --git a/docs/zh/docs/how-to/separate-openapi-schemas.md b/docs/zh/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 000000000..c3efe5f1a
--- /dev/null
+++ b/docs/zh/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# 是否为输入和输出分别生成 OpenAPI JSON Schema { #separate-openapi-schemas-for-input-and-output-or-not }
+
+自从发布了 **Pydantic v2**,生成的 OpenAPI 比之前更精确、更**正确**了。😎
+
+事实上,在某些情况下,对于同一个 Pydantic 模型,OpenAPI 中会根据是否带有**默认值**,为输入和输出分别生成**两个 JSON Schema**。
+
+我们来看看它如何工作,以及在需要时如何修改。
+
+## 用于输入和输出的 Pydantic 模型 { #pydantic-models-for-input-and-output }
+
+假设你有一个带有默认值的 Pydantic 模型,例如:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### 输入用的模型 { #model-for-input }
+
+如果你像下面这样把该模型用作输入:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+...那么 `description` 字段将**不是必填项**,因为它的默认值是 `None`。
+
+### 文档中的输入模型 { #input-model-in-docs }
+
+你可以在文档中确认,`description` 字段没有**红色星号**,也就是未被标记为必填:
+
+
+
+
+
+
+httpx - 使用 `TestClient` 时需要。
* jinja2 - 使用默认模板配置时需要。
-* python-multipart - 使用 `request.form()` 支持表单「解析」时需要。
+* python-multipart - 使用 `request.form()` 支持表单「解析」时需要。
FastAPI 使用:
diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md
index 3e1c593c1..4824b7558 100644
--- a/docs/zh/docs/python-types.md
+++ b/docs/zh/docs/python-types.md
@@ -2,11 +2,11 @@
Python 支持可选的“类型提示”(也叫“类型注解”)。
-这些“类型提示”或注解是一种特殊语法,用来声明变量的类型。
+这些“类型提示”或注解是一种特殊语法,用来声明变量的类型。
通过为变量声明类型,编辑器和工具可以为你提供更好的支持。
-这只是一个关于 Python 类型提示的快速入门/复习。它只涵盖与 **FastAPI** 一起使用所需的最少部分……实际上非常少。
+这只是一个关于 Python 类型提示的快速入门/复习。它只涵盖与 **FastAPI** 一起使用所需的最少部分...实际上非常少。
**FastAPI** 完全基于这些类型提示构建,它们带来了许多优势和好处。
@@ -22,7 +22,7 @@ Python 支持可选的“类型提示”(也叫“类型注解”)。
让我们从一个简单的例子开始:
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
运行这个程序会输出:
@@ -34,9 +34,9 @@ John Doe
* 接收 `first_name` 和 `last_name`。
* 通过 `title()` 将每个参数的第一个字母转换为大写。
-* 用一个空格将它们拼接起来。
+* 用一个空格将它们拼接起来。
-{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
### 修改它 { #edit-it }
@@ -78,7 +78,7 @@ John Doe
这些就是“类型提示”:
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
这和声明默认值不同,比如:
@@ -106,7 +106,7 @@ John Doe
看这个已经带有类型提示的函数:
-{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
因为编辑器知道变量的类型,你不仅能得到补全,还能获得错误检查:
@@ -114,7 +114,7 @@ John Doe
现在你知道需要修复它,用 `str(age)` 把 `age` 转成字符串:
-{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
## 声明类型 { #declaring-types }
@@ -133,29 +133,32 @@ John Doe
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### 带类型参数的泛型类型 { #generic-types-with-type-parameters }
+### typing 模块 { #typing-module }
-有些数据结构可以包含其他值,比如 `dict`、`list`、`set` 和 `tuple`。而内部的值也会有自己的类型。
+在一些额外的用例中,你可能需要从标准库的 `typing` 模块导入内容。比如当你想声明“任意类型”时,可以使用 `typing` 中的 `Any`:
-这些带有内部类型的类型称为“泛型”(generic)类型。可以把它们连同内部类型一起声明出来。
+```python
+from typing import Any
-要声明这些类型以及内部类型,你可以使用 Python 标准库模块 `typing`。它就是为支持这些类型提示而存在的。
-#### 更新的 Python 版本 { #newer-versions-of-python }
+def some_function(data: Any):
+ print(data)
+```
-使用 `typing` 的语法与所有版本兼容,从 Python 3.6 到最新版本(包括 Python 3.9、Python 3.10 等)。
+### 泛型类型 { #generic-types }
-随着 Python 的发展,更新的版本对这些类型注解的支持更好,在很多情况下你甚至不需要导入和使用 `typing` 模块来声明类型注解。
+有些类型可以在方括号中接收“类型参数”(type parameters),用于声明其内部值的类型。比如“字符串列表”可以写为 `list[str]`。
-如果你可以为项目选择更高版本的 Python,你将能享受到这种额外的简化。
+这些能接收类型参数的类型称为“泛型类型”(Generic types)或“泛型”(Generics)。
-在整个文档中,会根据不同 Python 版本提供相应的示例(当存在差异时)。
+你可以把相同的内建类型作为泛型使用(带方括号和内部类型):
-比如“Python 3.6+”表示兼容 Python 3.6 及以上(包括 3.7、3.8、3.9、3.10 等)。而“Python 3.9+”表示兼容 Python 3.9 及以上(包括 3.10 等)。
-
-如果你可以使用最新的 Python 版本,请使用最新版本的示例,它们将拥有最简洁的语法,例如“Python 3.10+”。
+* `list`
+* `tuple`
+* `set`
+* `dict`
#### 列表 { #list }
@@ -167,7 +170,7 @@ John Doe
因为 list 是一种包含内部类型的类型,把内部类型写在方括号里:
-{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
/// info | 信息
@@ -193,7 +196,7 @@ John Doe
声明 `tuple` 和 `set` 的方式类似:
-{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
这表示:
@@ -208,7 +211,7 @@ John Doe
第二个类型参数用于字典的值:
-{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
这表示:
@@ -220,44 +223,20 @@ John Doe
你可以声明一个变量可以是若干种类型中的任意一种,比如既可以是 `int` 也可以是 `str`。
-在 Python 3.6 及以上(包括 Python 3.10),你可以使用 `typing` 中的 `Union`,把可能的类型放到方括号里。
+定义时使用竖线(`|`)把两种类型分开。
-在 Python 3.10 中还有一种新的语法,可以用竖线(`|`)把可能的类型分隔开。
-
-//// tab | Python 3.10+
+这称为“联合类型”(union),因为变量可以是这两类类型集合的并集中的任意一个。
```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-////
-
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b_py39.py!}
-```
-
-////
-
-两种方式的含义一致:`item` 可以是 `int` 或 `str`。
+这表示 `item` 可以是 `int` 或 `str`。
#### 可能为 `None` { #possibly-none }
你可以声明一个值的类型是某种类型(比如 `str`),但它也可能是 `None`。
-在 Python 3.6 及以上(包括 Python 3.10),你可以通过从 `typing` 模块导入并使用 `Optional` 来声明:
-
-```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-使用 `Optional[str]` 而不是仅仅 `str`,可以让编辑器帮助你发现把值当成总是 `str` 的错误(实际上它也可能是 `None`)。
-
-`Optional[Something]` 实际上是 `Union[Something, None]` 的简写,它们等价。
-
-这也意味着在 Python 3.10 中,你可以使用 `Something | None`:
-
//// tab | Python 3.10+
```Python hl_lines="1"
@@ -266,96 +245,7 @@ John Doe
////
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-////
-
-//// tab | Python 3.9+ 另一种写法
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b_py39.py!}
-```
-
-////
-
-#### 使用 `Union` 或 `Optional` { #using-union-or-optional }
-
-如果你使用的是 3.10 以下的 Python 版本,这里有个来自我非常主观的建议:
-
-* 🚨 避免使用 `Optional[SomeType]`
-* 改用 ✨**`Union[SomeType, None]`**✨
-
-两者等价,底层相同,但我更推荐 `Union` 而不是 `Optional`,因为“optional(可选)”这个词看起来像是在说“参数可选”,而它实际上表示“它可以是 `None`”,即使它并不是可选的,仍然是必填的。
-
-我认为 `Union[SomeType, None]` 更明确地表达了它的意思。
-
-这只是关于词语和名字。但这些词会影响你和你的队友如何理解代码。
-
-例如,看下面这个函数:
-
-{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
-
-参数 `name` 被定义为 `Optional[str]`,但它并不是“可选”的,你不能不传这个参数就调用函数:
-
-```Python
-say_hi() # 哦不,这会抛错!😱
-```
-
-参数 `name` 仍然是必填的(不是“可选”),因为它没有默认值。不过,`name` 接受 `None` 作为值:
-
-```Python
-say_hi(name=None) # 这样可以,None 是有效值 🎉
-```
-
-好消息是,一旦你使用 Python 3.10,就无需再为此操心,因为你可以直接用 `|` 来定义类型联合:
-
-{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
-
-这样你就不必再考虑 `Optional` 和 `Union` 这些名字了。😎
-
-#### 泛型类型 { #generic-types }
-
-这些在方括号中接收类型参数的类型称为“泛型类型”(Generic types)或“泛型”(Generics),例如:
-
-//// tab | Python 3.10+
-
-你可以把同样的内建类型作为泛型使用(带方括号和内部类型):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-以及与之前的 Python 版本一样,来自 `typing` 模块的:
-
-* `Union`
-* `Optional`
-* ……以及其他。
-
-在 Python 3.10 中,作为使用泛型 `Union` 和 `Optional` 的替代,你可以使用竖线(`|`)来声明类型联合,这更好也更简单。
-
-////
-
-//// tab | Python 3.9+
-
-你可以把同样的内建类型作为泛型使用(带方括号和内部类型):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-以及来自 `typing` 模块的泛型:
-
-* `Union`
-* `Optional`
-* ……以及其他。
-
-////
+使用 `str | None` 而不是仅仅 `str`,可以让编辑器帮助你发现把值当成总是 `str` 的错误(实际上它也可能是 `None`)。
### 类作为类型 { #classes-as-types }
@@ -363,11 +253,11 @@ say_hi(name=None) # 这样可以,None 是有效值 🎉
假设你有一个名为 `Person` 的类,带有 name:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
然后你可以声明一个变量是 `Person` 类型:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
接着,你会再次获得所有的编辑器支持:
@@ -403,19 +293,13 @@ say_hi(name=None) # 这样可以,None 是有效值 🎉
你会在[教程 - 用户指南](tutorial/index.md){.internal-link target=_blank}中看到更多的实战示例。
-/// tip | 提示
-
-当你在没有默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,Pydantic 有一个特殊行为,你可以在 Pydantic 文档的 必填的 Optional 字段 中了解更多。
-
-///
-
## 带元数据注解的类型提示 { #type-hints-with-metadata-annotations }
-Python 还提供了一个特性,可以使用 `Annotated` 在这些类型提示中放入额外的元数据。
+Python 还提供了一个特性,可以使用 `Annotated` 在这些类型提示中放入额外的元数据。
-从 Python 3.9 起,`Annotated` 是标准库的一部分,因此可以从 `typing` 导入。
+你可以从 `typing` 导入 `Annotated`。
-{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
Python 本身不会对这个 `Annotated` 做任何处理。对于编辑器和其他工具,类型仍然是 `str`。
diff --git a/docs/zh/docs/resources/index.md b/docs/zh/docs/resources/index.md
new file mode 100644
index 000000000..2f55ac06f
--- /dev/null
+++ b/docs/zh/docs/resources/index.md
@@ -0,0 +1,3 @@
+# 资源 { #resources }
+
+更多资源、外部链接等。✈️
diff --git a/docs/zh/docs/translation-banner.md b/docs/zh/docs/translation-banner.md
new file mode 100644
index 000000000..76db203b0
--- /dev/null
+++ b/docs/zh/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 由 AI 与人类协作翻译
+
+本翻译由人类引导的 AI 生成。🤝
+
+可能存在误解原意或不够自然等问题。🤖
+
+你可以通过[帮助我们更好地引导 AI LLM](https://fastapi.tiangolo.com/zh/contributing/#translations)来改进此翻译。
+
+[英文版本](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md
index 8398472c3..d73fee429 100644
--- a/docs/zh/docs/tutorial/background-tasks.md
+++ b/docs/zh/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@
首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。
@@ -31,13 +31,13 @@
由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
## 添加后台任务 { #add-the-background-task }
在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` 接收以下参数:
@@ -69,7 +69,7 @@
在FastAPI中仍然可以单独使用 `BackgroundTask`,但您必须在代码中创建对象,并返回包含它的Starlette `Response`。
-更多细节查看 Starlette's official docs for Background Tasks.
+更多细节查看 Starlette 后台任务的官方文档.
## 告诫 { #caveat }
diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md
index 1ced002dc..a667d596f 100644
--- a/docs/zh/docs/tutorial/bigger-applications.md
+++ b/docs/zh/docs/tutorial/bigger-applications.md
@@ -85,7 +85,7 @@ from app.routers import items
你可以导入它并通过与 `FastAPI` 类相同的方式创建一个「实例」:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
### 使用 `APIRouter` 的*路径操作* { #path-operations-with-apirouter }
@@ -93,7 +93,7 @@ from app.routers import items
使用方式与 `FastAPI` 类相同:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
你可以将 `APIRouter` 视为一个「迷你 `FastAPI`」类。
@@ -117,7 +117,7 @@ from app.routers import items
现在我们将使用一个简单的依赖项来读取一个自定义的 `X-Token` 请求首部:
-{* ../../docs_src/bigger_applications/app_an_py39/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
/// tip | 提示
@@ -149,7 +149,7 @@ from app.routers import items
因此,我们可以将其添加到 `APIRouter` 中,而不是将其添加到每个路径操作中。
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
由于每个*路径操作*的路径都必须以 `/` 开头,例如:
@@ -208,7 +208,7 @@ async def read_item(item_id: str):
因此,我们通过 `..` 对依赖项使用了相对导入:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[3] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}
#### 相对导入如何工作 { #how-relative-imports-work }
@@ -279,11 +279,11 @@ from ...dependencies import get_token_header
但是我们仍然可以添加*更多*将会应用于特定的*路径操作*的 `tags`,以及一些特定于该*路径操作*的额外 `responses`:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}
/// tip | 提示
-最后的这个路径操作将包含标签的组合:`["items","custom"]`。
+最后的这个路径操作将包含标签的组合:`["items", "custom"]`。
并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。
@@ -305,13 +305,13 @@ from ...dependencies import get_token_header
我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[1,3,7] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
### 导入 `APIRouter` { #import-the-apirouter }
现在,我们导入具有 `APIRouter` 的其他子模块:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[4:5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}
由于文件 `app/routers/users.py` 和 `app/routers/items.py` 是同一 Python 包 `app` 一个部分的子模块,因此我们可以使用单个点 ` .` 通过「相对导入」来导入它们。
@@ -374,13 +374,13 @@ from .routers.users import router
因此,为了能够在同一个文件中使用它们,我们直接导入子模块:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}
### 包含 `users` 和 `items` 的 `APIRouter` { #include-the-apirouters-for-users-and-items }
现在,让我们来包含来自 `users` 和 `items` 子模块的 `router`。
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[10:11] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}
/// info | 信息
@@ -420,13 +420,13 @@ from .routers.users import router
对于此示例,它将非常简单。但是假设由于它是与组织中的其他项目所共享的,因此我们无法对其进行修改,以及直接在 `APIRouter` 中添加 `prefix`、`dependencies`、`tags` 等:
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
但是我们仍然希望在包含 `APIRouter` 时设置一个自定义的 `prefix`,以便其所有*路径操作*以 `/admin` 开头,我们希望使用本项目已经有的 `dependencies` 保护它,并且我们希望它包含自定义的 `tags` 和 `responses`。
我们可以通过将这些参数传递给 `app.include_router()` 来完成所有的声明,而不必修改原始的 `APIRouter`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[14:17] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}
这样,原始的 `APIRouter` 将保持不变,因此我们仍然可以与组织中的其他项目共享相同的 `app/internal/admin.py` 文件。
@@ -447,7 +447,7 @@ from .routers.users import router
这里我们这样做了...只是为了表明我们可以做到🤷:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[21:23] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}
它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。
diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md
index 7d0ddfc1e..39b84904f 100644
--- a/docs/zh/docs/tutorial/body-multiple-params.md
+++ b/docs/zh/docs/tutorial/body-multiple-params.md
@@ -104,12 +104,6 @@
q: str | None = None
```
-或者在 Python 3.9 中:
-
-```Python
-q: Union[str, None] = None
-```
-
比如:
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md
index 242aa5822..fe6902e83 100644
--- a/docs/zh/docs/tutorial/body-nested-models.md
+++ b/docs/zh/docs/tutorial/body-nested-models.md
@@ -163,7 +163,7 @@ images: list[Image]
例如:
-{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
## 无处不在的编辑器支持 { #editor-support-everywhere }
@@ -193,7 +193,7 @@ images: list[Image]
在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`:
-{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
/// tip | 提示
diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md
index 60088a048..4a72ba17c 100644
--- a/docs/zh/docs/tutorial/body.md
+++ b/docs/zh/docs/tutorial/body.md
@@ -153,7 +153,7 @@
FastAPI 会根据默认值 `= None` 知道 `q` 的值不是必填的。
-`str | None`(Python 3.10+)或 `Union[str, None]`(Python 3.9+ 中的 `Union`)并不是 FastAPI 用来判断是否必填的依据;是否必填由是否有默认值 `= None` 决定。
+`str | None` 并不是 FastAPI 用来判断是否必填的依据;是否必填由是否有默认值 `= None` 决定。
但添加这些类型注解可以让你的编辑器提供更好的支持并检测错误。
diff --git a/docs/zh/docs/tutorial/cookie-param-models.md b/docs/zh/docs/tutorial/cookie-param-models.md
index 707a6a9c7..8e094c7d3 100644
--- a/docs/zh/docs/tutorial/cookie-param-models.md
+++ b/docs/zh/docs/tutorial/cookie-param-models.md
@@ -46,17 +46,17 @@
在某些特殊使用情况下(可能并不常见),您可能希望**限制**您想要接收的 cookie。
-您的 API 现在可以控制自己的 cookie 同意。🤪🍪
+您的 API 现在可以控制自己的 cookie 同意。🤪🍪
您可以使用 Pydantic 的模型配置来禁止( `forbid` )任何额外( `extra` )字段:
{* ../../docs_src/cookie_param_models/tutorial002_an_py310.py hl[10] *}
-如果客户尝试发送一些**额外的 cookie**,他们将收到**错误**响应。
+如果客户端尝试发送一些**额外的 cookie**,他们将收到**错误**响应。
-可怜的 cookie 通知条,费尽心思为了获得您的同意,却被API 拒绝了。🍪
+可怜的 cookie 通知条,费尽心思为了获得您的同意,却被API 拒绝了。🍪
-例如,如果客户端尝试发送一个值为 `good-list-please` 的 `santa_tracker` cookie,客户端将收到一个**错误**响应,告知他们 `santa_tracker` cookie 是不允许的:
+例如,如果客户端尝试发送一个值为 `good-list-please` 的 `santa_tracker` cookie,客户端将收到一个**错误**响应,告知他们 `santa_tracker` cookie 是不允许的:
```json
{
@@ -73,4 +73,4 @@
## 总结 { #summary }
-您可以使用 **Pydantic 模型**在 **FastAPI** 中声明 **cookie**。😎
+您可以使用 **Pydantic 模型**在 **FastAPI** 中声明 **cookie**。😎
diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md
index 3a296ca72..2e271ec75 100644
--- a/docs/zh/docs/tutorial/cors.md
+++ b/docs/zh/docs/tutorial/cors.md
@@ -46,7 +46,7 @@
* 特定的 HTTP 方法(`POST`,`PUT`)或者使用通配符 `"*"` 允许所有方法。
* 特定的 HTTP 请求头或者使用通配符 `"*"` 允许所有请求头。
-{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *}
默认情况下,这个 `CORSMiddleware` 实现所使用的默认参数较为保守,所以你需要显式地启用特定的源、方法或者 headers,以便浏览器能够在跨域上下文中使用它们。
@@ -63,7 +63,7 @@
* `expose_headers` - 指示可以被浏览器访问的响应头。默认为 `[]`。
* `max_age` - 设定浏览器缓存 CORS 响应的最长时间,单位是秒。默认为 `600`。
-中间件响应两种特定类型的 HTTP 请求……
+中间件响应两种特定类型的 HTTP 请求...
### CORS 预检请求 { #cors-preflight-requests }
diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md
index 6e0cefe5b..1ff7d6127 100644
--- a/docs/zh/docs/tutorial/debugging.md
+++ b/docs/zh/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@
在你的 FastAPI 应用中直接导入 `uvicorn` 并运行:
-{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *}
### 关于 `__name__ == "__main__"` { #about-name-main }
@@ -68,7 +68,7 @@ from myapp import app
uvicorn.run(app, host="0.0.0.0", port=8000)
```
-/// info
+/// info | 信息
更多信息请检查 Python 官方文档.
diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md
index d83321ddd..43bd7a680 100644
--- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -14,7 +14,7 @@
对此,我们可以做的更好...
-## 什么构成了依赖项? { #what-makes-a-dependency }
+## 什么构成了依赖项 { #what-makes-a-dependency }
到目前为止,你看到的依赖项都被声明为函数。
@@ -101,7 +101,7 @@ fluffy = Cat(name="Mr Fluffy")
注意,我们在上面的代码中编写了两次`CommonQueryParams`:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ 未使用 Annotated
+//// tab | Python 3.10+ 未使用 Annotated
/// tip | 提示
@@ -129,7 +129,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
... Depends(CommonQueryParams)
```
-...实际上是 **Fastapi** 用来知道依赖项是什么的。
+...实际上是 **FastAPI** 用来知道依赖项是什么的。
FastAPI 将从依赖项中提取声明的参数,这才是 FastAPI 实际调用的。
@@ -137,7 +137,7 @@ FastAPI 将从依赖项中提取声明的参数,这才是 FastAPI 实际调用
在本例中,第一个 `CommonQueryParams` :
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.9+ 未使用 Annotated
+//// tab | Python 3.10+ 未使用 Annotated
/// tip | 提示
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
你实际上可以只这样编写:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ 未使用 Annotated
+//// tab | Python 3.10+ 未使用 Annotated
/// tip | 提示
@@ -197,7 +197,7 @@ commons = Depends(CommonQueryParams)
但是你可以看到,我们在这里有一些代码重复了,编写了`CommonQueryParams`两次:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ 未使用 Annotated
+//// tab | Python 3.10+ 未使用 Annotated
/// tip | 提示
@@ -225,7 +225,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
不是写成这样:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ 未使用 Annotated
+//// tab | Python 3.10+ 未使用 Annotated
/// tip | 提示
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
...而是这样写:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.9+ 未使用 Annotated
+//// tab | Python 3.10+ 未使用 Annotated
/// tip | 提示
diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 02fcf62a0..23412e465 100644
--- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -14,7 +14,7 @@
该参数的值是由 `Depends()` 组成的 `list`:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
路径操作装饰器依赖项的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。
@@ -22,13 +22,13 @@
有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。
-在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。
+在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器/工具报错。
使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。
///
-/// info | 说明
+/// info | 信息
本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。
@@ -44,13 +44,13 @@
路径装饰器依赖项可以声明请求的需求项(比如响应头)或其他子依赖项:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
### 触发异常 { #raise-exceptions }
路径装饰器依赖项与正常的依赖项一样,可以 `raise` 异常:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
### 返回值 { #return-values }
@@ -58,7 +58,7 @@
因此,可以复用在其他位置使用过的、(能返回值的)普通依赖项,即使没有使用这个值,也会执行该依赖项:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
## 为一组路径操作定义依赖项 { #dependencies-for-a-group-of-path-operations }
diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
index bf495c9f3..413dedb96 100644
--- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,6 +1,6 @@
# 使用 yield 的依赖项 { #dependencies-with-yield }
-FastAPI 支持那些在完成后执行一些额外步骤的依赖项。
+FastAPI 支持那些在完成后执行一些额外步骤的依赖项。
为此,使用 `yield` 而不是 `return`,并把这些额外步骤(代码)写在后面。
@@ -29,15 +29,15 @@ FastAPI 支持那些在完成后执行一些docstring 中声明*路径操作*的描述,**FastAPI** 会从中读取。
+描述内容比较长且占用多行时,可以在函数的 docstring 中声明*路径操作*的描述,**FastAPI** 会从中读取。
文档字符串支持 Markdown,能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进。
{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
-下图为 Markdown 文本在 API 文档中的显示效果:
+它会在交互式文档中使用:
@@ -72,7 +72,7 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用:
{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
-/// info | 说明
+/// info | 信息
注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。
@@ -90,9 +90,9 @@ OpenAPI 规定每个*路径操作*都要有响应描述。
## 弃用*路径操作* { #deprecate-a-path-operation }
-`deprecated` 参数可以把*路径操作*标记为弃用,无需直接删除:
+如果需要把*路径操作*标记为弃用,但不删除它,可以传入 `deprecated` 参数:
-{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
API 文档会把该路径操作标记为弃用:
diff --git a/docs/zh/docs/tutorial/path-params-numeric-validations.md b/docs/zh/docs/tutorial/path-params-numeric-validations.md
index ff8b1762c..608aa69a1 100644
--- a/docs/zh/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/zh/docs/tutorial/path-params-numeric-validations.md
@@ -54,11 +54,11 @@ FastAPI 在 0.95.0 版本添加了对 `Annotated` 的支持(并开始推荐使
因此,你可以将函数声明为:
-{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
但请记住,如果你使用 `Annotated`,你就不会遇到这个问题,因为你没有使用 `Query()` 或 `Path()` 作为函数参数的默认值。
-{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
## 按需对参数排序的技巧 { #order-the-parameters-as-you-need-tricks }
@@ -83,13 +83,13 @@ FastAPI 在 0.95.0 版本添加了对 `Annotated` 的支持(并开始推荐使
Python 不会对这个 `*` 做任何事,但它会知道之后的所有参数都应该作为关键字参数(键值对)来调用,也被称为 kwargs。即使它们没有默认值。
-{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
### 使用 `Annotated` 更好 { #better-with-annotated }
请记住,如果你使用 `Annotated`,因为你没有使用函数参数的默认值,所以你不会有这个问题,你大概率也不需要使用 `*`。
-{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
## 数值校验:大于等于 { #number-validations-greater-than-or-equal }
@@ -97,7 +97,7 @@ Python 不会对这个 `*` 做任何事,但它会知道之后的所有参数
在这里,使用 `ge=1` 后,`item_id` 必须是一个整数,值要「`g`reater than or `e`qual」1。
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
## 数值校验:大于和小于等于 { #number-validations-greater-than-and-less-than-or-equal }
@@ -106,7 +106,7 @@ Python 不会对这个 `*` 做任何事,但它会知道之后的所有参数
* `gt`:大于(`g`reater `t`han)
* `le`:小于等于(`l`ess than or `e`qual)
-{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
## 数值校验:浮点数、大于和小于 { #number-validations-floats-greater-than-and-less-than }
@@ -118,7 +118,7 @@ Python 不会对这个 `*` 做任何事,但它会知道之后的所有参数
对于 lt 也是一样的。
-{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
## 总结 { #recap }
diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md
index fa4c9514a..06a9f1b44 100644
--- a/docs/zh/docs/tutorial/path-params.md
+++ b/docs/zh/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
你可以使用与 Python 字符串格式化相同的语法声明路径“参数”或“变量”:
-{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
路径参数 `item_id` 的值会作为参数 `item_id` 传递给你的函数。
@@ -16,7 +16,7 @@
使用 Python 标准类型注解,声明路径操作函数中路径参数的类型:
-{* ../../docs_src/path_params/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
本例把 `item_id` 的类型声明为 `int`。
@@ -26,7 +26,7 @@
///
-## 数据转换 { #data-conversion }
+## 数据转换 { #data-conversion }
运行示例并访问 http://127.0.0.1:8000/items/3,返回的响应如下:
@@ -38,7 +38,7 @@
注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。
-**FastAPI** 通过类型声明自动**解析**请求中的数据。
+**FastAPI** 通过类型声明自动进行请求的解析。
///
@@ -118,19 +118,19 @@ FastAPI 充分地利用了 `Enum` 类型接收预设的路径参数。
+路径操作使用 Python 的 `Enum` 类型接收预设的路径参数。
### 创建 `Enum` 类 { #create-an-enum-class }
@@ -140,11 +140,11 @@ FastAPI 充分地利用了 模型的名字。
+**AlexNet**、**ResNet**、**LeNet** 是机器学习模型的名字。
///
@@ -152,7 +152,7 @@ FastAPI 充分地利用了 解析"
+- 数据 "解析"
- 数据校验
- API 注解和自动文档
diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md
index 62552e6d0..d41f30226 100644
--- a/docs/zh/docs/tutorial/query-params-str-validations.md
+++ b/docs/zh/docs/tutorial/query-params-str-validations.md
@@ -47,40 +47,16 @@ FastAPI 在 0.95.0 版本中添加了对 `Annotated` 的支持(并开始推荐
我们之前的类型标注是:
-//// tab | Python 3.10+
-
```Python
q: str | None = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Union[str, None] = None
-```
-
-////
-
我们要做的是用 `Annotated` 把它包起来,变成:
-//// tab | Python 3.10+
-
```Python
q: Annotated[str | None] = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Annotated[Union[str, None]] = None
-```
-
-////
-
这两种写法含义相同,`q` 是一个可以是 `str` 或 `None` 的参数,默认是 `None`。
现在进入更有趣的部分。🎉
@@ -109,7 +85,7 @@ FastAPI 现在会:
## 另一种(旧的)方式:把 `Query` 作为默认值 { #alternative-old-query-as-the-default-value }
-早期版本的 FastAPI(0.95.0 之前)要求你把 `Query` 作为参数的默认值,而不是放在 `Annotated` 里。你很可能会在别处看到这种写法,所以我也给你解释一下。
+早期版本的 FastAPI(0.95.0 之前)要求你把 `Query` 作为参数的默认值,而不是放在 `Annotated` 里。你很可能会在别处看到这种写法,所以我也给你解释一下。
/// tip | 提示
@@ -191,7 +167,7 @@ q: str = Query(default="rick")
## 添加正则表达式 { #add-regular-expressions }
-你可以定义一个参数必须匹配的 正则表达式 `pattern`:
+你可以定义一个参数必须匹配的 正则表达式 `pattern`:
{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
@@ -211,7 +187,7 @@ q: str = Query(default="rick")
假设你想要声明查询参数 `q` 的 `min_length` 为 `3`,并且默认值为 `"fixedquery"`:
-{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial005_an_py310.py hl[9] *}
/// note | 注意
@@ -241,7 +217,7 @@ q: Annotated[str | None, Query(min_length=3)] = None
因此,在使用 `Query` 的同时需要把某个值声明为必填时,只需不声明默认值:
-{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial006_an_py310.py hl[9] *}
### 必填,但可以为 `None` { #required-can-be-none }
@@ -292,7 +268,7 @@ http://localhost:8000/items/?q=foo&q=bar
你还可以定义在没有给定值时的默认 `list`:
-{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
如果你访问:
@@ -315,7 +291,7 @@ http://localhost:8000/items/
你也可以直接使用 `list`,而不是 `list[str]`:
-{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
/// note | 注意
@@ -371,7 +347,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
现在假设你不再喜欢这个参数了。
-由于还有客户端在使用它,你不得不保留一段时间,但你希望文档清楚地将其展示为已弃用。
+由于还有客户端在使用它,你不得不保留一段时间,但你希望文档清楚地将其展示为已弃用。
那么将参数 `deprecated=True` 传给 `Query`:
@@ -401,7 +377,7 @@ Pydantic 还有 ISBN 书号)或 `imdb-`(用于 IMDB 电影 URL 的 ID)开头:
+例如,这个自定义校验器会检查条目 ID 是否以 `isbn-`(用于 ISBN 书号)或 `imdb-`(用于 IMDB 电影 URL 的 ID)开头:
{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
@@ -435,7 +411,7 @@ Pydantic 还有 可迭代对象。
+使用 `data.items()` 我们会得到一个包含每个字典项键和值的元组的 可迭代对象。
我们用 `list(data.items())` 把这个可迭代对象转换成一个真正的 `list`。
diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md
index 9ef998731..4ea37d7e0 100644
--- a/docs/zh/docs/tutorial/query-params.md
+++ b/docs/zh/docs/tutorial/query-params.md
@@ -2,7 +2,7 @@
声明的参数不是路径参数时,路径操作函数会把该参数自动解释为**查询**参数。
-{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,以 `&` 分隔。
@@ -12,7 +12,7 @@
http://127.0.0.1:8000/items/?skip=0&limit=10
```
-……查询参数为:
+...查询参数为:
* `skip`:值为 `0`
* `limit`:值为 `10`
@@ -24,7 +24,7 @@ http://127.0.0.1:8000/items/?skip=0&limit=10
所有应用于路径参数的流程也适用于查询参数:
* (显而易见的)编辑器支持
-* 数据**解析**
+* 数据"解析"
* 数据校验
* 自动文档
@@ -75,7 +75,6 @@ http://127.0.0.1:8000/items/?skip=20
参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型:
-
{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
本例中,访问:
@@ -129,7 +128,7 @@ FastAPI 通过参数名进行检测:
如果要把查询参数设置为**必选**,就不要声明默认值:
-{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
这里的查询参数 `needy` 是类型为 `str` 的必选查询参数。
@@ -139,7 +138,7 @@ FastAPI 通过参数名进行检测:
http://127.0.0.1:8000/items/foo-item
```
-……因为路径中没有必选参数 `needy`,返回的响应中会显示如下错误信息:
+...因为路径中没有必选参数 `needy`,返回的响应中会显示如下错误信息:
```JSON
{
@@ -163,7 +162,7 @@ http://127.0.0.1:8000/items/foo-item
http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
```
-……这样就正常了:
+...这样就正常了:
```JSON
{
diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md
index 927bd093b..e3b543539 100644
--- a/docs/zh/docs/tutorial/request-files.md
+++ b/docs/zh/docs/tutorial/request-files.md
@@ -20,13 +20,13 @@ $ pip install python-multipart
从 `fastapi` 导入 `File` 和 `UploadFile`:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
## 定义 `File` 参数 { #define-file-parameters }
像为 `Body` 或 `Form` 一样创建文件参数:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
/// info | 信息
@@ -54,7 +54,7 @@ $ pip install python-multipart
将文件参数的类型声明为 `UploadFile`:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
与 `bytes` 相比,使用 `UploadFile` 有多项优势:
@@ -76,9 +76,9 @@ $ pip install python-multipart
`UploadFile` 具有以下 `async` 方法。它们都会在底层调用对应的文件方法(使用内部的 `SpooledTemporaryFile`)。
-* `write(data)`:将 `data`(`str` 或 `bytes`)写入文件。
-* `read(size)`:读取文件中 `size`(`int`)个字节/字符。
-* `seek(offset)`:移动到文件中字节位置 `offset`(`int`)。
+* `write(data)`:将 `data` (`str` 或 `bytes`) 写入文件。
+* `read(size)`:读取文件中 `size` (`int`) 个字节/字符。
+* `seek(offset)`:移动到文件中字节位置 `offset` (`int`)。
* 例如,`await myfile.seek(0)` 会移动到文件开头。
* 如果你先运行过 `await myfile.read()`,然后需要再次读取内容时,这尤其有用。
* `close()`:关闭文件。
@@ -121,7 +121,7 @@ HTML 表单(``)向服务器发送数据的方式通常会对数
但当表单包含文件时,会编码为 `multipart/form-data`。如果你使用 `File`,**FastAPI** 会知道需要从请求体的正确位置获取文件。
-如果你想进一步了解这些编码和表单字段,请参阅 MDN web docs for POST。
+如果你想进一步了解这些编码和表单字段,请参阅 MDN 关于 POST 的 Web 文档。
///
@@ -135,7 +135,7 @@ HTML 表单(``)向服务器发送数据的方式通常会对数
## 可选文件上传 { #optional-file-upload }
-您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选:
+您可以通过使用标准类型注解并将 `None` 作为默认值的方式将一个文件参数设为可选:
{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
@@ -143,7 +143,7 @@ HTML 表单(``)向服务器发送数据的方式通常会对数
您也可以将 `File()` 与 `UploadFile` 一起使用,例如,设置额外的元数据:
-{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
## 多文件上传 { #multiple-file-uploads }
@@ -153,7 +153,7 @@ FastAPI 支持同时上传多个文件。
要实现这一点,声明一个由 `bytes` 或 `UploadFile` 组成的列表(`List`):
-{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。
@@ -169,7 +169,7 @@ FastAPI 支持同时上传多个文件。
和之前的方式一样,你可以为 `File()` 设置额外参数,即使是 `UploadFile`:
-{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
## 小结 { #recap }
diff --git a/docs/zh/docs/tutorial/request-form-models.md b/docs/zh/docs/tutorial/request-form-models.md
index 4eb98ea22..63759df08 100644
--- a/docs/zh/docs/tutorial/request-form-models.md
+++ b/docs/zh/docs/tutorial/request-form-models.md
@@ -24,7 +24,7 @@ $ pip install python-multipart
你只需声明一个 **Pydantic 模型**,其中包含你希望接收的**表单字段**,然后将参数声明为 `Form`:
-{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
**FastAPI** 将从请求中的**表单数据**中**提取**出**每个字段**的数据,并提供你定义的 Pydantic 模型。
@@ -48,7 +48,7 @@ $ pip install python-multipart
你可以使用 Pydantic 的模型配置来 `forbid` 任何 `extra` 字段:
-{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *}
+{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *}
如果客户端尝试发送一些额外的数据,他们将收到**错误**响应。
diff --git a/docs/zh/docs/tutorial/request-forms-and-files.md b/docs/zh/docs/tutorial/request-forms-and-files.md
index 3c809868b..484fcd5d6 100644
--- a/docs/zh/docs/tutorial/request-forms-and-files.md
+++ b/docs/zh/docs/tutorial/request-forms-and-files.md
@@ -16,17 +16,17 @@ $ pip install python-multipart
## 导入 `File` 与 `Form` { #import-file-and-form }
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[3] *}
## 定义 `File` 与 `Form` 参数 { #define-file-and-form-parameters }
创建文件和表单参数的方式与 `Body` 和 `Query` 一样:
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[10:12] *}
文件和表单字段作为表单数据上传与接收。
-声明文件可以使用 `bytes` 或 `UploadFile` 。
+并且你可以将部分文件声明为 `bytes`,将部分文件声明为 `UploadFile`。
/// warning | 警告
diff --git a/docs/zh/docs/tutorial/request-forms.md b/docs/zh/docs/tutorial/request-forms.md
index 70eb93a26..1fc305a69 100644
--- a/docs/zh/docs/tutorial/request-forms.md
+++ b/docs/zh/docs/tutorial/request-forms.md
@@ -18,17 +18,17 @@ $ pip install python-multipart
从 `fastapi` 导入 `Form`:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[3] *}
## 定义 `Form` 参数 { #define-form-parameters }
创建表单参数的方式与 `Body` 或 `Query` 相同:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[9] *}
例如,在 OAuth2 规范的一种使用方式(称为“密码流”)中,要求将 `username` 和 `password` 作为表单字段发送。
-spec 要求这些字段必须精确命名为 `username` 和 `password`,并且作为表单字段发送,而不是 JSON。
+规范 要求这些字段必须精确命名为 `username` 和 `password`,并且作为表单字段发送,而不是 JSON。
使用 `Form` 可以像使用 `Body`(以及 `Query`、`Path`、`Cookie`)一样声明相同的配置,包括校验、示例、别名(例如将 `username` 写成 `user-name`)等。
diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md
index 791eb66fb..df0afa66f 100644
--- a/docs/zh/docs/tutorial/response-model.md
+++ b/docs/zh/docs/tutorial/response-model.md
@@ -183,7 +183,7 @@ FastAPI 在内部配合 Pydantic 做了多项处理,确保不会把类继承
最常见的情况是[直接返回 Response,详见进阶文档](../advanced/response-directly.md){.internal-link target=_blank}。
-{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
这个简单场景 FastAPI 会自动处理,因为返回类型注解是 `Response`(或其子类)。
@@ -193,7 +193,7 @@ FastAPI 在内部配合 Pydantic 做了多项处理,确保不会把类继承
你也可以在类型注解中使用 `Response` 的子类:
-{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
这同样可行,因为 `RedirectResponse` 是 `Response` 的子类,FastAPI 会自动处理这个简单场景。
@@ -201,7 +201,7 @@ FastAPI 在内部配合 Pydantic 做了多项处理,确保不会把类继承
但当你返回其他任意对象(如数据库对象)而它不是有效的 Pydantic 类型,并在函数中按此进行了注解时,FastAPI 会尝试基于该类型注解创建一个 Pydantic 响应模型,但会失败。
-如果你有一个在多个类型之间的联合类型,其中一个或多个不是有效的 Pydantic 类型,也会发生同样的情况,例如这个会失败 💥:
+如果你有一个在多个类型之间的联合类型,其中一个或多个不是有效的 Pydantic 类型,也会发生同样的情况,例如这个会失败 💥:
{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md
index 3630de280..266f919ba 100644
--- a/docs/zh/docs/tutorial/response-status-code.md
+++ b/docs/zh/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@
* `@app.delete()`
* 等...
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
/// note | 注意
@@ -74,7 +74,7 @@ FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
再看下之前的例子:
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201` 表示“已创建”的状态码。
@@ -82,7 +82,7 @@ FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
可以使用 `fastapi.status` 中的快捷变量。
-{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
这只是一种快捷方式,具有相同的数字代码,但它可以使用编辑器的自动补全功能:
diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md
index 818ff5087..ec1fc29e5 100644
--- a/docs/zh/docs/tutorial/schema-extra-example.md
+++ b/docs/zh/docs/tutorial/schema-extra-example.md
@@ -74,7 +74,7 @@ OpenAPI 3.1.0(自 FastAPI 0.99.0 起使用)增加了对 `examples` 的支持
这样做时,这些示例会成为该请求体数据内部 JSON Schema 的一部分。
-不过,在撰写本文时,用于展示文档 UI 的 Swagger UI 并不支持显示 JSON Schema 中数据的多个示例。但请继续阅读,下面有一种变通方法。
+不过,在撰写本文时,用于展示文档 UI 的 Swagger UI 并不支持显示 JSON Schema 中数据的多个示例。但请继续阅读,下面有一种变通方法。
### OpenAPI 特定的 `examples` { #openapi-specific-examples }
diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md
index 43b7c6657..8b1aeb70b 100644
--- a/docs/zh/docs/tutorial/security/first-steps.md
+++ b/docs/zh/docs/tutorial/security/first-steps.md
@@ -20,7 +20,7 @@
把下面的示例代码复制到 `main.py`:
-{* ../../docs_src/security/tutorial001_an_py39.py *}
+{* ../../docs_src/security/tutorial001_an_py310.py *}
## 运行 { #run-it }
@@ -132,7 +132,7 @@ OAuth2 的设计目标是让后端或 API 与负责用户认证的服务器解
创建 `OAuth2PasswordBearer` 类实例时,需要传入 `tokenUrl` 参数。该参数包含客户端(运行在用户浏览器中的前端)用来发送 `username` 和 `password` 以获取令牌的 URL。
-{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
/// tip | 提示
@@ -170,7 +170,7 @@ oauth2_scheme(some, parameters)
现在你可以通过 `Depends` 将 `oauth2_scheme` 作为依赖传入。
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
该依赖会提供一个 `str`,赋值给*路径操作函数*的参数 `token`。
diff --git a/docs/zh/docs/tutorial/security/get-current-user.md b/docs/zh/docs/tutorial/security/get-current-user.md
index c14bba28a..814ff2c82 100644
--- a/docs/zh/docs/tutorial/security/get-current-user.md
+++ b/docs/zh/docs/tutorial/security/get-current-user.md
@@ -2,7 +2,7 @@
上一章中,(基于依赖注入系统的)安全系统向*路径操作函数*传递了 `str` 类型的 `token`:
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
但这并不实用。
diff --git a/docs/zh/docs/tutorial/security/index.md b/docs/zh/docs/tutorial/security/index.md
index 589f93c3e..a4c352110 100644
--- a/docs/zh/docs/tutorial/security/index.md
+++ b/docs/zh/docs/tutorial/security/index.md
@@ -10,7 +10,7 @@
但首先,让我们来看一些小的概念。
-## 没有时间? { #in-a-hurry }
+## 赶时间 { #in-a-hurry }
如果你不关心这些术语,而只需要*立即*通过基于用户名和密码的身份认证来增加安全性,请跳转到接下来的章节。
diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md
index c7eb9bd90..b5ccfd3e3 100644
--- a/docs/zh/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md
@@ -116,7 +116,11 @@ pwdlib 也支持 bcrypt 哈希算法,但不包含遗留算法——如果需
再创建一个工具函数来进行身份验证并返回用户。
-{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,51,58:59,62:63,72:79] *}
+
+当使用一个在数据库中不存在的用户名调用 `authenticate_user` 时,我们仍然会针对一个虚拟哈希运行 `verify_password`。
+
+这可以确保无论用户名是否有效,端点的响应时间大致相同,从而防止可用于枚举已存在用户名的“时间攻击”(timing attacks)。
/// note | 注意
@@ -152,7 +156,7 @@ $ openssl rand -hex 32
创建一个生成新访问令牌的工具函数。
-{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,82:90] *}
## 更新依赖项 { #update-the-dependencies }
@@ -162,7 +166,7 @@ $ openssl rand -hex 32
如果令牌无效,立即返回一个 HTTP 错误。
-{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[93:110] *}
## 更新 `/token` 路径操作 { #update-the-token-path-operation }
@@ -170,7 +174,7 @@ $ openssl rand -hex 32
创建一个真正的 JWT 访问令牌并返回它。
-{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[121:136] *}
### 关于 JWT “主题” `sub` 的技术细节 { #technical-details-about-the-jwt-subject-sub }
diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md
index 3037a983b..95f708ae6 100644
--- a/docs/zh/docs/tutorial/security/simple-oauth2.md
+++ b/docs/zh/docs/tutorial/security/simple-oauth2.md
@@ -6,9 +6,9 @@
首先,使用 **FastAPI** 安全工具获取 `username` 和 `password`。
-OAuth2 规范要求使用**密码流**时,客户端或用户必须以表单数据形式发送 `username` 和 `password` 字段。
+OAuth2 规范要求使用“密码流”时,客户端或用户必须以表单数据形式发送 `username` 和 `password` 字段。
-并且,这两个字段必须命名为 `username` 和 `password` ,不能使用 `user-name` 或 `email` 等其它名称。
+并且,这两个字段必须命名为 `username` 和 `password`,不能使用 `user-name` 或 `email` 等其它名称。
不过也不用担心,前端仍可以显示终端用户所需的名称。
@@ -74,7 +74,7 @@ OAuth2 中,**作用域**只是声明指定权限的字符串。
/// info | 信息
-`OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。
+`OAuth2PasswordRequestForm` 并不像 `OAuth2PasswordBearer` 那样是 **FastAPI** 的特殊类。
**FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。
@@ -200,7 +200,7 @@ UserInDB(
此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。
-任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。
+任何 401“UNAUTHORIZED”HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。
本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。
@@ -220,7 +220,7 @@ UserInDB(
### 身份验证 { #authenticate }
-点击**Authorize**按钮。
+点击“Authorize”按钮。
使用以下凭证:
@@ -286,4 +286,4 @@ UserInDB(
唯一欠缺的是,它仍然不是真的**安全**。
-下一章,介绍使用密码哈希支持库与 JWT 令牌实现真正的安全机制。
+下一章你将看到如何使用安全的密码哈希库和 JWT 令牌。
diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md
index 944e960a7..ef0b7c460 100644
--- a/docs/zh/docs/tutorial/sql-databases.md
+++ b/docs/zh/docs/tutorial/sql-databases.md
@@ -216,7 +216,7 @@ $ fastapi dev main.py
它包含与 `HeroBase` 相同的字段,因此不会包括 `secret_name`。
-终于,我们英雄(hero)的身份得到了保护!🥷
+终于,我们英雄的身份得到了保护!🥷
它还重新声明了 `id: int`。这样我们便与 API 客户端建立了一种**约定**,使他们始终可以期待 `id` 存在并且是一个整数 `int`(永远不会是 `None`)。
diff --git a/docs/zh/docs/tutorial/static-files.md b/docs/zh/docs/tutorial/static-files.md
index 5b2f920b2..1f4ebae9a 100644
--- a/docs/zh/docs/tutorial/static-files.md
+++ b/docs/zh/docs/tutorial/static-files.md
@@ -7,9 +7,9 @@
* 导入 `StaticFiles`。
* 将一个 `StaticFiles()` 实例“挂载”(Mount)到指定路径。
-{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py310.py hl[2,6] *}
-/// note | 注意
+/// note | 技术细节
你也可以用 `from starlette.staticfiles import StaticFiles`。
diff --git a/docs/zh/docs/tutorial/testing.md b/docs/zh/docs/tutorial/testing.md
index 1aff9f799..7eb32f19e 100644
--- a/docs/zh/docs/tutorial/testing.md
+++ b/docs/zh/docs/tutorial/testing.md
@@ -30,7 +30,7 @@ $ pip install httpx
为你需要检查的地方用标准的Python表达式写个简单的 `assert` 语句(重申,标准的`pytest`)。
-{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py310.py hl[2,12,15:18] *}
/// tip | 提示
@@ -76,7 +76,7 @@ $ pip install httpx
在 `main.py` 文件中你有一个 **FastAPI** app:
-{* ../../docs_src/app_testing/app_a_py39/main.py *}
+{* ../../docs_src/app_testing/app_a_py310/main.py *}
### 测试文件 { #testing-file }
@@ -92,7 +92,7 @@ $ pip install httpx
因为这文件在同一个包中,所以你可以通过相对导入从 `main` 模块(`main.py`)导入`app`对象:
-{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py310/test_main.py hl[3] *}
...然后测试代码和之前一样的。
diff --git a/docs/zh/docs/virtual-environments.md b/docs/zh/docs/virtual-environments.md
index 29e272b59..60fb9e23f 100644
--- a/docs/zh/docs/virtual-environments.md
+++ b/docs/zh/docs/virtual-environments.md
@@ -30,7 +30,7 @@
首先,为你的工程创建一个目录。
-我 (指原作者 —— 译者注) 通常会在我的主目录下创建一个名为 `code` 的目录。
+我通常会在我的主目录下创建一个名为 `code` 的目录。
在这个目录下,我再为每个工程创建一个目录。
@@ -53,7 +53,7 @@ $ cd awesome-project
## 创建一个虚拟环境 { #create-a-virtual-environment }
-在开始一个 Python 工程的**第一时间**,**在你的工程内部**创建一个虚拟环境。
+在开始一个 Python 工程的**第一时间**,**在你的工程内部**创建一个虚拟环境。
/// tip | 提示
@@ -316,7 +316,7 @@ $ echo "*" > .venv/.gitignore
### 直接安装包 { #install-packages-directly }
-如果你急于安装,不想使用文件来声明工程的软件包依赖,您可以直接安装它们。
+如果你急于安装,不想使用文件来声明工程的软件包依赖,你可以直接安装它们。
/// tip | 提示
@@ -412,7 +412,7 @@ Hello World
## 配置编辑器 { #configure-your-editor }
-你可能会用到编辑器(即 IDE —— 译者注),请确保配置它使用与你创建的相同的虚拟环境(它可能会自动检测到),以便你可以获得自动补全和内联错误提示。
+你可能会用到编辑器,请确保配置它使用与你创建的相同的虚拟环境(它可能会自动检测到),以便你可以获得自动补全和内联错误提示。
例如:
@@ -437,7 +437,7 @@ $ deactivate
-## Cambiar los parámetros predeterminados de Swagger UI { #change-default-swagger-ui-parameters }
+## Cambiar los parámetros por defecto de Swagger UI { #change-default-swagger-ui-parameters }
-FastAPI incluye algunos parámetros de configuración predeterminados apropiados para la mayoría de los casos de uso.
+FastAPI incluye algunos parámetros de configuración por defecto apropiados para la mayoría de los casos de uso.
-Incluye estas configuraciones predeterminadas:
+Incluye estas configuraciones por defecto:
{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
@@ -46,7 +46,7 @@ Puedes sobrescribir cualquiera de ellos estableciendo un valor diferente en el a
Por ejemplo, para desactivar `deepLinking` podrías pasar estas configuraciones a `swagger_ui_parameters`:
-{* ../../docs_src/configure_swagger_ui/tutorial003_py39.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
## Otros parámetros de Swagger UI { #other-swagger-ui-parameters }
diff --git a/docs/es/docs/how-to/custom-docs-ui-assets.md b/docs/es/docs/how-to/custom-docs-ui-assets.md
index acd3f8d6d..faddab0d8 100644
--- a/docs/es/docs/how-to/custom-docs-ui-assets.md
+++ b/docs/es/docs/how-to/custom-docs-ui-assets.md
@@ -18,7 +18,7 @@ El primer paso es desactivar la documentación automática, ya que por defecto,
Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`:
-{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
### Incluye la documentación personalizada { #include-the-custom-docs }
@@ -34,7 +34,7 @@ Puedes reutilizar las funciones internas de FastAPI para crear las páginas HTML
Y de manera similar para ReDoc...
-{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[2:6,11:19,22:24,27:33] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
/// tip | Consejo
@@ -50,7 +50,7 @@ Swagger UI lo manejará detrás de escena para ti, pero necesita este auxiliar d
Ahora, para poder probar que todo funciona, crea una *path operation*:
-{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[36:38] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
### Pruébalo { #test-it }
@@ -118,7 +118,7 @@ Después de eso, tu estructura de archivos podría verse así:
* Importa `StaticFiles`.
* "Monta" una instance de `StaticFiles()` en un path específico.
-{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[7,11] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
### Prueba los archivos estáticos { #test-the-static-files }
@@ -144,7 +144,7 @@ Igual que cuando usas un CDN personalizado, el primer paso es desactivar la docu
Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`:
-{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[9] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
### Incluye la documentación personalizada para archivos estáticos { #include-the-custom-docs-for-static-files }
@@ -160,7 +160,7 @@ Nuevamente, puedes reutilizar las funciones internas de FastAPI para crear las p
Y de manera similar para ReDoc...
-{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[2:6,14:22,25:27,30:36] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
/// tip | Consejo
@@ -176,7 +176,7 @@ Swagger UI lo manejará detrás de escena para ti, pero necesita este auxiliar d
Ahora, para poder probar que todo funciona, crea una *path operation*:
-{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[39:41] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
### Prueba la UI de Archivos Estáticos { #test-static-files-ui }
diff --git a/docs/es/docs/how-to/extending-openapi.md b/docs/es/docs/how-to/extending-openapi.md
index 2611b6e1b..d08fae073 100644
--- a/docs/es/docs/how-to/extending-openapi.md
+++ b/docs/es/docs/how-to/extending-openapi.md
@@ -43,19 +43,19 @@ Por ejemplo, vamos a añadir documentación de Strawberry.
diff --git a/docs/es/docs/how-to/separate-openapi-schemas.md b/docs/es/docs/how-to/separate-openapi-schemas.md
index 903313599..db9b46ddb 100644
--- a/docs/es/docs/how-to/separate-openapi-schemas.md
+++ b/docs/es/docs/how-to/separate-openapi-schemas.md
@@ -85,7 +85,7 @@ Probablemente el caso principal para esto es si ya tienes algún código cliente
En ese caso, puedes desactivar esta funcionalidad en **FastAPI**, con el parámetro `separate_input_output_schemas=False`.
-/// info
+/// info | Información
El soporte para `separate_input_output_schemas` fue agregado en FastAPI `0.102.0`. 🤓
diff --git a/docs/es/docs/how-to/testing-database.md b/docs/es/docs/how-to/testing-database.md
index 2fa260312..0717ea5ff 100644
--- a/docs/es/docs/how-to/testing-database.md
+++ b/docs/es/docs/how-to/testing-database.md
@@ -1,7 +1,7 @@
-# Probando una Base de Datos { #testing-a-database }
+# Escribiendo pruebas para una base de datos { #testing-a-database }
Puedes estudiar sobre bases de datos, SQL y SQLModel en la documentación de SQLModel. 🤓
Hay un mini tutorial sobre el uso de SQLModel con FastAPI. ✨
-Ese tutorial incluye una sección sobre cómo probar bases de datos SQL. 😎
+Ese tutorial incluye una sección sobre escribir pruebas para bases de datos SQL. 😎
diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md
index ffea0ed54..0544eb9ba 100644
--- a/docs/es/docs/index.md
+++ b/docs/es/docs/index.md
@@ -40,7 +40,7 @@ Las funcionalidades clave son:
* **Rápido**: Muy alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks Python más rápidos disponibles](#performance).
* **Rápido de programar**: Aumenta la velocidad para desarrollar funcionalidades en aproximadamente un 200% a 300%. *
* **Menos bugs**: Reduce en aproximadamente un 40% los errores inducidos por humanos (desarrolladores). *
-* **Intuitivo**: Gran soporte para editores. Autocompletado en todas partes. Menos tiempo depurando.
+* **Intuitivo**: Gran soporte para editores. Autocompletado en todas partes. Menos tiempo depurando.
* **Fácil**: Diseñado para ser fácil de usar y aprender. Menos tiempo leyendo documentación.
* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades desde cada declaración de parámetro. Menos bugs.
* **Robusto**: Obtén código listo para producción. Con documentación interactiva automática.
@@ -368,7 +368,7 @@ item: Item
* Validación de datos:
* Errores automáticos y claros cuando los datos son inválidos.
* Validación incluso para objetos JSON profundamente anidados.
-* Conversión de datos de entrada: de la red a los datos y tipos de Python. Leyendo desde:
+* Conversión de datos de entrada: de la red a los datos y tipos de Python. Leyendo desde:
* JSON.
* Parámetros de path.
* Parámetros de query.
@@ -376,7 +376,7 @@ item: Item
* Headers.
* Forms.
* Archivos.
-* Conversión de datos de salida: convirtiendo de datos y tipos de Python a datos de red (como JSON):
+* Conversión de datos de salida: convirtiendo de datos y tipos de Python a datos de red (como JSON):
* Convertir tipos de Python (`str`, `int`, `float`, `bool`, `list`, etc).
* Objetos `datetime`.
* Objetos `UUID`.
@@ -439,7 +439,7 @@ Para un ejemplo más completo incluyendo más funcionalidades, ve al Inyección de Dependencias** muy poderoso y fácil de usar.
+* Un sistema de **Inyección de Dependencias** muy poderoso y fácil de usar.
* Seguridad y autenticación, incluyendo soporte para **OAuth2** con **tokens JWT** y autenticación **HTTP Basic**.
* Técnicas más avanzadas (pero igualmente fáciles) para declarar **modelos JSON profundamente anidados** (gracias a Pydantic).
* Integración con **GraphQL** usando Strawberry y otros paquetes.
@@ -524,7 +524,7 @@ Usadas por Starlette:
* httpx - Requerido si deseas usar el `TestClient`.
* jinja2 - Requerido si deseas usar la configuración de plantilla por defecto.
-* python-multipart - Requerido si deseas soportar "parsing" de forms, con `request.form()`.
+* python-multipart - Requerido si deseas soportar form "parsing", con `request.form()`.
Usadas por FastAPI:
diff --git a/docs/es/docs/project-generation.md b/docs/es/docs/project-generation.md
index b4aa11d0d..6d48d0be5 100644
--- a/docs/es/docs/project-generation.md
+++ b/docs/es/docs/project-generation.md
@@ -6,7 +6,7 @@ Puedes usar esta plantilla para comenzar, ya que incluye gran parte de la config
Repositorio de GitHub: Plantilla Full Stack FastAPI
-## Plantilla Full Stack FastAPI - Tecnología y Funcionalidades { #full-stack-fastapi-template-technology-stack-and-features }
+## Plantilla Full Stack FastAPI - Stack de tecnología y funcionalidades { #full-stack-fastapi-template-technology-stack-and-features }
- ⚡ [**FastAPI**](https://fastapi.tiangolo.com/es) para la API del backend en Python.
- 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para las interacciones con bases de datos SQL en Python (ORM).
diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md
index 60b50a08f..28e2953d3 100644
--- a/docs/es/docs/python-types.md
+++ b/docs/es/docs/python-types.md
@@ -2,7 +2,7 @@
Python tiene soporte para "anotaciones de tipos" opcionales (también llamadas "type hints").
-Estas **"anotaciones de tipos"** o type hints son una sintaxis especial que permite declarar el tipo de una variable.
+Estas **"anotaciones de tipos"** o type hints son una sintaxis especial que permite declarar el tipo de una variable.
Al declarar tipos para tus variables, los editores y herramientas te pueden proporcionar un mejor soporte.
@@ -22,7 +22,7 @@ Si eres un experto en Python, y ya sabes todo sobre las anotaciones de tipos, sa
Comencemos con un ejemplo simple:
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
Llamar a este programa genera:
@@ -34,9 +34,9 @@ La función hace lo siguiente:
* Toma un `first_name` y `last_name`.
* Convierte la primera letra de cada uno a mayúsculas con `title()`.
-* Concatena ambos con un espacio en el medio.
+* Concatena ambos con un espacio en el medio.
-{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
### Edítalo { #edit-it }
@@ -78,7 +78,7 @@ Eso es todo.
Esas son las "anotaciones de tipos":
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
Eso no es lo mismo que declarar valores predeterminados como sería con:
@@ -106,7 +106,7 @@ Con eso, puedes desplazarte, viendo las opciones, hasta que encuentres la que "t
Revisa esta función, ya tiene anotaciones de tipos:
-{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
Porque el editor conoce los tipos de las variables, no solo obtienes autocompletado, también obtienes chequeo de errores:
@@ -114,7 +114,7 @@ Porque el editor conoce los tipos de las variables, no solo obtienes autocomplet
Ahora sabes que debes corregirlo, convertir `age` a un string con `str(age)`:
-{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
## Declaración de tipos { #declaring-types }
@@ -133,29 +133,32 @@ Puedes usar, por ejemplo:
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### Tipos genéricos con parámetros de tipo { #generic-types-with-type-parameters }
+### Módulo `typing` { #typing-module }
-Hay algunas estructuras de datos que pueden contener otros valores, como `dict`, `list`, `set` y `tuple`. Y los valores internos también pueden tener su propio tipo.
+Para algunos casos adicionales, podrías necesitar importar algunas cosas del módulo `typing` de la standard library, por ejemplo cuando quieres declarar que algo tiene "cualquier tipo", puedes usar `Any` de `typing`:
-Estos tipos que tienen tipos internos se denominan tipos "**genéricos**". Y es posible declararlos, incluso con sus tipos internos.
+```python
+from typing import Any
-Para declarar esos tipos y los tipos internos, puedes usar el módulo estándar de Python `typing`. Existe específicamente para soportar estas anotaciones de tipos.
-#### Versiones más recientes de Python { #newer-versions-of-python }
+def some_function(data: Any):
+ print(data)
+```
-La sintaxis que utiliza `typing` es **compatible** con todas las versiones, desde Python 3.6 hasta las versiones más recientes, incluyendo Python 3.9, Python 3.10, etc.
+### Tipos genéricos { #generic-types }
-A medida que avanza Python, las **versiones más recientes** vienen con soporte mejorado para estas anotaciones de tipos y en muchos casos ni siquiera necesitarás importar y usar el módulo `typing` para declarar las anotaciones de tipos.
+Algunos tipos pueden tomar "parámetros de tipo" entre corchetes, para definir sus tipos internos, por ejemplo una "lista de strings" se declararía `list[str]`.
-Si puedes elegir una versión más reciente de Python para tu proyecto, podrás aprovechar esa simplicidad adicional.
+Estos tipos que pueden tomar parámetros de tipo se llaman **Tipos Genéricos** o **Genéricos**.
-En toda la documentación hay ejemplos compatibles con cada versión de Python (cuando hay una diferencia).
+Puedes usar los mismos tipos integrados como genéricos (con corchetes y tipos dentro):
-Por ejemplo, "**Python 3.6+**" significa que es compatible con Python 3.6 o superior (incluyendo 3.7, 3.8, 3.9, 3.10, etc). Y "**Python 3.9+**" significa que es compatible con Python 3.9 o superior (incluyendo 3.10, etc).
-
-Si puedes usar las **últimas versiones de Python**, utiliza los ejemplos para la última versión, esos tendrán la **mejor y más simple sintaxis**, por ejemplo, "**Python 3.10+**".
+* `list`
+* `tuple`
+* `set`
+* `dict`
#### Lista { #list }
@@ -167,7 +170,7 @@ Como tipo, pon `list`.
Como la lista es un tipo que contiene algunos tipos internos, los pones entre corchetes:
-{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
/// info | Información
@@ -193,7 +196,7 @@ Y aún así, el editor sabe que es un `str` y proporciona soporte para eso.
Harías lo mismo para declarar `tuple`s y `set`s:
-{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
Esto significa:
@@ -208,7 +211,7 @@ El primer parámetro de tipo es para las claves del `dict`.
El segundo parámetro de tipo es para los valores del `dict`:
-{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Esto significa:
@@ -218,46 +221,22 @@ Esto significa:
#### Union { #union }
-Puedes declarar que una variable puede ser cualquier de **varios tipos**, por ejemplo, un `int` o un `str`.
+Puedes declarar que una variable puede ser cualquiera de **varios tipos**, por ejemplo, un `int` o un `str`.
-En Python 3.6 y posterior (incluyendo Python 3.10) puedes usar el tipo `Union` de `typing` y poner dentro de los corchetes los posibles tipos a aceptar.
+Para definirlo usas la barra vertical (`|`) para separar ambos tipos.
-En Python 3.10 también hay una **nueva sintaxis** donde puedes poner los posibles tipos separados por una barra vertical (`|`).
-
-//// tab | Python 3.10+
+Esto se llama una "unión", porque la variable puede ser cualquiera en la unión de esos dos conjuntos de tipos.
```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-////
-
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b_py39.py!}
-```
-
-////
-
-En ambos casos, esto significa que `item` podría ser un `int` o un `str`.
+Esto significa que `item` podría ser un `int` o un `str`.
#### Posiblemente `None` { #possibly-none }
Puedes declarar que un valor podría tener un tipo, como `str`, pero que también podría ser `None`.
-En Python 3.6 y posteriores (incluyendo Python 3.10) puedes declararlo importando y usando `Optional` del módulo `typing`.
-
-```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-Usar `Optional[str]` en lugar de solo `str` te permitirá al editor ayudarte a detectar errores donde podrías estar asumiendo que un valor siempre es un `str`, cuando en realidad también podría ser `None`.
-
-`Optional[Something]` es realmente un atajo para `Union[Something, None]`, son equivalentes.
-
-Esto también significa que en Python 3.10, puedes usar `Something | None`:
-
//// tab | Python 3.10+
```Python hl_lines="1"
@@ -266,96 +245,7 @@ Esto también significa que en Python 3.10, puedes usar `Something | None`:
////
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-////
-
-//// tab | Python 3.9+ alternativa
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b_py39.py!}
-```
-
-////
-
-#### Uso de `Union` u `Optional` { #using-union-or-optional }
-
-Si estás usando una versión de Python inferior a 3.10, aquí tienes un consejo desde mi punto de vista muy **subjetivo**:
-
-* 🚨 Evita usar `Optional[SomeType]`
-* En su lugar ✨ **usa `Union[SomeType, None]`** ✨.
-
-Ambos son equivalentes y debajo son lo mismo, pero recomendaría `Union` en lugar de `Optional` porque la palabra "**opcional**" parecería implicar que el valor es opcional, y en realidad significa "puede ser `None`", incluso si no es opcional y aún es requerido.
-
-Creo que `Union[SomeType, None]` es más explícito sobre lo que significa.
-
-Se trata solo de las palabras y nombres. Pero esas palabras pueden afectar cómo tú y tus compañeros de equipo piensan sobre el código.
-
-Como ejemplo, tomemos esta función:
-
-{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
-
-El parámetro `name` está definido como `Optional[str]`, pero **no es opcional**, no puedes llamar a la función sin el parámetro:
-
-```Python
-say_hi() # ¡Oh, no, esto lanza un error! 😱
-```
-
-El parámetro `name` sigue siendo **requerido** (no *opcional*) porque no tiene un valor predeterminado. Aún así, `name` acepta `None` como valor:
-
-```Python
-say_hi(name=None) # Esto funciona, None es válido 🎉
-```
-
-La buena noticia es que, una vez que estés en Python 3.10, no tendrás que preocuparte por eso, ya que podrás simplemente usar `|` para definir uniones de tipos:
-
-{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
-
-Y entonces no tendrás que preocuparte por nombres como `Optional` y `Union`. 😎
-
-#### Tipos genéricos { #generic-types }
-
-Estos tipos que toman parámetros de tipo en corchetes se llaman **Tipos Genéricos** o **Genéricos**, por ejemplo:
-
-//// tab | Python 3.10+
-
-Puedes usar los mismos tipos integrados como genéricos (con corchetes y tipos dentro):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-Y, como con versiones anteriores de Python, desde el módulo `typing`:
-
-* `Union`
-* `Optional`
-* ...y otros.
-
-En Python 3.10, como alternativa a usar los genéricos `Union` y `Optional`, puedes usar la barra vertical (`|`) para declarar uniones de tipos, eso es mucho mejor y más simple.
-
-////
-
-//// tab | Python 3.9+
-
-Puedes usar los mismos tipos integrados como genéricos (con corchetes y tipos dentro):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-Y generics desde el módulo `typing`:
-
-* `Union`
-* `Optional`
-* ...y otros.
-
-////
+Usar `str | None` en lugar de solo `str` te permitirá al editor ayudarte a detectar errores donde podrías estar asumiendo que un valor siempre es un `str`, cuando en realidad también podría ser `None`.
### Clases como tipos { #classes-as-types }
@@ -363,11 +253,11 @@ También puedes declarar una clase como el tipo de una variable.
Digamos que tienes una clase `Person`, con un nombre:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
Luego puedes declarar una variable para que sea de tipo `Person`:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
Y luego, nuevamente, obtienes todo el soporte del editor:
@@ -403,19 +293,13 @@ Para saber más sobre Required Optional fields.
-
-///
-
## Anotaciones de tipos con metadata { #type-hints-with-metadata-annotations }
-Python también tiene una funcionalidad que permite poner **metadatos adicional** en estas anotaciones de tipos usando `Annotated`.
+Python también tiene una funcionalidad que permite poner **metadata adicional** en estas anotaciones de tipos usando `Annotated`.
-Desde Python 3.9, `Annotated` es parte de la standard library, así que puedes importarlo desde `typing`.
+Puedes importar `Annotated` desde `typing`.
-{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
Python en sí no hace nada con este `Annotated`. Y para los editores y otras herramientas, el tipo sigue siendo `str`.
diff --git a/docs/es/docs/translation-banner.md b/docs/es/docs/translation-banner.md
new file mode 100644
index 000000000..e38f20cbb
--- /dev/null
+++ b/docs/es/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Traducción por IA y humanos
+
+Esta traducción fue hecha por IA guiada por humanos. 🤝
+
+Podría tener errores al interpretar el significado original, o sonar poco natural, etc. 🤖
+
+Puedes mejorar esta traducción [ayudándonos a guiar mejor al LLM de IA](https://fastapi.tiangolo.com/es/contributing/#translations).
+
+[Versión en inglés](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/es/docs/tutorial/background-tasks.md b/docs/es/docs/tutorial/background-tasks.md
index cc8a2c9cb..10ad4b5eb 100644
--- a/docs/es/docs/tutorial/background-tasks.md
+++ b/docs/es/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@ Esto incluye, por ejemplo:
Primero, importa `BackgroundTasks` y define un parámetro en tu *path operation function* con una declaración de tipo de `BackgroundTasks`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI** creará el objeto de tipo `BackgroundTasks` por ti y lo pasará como ese parámetro.
@@ -31,13 +31,13 @@ En este caso, la función de tarea escribirá en un archivo (simulando el envío
Y como la operación de escritura no usa `async` y `await`, definimos la función con un `def` normal:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
## Agregar la tarea en segundo plano { #add-the-background-task }
Dentro de tu *path operation function*, pasa tu función de tarea al objeto de *background tasks* con el método `.add_task()`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` recibe como argumentos:
diff --git a/docs/es/docs/tutorial/bigger-applications.md b/docs/es/docs/tutorial/bigger-applications.md
index 7938a1215..96b58a720 100644
--- a/docs/es/docs/tutorial/bigger-applications.md
+++ b/docs/es/docs/tutorial/bigger-applications.md
@@ -85,7 +85,7 @@ Puedes crear las *path operations* para ese módulo usando `APIRouter`.
Lo importas y creas una "instance" de la misma manera que lo harías con la clase `FastAPI`:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
### *Path operations* con `APIRouter` { #path-operations-with-apirouter }
@@ -93,7 +93,7 @@ Y luego lo usas para declarar tus *path operations*.
Úsalo de la misma manera que usarías la clase `FastAPI`:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
Puedes pensar en `APIRouter` como una clase "mini `FastAPI`".
@@ -117,7 +117,7 @@ Así que las ponemos en su propio módulo `dependencies` (`app/dependencies.py`)
Ahora utilizaremos una dependencia simple para leer un header `X-Token` personalizado:
-{* ../../docs_src/bigger_applications/app_an_py39/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
/// tip | Consejo
@@ -149,7 +149,7 @@ Sabemos que todas las *path operations* en este módulo tienen el mismo:
Entonces, en lugar de agregar todo eso a cada *path operation*, podemos agregarlo al `APIRouter`.
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
Como el path de cada *path operation* tiene que empezar con `/`, como en:
@@ -208,7 +208,7 @@ Y necesitamos obtener la función de dependencia del módulo `app.dependencies`,
Así que usamos un import relativo con `..` para las dependencias:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[3] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}
#### Cómo funcionan los imports relativos { #how-relative-imports-work }
@@ -279,7 +279,7 @@ No estamos agregando el prefijo `/items` ni los `tags=["items"]` a cada *path op
Pero aún podemos agregar _más_ `tags` que se aplicarán a una *path operation* específica, y también algunas `responses` extra específicas para esa *path operation*:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}
/// tip | Consejo
@@ -305,13 +305,13 @@ Importas y creas una clase `FastAPI` como normalmente.
Y podemos incluso declarar [dependencias globales](dependencies/global-dependencies.md){.internal-link target=_blank} que se combinarán con las dependencias para cada `APIRouter`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[1,3,7] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
### Importar el `APIRouter` { #import-the-apirouter }
Ahora importamos los otros submódulos que tienen `APIRouter`s:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[4:5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}
Como los archivos `app/routers/users.py` y `app/routers/items.py` son submódulos que son parte del mismo paquete de Python `app`, podemos usar un solo punto `.` para importarlos usando "imports relativos".
@@ -374,13 +374,13 @@ el `router` de `users` sobrescribiría el de `items` y no podríamos usarlos al
Así que, para poder usar ambos en el mismo archivo, importamos los submódulos directamente:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}
### Incluir los `APIRouter`s para `users` y `items` { #include-the-apirouters-for-users-and-items }
Ahora, incluyamos los `router`s de los submódulos `users` y `items`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[10:11] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}
/// info | Información
@@ -420,13 +420,13 @@ Contiene un `APIRouter` con algunas *path operations* de administración que tu
Para este ejemplo será súper simple. Pero digamos que porque está compartido con otros proyectos en la organización, no podemos modificarlo y agregar un `prefix`, `dependencies`, `tags`, etc. directamente al `APIRouter`:
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
Pero aún queremos configurar un `prefix` personalizado al incluir el `APIRouter` para que todas sus *path operations* comiencen con `/admin`, queremos asegurarlo con las `dependencies` que ya tenemos para este proyecto, y queremos incluir `tags` y `responses`.
Podemos declarar todo eso sin tener que modificar el `APIRouter` original pasando esos parámetros a `app.include_router()`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[14:17] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}
De esa manera, el `APIRouter` original permanecerá sin modificar, por lo que aún podemos compartir ese mismo archivo `app/internal/admin.py` con otros proyectos en la organización.
@@ -447,7 +447,7 @@ También podemos agregar *path operations* directamente a la app de `FastAPI`.
Aquí lo hacemos... solo para mostrar que podemos 🤷:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[21:23] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}
y funcionará correctamente, junto con todas las otras *path operations* añadidas con `app.include_router()`.
diff --git a/docs/es/docs/tutorial/body-multiple-params.md b/docs/es/docs/tutorial/body-multiple-params.md
index c52486f9b..c78dd2881 100644
--- a/docs/es/docs/tutorial/body-multiple-params.md
+++ b/docs/es/docs/tutorial/body-multiple-params.md
@@ -104,12 +104,6 @@ Como, por defecto, los valores singulares se interpretan como parámetros de que
q: str | None = None
```
-O en Python 3.9:
-
-```Python
-q: Union[str, None] = None
-```
-
Por ejemplo:
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
diff --git a/docs/es/docs/tutorial/body-nested-models.md b/docs/es/docs/tutorial/body-nested-models.md
index 0dfd6576f..5f723e4c9 100644
--- a/docs/es/docs/tutorial/body-nested-models.md
+++ b/docs/es/docs/tutorial/body-nested-models.md
@@ -164,7 +164,7 @@ images: list[Image]
como en:
-{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
## Soporte de editor en todas partes { #editor-support-everywhere }
@@ -194,7 +194,7 @@ Eso es lo que vamos a ver aquí.
En este caso, aceptarías cualquier `dict` siempre que tenga claves `int` con valores `float`:
-{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
/// tip | Consejo
diff --git a/docs/es/docs/tutorial/body.md b/docs/es/docs/tutorial/body.md
index dde39f78c..3adf2e65c 100644
--- a/docs/es/docs/tutorial/body.md
+++ b/docs/es/docs/tutorial/body.md
@@ -74,7 +74,7 @@ Con solo esa declaración de tipo en Python, **FastAPI** hará lo siguiente:
* Proporcionar los datos recibidos en el parámetro `item`.
* Como lo declaraste en la función como de tipo `Item`, también tendrás todo el soporte del editor (autocompletado, etc.) para todos los atributos y sus tipos.
* Generar definiciones de JSON Schema para tu modelo, que también puedes usar en cualquier otro lugar si tiene sentido para tu proyecto.
-* Esos esquemas serán parte del esquema de OpenAPI generado y usados por las UIs de documentación automática.
+* Esos esquemas serán parte del esquema de OpenAPI generado y usados por las UIs de documentación automática.
## Documentación automática { #automatic-docs }
@@ -155,7 +155,7 @@ Los parámetros de la función se reconocerán de la siguiente manera:
FastAPI sabrá que el valor de `q` no es requerido debido al valor por defecto `= None`.
-El `str | None` (Python 3.10+) o `Union` en `Union[str, None]` (Python 3.9+) no es utilizado por FastAPI para determinar que el valor no es requerido, sabrá que no es requerido porque tiene un valor por defecto de `= None`.
+El `str | None` no es utilizado por FastAPI para determinar que el valor no es requerido, sabrá que no es requerido porque tiene un valor por defecto de `= None`.
Pero agregar las anotaciones de tipos permitirá que tu editor te brinde un mejor soporte y detecte errores.
@@ -163,4 +163,4 @@ Pero agregar las anotaciones de tipos permitirá que tu editor te brinde un mejo
## Sin Pydantic { #without-pydantic }
-Si no quieres usar modelos de Pydantic, también puedes usar parámetros **Body**. Consulta la documentación para [Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
+Si no quieres usar modelos de Pydantic, también puedes usar parámetros **Body**. Consulta la documentación para [Body - Múltiples parámetros: Valores singulares en el body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
diff --git a/docs/es/docs/tutorial/cookie-param-models.md b/docs/es/docs/tutorial/cookie-param-models.md
index dab7d8c0a..4e6038a46 100644
--- a/docs/es/docs/tutorial/cookie-param-models.md
+++ b/docs/es/docs/tutorial/cookie-param-models.md
@@ -46,7 +46,7 @@ Pero incluso si **rellenas los datos** y haces clic en "Execute", como la UI de
En algunos casos de uso especiales (probablemente no muy comunes), podrías querer **restringir** las cookies que deseas recibir.
-Tu API ahora tiene el poder de controlar su propio consentimiento de cookies. 🤪🍪
+Tu API ahora tiene el poder de controlar su propio consentimiento de cookies. 🤪🍪
Puedes usar la configuración del modelo de Pydantic para `prohibir` cualquier campo `extra`:
@@ -54,9 +54,9 @@ Puedes usar la configuración del modelo de Pydantic para `prohibir` cualquier c
Si un cliente intenta enviar algunas **cookies extra**, recibirán un response de **error**.
-Pobres banners de cookies con todo su esfuerzo para obtener tu consentimiento para que la API lo rechace. 🍪
+Pobres banners de cookies con todo su esfuerzo para obtener tu consentimiento para que la API lo rechace. 🍪
-Por ejemplo, si el cliente intenta enviar una cookie `santa_tracker` con un valor de `good-list-please`, el cliente recibirá un response de **error** que le informa que la cookie `santa_tracker` no está permitida:
+Por ejemplo, si el cliente intenta enviar una cookie `santa_tracker` con un valor de `good-list-please`, el cliente recibirá un response de **error** que le informa que la `santa_tracker` cookie no está permitida:
```json
{
@@ -73,4 +73,4 @@ Por ejemplo, si el cliente intenta enviar una cookie `santa_tracker` con un valo
## Resumen { #summary }
-Puedes usar **modelos de Pydantic** para declarar **cookies** en **FastAPI**. 😎
+Puedes usar **modelos de Pydantic** para declarar **cookies** en **FastAPI**. 😎
diff --git a/docs/es/docs/tutorial/cors.md b/docs/es/docs/tutorial/cors.md
index c1a23295e..a118d814b 100644
--- a/docs/es/docs/tutorial/cors.md
+++ b/docs/es/docs/tutorial/cors.md
@@ -46,7 +46,8 @@ También puedes especificar si tu backend permite:
* Métodos HTTP específicos (`POST`, `PUT`) o todos ellos con el comodín `"*"`.
* Headers HTTP específicos o todos ellos con el comodín `"*"`.
-{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *}
+
Los parámetros predeterminados utilizados por la implementación de `CORSMiddleware` son restrictivos por defecto, por lo que necesitarás habilitar explícitamente orígenes, métodos o headers particulares para que los navegadores estén permitidos de usarlos en un contexto de Cross-Domain.
diff --git a/docs/es/docs/tutorial/debugging.md b/docs/es/docs/tutorial/debugging.md
index c31daf40f..a2d47f2da 100644
--- a/docs/es/docs/tutorial/debugging.md
+++ b/docs/es/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@ Puedes conectar el depurador en tu editor, por ejemplo con Visual Studio Code o
En tu aplicación de FastAPI, importa y ejecuta `uvicorn` directamente:
-{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *}
### Acerca de `__name__ == "__main__"` { #about-name-main }
diff --git a/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md
index a3a75efcd..7506bda47 100644
--- a/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -101,7 +101,7 @@ Ahora puedes declarar tu dependencia usando esta clase.
Nota cómo escribimos `CommonQueryParams` dos veces en el código anterior:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ sin `Annotated`
+//// tab | Python 3.10+ sin `Annotated`
/// tip | Consejo
@@ -137,7 +137,7 @@ Es a partir de este que **FastAPI** extraerá los parámetros declarados y es lo
En este caso, el primer `CommonQueryParams`, en:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.9+ sin `Annotated`
+//// tab | Python 3.10+ sin `Annotated`
/// tip | Consejo
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
De hecho, podrías escribir simplemente:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ sin `Annotated`
+//// tab | Python 3.10+ sin `Annotated`
/// tip | Consejo
@@ -197,7 +197,7 @@ Pero declarar el tipo es recomendable, ya que de esa manera tu editor sabrá lo
Pero ves que estamos teniendo algo de repetición de código aquí, escribiendo `CommonQueryParams` dos veces:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ sin `Annotated`
+//// tab | Python 3.10+ sin `Annotated`
/// tip | Consejo
@@ -225,7 +225,7 @@ Para esos casos específicos, puedes hacer lo siguiente:
En lugar de escribir:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ sin `Annotated`
+//// tab | Python 3.10+ sin `Annotated`
/// tip | Consejo
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
...escribes:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.9+ sin `Annotated`
+//// tab | Python 3.10+ sin `Annotated`
/// tip | Consejo
diff --git a/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 60baa93a9..5eadbe7e1 100644
--- a/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -14,7 +14,7 @@ El decorador de *path operation* recibe un argumento opcional `dependencies`.
Debe ser una `list` de `Depends()`:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
Estas dependencias serán ejecutadas/resueltas de la misma manera que las dependencias normales. Pero su valor (si devuelven alguno) no será pasado a tu *path operation function*.
@@ -44,13 +44,13 @@ Puedes usar las mismas *funciones* de dependencia que usas normalmente.
Pueden declarar requisitos de request (como headers) u otras sub-dependencias:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
### Lanzar excepciones { #raise-exceptions }
Estas dependencias pueden `raise` excepciones, igual que las dependencias normales:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
### Valores de retorno { #return-values }
@@ -58,7 +58,7 @@ Y pueden devolver valores o no, los valores no serán usados.
Así que, puedes reutilizar una dependencia normal (que devuelve un valor) que ya uses en otro lugar, y aunque el valor no se use, la dependencia será ejecutada:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
## Dependencias para un grupo de *path operations* { #dependencies-for-a-group-of-path-operations }
diff --git a/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md
index aa645daa4..2cd68eddd 100644
--- a/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,6 +1,6 @@
# Dependencias con yield { #dependencies-with-yield }
-FastAPI admite dependencias que realizan algunos pasos adicionales después de finalizar.
+FastAPI admite dependencias que realizan algunos pasos adicionales después de finalizar.
Para hacer esto, usa `yield` en lugar de `return`, y escribe los pasos adicionales (código) después.
@@ -29,15 +29,15 @@ Por ejemplo, podrías usar esto para crear una sesión de base de datos y cerrar
Solo el código anterior e incluyendo la declaración `yield` se ejecuta antes de crear un response:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
El valor generado es lo que se inyecta en *path operations* y otras dependencias:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
El código posterior a la declaración `yield` se ejecuta después del response:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
/// tip | Consejo
@@ -57,7 +57,7 @@ Por lo tanto, puedes buscar esa excepción específica dentro de la dependencia
Del mismo modo, puedes usar `finally` para asegurarte de que los pasos de salida se ejecuten, sin importar si hubo una excepción o no.
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
## Sub-dependencias con `yield` { #sub-dependencies-with-yield }
@@ -67,7 +67,7 @@ Puedes tener sub-dependencias y "árboles" de sub-dependencias de cualquier tama
Por ejemplo, `dependency_c` puede tener una dependencia de `dependency_b`, y `dependency_b` de `dependency_a`:
-{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *}
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
Y todas ellas pueden usar `yield`.
@@ -75,7 +75,7 @@ En este caso, `dependency_c`, para ejecutar su código de salida, necesita que e
Y, a su vez, `dependency_b` necesita que el valor de `dependency_a` (aquí llamado `dep_a`) esté disponible para su código de salida.
-{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *}
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
De la misma manera, podrías tener algunas dependencias con `yield` y otras dependencias con `return`, y hacer que algunas de esas dependan de algunas de las otras.
@@ -109,7 +109,7 @@ Pero está ahí para ti si la necesitas. 🤓
///
-{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *}
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
Si quieres capturar excepciones y crear un response personalizado en base a eso, crea un [Manejador de Excepciones Personalizado](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
@@ -117,7 +117,7 @@ Si quieres capturar excepciones y crear un response personalizado en base a eso,
Si capturas una excepción usando `except` en una dependencia con `yield` y no la lanzas nuevamente (o lanzas una nueva excepción), FastAPI no podrá notar que hubo una excepción, al igual que sucedería con Python normal:
-{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *}
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
En este caso, el cliente verá un response *HTTP 500 Internal Server Error* como debería, dado que no estamos lanzando una `HTTPException` o similar, pero el servidor **no tendrá ningún registro** ni ninguna otra indicación de cuál fue el error. 😱
@@ -127,7 +127,7 @@ Si capturas una excepción en una dependencia con `yield`, a menos que estés la
Puedes volver a lanzar la misma excepción usando `raise`:
-{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *}
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
Ahora el cliente obtendrá el mismo response *HTTP 500 Internal Server Error*, pero el servidor tendrá nuestro `InternalError` personalizado en los registros. 😎
@@ -190,7 +190,7 @@ Normalmente, el código de salida de las dependencias con `yield` se ejecuta **d
Pero si sabes que no necesitarás usar la dependencia después de regresar de la *path operation function*, puedes usar `Depends(scope="function")` para decirle a FastAPI que debe cerrar la dependencia después de que la *path operation function* regrese, pero **antes** de que se envíe el **response**.
-{* ../../docs_src/dependencies/tutorial008e_an_py39.py hl[12,16] *}
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
`Depends()` recibe un parámetro `scope` que puede ser:
@@ -234,7 +234,6 @@ participant operation as Path Operation
Las dependencias con `yield` han evolucionado con el tiempo para cubrir diferentes casos de uso y corregir algunos problemas.
Si quieres ver qué ha cambiado en diferentes versiones de FastAPI, puedes leer más al respecto en la guía avanzada, en [Dependencias avanzadas - Dependencias con `yield`, `HTTPException`, `except` y Tareas en Background](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks){.internal-link target=_blank}.
-
## Context Managers { #context-managers }
### Qué son los "Context Managers" { #what-are-context-managers }
@@ -270,7 +269,7 @@ En Python, puedes crear Context Managers Inyección de Dependencias** muy poderoso pero intuitivo.
+**FastAPI** tiene un sistema de **Inyección de Dependencias** muy poderoso pero intuitivo.
Está diseñado para ser muy simple de usar, y para hacer que cualquier desarrollador integre otros componentes con **FastAPI** de forma muy sencilla.
diff --git a/docs/es/docs/tutorial/dependencies/sub-dependencies.md b/docs/es/docs/tutorial/dependencies/sub-dependencies.md
index e74d65d7e..95f3fe817 100644
--- a/docs/es/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/es/docs/tutorial/dependencies/sub-dependencies.md
@@ -58,11 +58,11 @@ query_extractor --> query_or_cookie_extractor --> read_query
Si una de tus dependencias se declara varias veces para la misma *path operation*, por ejemplo, múltiples dependencias tienen una sub-dependencia común, **FastAPI** sabrá llamar a esa sub-dependencia solo una vez por request.
-Y guardará el valor devuelto en un "cache" y lo pasará a todos los "dependants" que lo necesiten en ese request específico, en lugar de llamar a la dependencia varias veces para el mismo request.
+Y guardará el valor devuelto en un "caché" y lo pasará a todos los "dependants" que lo necesiten en ese request específico, en lugar de llamar a la dependencia varias veces para el mismo request.
-En un escenario avanzado donde sabes que necesitas que la dependencia se llame en cada paso (posiblemente varias veces) en el mismo request en lugar de usar el valor "cache", puedes establecer el parámetro `use_cache=False` al usar `Depends`:
+En un escenario avanzado donde sabes que necesitas que la dependencia se llame en cada paso (posiblemente varias veces) en el mismo request en lugar de usar el valor "en caché", puedes establecer el parámetro `use_cache=False` al usar `Depends`:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python hl_lines="1"
async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
@@ -71,7 +71,7 @@ async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_ca
////
-//// tab | Python 3.9+ sin Anotaciones
+//// tab | Python 3.10+ sin Anotaciones
/// tip | Consejo
diff --git a/docs/es/docs/tutorial/encoder.md b/docs/es/docs/tutorial/encoder.md
index 319ae1bde..df6099a8b 100644
--- a/docs/es/docs/tutorial/encoder.md
+++ b/docs/es/docs/tutorial/encoder.md
@@ -26,7 +26,7 @@ En este ejemplo, convertiría el modelo de Pydantic a un `dict`, y el `datetime`
El resultado de llamarlo es algo que puede ser codificado con la función estándar de Python `json.dumps()`.
-No devuelve un gran `str` que contenga los datos en formato JSON (como una cadena de texto). Devuelve una estructura de datos estándar de Python (por ejemplo, un `dict`) con valores y sub-valores que son todos compatibles con JSON.
+No devuelve un gran `str` que contenga los datos en formato JSON (como un string). Devuelve una estructura de datos estándar de Python (por ejemplo, un `dict`) con valores y sub-valores que son todos compatibles con JSON.
/// note | Nota
diff --git a/docs/es/docs/tutorial/extra-models.md b/docs/es/docs/tutorial/extra-models.md
index d72c73e24..4621b2db2 100644
--- a/docs/es/docs/tutorial/extra-models.md
+++ b/docs/es/docs/tutorial/extra-models.md
@@ -190,9 +190,9 @@ Pero si ponemos eso en la asignación `response_model=PlaneItem | CarItem` obten
De la misma manera, puedes declarar responses de listas de objetos.
-Para eso, usa el `typing.List` estándar de Python (o simplemente `list` en Python 3.9 y posteriores):
+Para eso, usa la `list` estándar de Python:
-{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *}
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
## Response con `dict` arbitrario { #response-with-arbitrary-dict }
@@ -200,9 +200,9 @@ También puedes declarar un response usando un `dict` arbitrario plano, declaran
Esto es útil si no conoces los nombres de los campos/atributos válidos (que serían necesarios para un modelo Pydantic) de antemano.
-En este caso, puedes usar `typing.Dict` (o solo `dict` en Python 3.9 y posteriores):
+En este caso, puedes usar `dict`:
-{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *}
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
## Recapitulación { #recap }
diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md
index 789b2a011..b7ffd2c2a 100644
--- a/docs/es/docs/tutorial/first-steps.md
+++ b/docs/es/docs/tutorial/first-steps.md
@@ -2,7 +2,7 @@
El archivo FastAPI más simple podría verse así:
-{* ../../docs_src/first_steps/tutorial001_py39.py *}
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
Copia eso en un archivo `main.py`.
@@ -56,7 +56,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Esa línea muestra la URL donde tu aplicación está siendo servida, en tu máquina local.
-### Compruébalo { #check-it }
+### Revisa { #check-it }
Abre tu navegador en http://127.0.0.1:8000.
@@ -183,7 +183,7 @@ Deploying to FastAPI Cloud...
### Paso 1: importa `FastAPI` { #step-1-import-fastapi }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[1] *}
`FastAPI` es una clase de Python que proporciona toda la funcionalidad para tu API.
@@ -197,7 +197,7 @@ Puedes usar toda la funcionalidad de get operation
+* usando una get operación
/// info | Información sobre `@decorator`
@@ -320,7 +320,7 @@ Esta es nuestra "**path operation function**":
* **operation**: es `get`.
* **function**: es la función debajo del "decorador" (debajo de `@app.get("/")`).
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
Esta es una función de Python.
@@ -332,7 +332,7 @@ En este caso, es una función `async`.
También podrías definirla como una función normal en lugar de `async def`:
-{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
/// note | Nota
@@ -342,7 +342,7 @@ Si no sabes la diferencia, Revisa la sección [Async: *"¿Tienes prisa?"*](../as
### Paso 5: retorna el contenido { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
Puedes retornar un `dict`, `list`, valores singulares como `str`, `int`, etc.
diff --git a/docs/es/docs/tutorial/handling-errors.md b/docs/es/docs/tutorial/handling-errors.md
index 71e056320..265269e87 100644
--- a/docs/es/docs/tutorial/handling-errors.md
+++ b/docs/es/docs/tutorial/handling-errors.md
@@ -25,7 +25,7 @@ Para devolver responses HTTP con errores al cliente, usa `HTTPException`.
### Importa `HTTPException` { #import-httpexception }
-{* ../../docs_src/handling_errors/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
### Lanza un `HTTPException` en tu código { #raise-an-httpexception-in-your-code }
@@ -39,7 +39,7 @@ El beneficio de lanzar una excepción en lugar de `return`ar un valor será más
En este ejemplo, cuando el cliente solicita un ítem por un ID que no existe, lanza una excepción con un código de estado de `404`:
-{* ../../docs_src/handling_errors/tutorial001_py39.py hl[11] *}
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
### El response resultante { #the-resulting-response }
@@ -77,7 +77,7 @@ Probablemente no necesitarás usarlos directamente en tu código.
Pero en caso de que los necesites para un escenario avanzado, puedes agregar headers personalizados:
-{* ../../docs_src/handling_errors/tutorial002_py39.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
## Instalar manejadores de excepciones personalizados { #install-custom-exception-handlers }
@@ -89,7 +89,7 @@ Y quieres manejar esta excepción globalmente con FastAPI.
Podrías agregar un manejador de excepciones personalizado con `@app.exception_handler()`:
-{* ../../docs_src/handling_errors/tutorial003_py39.py hl[5:7,13:18,24] *}
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
Aquí, si solicitas `/unicorns/yolo`, la *path operation* lanzará un `UnicornException`.
@@ -127,7 +127,7 @@ Para sobrescribirlo, importa el `RequestValidationError` y úsalo con `@app.exce
El manejador de excepciones recibirá un `Request` y la excepción.
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[2,14:19] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
Ahora, si vas a `/items/foo`, en lugar de obtener el error JSON por defecto con:
@@ -159,7 +159,7 @@ De la misma manera, puedes sobrescribir el manejador de `HTTPException`.
Por ejemplo, podrías querer devolver un response de texto plano en lugar de JSON para estos errores:
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[3:4,9:11,25] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
/// note | Nota Técnica
@@ -183,7 +183,7 @@ El `RequestValidationError` contiene el `body` que recibió con datos inválidos
Podrías usarlo mientras desarrollas tu aplicación para registrar el body y depurarlo, devolverlo al usuario, etc.
-{* ../../docs_src/handling_errors/tutorial005_py39.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
Ahora intenta enviar un ítem inválido como:
@@ -239,6 +239,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
Si quieres usar la excepción junto con los mismos manejadores de excepciones predeterminados de **FastAPI**, puedes importar y reutilizar los manejadores de excepciones predeterminados de `fastapi.exception_handlers`:
-{* ../../docs_src/handling_errors/tutorial006_py39.py hl[2:5,15,21] *}
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
En este ejemplo solo estás `print`eando el error con un mensaje muy expresivo, pero te haces una idea. Puedes usar la excepción y luego simplemente reutilizar los manejadores de excepciones predeterminados.
diff --git a/docs/es/docs/tutorial/metadata.md b/docs/es/docs/tutorial/metadata.md
index a5d9b5ead..2163a1cb2 100644
--- a/docs/es/docs/tutorial/metadata.md
+++ b/docs/es/docs/tutorial/metadata.md
@@ -18,7 +18,7 @@ Puedes establecer los siguientes campos que se usan en la especificación OpenAP
Puedes configurarlos de la siguiente manera:
-{* ../../docs_src/metadata/tutorial001_py39.py hl[3:16, 19:32] *}
+{* ../../docs_src/metadata/tutorial001_py310.py hl[3:16, 19:32] *}
/// tip | Consejo
@@ -36,7 +36,7 @@ Desde OpenAPI 3.1.0 y FastAPI 0.99.0, también puedes establecer la `license_inf
Por ejemplo:
-{* ../../docs_src/metadata/tutorial001_1_py39.py hl[31] *}
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
## Metadata para etiquetas { #metadata-for-tags }
@@ -58,7 +58,7 @@ Probemos eso en un ejemplo con etiquetas para `users` y `items`.
Crea metadata para tus etiquetas y pásala al parámetro `openapi_tags`:
-{* ../../docs_src/metadata/tutorial004_py39.py hl[3:16,18] *}
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
Nota que puedes utilizar Markdown dentro de las descripciones, por ejemplo "login" se mostrará en negrita (**login**) y "fancy" se mostrará en cursiva (_fancy_).
@@ -72,7 +72,7 @@ No tienes que agregar metadata para todas las etiquetas que uses.
Usa el parámetro `tags` con tus *path operations* (y `APIRouter`s) para asignarlas a diferentes etiquetas:
-{* ../../docs_src/metadata/tutorial004_py39.py hl[21,26] *}
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
/// info | Información
@@ -100,7 +100,7 @@ Pero puedes configurarlo con el parámetro `openapi_url`.
Por ejemplo, para configurarlo para que se sirva en `/api/v1/openapi.json`:
-{* ../../docs_src/metadata/tutorial002_py39.py hl[3] *}
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
Si quieres deshabilitar el esquema OpenAPI completamente, puedes establecer `openapi_url=None`, eso también deshabilitará las interfaces de usuario de documentación que lo usan.
@@ -117,4 +117,4 @@ Puedes configurar las dos interfaces de usuario de documentación incluidas:
Por ejemplo, para configurar Swagger UI para que se sirva en `/documentation` y deshabilitar ReDoc:
-{* ../../docs_src/metadata/tutorial003_py39.py hl[3] *}
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/es/docs/tutorial/middleware.md b/docs/es/docs/tutorial/middleware.md
index de636a485..766e30cad 100644
--- a/docs/es/docs/tutorial/middleware.md
+++ b/docs/es/docs/tutorial/middleware.md
@@ -31,7 +31,7 @@ La función middleware recibe:
* Luego devuelve la `response` generada por la correspondiente *path operation*.
* Puedes entonces modificar aún más la `response` antes de devolverla.
-{* ../../docs_src/middleware/tutorial001_py39.py hl[8:9,11,14] *}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
/// tip | Consejo
@@ -57,7 +57,7 @@ Y también después de que se genere la `response`, antes de devolverla.
Por ejemplo, podrías añadir un custom header `X-Process-Time` que contenga el tiempo en segundos que tomó procesar la request y generar una response:
-{* ../../docs_src/middleware/tutorial001_py39.py hl[10,12:13] *}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
/// tip | Consejo
diff --git a/docs/es/docs/tutorial/path-operation-configuration.md b/docs/es/docs/tutorial/path-operation-configuration.md
index f57b322fb..90e4335b3 100644
--- a/docs/es/docs/tutorial/path-operation-configuration.md
+++ b/docs/es/docs/tutorial/path-operation-configuration.md
@@ -46,7 +46,7 @@ En estos casos, podría tener sentido almacenar las tags en un `Enum`.
**FastAPI** soporta eso de la misma manera que con strings normales:
-{* ../../docs_src/path_operation_configuration/tutorial002b_py39.py hl[1,8:10,13,18] *}
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
## Resumen y Descripción { #summary-and-description }
@@ -56,7 +56,7 @@ Puedes añadir un `summary` y `description`:
## Descripción desde docstring { #description-from-docstring }
-Como las descripciones tienden a ser largas y cubrir múltiples líneas, puedes declarar la descripción de la *path operation* en la docstring de la función y **FastAPI** la leerá desde allí.
+Como las descripciones tienden a ser largas y cubrir múltiples líneas, puedes declarar la descripción de la *path operation* en la docstring de la función y **FastAPI** la leerá desde allí.
Puedes escribir Markdown en el docstring, se interpretará y mostrará correctamente (teniendo en cuenta la indentación del docstring).
@@ -90,9 +90,9 @@ Entonces, si no proporcionas una, **FastAPI** generará automáticamente una de
## Deprecar una *path operation* { #deprecate-a-path-operation }
-Si necesitas marcar una *path operation* como deprecated, pero sin eliminarla, pasa el parámetro `deprecated`:
+Si necesitas marcar una *path operation* como deprecated, pero sin eliminarla, pasa el parámetro `deprecated`:
-{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
Se marcará claramente como deprecado en la documentación interactiva:
diff --git a/docs/es/docs/tutorial/path-params-numeric-validations.md b/docs/es/docs/tutorial/path-params-numeric-validations.md
index 569dd03dd..3a38d1d63 100644
--- a/docs/es/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/es/docs/tutorial/path-params-numeric-validations.md
@@ -2,7 +2,7 @@
De la misma manera que puedes declarar más validaciones y metadatos para los parámetros de query con `Query`, puedes declarar el mismo tipo de validaciones y metadatos para los parámetros de path con `Path`.
-## Importar Path { #import-path }
+## Importar `Path` { #import-path }
Primero, importa `Path` de `fastapi`, e importa `Annotated`:
@@ -46,19 +46,19 @@ Y no necesitas declarar nada más para ese parámetro, así que realmente no nec
Pero aún necesitas usar `Path` para el parámetro de path `item_id`. Y no quieres usar `Annotated` por alguna razón.
-Python se quejará si pones un valor con un "default" antes de un valor que no tenga un "default".
+Python se quejará si pones un valor con "por defecto" antes de un valor que no tenga "por defecto".
-Pero puedes reordenarlos y poner el valor sin un default (el parámetro de query `q`) primero.
+Pero puedes reordenarlos y poner el valor sin un valor por defecto (el parámetro de query `q`) primero.
-No importa para **FastAPI**. Detectará los parámetros por sus nombres, tipos y declaraciones por defecto (`Query`, `Path`, etc.), no le importa el orden.
+No importa para **FastAPI**. Detectará los parámetros por sus nombres, tipos y declaraciones por defecto (`Query`, `Path`, etc), no le importa el orden.
Así que puedes declarar tu función como:
-{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
Pero ten en cuenta que si usas `Annotated`, no tendrás este problema, no importará ya que no estás usando los valores por defecto de los parámetros de la función para `Query()` o `Path()`.
-{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
## Ordena los parámetros como necesites, trucos { #order-the-parameters-as-you-need-tricks }
@@ -83,13 +83,13 @@ Pasa `*`, como el primer parámetro de la función.
Python no hará nada con ese `*`, pero sabrá que todos los parámetros siguientes deben ser llamados como argumentos de palabras clave (parejas key-value), también conocidos como kwargs. Incluso si no tienen un valor por defecto.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
### Mejor con `Annotated` { #better-with-annotated }
Ten en cuenta que si usas `Annotated`, como no estás usando valores por defecto de los parámetros de la función, no tendrás este problema y probablemente no necesitarás usar `*`.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
## Validaciones numéricas: mayor o igual { #number-validations-greater-than-or-equal }
@@ -97,7 +97,7 @@ Con `Query` y `Path` (y otros que verás más adelante) puedes declarar restricc
Aquí, con `ge=1`, `item_id` necesitará ser un número entero "`g`reater than or `e`qual" a `1`.
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
## Validaciones numéricas: mayor que y menor o igual { #number-validations-greater-than-and-less-than-or-equal }
@@ -106,19 +106,19 @@ Lo mismo aplica para:
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
## Validaciones numéricas: flotantes, mayor y menor { #number-validations-floats-greater-than-and-less-than }
Las validaciones numéricas también funcionan para valores `float`.
-Aquí es donde se convierte en importante poder declarar gt y no solo ge. Ya que con esto puedes requerir, por ejemplo, que un valor sea mayor que `0`, incluso si es menor que `1`.
+Aquí es donde se convierte en importante poder declarar gt y no solo ge. Ya que con esto puedes requerir, por ejemplo, que un valor sea mayor que `0`, incluso si es menor que `1`.
Así, `0.5` sería un valor válido. Pero `0.0` o `0` no lo serían.
-Y lo mismo para lt.
+Y lo mismo para lt.
-{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
## Resumen { #recap }
diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md
index 7ba49f3b0..8dc3db351 100644
--- a/docs/es/docs/tutorial/path-params.md
+++ b/docs/es/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Puedes declarar "parámetros" o "variables" de path con la misma sintaxis que se usa en los format strings de Python:
-{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
El valor del parámetro de path `item_id` se pasará a tu función como el argumento `item_id`.
@@ -16,7 +16,7 @@ Así que, si ejecutas este ejemplo y vas a Conversión de datos { #data-conversion }
+## Conversión de datos { #data-conversion }
Si ejecutas este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/3, verás un response de:
@@ -38,7 +38,7 @@ Si ejecutas este ejemplo y abres tu navegador en "parsing" automático de request.
+Entonces, con esa declaración de tipo, **FastAPI** te ofrece "parsing" automático de request.
///
@@ -118,13 +118,13 @@ Y luego también puedes tener un path `/users/{user_id}` para obtener datos sobr
Debido a que las *path operations* se evalúan en orden, necesitas asegurarte de que el path para `/users/me` se declara antes que el de `/users/{user_id}`:
-{* ../../docs_src/path_params/tutorial003_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
De lo contrario, el path para `/users/{user_id}` también coincidiría para `/users/me`, "pensando" que está recibiendo un parámetro `user_id` con un valor de `"me"`.
De manera similar, no puedes redefinir una path operation:
-{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
La primera siempre será utilizada ya que el path coincide primero.
@@ -140,11 +140,11 @@ Al heredar de `str`, la documentación de la API podrá saber que los valores de
Luego crea atributos de clase con valores fijos, que serán los valores válidos disponibles:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
/// tip | Consejo
-Si te estás preguntando, "AlexNet", "ResNet" y "LeNet" son solo nombres de modelos de Machine Learning.
+Si te estás preguntando, "AlexNet", "ResNet" y "LeNet" son solo nombres de modelos de Machine Learning.
///
@@ -152,7 +152,7 @@ Si te estás preguntando, "AlexNet", "ResNet" y "LeNet" son solo nombres de POST.
+Si deseas leer más sobre estas codificaciones y campos de formularios, dirígete a la MDN web docs para POST.
///
@@ -143,7 +143,7 @@ Puedes hacer un archivo opcional utilizando anotaciones de tipos estándar y est
También puedes usar `File()` con `UploadFile`, por ejemplo, para establecer metadatos adicionales:
-{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
## Subidas de Múltiples Archivos { #multiple-file-uploads }
@@ -151,9 +151,9 @@ Es posible subir varios archivos al mismo tiempo.
Estarían asociados al mismo "campo de formulario" enviado usando "form data".
-Para usar eso, declara una lista de `bytes` o `UploadFile`:
+Para usar eso, declara una `list` de `bytes` o `UploadFile`:
-{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
Recibirás, como se declaró, una `list` de `bytes` o `UploadFile`s.
@@ -169,7 +169,7 @@ También podrías usar `from starlette.responses import HTMLResponse`.
Y de la misma manera que antes, puedes usar `File()` para establecer parámetros adicionales, incluso para `UploadFile`:
-{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
## Recapitulación { #recap }
diff --git a/docs/es/docs/tutorial/request-form-models.md b/docs/es/docs/tutorial/request-form-models.md
index 1f4668c84..9afadf0b2 100644
--- a/docs/es/docs/tutorial/request-form-models.md
+++ b/docs/es/docs/tutorial/request-form-models.md
@@ -24,7 +24,7 @@ Esto es compatible desde la versión `0.113.0` de FastAPI. 🤓
Solo necesitas declarar un **modelo de Pydantic** con los campos que quieres recibir como **campos de formulario**, y luego declarar el parámetro como `Form`:
-{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
**FastAPI** **extraerá** los datos de **cada campo** de los **form data** en el request y te dará el modelo de Pydantic que definiste.
@@ -48,7 +48,7 @@ Esto es compatible desde la versión `0.114.0` de FastAPI. 🤓
Puedes usar la configuración del modelo de Pydantic para `forbid` cualquier campo `extra`:
-{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *}
+{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *}
Si un cliente intenta enviar datos extra, recibirá un response de **error**.
diff --git a/docs/es/docs/tutorial/request-forms-and-files.md b/docs/es/docs/tutorial/request-forms-and-files.md
index 363553e86..738a2bc4b 100644
--- a/docs/es/docs/tutorial/request-forms-and-files.md
+++ b/docs/es/docs/tutorial/request-forms-and-files.md
@@ -16,13 +16,13 @@ $ pip install python-multipart
## Importa `File` y `Form` { #import-file-and-form }
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[3] *}
## Define parámetros `File` y `Form` { #define-file-and-form-parameters }
Crea parámetros de archivo y formulario de la misma manera que lo harías para `Body` o `Query`:
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[10:12] *}
Los archivos y campos de formulario se subirán como form data y recibirás los archivos y campos de formulario.
diff --git a/docs/es/docs/tutorial/request-forms.md b/docs/es/docs/tutorial/request-forms.md
index 33061e6a1..cc29296ee 100644
--- a/docs/es/docs/tutorial/request-forms.md
+++ b/docs/es/docs/tutorial/request-forms.md
@@ -18,17 +18,17 @@ $ pip install python-multipart
Importar `Form` desde `fastapi`:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[3] *}
## Definir parámetros de `Form` { #define-form-parameters }
Crea parámetros de formulario de la misma manera que lo harías para `Body` o `Query`:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[9] *}
Por ejemplo, en una de las formas en las que se puede usar la especificación OAuth2 (llamada "password flow") se requiere enviar un `username` y `password` como campos de formulario.
-La spec requiere que los campos se llamen exactamente `username` y `password`, y que se envíen como campos de formulario, no JSON.
+La especificación requiere que los campos se llamen exactamente `username` y `password`, y que se envíen como campos de formulario, no JSON.
Con `Form` puedes declarar las mismas configuraciones que con `Body` (y `Query`, `Path`, `Cookie`), incluyendo validación, ejemplos, un alias (por ejemplo, `user-name` en lugar de `username`), etc.
@@ -56,7 +56,7 @@ Los datos de formularios normalmente se codifican usando el "media type" `applic
Pero cuando el formulario incluye archivos, se codifica como `multipart/form-data`. Leerás sobre la gestión de archivos en el próximo capítulo.
-Si quieres leer más sobre estas codificaciones y campos de formulario, dirígete a la MDN web docs para POST.
+Si quieres leer más sobre estas codificaciones y campos de formulario, dirígete a la MDN web docs para POST.
///
diff --git a/docs/es/docs/tutorial/response-model.md b/docs/es/docs/tutorial/response-model.md
index 8cfe69e78..c9e931d47 100644
--- a/docs/es/docs/tutorial/response-model.md
+++ b/docs/es/docs/tutorial/response-model.md
@@ -51,7 +51,7 @@ FastAPI usará este `response_model` para hacer toda la documentación de datos,
/// tip | Consejo
-Si tienes chequeos estrictos de tipos en tu editor, mypy, etc., puedes declarar el tipo de retorno de la función como `Any`.
+Si tienes chequeo de tipos estricto en tu editor, mypy, etc., puedes declarar el tipo de retorno de la función como `Any`.
De esa manera le dices al editor que intencionalmente estás devolviendo cualquier cosa. Pero FastAPI todavía hará la documentación de datos, validación, filtrado, etc. con `response_model`.
@@ -183,7 +183,7 @@ Podría haber casos en los que devuelvas algo que no es un campo válido de Pyda
El caso más común sería [devolver un Response directamente como se explica más adelante en la documentación avanzada](../advanced/response-directly.md){.internal-link target=_blank}.
-{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
Este caso simple es manejado automáticamente por FastAPI porque la anotación del tipo de retorno es la clase (o una subclase de) `Response`.
@@ -193,7 +193,7 @@ Y las herramientas también estarán felices porque tanto `RedirectResponse` com
También puedes usar una subclase de `Response` en la anotación del tipo:
-{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
Esto también funcionará porque `RedirectResponse` es una subclase de `Response`, y FastAPI manejará automáticamente este caso simple.
@@ -201,7 +201,7 @@ Esto también funcionará porque `RedirectResponse` es una subclase de `Response
Pero cuando devuelves algún otro objeto arbitrario que no es un tipo válido de Pydantic (por ejemplo, un objeto de base de datos) y lo anotas así en la función, FastAPI intentará crear un modelo de response de Pydantic a partir de esa anotación de tipo, y fallará.
-Lo mismo sucedería si tuvieras algo como un union entre diferentes tipos donde uno o más de ellos no son tipos válidos de Pydantic, por ejemplo esto fallaría 💥:
+Lo mismo sucedería si tuvieras algo como una unión entre diferentes tipos donde uno o más de ellos no son tipos válidos de Pydantic, por ejemplo esto fallaría 💥:
{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
diff --git a/docs/es/docs/tutorial/response-status-code.md b/docs/es/docs/tutorial/response-status-code.md
index dce69f9bc..35235eb88 100644
--- a/docs/es/docs/tutorial/response-status-code.md
+++ b/docs/es/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@ De la misma manera que puedes especificar un modelo de response, también puedes
* `@app.delete()`
* etc.
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
/// note | Nota
@@ -66,7 +66,7 @@ En breve:
/// tip | Consejo
-Para saber más sobre cada código de estado y qué código es para qué, revisa la documentación de MDN sobre códigos de estado HTTP.
+Para saber más sobre cada código de estado y qué código es para qué, revisa la documentación de MDN sobre códigos de estado HTTP.
///
@@ -74,7 +74,7 @@ Para saber más sobre cada código de estado y qué código es para qué, revisa
Veamos de nuevo el ejemplo anterior:
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201` es el código de estado para "Created".
@@ -82,7 +82,7 @@ Pero no tienes que memorizar lo que significa cada uno de estos códigos.
Puedes usar las variables de conveniencia de `fastapi.status`.
-{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
Son solo una conveniencia, mantienen el mismo número, pero de esa manera puedes usar el autocompletado del editor para encontrarlos:
diff --git a/docs/es/docs/tutorial/schema-extra-example.md b/docs/es/docs/tutorial/schema-extra-example.md
index 396a2a6bf..9af826138 100644
--- a/docs/es/docs/tutorial/schema-extra-example.md
+++ b/docs/es/docs/tutorial/schema-extra-example.md
@@ -74,7 +74,7 @@ Por supuesto, también puedes pasar múltiples `examples`:
Cuando haces esto, los ejemplos serán parte del **JSON Schema** interno para esos datos del body.
-Sin embargo, al momento de escribir esto, Swagger UI, la herramienta encargada de mostrar la interfaz de documentación, no soporta mostrar múltiples ejemplos para los datos en **JSON Schema**. Pero lee más abajo para una solución alternativa.
+Sin embargo, al momento de escribir esto, Swagger UI, la herramienta encargada de mostrar la interfaz de documentación, no soporta mostrar múltiples ejemplos para los datos en **JSON Schema**. Pero lee más abajo para una solución alternativa.
### `examples` específicos de OpenAPI { #openapi-specific-examples }
diff --git a/docs/es/docs/tutorial/security/first-steps.md b/docs/es/docs/tutorial/security/first-steps.md
index 604adedad..909f14765 100644
--- a/docs/es/docs/tutorial/security/first-steps.md
+++ b/docs/es/docs/tutorial/security/first-steps.md
@@ -20,7 +20,7 @@ Primero solo usemos el código y veamos cómo funciona, y luego volveremos para
Copia el ejemplo en un archivo `main.py`:
-{* ../../docs_src/security/tutorial001_an_py39.py *}
+{* ../../docs_src/security/tutorial001_an_py310.py *}
## Ejecútalo { #run-it }
@@ -132,7 +132,7 @@ En ese caso, **FastAPI** también te proporciona las herramientas para construir
Cuando creamos una instance de la clase `OAuth2PasswordBearer` pasamos el parámetro `tokenUrl`. Este parámetro contiene la URL que el cliente (el frontend corriendo en el navegador del usuario) usará para enviar el `username` y `password` a fin de obtener un token.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
/// tip | Consejo
@@ -170,7 +170,7 @@ Así que, puede usarse con `Depends`.
Ahora puedes pasar ese `oauth2_scheme` en una dependencia con `Depends`.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
Esta dependencia proporcionará un `str` que se asigna al parámetro `token` de la *path operation function*.
diff --git a/docs/es/docs/tutorial/security/get-current-user.md b/docs/es/docs/tutorial/security/get-current-user.md
index ced002f59..67b6c5835 100644
--- a/docs/es/docs/tutorial/security/get-current-user.md
+++ b/docs/es/docs/tutorial/security/get-current-user.md
@@ -2,7 +2,7 @@
En el capítulo anterior, el sistema de seguridad (que se basa en el sistema de inyección de dependencias) le estaba dando a la *path operation function* un `token` como un `str`:
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
Pero eso aún no es tan útil. Vamos a hacer que nos dé el usuario actual.
diff --git a/docs/es/docs/tutorial/security/oauth2-jwt.md b/docs/es/docs/tutorial/security/oauth2-jwt.md
index f7004ffb2..e481fb646 100644
--- a/docs/es/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/es/docs/tutorial/security/oauth2-jwt.md
@@ -116,7 +116,11 @@ Y otra utilidad para verificar si una contraseña recibida coincide con el hash
Y otra más para autenticar y devolver un usuario.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,51,58:59,62:63,72:79] *}
+
+Cuando `authenticate_user` se llama con un nombre de usuario que no existe en la base de datos, aun así ejecutamos `verify_password` contra un hash ficticio.
+
+Esto asegura que el endpoint tarda aproximadamente la misma cantidad de tiempo en responder tanto si el nombre de usuario es válido como si no, previniendo los **timing attacks** que podrían usarse para enumerar nombres de usuario existentes.
/// note | Nota
@@ -152,7 +156,7 @@ Define un Modelo de Pydantic que se usará en el endpoint de token para el respo
Crea una función de utilidad para generar un nuevo token de acceso.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,82:90] *}
## Actualizar las dependencias { #update-the-dependencies }
@@ -162,7 +166,7 @@ Decodifica el token recibido, verifícalo y devuelve el usuario actual.
Si el token es inválido, devuelve un error HTTP de inmediato.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[93:110] *}
## Actualizar la *path operation* `/token` { #update-the-token-path-operation }
@@ -170,7 +174,7 @@ Crea un `timedelta` con el tiempo de expiración del token.
Crea un verdadero token de acceso JWT y devuélvelo.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[121:136] *}
### Detalles técnicos sobre el "sujeto" `sub` de JWT { #technical-details-about-the-jwt-subject-sub }
diff --git a/docs/es/docs/tutorial/sql-databases.md b/docs/es/docs/tutorial/sql-databases.md
index 6273c7059..b57ebdbbe 100644
--- a/docs/es/docs/tutorial/sql-databases.md
+++ b/docs/es/docs/tutorial/sql-databases.md
@@ -8,7 +8,7 @@ Aquí veremos un ejemplo usando "ORMs"), FastAPI no te obliga a usar nada. 😎
+Puedes usar cualquier otro paquete de bases de datos SQL o NoSQL que quieras (en algunos casos llamadas "ORMs"), FastAPI no te obliga a usar nada. 😎
///
@@ -354,4 +354,4 @@ Si vas a la interfaz de `/docs` de la API, verás que ahora está actualizada, y
Puedes usar **SQLModel** para interactuar con una base de datos SQL y simplificar el código con *modelos de datos* y *modelos de tablas*.
-Puedes aprender mucho más en la documentación de **SQLModel**, hay un mini tutorial sobre el uso de SQLModel con **FastAPI**. 🚀
+Puedes aprender mucho más en la documentación de **SQLModel**, hay un mini tutorial más largo sobre el uso de SQLModel con **FastAPI**. 🚀
diff --git a/docs/es/docs/tutorial/static-files.md b/docs/es/docs/tutorial/static-files.md
index f1badd2af..84d2e94a9 100644
--- a/docs/es/docs/tutorial/static-files.md
+++ b/docs/es/docs/tutorial/static-files.md
@@ -7,7 +7,7 @@ Puedes servir archivos estáticos automáticamente desde un directorio utilizand
* Importa `StaticFiles`.
* "Monta" una instance de `StaticFiles()` en un path específico.
-{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py310.py hl[2,6] *}
/// note | Detalles Técnicos
diff --git a/docs/es/docs/tutorial/testing.md b/docs/es/docs/tutorial/testing.md
index 555da55bf..c47712903 100644
--- a/docs/es/docs/tutorial/testing.md
+++ b/docs/es/docs/tutorial/testing.md
@@ -30,7 +30,7 @@ Usa el objeto `TestClient` de la misma manera que con `httpx`.
Escribe declaraciones `assert` simples con las expresiones estándar de Python que necesites revisar (otra vez, estándar de `pytest`).
-{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py310.py hl[2,12,15:18] *}
/// tip | Consejo
@@ -75,7 +75,7 @@ Digamos que tienes una estructura de archivos como se describe en [Aplicaciones
En el archivo `main.py` tienes tu aplicación de **FastAPI**:
-{* ../../docs_src/app_testing/app_a_py39/main.py *}
+{* ../../docs_src/app_testing/app_a_py310/main.py *}
### Archivo de prueba { #testing-file }
@@ -91,7 +91,7 @@ Entonces podrías tener un archivo `test_main.py` con tus pruebas. Podría estar
Debido a que este archivo está en el mismo paquete, puedes usar importaciones relativas para importar el objeto `app` desde el módulo `main` (`main.py`):
-{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py310/test_main.py hl[3] *}
...y tener el código para las pruebas tal como antes.
diff --git a/docs/es/docs/virtual-environments.md b/docs/es/docs/virtual-environments.md
index 8c90c28f0..f8839ac6c 100644
--- a/docs/es/docs/virtual-environments.md
+++ b/docs/es/docs/virtual-environments.md
@@ -53,7 +53,7 @@ $ cd awesome-project
## Crea un Entorno Virtual { #create-a-virtual-environment }
-Cuando empiezas a trabajar en un proyecto de Python **por primera vez**, crea un entorno virtual **dentro de tu proyecto**.
+Cuando empiezas a trabajar en un proyecto de Python **por primera vez**, crea un entorno virtual **dentro de tu proyecto**.
/// tip | Consejo
@@ -170,9 +170,9 @@ Esto asegura que si usas un programa de **terminal (
Date: Fri, 13 Feb 2026 13:42:06 +0000
Subject: [PATCH 125/195] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
[skip ci]
---
docs/en/docs/release-notes.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md
index af7e7f27d..deee633c2 100644
--- a/docs/en/docs/release-notes.md
+++ b/docs/en/docs/release-notes.md
@@ -13,6 +13,7 @@ hide:
### Translations
+* 🌐 Update translations for es (update-all and add-missing). PR [#14911](https://github.com/fastapi/fastapi/pull/14911) by [@YuriiMotov](https://github.com/YuriiMotov).
* 🌐 Update translations for zh (update-all). PR [#14917](https://github.com/fastapi/fastapi/pull/14917) by [@YuriiMotov](https://github.com/YuriiMotov).
* 🌐 Update translations for uk (update-all). PR [#14914](https://github.com/fastapi/fastapi/pull/14914) by [@YuriiMotov](https://github.com/YuriiMotov).
* 🌐 Update translations for tr (update-all). PR [#14913](https://github.com/fastapi/fastapi/pull/14913) by [@YuriiMotov](https://github.com/YuriiMotov).
From 0d1f4d935b43628c966903d1e213d1bffa860953 Mon Sep 17 00:00:00 2001
From: Motov Yurii <109919500+YuriiMotov@users.noreply.github.com>
Date: Fri, 13 Feb 2026 14:48:53 +0100
Subject: [PATCH 126/195] =?UTF-8?q?=F0=9F=8C=90=20Update=20translations=20?=
=?UTF-8?q?for=20pt=20(update-all)=20(#14912)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* Update all
* 🎨 Auto format
---------
Co-authored-by: github-actions[bot]
-### Desencriptando a Solicitação { #decrypt-the-request }
+### Desencripte a Solicitação { #decrypt-the-request }
O Proxy de Terminação TLS então usaria a encriptação combinada para desencriptar a solicitação, e transmitiria a solicitação básica (desencriptada) para o processo executando a aplicação (por exemplo, um processo com Uvicorn executando a aplicação FastAPI).
@@ -186,7 +186,7 @@ Para fazer isso, e acomodar as necessidades de diferentes aplicações, existem
* Executar como um servidor (ao menos durante o processo de aquisição do certificado) no endereço IP público associado com o domínio.
* Como dito anteriormente, apenas um processo pode estar ligado a uma porta e IP específicos.
* Essa é uma dos motivos que fazem utilizar o mesmo Proxy de Terminação TLS para gerenciar a renovação de certificados ser tão útil.
- * Caso contrário, você pode ter que parar a execução do Proxy de Terminação TLS momentaneamente, inicializar o programa de renovação para renovar os certificados, e então reiniciar o Proxy de Terminação TLS. Isso não é o ideal, já que sua(s) aplicação(ões) não vão estar disponíveis enquanto o Proxy de Terminação TLS estiver desligado.
+ * Caso contrário, você pode ter que parar a execução do Proxy de Terminação TLS momentaneamente, inicializar o programa de renovação para adquirir os certificados, depois configurá-los com o Proxy de Terminação TLS, e então reiniciar o Proxy de Terminação TLS. Isso não é o ideal, já que sua(s) aplicação(ões) não vão estar disponíveis enquanto o Proxy de Terminação TLS estiver desligado.
Todo esse processo de renovação, enquanto o aplicativo ainda funciona, é uma das principais razões para preferir um sistema separado para gerenciar HTTPS com um Proxy de Terminação TLS em vez de usar os certificados TLS no servidor da aplicação diretamente (e.g. com o Uvicorn).
diff --git a/docs/pt/docs/deployment/index.md b/docs/pt/docs/deployment/index.md
index 6a6c21804..d9755d0a2 100644
--- a/docs/pt/docs/deployment/index.md
+++ b/docs/pt/docs/deployment/index.md
@@ -4,7 +4,7 @@ Implantar uma aplicação **FastAPI** é relativamente fácil.
## O que significa Implantação { #what-does-deployment-mean }
-Implantar uma aplicação significa executar as etapas necessárias para torná-la disponível para os usuários.
+**Implantar** uma aplicação significa executar as etapas necessárias para torná-la **disponível para os usuários**.
Para uma **web API**, isso normalmente envolve colocá-la em uma **máquina remota**, com um **programa de servidor** que ofereça bom desempenho, estabilidade, etc., de modo que seus **usuários** possam **acessar** a aplicação com eficiência e sem interrupções ou problemas.
diff --git a/docs/pt/docs/deployment/manually.md b/docs/pt/docs/deployment/manually.md
index 21d0f44cd..da3a52cf3 100644
--- a/docs/pt/docs/deployment/manually.md
+++ b/docs/pt/docs/deployment/manually.md
@@ -46,7 +46,7 @@ Você pode utilizar esse comando, por exemplo, para iniciar sua aplicação **Fa
Vamos nos aprofundar um pouco mais em detalhes.
-FastAPI utiliza um padrão para construir frameworks e servidores web em Python chamado ASGI. FastAPI é um framework web ASGI.
+FastAPI utiliza um padrão para construir frameworks e servidores web em Python chamado ASGI. FastAPI é um framework web ASGI.
A principal coisa que você precisa para executar uma aplicação **FastAPI** (ou qualquer outra aplicação ASGI) em uma máquina de servidor remoto é um programa de servidor ASGI como o **Uvicorn**, que é o que vem por padrão no comando `fastapi`.
diff --git a/docs/pt/docs/deployment/versions.md b/docs/pt/docs/deployment/versions.md
index a2aca5a17..32676da23 100644
--- a/docs/pt/docs/deployment/versions.md
+++ b/docs/pt/docs/deployment/versions.md
@@ -64,9 +64,9 @@ O "MINOR" é o número do meio, por exemplo, em `0.2.3`, a versão MINOR é `2`.
## Atualizando as versões do FastAPI { #upgrading-the-fastapi-versions }
-Você deve adicionar testes para a sua aplicação.
+Você deveria adicionar testes para a sua aplicação.
-Com **FastAPI** isso é muito fácil (graças ao Starlette), veja a documentação: [Testing](../tutorial/testing.md){.internal-link target=_blank}
+Com **FastAPI** isso é muito fácil (graças ao Starlette), veja a documentação: [Testes](../tutorial/testing.md){.internal-link target=_blank}
Depois que você tiver testes, você pode atualizar a sua versão do **FastAPI** para uma mais recente e se certificar de que todo o seu código está funcionando corretamente executando seus testes.
diff --git a/docs/pt/docs/fastapi-cli.md b/docs/pt/docs/fastapi-cli.md
index 0bd7bcd21..f1e633a23 100644
--- a/docs/pt/docs/fastapi-cli.md
+++ b/docs/pt/docs/fastapi-cli.md
@@ -58,7 +58,7 @@ Internamente, o **FastAPI CLI** usa o OpenAPI para criação de APIs, incluindo declarações de caminho operações, parâmetros, requisições de corpo, segurança etc.
+* OpenAPI para criação de APIs, incluindo declarações de caminho operações, parâmetros, requisições de corpo, segurança etc.
* Modelo de documentação automática com JSON Schema (já que o OpenAPI em si é baseado no JSON Schema).
* Projetado em cima desses padrões após um estudo meticuloso, em vez de uma reflexão breve.
* Isso também permite o uso de **geração de código do cliente** automaticamente em muitas linguagens.
@@ -136,7 +136,7 @@ Tudo construído como ferramentas e componentes reutilizáveis que são fáceis
### Injeção de dependência { #dependency-injection }
-FastAPI inclui um sistema de injeção de dependência extremamente fácil de usar, mas extremamente poderoso.
+FastAPI inclui um sistema de injeção de dependência extremamente fácil de usar, mas extremamente poderoso.
* Mesmo dependências podem ter dependências, criando uma hierarquia ou **"grafo" de dependências**.
* Tudo **automaticamente controlado** pelo framework.
@@ -153,8 +153,8 @@ Qualquer integração é projetada para ser tão simples de usar (com dependênc
### Testado { #tested }
-* 100% de cobertura de testes.
-* 100% do código com anotações de tipo.
+* 100% de cobertura de testes.
+* 100% do código com anotações de tipo.
* Usado para aplicações em produção.
## Recursos do Starlette { #starlette-features }
@@ -179,7 +179,7 @@ Com **FastAPI**, você terá todos os recursos do **Starlette** (já que FastAPI
**FastAPI** é totalmente compatível com (e baseado no) Pydantic. Então, qualquer código Pydantic adicional que você tiver, também funcionará.
-Incluindo bibliotecas externas também baseadas no Pydantic, como ORMs e ODMs para bancos de dados.
+Incluindo bibliotecas externas também baseadas no Pydantic, como ORMs e ODMs para bancos de dados.
Isso também significa que em muitos casos você poderá passar o mesmo objeto que você receber de uma requisição **diretamente para o banco de dados**, já que tudo é validado automaticamente.
@@ -190,7 +190,7 @@ Com **FastAPI** você terá todos os recursos do **Pydantic** (já que FastAPI u
* **Sem pegadinhas**:
* Sem novas definições de esquema de micro-linguagem para aprender.
* Se você conhece os tipos do Python, você sabe como usar o Pydantic.
-* Vai bem com o/a seu/sua **IDE/linter/cérebro**:
+* Vai bem com o/a seu/sua **IDE/linter/cérebro**:
* Como as estruturas de dados do Pydantic são apenas instâncias de classes que você define, o preenchimento automático, linting, mypy e a sua intuição devem funcionar corretamente com seus dados validados.
* Valida **estruturas complexas**:
* Use modelos hierárquicos do Pydantic, `List` e `Dict` do `typing` do Python, etc.
diff --git a/docs/pt/docs/history-design-future.md b/docs/pt/docs/history-design-future.md
index 699528739..fb90d1e1c 100644
--- a/docs/pt/docs/history-design-future.md
+++ b/docs/pt/docs/history-design-future.md
@@ -24,7 +24,7 @@ Há muitas ferramentas criadas antes que ajudaram a inspirar sua criação.
Eu estive evitando a criação de um novo _framework_ por vários anos. Primeiro tentei resolver todas as funcionalidades cobertas por **FastAPI** usando muitos _frameworks_, _plug-ins_ e ferramentas diferentes.
-Mas em algum ponto, não havia outra opção senão criar algo que oferecia todas as funcionalidades, aproveitando as melhores ideias de ferramentas anteriores, e combinando-as da melhor maneira possível, usando funcionalidades da linguagem que nem estavam disponíveis antes (_type hints_ do Python 3.6+).
+Mas em algum ponto, não havia outra opção senão criar algo que oferecia todas as funcionalidades, aproveitando as melhores ideias de ferramentas anteriores, e combinando-as da melhor maneira possível, usando funcionalidades da linguagem que nem estavam disponíveis antes (anotações de tipo do Python 3.6+).
@@ -32,7 +32,7 @@ Mas em algum ponto, não havia outra opção senão criar algo que oferecia toda
Ao usar todas as alternativas anteriores, eu tive a chance de aprender com todas elas, aproveitar ideias e combiná-las da melhor maneira que encontrei para mim e para os times de desenvolvedores com os quais trabalhava.
-Por exemplo, estava claro que idealmente ele deveria ser baseado nos _type hints_ padrões do Python.
+Por exemplo, estava claro que idealmente ele deveria ser baseado nas anotações de tipo padrão do Python.
Também, a melhor abordagem era usar padrões já existentes.
diff --git a/docs/pt/docs/how-to/authentication-error-status-code.md b/docs/pt/docs/how-to/authentication-error-status-code.md
index 878a1ca1a..40790f180 100644
--- a/docs/pt/docs/how-to/authentication-error-status-code.md
+++ b/docs/pt/docs/how-to/authentication-error-status-code.md
@@ -8,7 +8,7 @@ Mas, se por algum motivo seus clientes dependem do comportamento antigo, você p
Por exemplo, você pode criar uma subclasse de `HTTPBearer` que retorne um erro `403 Forbidden` em vez do erro padrão `401 Unauthorized`:
-{* ../../docs_src/authentication_error_status_code/tutorial001_an_py39.py hl[9:13] *}
+{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *}
/// tip | Dica
diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md
index b475dae6d..b77600a7b 100644
--- a/docs/pt/docs/how-to/conditional-openapi.md
+++ b/docs/pt/docs/how-to/conditional-openapi.md
@@ -29,13 +29,13 @@ Você pode usar facilmente as mesmas configurações do Pydantic para configurar
Por exemplo:
-{* ../../docs_src/conditional_openapi/tutorial001_py39.py hl[6,11] *}
+{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *}
Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`.
E então a usamos ao criar a aplicação `FastAPI`.
-Então você pode desabilitar o OpenAPI (incluindo a documentação da interface do usuário) definindo a variável de ambiente `OPENAPI_URL` como uma string vazia, como:
+Então você pode desabilitar o OpenAPI (incluindo a documentação da interface do usuário) definindo a variável de ambiente `OPENAPI_URL` como a string vazia, como:
httpx - Obrigatório caso você queira utilizar o `TestClient`.
* jinja2 - Obrigatório se você quer utilizar a configuração padrão de templates.
-* python-multipart - Obrigatório se você deseja suporte a "parsing" de formulário, com `request.form()`.
+* python-multipart - Obrigatório se você deseja suporte a "parsing" de formulário, com `request.form()`.
Utilizado pelo FastAPI:
diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md
index fc983d1df..bc3f47858 100644
--- a/docs/pt/docs/python-types.md
+++ b/docs/pt/docs/python-types.md
@@ -1,14 +1,14 @@
# Introdução aos tipos Python { #python-types-intro }
-O Python possui suporte para "dicas de tipo" ou "type hints" (também chamado de "anotações de tipo" ou "type annotations")
+O Python possui suporte para "type hints" opcionais (também chamados de "type annotations").
-Esses **"type hints"** são uma sintaxe especial que permite declarar o tipo de uma variável.
+Esses **"type hints"** ou anotações são uma sintaxe especial que permite declarar o tipo de uma variável.
Ao declarar tipos para suas variáveis, editores e ferramentas podem oferecer um melhor suporte.
Este é apenas um **tutorial rápido / atualização** sobre type hints do Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI**... que é realmente muito pouco.
-O **FastAPI** é baseado nesses type hints, eles oferecem muitas vantagens e benefícios.
+O **FastAPI** é todo baseado nesses type hints, eles oferecem muitas vantagens e benefícios.
Mas mesmo que você nunca use o **FastAPI**, você se beneficiaria de aprender um pouco sobre eles.
@@ -22,7 +22,7 @@ Se você é um especialista em Python e já sabe tudo sobre type hints, pule par
Vamos começar com um exemplo simples:
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
A chamada deste programa gera:
@@ -34,9 +34,9 @@ A função faz o seguinte:
* Pega um `first_name` e `last_name`.
* Converte a primeira letra de cada uma em maiúsculas com `title()`.
-* Concatena com um espaço no meio.
+* Concatena com um espaço no meio.
-{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
### Edite-o { #edit-it }
@@ -52,7 +52,7 @@ Era `upper`? Era `uppercase`? `first_uppercase`? `capitalize`?
Em seguida, tente com o velho amigo do programador, o preenchimento automático do editor.
-Você digita o primeiro parâmetro da função, `first_name`, depois um ponto (`.`) e, em seguida, pressiona `Ctrl + Space` para acionar a conclusão.
+Você digita o primeiro parâmetro da função, `first_name`, depois um ponto (`.`) e, em seguida, pressiona `Ctrl+Space` para acionar o preenchimento automático.
Mas, infelizmente, você não obtém nada útil:
@@ -78,7 +78,7 @@ para:
Esses são os "type hints":
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
Isso não é o mesmo que declarar valores padrão como seria com:
@@ -88,7 +88,7 @@ Isso não é o mesmo que declarar valores padrão como seria com:
É uma coisa diferente.
-Estamos usando dois pontos (`:`), não é igual a (`=`).
+Estamos usando dois pontos (`:`), não sinal de igual (`=`).
E adicionar type hints normalmente não muda o que acontece do que aconteceria sem eles.
@@ -106,17 +106,17 @@ Com isso, você pode rolar, vendo as opções, até encontrar o que "soa familia
Verifique esta função, ela já possui type hints:
-{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
-Como o editor conhece os tipos de variáveis, você não obtém apenas o preenchimento automático, mas também as verificações de erro:
+Como o editor conhece os tipos das variáveis, você não obtém apenas o preenchimento automático, mas também as verificações de erro:
-Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str(age)`:
+Agora você sabe que precisa corrigi-la, convertendo `age` em uma string com `str(age)`:
-{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
-## Declarando Tipos { #declaring-types }
+## Declarando tipos { #declaring-types }
Você acabou de ver o local principal para declarar type hints. Como parâmetros de função.
@@ -133,29 +133,32 @@ Você pode usar, por exemplo:
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### Tipos genéricos com parâmetros de tipo { #generic-types-with-type-parameters }
+### Módulo `typing` { #typing-module }
-Existem algumas estruturas de dados que podem conter outros valores, como `dict`, `list`, `set` e `tuple`. E os valores internos também podem ter seu próprio tipo.
+Para alguns casos adicionais, você pode precisar importar alguns itens do módulo padrão `typing`, por exemplo, quando quiser declarar que algo pode ter "qualquer tipo", você pode usar `Any` de `typing`:
-Estes tipos que possuem tipos internos são chamados de tipos "**genéricos**". E é possível declará-los mesmo com os seus tipos internos.
+```python
+from typing import Any
-Para declarar esses tipos e os tipos internos, você pode usar o módulo Python padrão `typing`. Ele existe especificamente para suportar esses type hints.
-#### Versões mais recentes do Python { #newer-versions-of-python }
+def some_function(data: Any):
+ print(data)
+```
-A sintaxe utilizando `typing` é **compatível** com todas as versões, desde o Python 3.6 até as últimas, incluindo o Python 3.9, 3.10, etc.
+### Tipos genéricos { #generic-types }
-Conforme o Python evolui, **novas versões** chegam com suporte melhorado para esses type annotations, e em muitos casos, você não precisará nem importar e utilizar o módulo `typing` para declarar os type annotations.
+Alguns tipos podem receber "parâmetros de tipo" entre colchetes, para definir seus tipos internos, por exemplo, uma "lista de strings" seria declarada como `list[str]`.
-Se você pode escolher uma versão mais recente do Python para o seu projeto, você poderá aproveitar isso ao seu favor.
+Esses tipos que podem receber parâmetros de tipo são chamados **tipos genéricos** ou **genéricos**.
-Em todos os documentos existem exemplos compatíveis com cada versão do Python (quando existem diferenças).
+Você pode usar os mesmos tipos internos como genéricos (com colchetes e tipos dentro):
-Por exemplo, "**Python 3.6+**" significa que é compatível com o Python 3.6 ou superior (incluindo o 3.7, 3.8, 3.9, 3.10, etc). E "**Python 3.9+**" significa que é compatível com o Python 3.9 ou mais recente (incluindo o 3.10, etc).
-
-Se você pode utilizar a **versão mais recente do Python**, utilize os exemplos para as últimas versões. Eles terão as **melhores e mais simples sintaxes**, como por exemplo, "**Python 3.10+**".
+* `list`
+* `tuple`
+* `set`
+* `dict`
#### List { #list }
@@ -167,11 +170,11 @@ Como o tipo, coloque `list`.
Como a lista é um tipo que contém tipos internos, você os coloca entre colchetes:
-{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
/// info | Informação
-Estes tipos internos dentro dos colchetes são chamados "parâmetros de tipo" (type parameters).
+Esses tipos internos dentro dos colchetes são chamados de "parâmetros de tipo".
Neste caso, `str` é o parâmetro de tipo passado para `list`.
@@ -193,9 +196,9 @@ E, ainda assim, o editor sabe que é um `str` e fornece suporte para isso.
Você faria o mesmo para declarar `tuple`s e `set`s:
-{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
-Isso significa que:
+Isso significa:
* A variável `items_t` é uma `tuple` com 3 itens, um `int`, outro `int` e uma `str`.
* A variável `items_s` é um `set`, e cada um de seus itens é do tipo `bytes`.
@@ -208,7 +211,7 @@ O primeiro parâmetro de tipo é para as chaves do `dict`.
O segundo parâmetro de tipo é para os valores do `dict`:
-{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Isso significa que:
@@ -218,46 +221,22 @@ Isso significa que:
#### Union { #union }
-Você pode declarar que uma variável pode ser de qualquer um dentre **diversos tipos**. Por exemplo, um `int` ou um `str`.
+Você pode declarar que uma variável pode ser de qualquer um dentre **vários tipos**, por exemplo, um `int` ou um `str`.
-No Python 3.6 e superior (incluindo o Python 3.10), você pode utilizar o tipo `Union` de `typing`, e colocar dentro dos colchetes os possíveis tipos aceitáveis.
+Para defini-la, você usa a barra vertical (`|`) para separar ambos os tipos.
-No Python 3.10 também existe uma **nova sintaxe** onde você pode colocar os possíveis tipos separados por uma barra vertical (`|`).
-
-//// tab | Python 3.10+
+Isso é chamado de "união", porque a variável pode ser qualquer coisa na união desses dois conjuntos de tipos.
```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-////
-
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b_py39.py!}
-```
-
-////
-
-Em ambos os casos, isso significa que `item` poderia ser um `int` ou um `str`.
+Isso significa que `item` pode ser um `int` ou um `str`.
#### Possivelmente `None` { #possibly-none }
Você pode declarar que um valor pode ter um tipo, como `str`, mas que ele também pode ser `None`.
-No Python 3.6 e superior (incluindo o Python 3.10) você pode declará-lo importando e utilizando `Optional` do módulo `typing`.
-
-```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-O uso de `Optional[str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`.
-
-`Optional[Something]` é na verdade um atalho para `Union[Something, None]`, eles são equivalentes.
-
-Isso também significa que no Python 3.10, você pode utilizar `Something | None`:
-
//// tab | Python 3.10+
```Python hl_lines="1"
@@ -266,96 +245,7 @@ Isso também significa que no Python 3.10, você pode utilizar `Something | None
////
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-////
-
-//// tab | Python 3.9+ alternativa
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b_py39.py!}
-```
-
-////
-
-#### Utilizando `Union` ou `Optional` { #using-union-or-optional }
-
-Se você está utilizando uma versão do Python abaixo da 3.10, aqui vai uma dica do meu ponto de vista bem **subjetivo**:
-
-* 🚨 Evite utilizar `Optional[SomeType]`
-* No lugar, ✨ **use `Union[SomeType, None]`** ✨.
-
-Ambos são equivalentes, e no final das contas, eles são o mesmo. Mas eu recomendaria o `Union` ao invés de `Optional` porque a palavra **Optional** parece implicar que o valor é opcional, quando na verdade significa "isso pode ser `None`", mesmo que ele não seja opcional e ainda seja obrigatório.
-
-Eu penso que `Union[SomeType, None]` é mais explícito sobre o que ele significa.
-
-Isso é apenas sobre palavras e nomes. Mas estas palavras podem afetar como os seus colegas de trabalho pensam sobre o código.
-
-Por exemplo, vamos pegar esta função:
-
-{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
-
-O parâmetro `name` é definido como `Optional[str]`, mas ele **não é opcional**, você não pode chamar a função sem o parâmetro:
-
-```Python
-say_hi() # Oh, no, this throws an error! 😱
-```
-
-O parâmetro `name` **ainda é obrigatório** (não *opcional*) porque ele não possui um valor padrão. Mesmo assim, `name` aceita `None` como valor:
-
-```Python
-say_hi(name=None) # This works, None is valid 🎉
-```
-
-A boa notícia é, quando você estiver no Python 3.10 você não precisará se preocupar mais com isso, pois você poderá simplesmente utilizar o `|` para definir uniões de tipos:
-
-{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
-
-E então você não precisará mais se preocupar com nomes como `Optional` e `Union`. 😎
-
-#### Tipos genéricos { #generic-types }
-
-Esses tipos que usam parâmetros de tipo entre colchetes são chamados **tipos genéricos** ou **genéricos**. Por exemplo:
-
-//// tab | Python 3.10+
-
-Você pode utilizar os mesmos tipos internos como genéricos (com colchetes e tipos dentro):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-E o mesmo que com versões anteriores do Python, do módulo `typing`:
-
-* `Union`
-* `Optional`
-* ...entre outros.
-
-No Python 3.10, como uma alternativa para a utilização dos genéricos `Union` e `Optional`, você pode usar a barra vertical (`|`) para declarar uniões de tipos. Isso é muito melhor e mais simples.
-
-////
-
-//// tab | Python 3.9+
-
-Você pode utilizar os mesmos tipos internos como genéricos (com colchetes e tipos dentro):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-E genéricos do módulo `typing`:
-
-* `Union`
-* `Optional`
-* ...entre outros.
-
-////
+Usar `str | None` em vez de apenas `str` permitirá que o editor o ajude a detectar erros em que você poderia estar assumindo que um valor é sempre um `str`, quando na verdade ele também pode ser `None`.
### Classes como tipos { #classes-as-types }
@@ -363,13 +253,13 @@ Você também pode declarar uma classe como o tipo de uma variável.
Digamos que você tenha uma classe `Person`, com um nome:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
Então você pode declarar que uma variável é do tipo `Person`:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
-E então, novamente, você recebe todo o apoio do editor:
+E então, novamente, você recebe todo o suporte do editor:
@@ -379,7 +269,7 @@ Isso não significa que "`one_person` é a **classe** chamada `Person`".
## Modelos Pydantic { #pydantic-models }
-O Pydantic é uma biblioteca Python para executar a validação de dados.
+Pydantic é uma biblioteca Python para executar a validação de dados.
Você declara a "forma" dos dados como classes com atributos.
@@ -403,23 +293,17 @@ O **FastAPI** é todo baseado em Pydantic.
Você verá muito mais disso na prática no [Tutorial - Guia do usuário](tutorial/index.md){.internal-link target=_blank}.
-/// tip | Dica
-
-O Pydantic tem um comportamento especial quando você usa `Optional` ou `Union[Something, None]` sem um valor padrão. Você pode ler mais sobre isso na documentação do Pydantic sobre campos Opcionais Obrigatórios.
-
-///
-
## Type Hints com Metadados de Anotações { #type-hints-with-metadata-annotations }
-O Python possui uma funcionalidade que nos permite incluir **metadados adicionais** nos type hints utilizando `Annotated`.
+O Python também possui uma funcionalidade que permite incluir **metadados adicionais** nesses type hints utilizando `Annotated`.
-Desde o Python 3.9, `Annotated` faz parte da biblioteca padrão, então você pode importá-lo de `typing`.
+Você pode importar `Annotated` de `typing`.
-{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
O Python em si não faz nada com este `Annotated`. E para editores e outras ferramentas, o tipo ainda é `str`.
-Mas você pode utilizar este espaço dentro do `Annotated` para fornecer ao **FastAPI** metadata adicional sobre como você deseja que a sua aplicação se comporte.
+Mas você pode utilizar este espaço dentro do `Annotated` para fornecer ao **FastAPI** metadados adicionais sobre como você deseja que a sua aplicação se comporte.
O importante aqui de se lembrar é que **o primeiro *type parameter*** que você informar ao `Annotated` é o **tipo de fato**. O resto é apenas metadado para outras ferramentas.
@@ -446,12 +330,12 @@ Com o **FastAPI**, você declara parâmetros com type hints e obtém:
... e o **FastAPI** usa as mesmas declarações para:
-* **Definir requisitos**: dos parâmetros de rota, parâmetros da consulta, cabeçalhos, corpos, dependências, etc.
-* **Converter dados**: da solicitação para o tipo necessário.
-* **Validar dados**: provenientes de cada solicitação:
+* **Definir requisitos**: dos parâmetros de path da request, parâmetros da query, cabeçalhos, corpos, dependências, etc.
+* **Converter dados**: da request para o tipo necessário.
+* **Validar dados**: provenientes de cada request:
* Gerando **erros automáticos** retornados ao cliente quando os dados são inválidos.
* **Documentar** a API usando OpenAPI:
- * que é usado pelas interfaces de usuário da documentação interativa automática.
+ * que é usada pelas interfaces de usuário da documentação interativa automática.
Tudo isso pode parecer abstrato. Não se preocupe. Você verá tudo isso em ação no [Tutorial - Guia do usuário](tutorial/index.md){.internal-link target=_blank}.
@@ -459,6 +343,6 @@ O importante é que, usando tipos padrão de Python, em um único local (em vez
/// info | Informação
-Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` .
+Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy`.
///
diff --git a/docs/pt/docs/translation-banner.md b/docs/pt/docs/translation-banner.md
new file mode 100644
index 000000000..f3069ddd7
--- /dev/null
+++ b/docs/pt/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Tradução por IA e humanos
+
+Esta tradução foi feita por IA orientada por humanos. 🤝
+
+Ela pode conter erros de interpretação do significado original ou soar pouco natural, etc. 🤖
+
+Você pode melhorar esta tradução [ajudando-nos a orientar melhor o LLM de IA](https://fastapi.tiangolo.com/pt/contributing/#translations).
+
+[Versão em inglês](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/pt/docs/tutorial/background-tasks.md b/docs/pt/docs/tutorial/background-tasks.md
index 34805364b..462fb00dc 100644
--- a/docs/pt/docs/tutorial/background-tasks.md
+++ b/docs/pt/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@ Isso inclui, por exemplo:
Primeiro, importe `BackgroundTasks` e defina um parâmetro na sua *função de operação de rota* com uma declaração de tipo `BackgroundTasks`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
O **FastAPI** criará o objeto do tipo `BackgroundTasks` para você e o passará como esse parâmetro.
@@ -31,13 +31,13 @@ Neste caso, a função da tarefa escreverá em um arquivo (simulando o envio de
E como a operação de escrita não usa `async` e `await`, definimos a função com um `def` normal:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
## Adicione a tarefa em segundo plano { #add-the-background-task }
Dentro da sua *função de operação de rota*, passe sua função de tarefa para o objeto de *tarefas em segundo plano* com o método `.add_task()`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
O `.add_task()` recebe como argumentos:
diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md
index 87bd13375..ad758988f 100644
--- a/docs/pt/docs/tutorial/bigger-applications.md
+++ b/docs/pt/docs/tutorial/bigger-applications.md
@@ -58,17 +58,17 @@ A mesma estrutura de arquivos com comentários:
```bash
.
-├── app # "app" is a Python package
-│ ├── __init__.py # this file makes "app" a "Python package"
-│ ├── main.py # "main" module, e.g. import app.main
-│ ├── dependencies.py # "dependencies" module, e.g. import app.dependencies
-│ └── routers # "routers" is a "Python subpackage"
-│ │ ├── __init__.py # makes "routers" a "Python subpackage"
-│ │ ├── items.py # "items" submodule, e.g. import app.routers.items
-│ │ └── users.py # "users" submodule, e.g. import app.routers.users
-│ └── internal # "internal" is a "Python subpackage"
-│ ├── __init__.py # makes "internal" a "Python subpackage"
-│ └── admin.py # "admin" submodule, e.g. import app.internal.admin
+├── app # "app" é um pacote Python
+│ ├── __init__.py # este arquivo torna "app" um "pacote Python"
+│ ├── main.py # módulo "main", p.ex., import app.main
+│ ├── dependencies.py # módulo "dependencies", p.ex., import app.dependencies
+│ └── routers # "routers" é um "subpacote Python"
+│ │ ├── __init__.py # torna "routers" um "subpacote Python"
+│ │ ├── items.py # submódulo "items", p.ex., import app.routers.items
+│ │ └── users.py # submódulo "users", p.ex., import app.routers.users
+│ └── internal # "internal" é um "subpacote Python"
+│ ├── __init__.py # torna "internal" um "subpacote Python"
+│ └── admin.py # submódulo "admin", p.ex., import app.internal.admin
```
## `APIRouter` { #apirouter }
@@ -85,7 +85,7 @@ Você pode criar as *operações de rota* para esse módulo usando o `APIRouter`
Você o importa e cria uma "instância" da mesma maneira que faria com a classe `FastAPI`:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
### *Operações de Rota* com `APIRouter` { #path-operations-with-apirouter }
@@ -93,7 +93,7 @@ E então você o utiliza para declarar suas *operações de rota*.
Utilize-o da mesma maneira que utilizaria a classe `FastAPI`:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
Você pode pensar em `APIRouter` como uma classe "mini `FastAPI`".
@@ -117,7 +117,7 @@ Então, as colocamos em seu próprio módulo de `dependencies` (`app/dependencie
Agora usaremos uma dependência simples para ler um cabeçalho `X-Token` personalizado:
-{* ../../docs_src/bigger_applications/app_an_py39/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
/// tip | Dica
@@ -149,7 +149,7 @@ Sabemos que todas as *operações de rota* neste módulo têm o mesmo:
Então, em vez de adicionar tudo isso a cada *operação de rota*, podemos adicioná-lo ao `APIRouter`.
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
Como o path de cada *operação de rota* tem que começar com `/`, como em:
@@ -208,7 +208,7 @@ E precisamos obter a função de dependência do módulo `app.dependencies`, o a
Então usamos uma importação relativa com `..` para as dependências:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[3] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}
#### Como funcionam as importações relativas { #how-relative-imports-work }
@@ -279,7 +279,7 @@ Não estamos adicionando o prefixo `/items` nem `tags=["items"]` a cada *operaç
Mas ainda podemos adicionar _mais_ `tags` que serão aplicadas a uma *operação de rota* específica, e também algumas `responses` extras específicas para essa *operação de rota*:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}
/// tip | Dica
@@ -305,13 +305,13 @@ Você importa e cria uma classe `FastAPI` normalmente.
E podemos até declarar [dependências globais](dependencies/global-dependencies.md){.internal-link target=_blank} que serão combinadas com as dependências para cada `APIRouter`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[1,3,7] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
### Importe o `APIRouter` { #import-the-apirouter }
Agora importamos os outros submódulos que possuem `APIRouter`s:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[4:5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}
Como os arquivos `app/routers/users.py` e `app/routers/items.py` são submódulos que fazem parte do mesmo pacote Python `app`, podemos usar um único ponto `.` para importá-los usando "importações relativas".
@@ -374,13 +374,13 @@ o `router` de `users` sobrescreveria o de `items` e não poderíamos usá-los ao
Então, para poder usar ambos no mesmo arquivo, importamos os submódulos diretamente:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}
### Inclua os `APIRouter`s para `users` e `items` { #include-the-apirouters-for-users-and-items }
Agora, vamos incluir os `router`s dos submódulos `users` e `items`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[10:11] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}
/// info | Informação
@@ -420,13 +420,13 @@ Ele contém um `APIRouter` com algumas *operações de rota* de administração
Para este exemplo, será super simples. Mas digamos que, como ele é compartilhado com outros projetos na organização, não podemos modificá-lo e adicionar um `prefix`, `dependencies`, `tags`, etc. diretamente ao `APIRouter`:
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
Mas ainda queremos definir um `prefix` personalizado ao incluir o `APIRouter` para que todas as suas *operações de rota* comecem com `/admin`, queremos protegê-lo com as `dependencies` que já temos para este projeto e queremos incluir `tags` e `responses`.
Podemos declarar tudo isso sem precisar modificar o `APIRouter` original passando esses parâmetros para `app.include_router()`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[14:17] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}
Dessa forma, o `APIRouter` original permanecerá inalterado, para que possamos compartilhar o mesmo arquivo `app/internal/admin.py` com outros projetos na organização.
@@ -447,7 +447,7 @@ Também podemos adicionar *operações de rota* diretamente ao aplicativo `FastA
Aqui fazemos isso... só para mostrar que podemos 🤷:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[21:23] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}
e funcionará corretamente, junto com todas as outras *operações de rota* adicionadas com `app.include_router()`.
diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md
index 24f35b210..828cde633 100644
--- a/docs/pt/docs/tutorial/body-multiple-params.md
+++ b/docs/pt/docs/tutorial/body-multiple-params.md
@@ -104,12 +104,6 @@ Dado que, por padrão, valores singulares são interpretados como parâmetros de
q: str | None = None
```
-Ou em Python 3.9:
-
-```Python
-q: Union[str, None] = None
-```
-
Por exemplo:
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md
index f2bec19a2..d53d3f649 100644
--- a/docs/pt/docs/tutorial/body-nested-models.md
+++ b/docs/pt/docs/tutorial/body-nested-models.md
@@ -164,7 +164,7 @@ images: list[Image]
como em:
-{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
## Suporte de editor em todo canto { #editor-support-everywhere }
@@ -194,7 +194,7 @@ Outro caso útil é quando você deseja ter chaves de outro tipo, por exemplo, `
Neste caso, você aceitaria qualquer `dict`, desde que tenha chaves` int` com valores `float`:
-{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
/// tip | Dica
diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md
index 669334439..bec553e21 100644
--- a/docs/pt/docs/tutorial/body.md
+++ b/docs/pt/docs/tutorial/body.md
@@ -72,9 +72,9 @@ Apenas com essa declaração de tipos do Python, o **FastAPI** irá:
* Validar os dados.
* Se algum dado for inválido, irá retornar um erro bem claro, indicando exatamente onde e o que estava incorreto.
* Entregar a você a informação recebida no parâmetro `item`.
- * Como você o declarou na função como do tipo `Item`, você também terá o suporte do editor (completação, etc) para todos os atributos e seus tipos.
+ * Como você o declarou na função como do tipo `Item`, você também terá o suporte do editor (preenchimento automático, etc) para todos os atributos e seus tipos.
* Gerar definições de JSON Schema para o seu modelo; você também pode usá-las em qualquer outro lugar se fizer sentido para o seu projeto.
-* Esses schemas farão parte do esquema OpenAPI gerado, e serão usados pelas UIs de documentação automática.
+* Esses schemas farão parte do esquema OpenAPI gerado, e serão usados pelas UIs de documentação automática.
## Documentação automática { #automatic-docs }
@@ -88,7 +88,7 @@ E também serão utilizados na documentação da API dentro de cada *operação
## Suporte do editor { #editor-support }
-No seu editor, dentro da função você receberá dicas de tipos e completação em todo lugar (isso não aconteceria se você recebesse um `dict` em vez de um modelo Pydantic):
+No seu editor, dentro da função você receberá dicas de tipos e preenchimento automático em todo lugar (isso não aconteceria se você recebesse um `dict` em vez de um modelo Pydantic):
@@ -155,7 +155,7 @@ Os parâmetros da função serão reconhecidos conforme abaixo:
O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
-O `str | None` (Python 3.10+) ou o `Union` em `Union[str, None]` (Python 3.9+) não é utilizado pelo FastAPI para determinar que o valor não é obrigatório, ele saberá que não é obrigatório porque tem um valor padrão `= None`.
+O `str | None` não é utilizado pelo FastAPI para determinar que o valor não é obrigatório, ele saberá que não é obrigatório porque tem um valor padrão `= None`.
Mas adicionar as anotações de tipo permitirá ao seu editor oferecer um suporte melhor e detectar erros.
diff --git a/docs/pt/docs/tutorial/cookie-param-models.md b/docs/pt/docs/tutorial/cookie-param-models.md
index 73c94050f..f125314c8 100644
--- a/docs/pt/docs/tutorial/cookie-param-models.md
+++ b/docs/pt/docs/tutorial/cookie-param-models.md
@@ -18,7 +18,7 @@ Essa mesma técnica se aplica para `Query`, `Cookie`, e `Header`. 😎
## Cookies com Modelos Pydantic { #cookies-with-a-pydantic-model }
-Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, e depois declare o parâmetro como um `Cookie`:
+Declare os parâmetros de **cookie** de que você precisa em um **modelo Pydantic**, e depois declare o parâmetro como `Cookie`:
{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
@@ -46,7 +46,7 @@ Mas mesmo que você **adicionar os dados** e clicar em "Executar", pelo motivo d
Em alguns casos especiais (provavelmente não muito comuns), você pode querer **restringir** os cookies que você deseja receber.
-Agora a sua API possui o poder de controlar o seu próprio consentimento de cookie. 🤪🍪
+Agora a sua API possui o poder de controlar o seu próprio consentimento de cookie. 🤪🍪
Você pode utilizar a configuração do modelo Pydantic para `proibir` qualquer campo `extra`:
@@ -54,9 +54,9 @@ Você pode utilizar a configuração do modelo Pydantic para `proibir` qualquer
Se o cliente tentar enviar alguns **cookies extras**, eles receberão um retorno de **erro**.
-Coitados dos banners de cookies com todo o seu esforço para obter o seu consentimento para a API rejeitá-lo. 🍪
+Coitados dos banners de cookies com todo o seu esforço para obter o seu consentimento para a API rejeitá-lo. 🍪
-Por exemplo, se o cliente tentar enviar um cookie `santa_tracker` com o valor de `good-list-please`, o cliente receberá uma resposta de **erro** informando que o `santa_tracker` cookie não é permitido:
+Por exemplo, se o cliente tentar enviar um cookie `santa_tracker` com o valor de `good-list-please`, o cliente receberá uma resposta de **erro** informando que o `santa_tracker` cookie não é permitido:
```json
{
@@ -73,4 +73,4 @@ Por exemplo, se o cliente tentar enviar um cookie `santa_tracker` com o valor de
## Resumo { #summary }
-Você consegue utilizar **modelos Pydantic** para declarar **cookies** no **FastAPI**. 😎
+Você consegue utilizar **modelos Pydantic** para declarar **cookies** no **FastAPI**. 😎
diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md
index 0f99db888..055cfeaca 100644
--- a/docs/pt/docs/tutorial/cors.md
+++ b/docs/pt/docs/tutorial/cors.md
@@ -46,7 +46,8 @@ Você também pode especificar se o seu backend permite:
* Métodos HTTP específicos (`POST`, `PUT`) ou todos eles com o curinga `"*"`.
* Cabeçalhos HTTP específicos ou todos eles com o curinga `"*"`.
-{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *}
+
Os parâmetros padrão usados pela implementação `CORSMiddleware` são restritivos por padrão, então você precisará habilitar explicitamente as origens, métodos ou cabeçalhos específicos para que os navegadores tenham permissão para usá-los em um contexto cross domain.
diff --git a/docs/pt/docs/tutorial/debugging.md b/docs/pt/docs/tutorial/debugging.md
index e39c7d128..773921bb3 100644
--- a/docs/pt/docs/tutorial/debugging.md
+++ b/docs/pt/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@ Você pode conectar o depurador no seu editor, por exemplo, com o Visual Studio
Em sua aplicação FastAPI, importe e execute `uvicorn` diretamente:
-{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *}
### Sobre `__name__ == "__main__"` { #about-name-main }
@@ -62,7 +62,7 @@ from myapp import app
# Mais um pouco de código
```
-nesse caso, a variável criada automaticamente dentro de `myapp.py` não terá a variável `__name__` com o valor `"__main__"`.
+nesse caso, a variável `__name__` criada automaticamente dentro de `myapp.py` não terá o valor `"__main__"`.
Então, a linha:
diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
index c30d0b5f0..7231373a7 100644
--- a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -101,7 +101,7 @@ O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" des
Perceba como escrevemos `CommonQueryParams` duas vezes no código abaixo:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ non-Annotated
/// tip | Dica
@@ -137,7 +137,7 @@ O último `CommonQueryParams`, em:
Nesse caso, o primeiro `CommonQueryParams`, em:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ non-Annotated
/// tip | Dica
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
Na verdade você poderia escrever apenas:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ non-Annotated
/// tip | Dica
@@ -197,7 +197,7 @@ Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto s
Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ non-Annotated
/// tip | Dica
@@ -225,7 +225,7 @@ Para esses casos específicos, você pode fazer o seguinte:
Em vez de escrever:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ non-Annotated
/// tip | Dica
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
...escreva:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ non-Annotated
/// tip | Dica
diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index ee8a58dc2..4a99091d1 100644
--- a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -1,6 +1,6 @@
# Dependências em decoradores de operações de rota { #dependencies-in-path-operation-decorators }
-Em alguns casos você não precisa necessariamente retornar o valor de uma dependência dentro de uma *função de operação de rota*.
+Em alguns casos você não precisa necessariamente do valor de retorno de uma dependência dentro de uma *função de operação de rota*.
Ou a dependência não retorna nenhum valor.
@@ -14,7 +14,7 @@ O *decorador da operação de rota* recebe um argumento opcional `dependencies`.
Ele deve ser uma lista de `Depends()`:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*.
@@ -44,13 +44,13 @@ Você pode utilizar as mesmas *funções* de dependências que você usaria norm
Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
### Levantar exceções { #raise-exceptions }
Essas dependências podem `raise` exceções, da mesma forma que dependências comuns:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
### Valores de retorno { #return-values }
@@ -58,7 +58,7 @@ E elas também podem ou não retornar valores, eles não serão utilizados.
Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
## Dependências para um grupo de *operações de rota* { #dependencies-for-a-group-of-path-operations }
diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
index 367873013..dd9d9fbe6 100644
--- a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,6 +1,6 @@
# Dependências com yield { #dependencies-with-yield }
-O **FastAPI** possui suporte para dependências que realizam alguns passos extras ao finalizar.
+O **FastAPI** possui suporte para dependências que realizam alguns passos extras ao finalizar.
Para fazer isso, utilize `yield` em vez de `return`, e escreva os passos extras (código) depois.
@@ -29,15 +29,15 @@ Por exemplo, você poderia utilizar isso para criar uma sessão do banco de dado
Apenas o código anterior à declaração com `yield` e o código contendo essa declaração são executados antes de criar uma resposta:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
O valor gerado (yielded) é o que é injetado nas *operações de rota* e outras dependências:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
O código após o `yield` é executado após a resposta:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
/// tip | Dica
@@ -57,7 +57,7 @@ Então, você pode procurar por essa exceção específica dentro da dependênci
Da mesma forma, você pode utilizar `finally` para garantir que os passos de saída são executados, com ou sem exceções.
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
## Subdependências com `yield` { #sub-dependencies-with-yield }
@@ -67,7 +67,7 @@ O **FastAPI** garantirá que o "código de saída" em cada dependência com `yie
Por exemplo, `dependency_c` pode depender de `dependency_b`, e `dependency_b` depender de `dependency_a`:
-{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *}
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
E todas elas podem utilizar `yield`.
@@ -75,7 +75,7 @@ Neste caso, `dependency_c`, para executar seu código de saída, precisa que o v
E, por outro lado, `dependency_b` precisa que o valor de `dependency_a` (nomeado de `dep_a`) esteja disponível para executar seu código de saída.
-{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *}
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
Da mesma forma, você pode ter algumas dependências com `yield` e outras com `return` e ter uma relação de dependência entre algumas das duas.
@@ -109,7 +109,7 @@ Mas ela existe para ser utilizada caso você precise. 🤓
///
-{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *}
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
Se você quiser capturar exceções e criar uma resposta personalizada com base nisso, crie um [Manipulador de Exceções Customizado](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
@@ -117,7 +117,7 @@ Se você quiser capturar exceções e criar uma resposta personalizada com base
Se você capturar uma exceção com `except` em uma dependência que utilize `yield` e ela não for levantada novamente (ou uma nova exceção for levantada), o FastAPI não será capaz de identificar que houve uma exceção, da mesma forma que aconteceria com Python puro:
-{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *}
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
Neste caso, o cliente irá ver uma resposta *HTTP 500 Internal Server Error* como deveria acontecer, já que não estamos levantando nenhuma `HTTPException` ou coisa parecida, mas o servidor **não terá nenhum log** ou qualquer outra indicação de qual foi o erro. 😱
@@ -127,7 +127,7 @@ Se você capturar uma exceção em uma dependência com `yield`, a menos que voc
Você pode relançar a mesma exceção utilizando `raise`:
-{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *}
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
Agora o cliente irá receber a mesma resposta *HTTP 500 Internal Server Error*, mas o servidor terá nosso `InternalError` personalizado nos logs. 😎
@@ -190,7 +190,7 @@ Normalmente, o código de saída das dependências com `yield` é executado **ap
Mas se você sabe que não precisará usar a dependência depois de retornar da *função de operação de rota*, você pode usar `Depends(scope="function")` para dizer ao FastAPI que deve fechar a dependência depois que a *função de operação de rota* retornar, mas **antes** de a **resposta ser enviada**.
-{* ../../docs_src/dependencies/tutorial008e_an_py39.py hl[12,16] *}
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
`Depends()` recebe um parâmetro `scope` que pode ser:
@@ -269,7 +269,7 @@ Em Python, você pode criar Gerenciadores de Contexto ao Injeção de Dependência**.
+O **FastAPI** possui um poderoso, mas intuitivo sistema de **Injeção de Dependência**.
Esse sistema foi pensado para ser fácil de usar, e permitir que qualquer desenvolvedor possa integrar facilmente outros componentes ao **FastAPI**.
@@ -25,7 +25,7 @@ Vamos ver um exemplo simples. Tão simples que não será muito útil, por enqua
Mas dessa forma podemos focar em como o sistema de **Injeção de Dependência** funciona.
-### Criando uma dependência, ou "injetável" { #create-a-dependency-or-dependable }
+### Criando uma dependência, ou "dependable" { #create-a-dependency-or-dependable }
Primeiro vamos focar na dependência.
@@ -89,7 +89,7 @@ Você verá quais outras "coisas", além de funções, podem ser usadas como dep
Sempre que uma nova requisição for realizada, o **FastAPI** se encarrega de:
-* Chamar sua dependência ("injetável") com os parâmetros corretos.
+* Chamar sua dependência ("dependable") com os parâmetros corretos.
* Obter o resultado da função.
* Atribuir esse resultado para o parâmetro em sua *função de operação de rota*.
@@ -186,7 +186,7 @@ Outros termos comuns para essa mesma ideia de "injeção de dependência" são:
Integrações e "plug-ins" podem ser construídos com o sistema de **Injeção de Dependência**. Mas na verdade, **não há necessidade de criar "plug-ins"**, já que utilizando dependências é possível declarar um número infinito de integrações e interações que se tornam disponíveis para as suas *funções de operação de rota*.
-E as dependências pode ser criadas de uma forma bastante simples e intuitiva que permite que você importe apenas os pacotes Python que forem necessários, e integrá-los com as funções de sua API em algumas linhas de código, *literalmente*.
+E as dependências podem ser criadas de uma forma bastante simples e intuitiva que permite que você importe apenas os pacotes Python que forem necessários, e integrá-los com as funções de sua API em algumas linhas de código, *literalmente*.
Você verá exemplos disso nos próximos capítulos, acerca de bancos de dados relacionais e NoSQL, segurança, etc.
@@ -199,7 +199,7 @@ A simplicidade do sistema de injeção de dependência do **FastAPI** faz ele co
* pacotes externos
* APIs externas
* sistemas de autenticação e autorização
-* istemas de monitoramento de uso para APIs
+* sistemas de monitoramento de uso para APIs
* sistemas de injeção de dados de resposta
* etc.
@@ -209,7 +209,7 @@ Mesmo que o sistema hierárquico de injeção de dependência seja simples de de
Você pode definir dependências que por sua vez definem suas próprias dependências.
-No fim, uma árvore hierárquica de dependências é criadas, e o sistema de **Injeção de Dependência** toma conta de resolver todas essas dependências (e as sub-dependências delas) para você, e provê (injeta) os resultados em cada passo.
+Por fim, uma árvore hierárquica de dependências é criada, e o sistema de **Injeção de Dependência** toma conta de resolver todas essas dependências (e as sub-dependências delas) para você, e provê (injeta) os resultados em cada passo.
Por exemplo, vamos supor que você possua 4 endpoints na sua API (*operações de rota*):
diff --git a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md
index e2dc9bbf9..63ed0e48a 100644
--- a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md
@@ -58,11 +58,11 @@ query_extractor --> query_or_cookie_extractor --> read_query
Se uma de suas dependências é declarada várias vezes para a mesma *operação de rota*, por exemplo, múltiplas dependências com uma mesma subdependência, o **FastAPI** irá chamar essa subdependência uma única vez para cada requisição.
-E o valor retornado é salvo em um "cache" e repassado para todos os "dependentes" que precisam dele em uma requisição específica, em vez de chamar a dependência múltiplas vezes para uma mesma requisição.
+E o valor retornado é salvo em um "cache" e repassado para todos os "dependentes" que precisam dele em uma requisição específica, em vez de chamar a dependência múltiplas vezes para uma mesma requisição.
Em um cenário avançado onde você precise que a dependência seja calculada em cada passo (possivelmente várias vezes) de uma requisição em vez de utilizar o valor em "cache", você pode definir o parâmetro `use_cache=False` em `Depends`:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python hl_lines="1"
async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
@@ -71,7 +71,7 @@ async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_ca
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ non-Annotated
/// tip | Dica
diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md
index 24eafce01..313659741 100644
--- a/docs/pt/docs/tutorial/extra-models.md
+++ b/docs/pt/docs/tutorial/extra-models.md
@@ -190,9 +190,9 @@ Mas se colocarmos isso na atribuição `response_model=PlaneItem | CarItem`, ter
Da mesma forma, você pode declarar respostas de listas de objetos.
-Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python 3.9 e superior):
+Para isso, use o padrão Python `list`:
-{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *}
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
## Resposta com `dict` arbitrário { #response-with-arbitrary-dict }
@@ -200,9 +200,9 @@ Você também pode declarar uma resposta usando um simples `dict` arbitrário, d
Isso é útil se você não souber os nomes de campo / atributo válidos (que seriam necessários para um modelo Pydantic) antecipadamente.
-Neste caso, você pode usar `typing.Dict` (ou simplesmente `dict` no Python 3.9 e superior):
+Neste caso, você pode usar `dict`:
-{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *}
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
## Recapitulação { #recap }
diff --git a/docs/pt/docs/tutorial/first-steps.md b/docs/pt/docs/tutorial/first-steps.md
index 86cddde5d..4ccc7cf04 100644
--- a/docs/pt/docs/tutorial/first-steps.md
+++ b/docs/pt/docs/tutorial/first-steps.md
@@ -2,7 +2,7 @@
O arquivo FastAPI mais simples pode se parecer com:
-{* ../../docs_src/first_steps/tutorial001_py39.py *}
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
Copie o conteúdo para um arquivo `main.py`.
@@ -183,7 +183,7 @@ Deploying to FastAPI Cloud...
### Passo 1: importe `FastAPI` { #step-1-import-fastapi }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[1] *}
`FastAPI` é uma classe Python que fornece todas as funcionalidades para sua API.
@@ -197,7 +197,7 @@ Você pode usar todas as funcionalidades do operação get
+* usando uma get operação
/// info | Informações sobre `@decorator`
@@ -320,7 +320,7 @@ Esta é a nossa "**função de operação de rota**":
* **operação**: é `get`.
* **função**: é a função abaixo do "decorador" (abaixo do `@app.get("/")`).
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
Esta é uma função Python.
@@ -332,7 +332,7 @@ Neste caso, é uma função `async`.
Você também pode defini-la como uma função normal em vez de `async def`:
-{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
/// note | Nota
@@ -342,7 +342,7 @@ Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.m
### Passo 5: retorne o conteúdo { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
Você pode retornar um `dict`, `list` e valores singulares como `str`, `int`, etc.
diff --git a/docs/pt/docs/tutorial/handling-errors.md b/docs/pt/docs/tutorial/handling-errors.md
index 1c162c205..252dbb06f 100644
--- a/docs/pt/docs/tutorial/handling-errors.md
+++ b/docs/pt/docs/tutorial/handling-errors.md
@@ -25,7 +25,7 @@ Para retornar ao cliente *responses* HTTP com erros, use o `HTTPException`.
### Import `HTTPException` { #import-httpexception }
-{* ../../docs_src/handling_errors/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
### Lance o `HTTPException` no seu código { #raise-an-httpexception-in-your-code }
@@ -33,13 +33,13 @@ Para retornar ao cliente *responses* HTTP com erros, use o `HTTPException`.
E porque é uma exceção do Python, você não **retorna** (return) o `HTTPException`, você lança o (raise) no seu código.
-Isso também significa que, se você está escrevendo uma função de utilidade, a qual você está chamando dentro da sua função de operações de caminhos, e você lança o `HTTPException` dentro da função de utilidade, o resto do seu código não será executado dentro da função de operações de caminhos. Ao contrário, o `HTTPException` irá finalizar a requisição no mesmo instante e enviará o erro HTTP oriundo do `HTTPException` para o cliente.
+Isso também significa que, se você está escrevendo uma função de utilidade, a qual você está chamando dentro da sua função de operação de rota, e você lança o `HTTPException` dentro da função de utilidade, o resto do seu código não será executado dentro da função de operação de rota. Ao contrário, o `HTTPException` irá finalizar a requisição no mesmo instante e enviará o erro HTTP oriundo do `HTTPException` para o cliente.
O benefício de lançar uma exceção em vez de retornar um valor ficará mais evidente na seção sobre Dependências e Segurança.
Neste exemplo, quando o cliente pede, na requisição, por um item cujo ID não existe, a exceção com o status code `404` é lançada:
-{* ../../docs_src/handling_errors/tutorial001_py39.py hl[11] *}
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
### A response resultante { #the-resulting-response }
@@ -77,7 +77,7 @@ Você provavelmente não precisará utilizar esses headers diretamente no seu c
Mas caso você precise, para um cenário mais complexo, você pode adicionar headers customizados:
-{* ../../docs_src/handling_errors/tutorial002_py39.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
## Instale manipuladores de exceções customizados { #install-custom-exception-handlers }
@@ -87,9 +87,9 @@ Digamos que você tenha uma exceção customizada `UnicornException` que você (
Nesse cenário, se você precisa manipular essa exceção de modo global com o FastAPI, você pode adicionar um manipulador de exceção customizada com `@app.exception_handler()`.
-{* ../../docs_src/handling_errors/tutorial003_py39.py hl[5:7,13:18,24] *}
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
-Nesse cenário, se você fizer uma requisição para `/unicorns/yolo`, a *operação de caminho* vai lançar (`raise`) o `UnicornException`.
+Nesse cenário, se você fizer uma requisição para `/unicorns/yolo`, a *operação de rota* vai lançar (`raise`) o `UnicornException`.
Essa exceção será manipulada, contudo, pelo `unicorn_exception_handler`.
@@ -125,7 +125,7 @@ Para sobrescrevê-lo, importe o `RequestValidationError` e use-o com o `@app.exc
O manipulador de exceções receberá um `Request` e a exceção.
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[2,14:19] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
Se você for ao `/items/foo`, em vez de receber o JSON padrão com o erro:
@@ -157,7 +157,7 @@ Do mesmo modo, você pode sobrescrever o `HTTPException`.
Por exemplo, você pode querer retornar uma *response* em *plain text* ao invés de um JSON para os seguintes erros:
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[3:4,9:11,25] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
/// note | Detalhes Técnicos
@@ -181,7 +181,7 @@ O `RequestValidationError` contém o `body` que ele recebeu de dados inválidos.
Você pode utilizá-lo enquanto desenvolve seu app para registrar o *body* e debugá-lo, e assim retorná-lo ao usuário, etc.
-{* ../../docs_src/handling_errors/tutorial005_py39.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
Tente enviar um item inválido como este:
@@ -237,6 +237,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
Se você quer usar a exceção em conjunto com o mesmo manipulador de exceção *default* do **FastAPI**, você pode importar e re-usar esses manipuladores de exceção do `fastapi.exception_handlers`:
-{* ../../docs_src/handling_errors/tutorial006_py39.py hl[2:5,15,21] *}
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
Nesse exemplo você apenas imprime (`print`) o erro com uma mensagem expressiva. Mesmo assim, dá para pegar a ideia. Você pode usar a exceção e então apenas re-usar o manipulador de exceção *default*.
diff --git a/docs/pt/docs/tutorial/header-params.md b/docs/pt/docs/tutorial/header-params.md
index a0deb98be..a56f5805e 100644
--- a/docs/pt/docs/tutorial/header-params.md
+++ b/docs/pt/docs/tutorial/header-params.md
@@ -12,7 +12,7 @@ Primeiro importe `Header`:
Então declare os paramêtros de cabeçalho usando a mesma estrutura que em `Path`, `Query` e `Cookie`.
-O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação:
+Você pode definir o valor padrão, assim como todas as validações extras ou parâmetros de anotação:
{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *}
diff --git a/docs/pt/docs/tutorial/metadata.md b/docs/pt/docs/tutorial/metadata.md
index df77e5648..476b5c806 100644
--- a/docs/pt/docs/tutorial/metadata.md
+++ b/docs/pt/docs/tutorial/metadata.md
@@ -1,4 +1,4 @@
-# Metadados e Urls de Documentos { #metadata-and-docs-urls }
+# Metadados e URLs da Documentação { #metadata-and-docs-urls }
Você pode personalizar várias configurações de metadados na sua aplicação **FastAPI**.
@@ -18,7 +18,7 @@ Você pode definir os seguintes campos que são usados na especificação OpenAP
Você pode defini-los da seguinte maneira:
-{* ../../docs_src/metadata/tutorial001_py39.py hl[3:16, 19:32] *}
+{* ../../docs_src/metadata/tutorial001_py310.py hl[3:16, 19:32] *}
/// tip | Dica
@@ -32,11 +32,11 @@ Com essa configuração, a documentação automática da API se pareceria com:
## Identificador de Licença { #license-identifier }
-Desde o OpenAPI 3.1.0 e FastAPI 0.99.0, você também pode definir o license_info com um identifier em vez de uma url.
+Desde o OpenAPI 3.1.0 e FastAPI 0.99.0, você também pode definir o `license_info` com um `identifier` em vez de uma `url`.
Por exemplo:
-{* ../../docs_src/metadata/tutorial001_1_py39.py hl[31] *}
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
## Metadados para tags { #metadata-for-tags }
@@ -58,7 +58,7 @@ Vamos tentar isso em um exemplo com tags para `users` e `items`.
Crie metadados para suas tags e passe-os para o parâmetro `openapi_tags`:
-{* ../../docs_src/metadata/tutorial004_py39.py hl[3:16,18] *}
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
Observe que você pode usar Markdown dentro das descrições. Por exemplo, "login" será exibido em negrito (**login**) e "fancy" será exibido em itálico (_fancy_).
@@ -72,7 +72,7 @@ Você não precisa adicionar metadados para todas as tags que você usa.
Use o parâmetro `tags` com suas *operações de rota* (e `APIRouter`s) para atribuí-los a diferentes tags:
-{* ../../docs_src/metadata/tutorial004_py39.py hl[21,26] *}
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
/// info | Informação
@@ -100,7 +100,7 @@ Mas você pode configurá-lo com o parâmetro `openapi_url`.
Por exemplo, para defini-lo para ser servido em `/api/v1/openapi.json`:
-{* ../../docs_src/metadata/tutorial002_py39.py hl[3] *}
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
Se você quiser desativar completamente o esquema OpenAPI, pode definir `openapi_url=None`, o que também desativará as interfaces de documentação que o utilizam.
@@ -117,4 +117,4 @@ Você pode configurar as duas interfaces de documentação incluídas:
Por exemplo, para definir o Swagger UI para ser servido em `/documentation` e desativar o ReDoc:
-{* ../../docs_src/metadata/tutorial003_py39.py hl[3] *}
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/pt/docs/tutorial/middleware.md b/docs/pt/docs/tutorial/middleware.md
index b49c1eaa1..7cccfcb6a 100644
--- a/docs/pt/docs/tutorial/middleware.md
+++ b/docs/pt/docs/tutorial/middleware.md
@@ -31,13 +31,13 @@ A função middleware recebe:
* Então ela retorna a `response` gerada pela *operação de rota* correspondente.
* Você pode então modificar ainda mais o `response` antes de retorná-lo.
-{* ../../docs_src/middleware/tutorial001_py39.py hl[8:9,11,14] *}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
/// tip | Dica
Tenha em mente que cabeçalhos proprietários personalizados podem ser adicionados usando o prefixo `X-`.
-Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em Documentos CORS da Starlette.
+Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em Documentação CORS da Starlette.
///
@@ -57,7 +57,7 @@ E também depois que a `response` é gerada, antes de retorná-la.
Por exemplo, você pode adicionar um cabeçalho personalizado `X-Process-Time` contendo o tempo em segundos que levou para processar a solicitação e gerar uma resposta:
-{* ../../docs_src/middleware/tutorial001_py39.py hl[10,12:13] *}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
/// tip | Dica
diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md
index 2527c2892..c17b12e2b 100644
--- a/docs/pt/docs/tutorial/path-operation-configuration.md
+++ b/docs/pt/docs/tutorial/path-operation-configuration.md
@@ -46,7 +46,7 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`.
**FastAPI** suporta isso da mesma maneira que com strings simples:
-{* ../../docs_src/path_operation_configuration/tutorial002b_py39.py hl[1,8:10,13,18] *}
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
## Resumo e descrição { #summary-and-description }
@@ -56,7 +56,7 @@ Você pode adicionar um `summary` e uma `description`:
## Descrição do docstring { #description-from-docstring }
-Como as descrições tendem a ser longas e cobrir várias linhas, você pode declarar a descrição da *operação de rota* na docstring da função e o **FastAPI** irá lê-la de lá.
+Como as descrições tendem a ser longas e cobrir várias linhas, você pode declarar a descrição da *operação de rota* na docstring da função e o **FastAPI** irá lê-la de lá.
Você pode escrever Markdown na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring).
@@ -90,9 +90,9 @@ Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma
## Descontinuar uma *operação de rota* { #deprecate-a-path-operation }
-Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`:
+Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`:
-{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
Ela será claramente marcada como descontinuada nas documentações interativas:
diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md
index 9f12ba38f..bb2e154f4 100644
--- a/docs/pt/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md
@@ -54,11 +54,11 @@ Isso não faz diferença para o **FastAPI**. Ele vai detectar os parâmetros pel
Então, você pode declarar sua função assim:
-{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
Mas tenha em mente que, se você usar `Annotated`, você não terá esse problema, não fará diferença, pois você não está usando valores padrão de parâmetros de função para `Query()` ou `Path()`.
-{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
## Ordene os parâmetros de acordo com sua necessidade, truques { #order-the-parameters-as-you-need-tricks }
@@ -81,15 +81,15 @@ Se você quiser:
Passe `*`, como o primeiro parâmetro da função.
-O Python não fará nada com esse `*`, mas saberá que todos os parâmetros seguintes devem ser chamados como argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não tenham um valor padrão.
+O Python não fará nada com esse `*`, mas saberá que todos os parâmetros seguintes devem ser chamados como argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não tenham um valor padrão.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
### Melhor com `Annotated` { #better-with-annotated }
Tenha em mente que, se você usar `Annotated`, como você não está usando valores padrão de parâmetros de função, você não terá esse problema e provavelmente não precisará usar `*`.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
## Validações numéricas: maior que ou igual { #number-validations-greater-than-or-equal }
@@ -97,7 +97,7 @@ Com `Query` e `Path` (e outras que você verá depois) você pode declarar restr
Aqui, com `ge=1`, `item_id` precisará ser um número inteiro “`g`reater than or `e`qual” a `1`.
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
## Validações numéricas: maior que e menor que ou igual { #number-validations-greater-than-and-less-than-or-equal }
@@ -106,7 +106,7 @@ O mesmo se aplica a:
* `gt`: maior que (`g`reater `t`han)
* `le`: menor que ou igual (`l`ess than or `e`qual)
-{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
## Validações numéricas: floats, maior que e menor que { #number-validations-floats-greater-than-and-less-than }
@@ -118,7 +118,7 @@ Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seriam.
E o mesmo para lt.
-{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
## Recapitulando { #recap }
diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md
index 1f47ca6e5..e8e420ad0 100644
--- a/docs/pt/docs/tutorial/path-params.md
+++ b/docs/pt/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Você pode declarar "parâmetros" ou "variáveis" de path com a mesma sintaxe usada por strings de formatação do Python:
-{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
O valor do parâmetro de path `item_id` será passado para a sua função como o argumento `item_id`.
@@ -16,7 +16,7 @@ Então, se você executar este exemplo e acessar conversão { #data-conversion }
+## Dados conversão { #data-conversion }
Se você executar este exemplo e abrir seu navegador em http://127.0.0.1:8000/items/3, você verá uma resposta:
@@ -35,7 +35,7 @@ Se você executar este exemplo e abrir seu navegador em "parsing" automático do request.
+Então, com essa declaração de tipo, o **FastAPI** fornece "parsing" automático do request.
///
## Validação de dados { #data-validation }
@@ -110,19 +110,19 @@ E então você também pode ter um path `/users/{user_id}` para obter dados sobr
Como as *operações de rota* são avaliadas em ordem, você precisa garantir que o path para `/users/me` seja declarado antes do de `/users/{user_id}`:
-{* ../../docs_src/path_params/tutorial003_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
Caso contrário, o path para `/users/{user_id}` também corresponderia a `/users/me`, "achando" que está recebendo um parâmetro `user_id` com o valor `"me"`.
Da mesma forma, você não pode redefinir uma operação de rota:
-{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
A primeira sempre será usada, já que o path corresponde primeiro.
## Valores predefinidos { #predefined-values }
-Se você tem uma *operação de rota* que recebe um *parâmetro de path*, mas quer que os valores válidos possíveis do *parâmetro de path* sejam predefinidos, você pode usar um `Enum` padrão do Python.
+Se você tem uma *operação de rota* que recebe um *parâmetro de path*, mas quer que os valores válidos possíveis do *parâmetro de path* sejam predefinidos, você pode usar um `Enum` padrão do Python.
### Crie uma classe `Enum` { #create-an-enum-class }
@@ -132,17 +132,17 @@ Ao herdar de `str`, a documentação da API saberá que os valores devem ser do
Em seguida, crie atributos de classe com valores fixos, que serão os valores válidos disponíveis:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
/// tip | Dica
-Se você está se perguntando, "AlexNet", "ResNet" e "LeNet" são apenas nomes de modelos de Aprendizado de Máquina.
+Se você está se perguntando, "AlexNet", "ResNet" e "LeNet" são apenas nomes de modelos de Aprendizado de Máquina modelos.
///
### Declare um parâmetro de path { #declare-a-path-parameter }
Em seguida, crie um *parâmetro de path* com anotação de tipo usando a classe enum que você criou (`ModelName`):
-{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
### Verifique a documentação { #check-the-docs }
@@ -158,13 +158,13 @@ O valor do *parâmetro de path* será um *membro de enumeração*.
Você pode compará-lo com o *membro de enumeração* no seu enum `ModelName` criado:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[17] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
#### Obtenha o valor da enumeração { #get-the-enumeration-value }
Você pode obter o valor real (um `str` neste caso) usando `model_name.value`, ou, em geral, `your_enum_member.value`:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[20] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
/// tip | Dica
Você também pode acessar o valor `"lenet"` com `ModelName.lenet.value`.
@@ -176,7 +176,7 @@ Você pode retornar *membros de enum* da sua *operação de rota*, até mesmo an
Eles serão convertidos para seus valores correspondentes (strings neste caso) antes de serem retornados ao cliente:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[18,21,23] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
No seu cliente, você receberá uma resposta JSON como:
@@ -215,7 +215,7 @@ Nesse caso, o nome do parâmetro é `file_path`, e a última parte, `:path`, diz
Então, você pode usá-lo com:
-{* ../../docs_src/path_params/tutorial004_py39.py hl[6] *}
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
/// tip | Dica
Você pode precisar que o parâmetro contenha `/home/johndoe/myfile.txt`, com uma barra inicial (`/`).
@@ -227,8 +227,8 @@ Nesse caso, a URL seria: `/files//home/johndoe/myfile.txt`, com uma barra dupla
Com o **FastAPI**, ao usar declarações de tipo do Python curtas, intuitivas e padrão, você obtém:
-- Suporte no editor: verificações de erro, autocompletar, etc.
-- "Parsing" de dados
+- Suporte no editor: verificações de erro, preenchimento automático, etc.
+- "parsing" de dados
- Validação de dados
- Anotação da API e documentação automática
diff --git a/docs/pt/docs/tutorial/query-param-models.md b/docs/pt/docs/tutorial/query-param-models.md
index 42d2604cd..7fc59c033 100644
--- a/docs/pt/docs/tutorial/query-param-models.md
+++ b/docs/pt/docs/tutorial/query-param-models.md
@@ -18,10 +18,9 @@ Declare os **parâmetros de consulta** que você precisa em um **modelo Pydantic
O **FastAPI** **extrairá** os dados para **cada campo** dos **parâmetros de consulta** presentes na requisição, e fornecerá o modelo Pydantic que você definiu.
+## Verifique a Documentação { #check-the-docs }
-## Verifique os Documentos { #check-the-docs }
-
-Você pode ver os parâmetros de consulta nos documentos de IU em `/docs`:
+Você pode ver os parâmetros de consulta na IU da documentação em `/docs`:
@@ -29,9 +28,9 @@ Você pode ver os parâmetros de consulta nos documentos de IU em `/docs`:
## Restrinja Parâmetros de Consulta Extras { #forbid-extra-query-parameters }
-Em alguns casos especiais (provavelmente não muito comuns), você queira **restrinjir** os parâmetros de consulta que deseja receber.
+Em alguns casos especiais (provavelmente não muito comuns), você queira **restringir** os parâmetros de consulta que deseja receber.
-Você pode usar a configuração do modelo Pydantic para `forbid` (proibir) qualquer campo `extra`:
+Você pode usar a configuração do modelo Pydantic para `forbid` qualquer campo `extra`:
{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *}
@@ -43,7 +42,7 @@ Por exemplo, se o cliente tentar enviar um parâmetro de consulta `tool` com o v
https://example.com/items/?limit=10&tool=plumbus
```
-Eles receberão um retorno de **erro** informando-os que o parâmentro de consulta `tool` não é permitido:
+Eles receberão um retorno de **erro** informando-os que o parâmetro de consulta `tool` não é permitido:
```json
{
diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md
index c93a941e5..b76b76a26 100644
--- a/docs/pt/docs/tutorial/query-params-str-validations.md
+++ b/docs/pt/docs/tutorial/query-params-str-validations.md
@@ -18,7 +18,7 @@ Ter `str | None` permitirá que seu editor lhe ofereça melhor suporte e detecte
## Validação adicional { #additional-validation }
-Vamos impor que, embora `q` seja opcional, sempre que for fornecido, **seu comprimento não exceda 50 caracteres**.
+Vamos impor que, embora `q` seja opcional, sempre que for fornecido, seu comprimento não exceda 50 caracteres.
### Importe `Query` e `Annotated` { #import-query-and-annotated }
@@ -47,40 +47,16 @@ Agora é a hora de usá-lo com FastAPI. 🚀
Tínhamos esta anotação de tipo:
-//// tab | Python 3.10+
-
```Python
q: str | None = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Union[str, None] = None
-```
-
-////
-
O que faremos é envolver isso com `Annotated`, para que fique assim:
-//// tab | Python 3.10+
-
```Python
q: Annotated[str | None] = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Annotated[Union[str, None]] = None
-```
-
-////
-
Ambas as versões significam a mesma coisa, `q` é um parâmetro que pode ser `str` ou `None`, e por padrão é `None`.
Agora vamos pular para a parte divertida. 🎉
@@ -93,23 +69,23 @@ Agora que temos esse `Annotated` onde podemos colocar mais informações (neste
Perceba que o valor padrão continua sendo `None`, então o parâmetro ainda é opcional.
-Mas agora, com `Query(max_length=50)` dentro de `Annotated`, estamos dizendo ao FastAPI que queremos **validação adicional** para este valor, queremos que tenha no máximo 50 caracteres. 😎
+Mas agora, com `Query(max_length=50)` dentro de `Annotated`, estamos dizendo ao FastAPI que queremos validação adicional para este valor, queremos que tenha no máximo 50 caracteres. 😎
/// tip | Dica
-Aqui estamos usando `Query()` porque este é um **parâmetro de consulta**. Mais adiante veremos outros como `Path()`, `Body()`, `Header()` e `Cookie()`, que também aceitam os mesmos argumentos que `Query()`.
+Aqui estamos usando `Query()` porque este é um parâmetro de consulta. Mais adiante veremos outros como `Path()`, `Body()`, `Header()` e `Cookie()`, que também aceitam os mesmos argumentos que `Query()`.
///
Agora o FastAPI vai:
-* **Validar** os dados garantindo que o comprimento máximo seja de 50 caracteres
-* Mostrar um **erro claro** para o cliente quando os dados não forem válidos
-* **Documentar** o parâmetro na *operação de rota* do esquema OpenAPI (então ele aparecerá na **UI de docs automática**)
+* Validar os dados garantindo que o comprimento máximo seja de 50 caracteres
+* Mostrar um erro claro para o cliente quando os dados não forem válidos
+* Documentar o parâmetro na operação de rota do esquema OpenAPI (então ele aparecerá na UI de docs automática)
## Alternativa (antiga): `Query` como valor padrão { #alternative-old-query-as-the-default-value }
-Versões anteriores do FastAPI (antes de 0.95.0) exigiam que você usasse `Query` como valor padrão do seu parâmetro, em vez de colocá-lo em `Annotated`, há uma grande chance de você ver código usando isso por aí, então vou explicar.
+Versões anteriores do FastAPI (antes de 0.95.0) exigiam que você usasse `Query` como valor padrão do seu parâmetro, em vez de colocá-lo em `Annotated`, há uma grande chance de você ver código usando isso por aí, então vou explicar.
/// tip | Dica
@@ -144,7 +120,7 @@ Então, podemos passar mais parâmetros para `Query`. Neste caso, o parâmetro `
q: str | None = Query(default=None, max_length=50)
```
-Isso validará os dados, mostrará um erro claro quando os dados não forem válidos e documentará o parâmetro na *operação de rota* do esquema OpenAPI.
+Isso validará os dados, mostrará um erro claro quando os dados não forem válidos e documentará o parâmetro na operação de rota do esquema OpenAPI.
### `Query` como valor padrão ou em `Annotated` { #query-as-the-default-value-or-in-annotated }
@@ -174,13 +150,13 @@ q: str = Query(default="rick")
### Vantagens de `Annotated` { #advantages-of-annotated }
-**Usar `Annotated` é recomendado** em vez do valor padrão nos parâmetros da função, é **melhor** por vários motivos. 🤓
+Usar `Annotated` é recomendado em vez do valor padrão nos parâmetros da função, é melhor por vários motivos. 🤓
-O valor **padrão** do **parâmetro da função** é o **valor padrão real**, isso é mais intuitivo com Python em geral. 😌
+O valor padrão do parâmetro da função é o valor padrão real, isso é mais intuitivo com Python em geral. 😌
-Você poderia **chamar** essa mesma função em **outros lugares** sem FastAPI, e ela **funcionaria como esperado**. Se houver um parâmetro **obrigatório** (sem valor padrão), seu **editor** vai avisar com um erro, e o **Python** também reclamará se você executá-la sem passar o parâmetro obrigatório.
+Você poderia chamar essa mesma função em outros lugares sem FastAPI, e ela funcionaria como esperado. Se houver um parâmetro obrigatório (sem valor padrão), seu editor vai avisar com um erro, e o Python também reclamará se você executá-la sem passar o parâmetro obrigatório.
-Quando você não usa `Annotated` e em vez disso usa o estilo de **valor padrão (antigo)**, se você chamar essa função sem FastAPI em **outros lugares**, terá que **lembrar** de passar os argumentos para a função para que funcione corretamente, caso contrário os valores serão diferentes do esperado (por exemplo, `QueryInfo` ou algo parecido em vez de `str`). E seu editor não vai avisar, e o Python também não vai reclamar ao executar a função, apenas quando as operações internas falharem.
+Quando você não usa `Annotated` e em vez disso usa o estilo de valor padrão (antigo), se você chamar essa função sem FastAPI em outros lugares, terá que lembrar de passar os argumentos para a função para que funcione corretamente, caso contrário os valores serão diferentes do esperado (por exemplo, `QueryInfo` ou algo parecido em vez de `str`). E seu editor não vai avisar, e o Python também não vai reclamar ao executar a função, apenas quando as operações internas falharem.
Como `Annotated` pode ter mais de uma anotação de metadados, você agora pode até usar a mesma função com outras ferramentas, como o Typer. 🚀
@@ -192,7 +168,7 @@ Você também pode adicionar um parâmetro `min_length`:
## Adicione expressões regulares { #add-regular-expressions }
-Você pode definir um `pattern` de expressão regular que o parâmetro deve corresponder:
+Você pode definir um `pattern` de expressão regular que o parâmetro deve corresponder:
{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
@@ -202,9 +178,9 @@ Esse padrão específico de expressão regular verifica se o valor recebido no p
* `fixedquery`: tem exatamente o valor `fixedquery`.
* `$`: termina ali, não tem mais caracteres depois de `fixedquery`.
-Se você se sentir perdido com essas ideias de **"expressão regular"**, não se preocupe. Esse é um assunto difícil para muitas pessoas. Você ainda pode fazer muitas coisas sem precisar de expressões regulares por enquanto.
+Se você se sentir perdido com essas ideias de "expressão regular", não se preocupe. Esse é um assunto difícil para muitas pessoas. Você ainda pode fazer muitas coisas sem precisar de expressões regulares por enquanto.
-Agora você sabe que, sempre que precisar delas, pode usá-las no **FastAPI**.
+Agora você sabe que, sempre que precisar delas, pode usá-las no FastAPI.
## Valores padrão { #default-values }
@@ -212,7 +188,7 @@ Você pode, claro, usar valores padrão diferentes de `None`.
Digamos que você queira declarar o parâmetro de consulta `q` com `min_length` de `3` e ter um valor padrão de `"fixedquery"`:
-{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial005_an_py310.py hl[9] *}
/// note | Nota
@@ -242,7 +218,7 @@ q: Annotated[str | None, Query(min_length=3)] = None
Então, quando você precisa declarar um valor como obrigatório usando `Query`, você pode simplesmente não declarar um valor padrão:
-{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial006_an_py310.py hl[9] *}
### Obrigatório, pode ser `None` { #required-can-be-none }
@@ -266,7 +242,7 @@ Então, com uma URL como:
http://localhost:8000/items/?q=foo&q=bar
```
-você receberia os múltiplos valores dos *parâmetros de consulta* `q` (`foo` e `bar`) em uma `list` Python dentro da sua *função de operação de rota*, no *parâmetro da função* `q`.
+você receberia os múltiplos valores dos parâmetros de consulta `q` (`foo` e `bar`) em uma `list` Python dentro da sua função de operação de rota, no parâmetro da função `q`.
Assim, a resposta para essa URL seria:
@@ -293,7 +269,7 @@ A documentação interativa da API será atualizada de acordo, permitindo múlti
Você também pode definir uma `list` de valores padrão caso nenhum seja fornecido:
-{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
Se você for até:
@@ -316,13 +292,13 @@ o valor padrão de `q` será: `["foo", "bar"]` e sua resposta será:
Você também pode usar `list` diretamente em vez de `list[str]`:
-{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
/// note | Nota
Tenha em mente que, neste caso, o FastAPI não verificará o conteúdo da lista.
-Por exemplo, `list[int]` verificaria (e documentaria) que os conteúdos da lista são inteiros. Mas `list` sozinho não.
+Por exemplo, `list[int]` verificaria (and documentaria) que os conteúdos da lista são inteiros. Mas `list` sozinho não.
///
@@ -372,7 +348,7 @@ Então você pode declarar um `alias`, e esse alias será usado para encontrar o
Agora digamos que você não gosta mais desse parâmetro.
-Você tem que deixá-lo por um tempo, pois há clientes usando-o, mas quer que a documentação mostre claramente que ele está deprecated.
+Você tem que deixá-lo por um tempo, pois há clientes usando-o, mas quer que a documentação mostre claramente que ele está descontinuado.
Então passe o parâmetro `deprecated=True` para `Query`:
@@ -390,9 +366,9 @@ Para excluir um parâmetro de consulta do OpenAPI gerado (e portanto, dos sistem
## Validação personalizada { #custom-validation }
-Podem existir casos em que você precise fazer alguma **validação personalizada** que não pode ser feita com os parâmetros mostrados acima.
+Podem existir casos em que você precise fazer alguma validação personalizada que não pode ser feita com os parâmetros mostrados acima.
-Nesses casos, você pode usar uma **função validadora personalizada** que é aplicada após a validação normal (por exemplo, depois de validar que o valor é uma `str`).
+Nesses casos, você pode usar uma função validadora personalizada que é aplicada após a validação normal (por exemplo, depois de validar que o valor é uma `str`).
Você pode fazer isso usando o `AfterValidator` do Pydantic dentro de `Annotated`.
@@ -402,7 +378,7 @@ O Pydantic também tem ISBN ou com `imdb-` para um ID de URL de filme IMDB:
+Por exemplo, este validador personalizado verifica se o ID do item começa com `isbn-` para um número de livro ISBN ou com `imdb-` para um ID de URL de filme IMDB:
{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
@@ -414,15 +390,15 @@ Isso está disponível com a versão 2 do Pydantic ou superior. 😎
/// tip | Dica
-Se você precisar fazer qualquer tipo de validação que exija comunicação com algum **componente externo**, como um banco de dados ou outra API, você deveria usar **Dependências do FastAPI** em vez disso; você aprenderá sobre elas mais adiante.
+Se você precisar fazer qualquer tipo de validação que exija comunicação com algum componente externo, como um banco de dados ou outra API, você deveria usar Dependências do FastAPI em vez disso; você aprenderá sobre elas mais adiante.
-Esses validadores personalizados são para coisas que podem ser verificadas **apenas** com os **mesmos dados** fornecidos na requisição.
+Esses validadores personalizados são para coisas que podem ser verificadas apenas com os mesmos dados fornecidos na requisição.
///
### Entenda esse código { #understand-that-code }
-O ponto importante é apenas usar **`AfterValidator` com uma função dentro de `Annotated`**. Sinta-se à vontade para pular esta parte. 🤸
+O ponto importante é apenas usar `AfterValidator` com uma função dentro de `Annotated`. Sinta-se à vontade para pular esta parte. 🤸
---
@@ -436,17 +412,17 @@ Percebeu? Uma string usando `value.startswith()` pode receber uma tupla, e verif
#### Um item aleatório { #a-random-item }
-Com `data.items()` obtemos um objeto iterável com tuplas contendo a chave e o valor de cada item do dicionário.
+Com `data.items()` obtemos um objeto iterável com tuplas contendo a chave e o valor de cada item do dicionário.
Convertimos esse objeto iterável em uma `list` adequada com `list(data.items())`.
-Em seguida, com `random.choice()` podemos obter um **valor aleatório** da lista, então obtemos uma tupla com `(id, name)`. Será algo como `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
+Em seguida, com `random.choice()` podemos obter um valor aleatório da lista, então obtemos uma tupla com `(id, name)`. Será algo como `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
-Depois **atribuímos esses dois valores** da tupla às variáveis `id` e `name`.
+Depois atribuímos esses dois valores da tupla às variáveis `id` e `name`.
Assim, se o usuário não fornecer um ID de item, ele ainda receberá uma sugestão aleatória.
-...fazemos tudo isso em **uma única linha simples**. 🤯 Você não ama Python? 🐍
+...fazemos tudo isso em uma única linha simples. 🤯 Você não ama Python? 🐍
{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md
index 8826602a2..f42988566 100644
--- a/docs/pt/docs/tutorial/query-params.md
+++ b/docs/pt/docs/tutorial/query-params.md
@@ -2,7 +2,7 @@
Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta".
-{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`.
@@ -24,7 +24,7 @@ Mas quando você declara eles com os tipos do Python (no exemplo acima, como `in
Todo o processo que era aplicado para parâmetros de rota também é aplicado para parâmetros de consulta:
* Suporte do editor (obviamente)
-* "Parsing" de dados
+* "análise" de dados
* Validação de dados
* Documentação automática
@@ -127,7 +127,7 @@ Caso você não queira adicionar um valor específico mas queira apenas torná-l
Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão.
-{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`.
diff --git a/docs/pt/docs/tutorial/request-files.md b/docs/pt/docs/tutorial/request-files.md
index 5d0891163..1364a1dd4 100644
--- a/docs/pt/docs/tutorial/request-files.md
+++ b/docs/pt/docs/tutorial/request-files.md
@@ -20,13 +20,13 @@ Isso é necessário, visto que os arquivos enviados são enviados como "dados de
Importe `File` e `UploadFile` de `fastapi`:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
## Definir Parâmetros `File` { #define-file-parameters }
Crie parâmetros de arquivo da mesma forma que você faria para `Body` ou `Form`:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
/// info | Informação
@@ -54,7 +54,7 @@ Mas há muitos casos em que você pode se beneficiar do uso de `UploadFile`.
Defina um parâmetro de arquivo com um tipo de `UploadFile`:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
Utilizar `UploadFile` tem várias vantagens sobre `bytes`:
@@ -121,7 +121,7 @@ Dados de formulários normalmente são codificados usando o "media type" `applic
Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Se você usar `File`, o **FastAPI** saberá que tem que pegar os arquivos da parte correta do corpo da requisição.
-Se você quiser ler mais sobre essas codificações e campos de formulário, vá para a MDN web docs para POST.
+Se você quiser ler mais sobre essas codificações e campos de formulário, vá para a MDN web docs para POST.
///
@@ -143,7 +143,7 @@ Você pode tornar um arquivo opcional usando anotações de tipo padrão e defin
Você também pode usar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais:
-{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
## Uploads de Múltiplos Arquivos { #multiple-file-uploads }
@@ -153,13 +153,13 @@ Eles serão associados ao mesmo "campo de formulário" enviado usando "dados de
Para usar isso, declare uma lista de `bytes` ou `UploadFile`:
-{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
Você receberá, tal como declarado, uma `list` de `bytes` ou `UploadFile`.
/// note | Detalhes Técnicos
-Você pode também pode usar `from starlette.responses import HTMLResponse`.
+Você também pode usar `from starlette.responses import HTMLResponse`.
**FastAPI** providencia o mesmo `starlette.responses` que `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette.
@@ -169,7 +169,7 @@ Você pode também pode usar `from starlette.responses import HTMLResponse`.
Da mesma forma de antes, você pode usar `File()` para definir parâmetros adicionais, mesmo para `UploadFile`:
-{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
## Recapitulando { #recap }
diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md
index 8eeffac2a..38f160aa8 100644
--- a/docs/pt/docs/tutorial/request-form-models.md
+++ b/docs/pt/docs/tutorial/request-form-models.md
@@ -24,7 +24,7 @@ Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓
Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja receber como **campos de formulários**, e então declarar o parâmetro como um `Form`:
-{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
O **FastAPI** irá **extrair** as informações para **cada campo** dos **dados do formulário** na requisição e dar para você o modelo Pydantic que você definiu.
@@ -42,13 +42,13 @@ Em alguns casos de uso especiais (provavelmente não muito comum), você pode de
/// note | Nota
-Isso é suportado deste a versão `0.114.0` do FastAPI. 🤓
+Isso é suportado desde a versão `0.114.0` do FastAPI. 🤓
///
Você pode utilizar a configuração de modelo do Pydantic para `proibir` qualquer campo `extra`:
-{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *}
+{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *}
Caso um cliente tente enviar informações adicionais, ele receberá um retorno de **erro**.
diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md
index 277fc2f60..8b5f034e9 100644
--- a/docs/pt/docs/tutorial/request-forms-and-files.md
+++ b/docs/pt/docs/tutorial/request-forms-and-files.md
@@ -16,13 +16,13 @@ $ pip install python-multipart
## Importe `File` e `Form` { #import-file-and-form }
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[3] *}
## Defina parâmetros de `File` e `Form` { #define-file-and-form-parameters }
Crie parâmetros de arquivo e formulário da mesma forma que você faria para `Body` ou `Query`:
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[10:12] *}
Os arquivos e campos de formulário serão carregados como dados de formulário e você receberá os arquivos e campos de formulário.
@@ -30,7 +30,7 @@ E você pode declarar alguns dos arquivos como `bytes` e alguns como `UploadFile
/// warning | Atenção
-Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`.
+Você pode declarar vários parâmetros `File` e `Form` em uma *operação de rota*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`.
Isso não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
@@ -38,4 +38,4 @@ Isso não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
## Recapitulando { #recap }
-Usar `File` e `Form` juntos quando precisar receber dados e arquivos na mesma requisição.
+Use `File` e `Form` juntos quando precisar receber dados e arquivos na mesma requisição.
diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md
index faa50bcbf..d255d0f9b 100644
--- a/docs/pt/docs/tutorial/request-forms.md
+++ b/docs/pt/docs/tutorial/request-forms.md
@@ -18,17 +18,17 @@ $ pip install python-multipart
Importe `Form` de `fastapi`:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[3] *}
## Defina parâmetros de `Form` { #define-form-parameters }
Crie parâmetros de formulário da mesma forma que você faria para `Body` ou `Query`:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[9] *}
Por exemplo, em uma das maneiras que a especificação OAuth2 pode ser usada (chamada "fluxo de senha"), é necessário enviar um `username` e uma `password` como campos do formulário.
-A spec exige que os campos sejam exatamente nomeados como `username` e `password` e sejam enviados como campos de formulário, não JSON.
+A especificação exige que os campos sejam exatamente nomeados como `username` e `password` e sejam enviados como campos de formulário, não JSON.
Com `Form` você pode declarar as mesmas configurações que com `Body` (e `Query`, `Path`, `Cookie`), incluindo validação, exemplos, um alias (por exemplo, `user-name` em vez de `username`), etc.
diff --git a/docs/pt/docs/tutorial/response-model.md b/docs/pt/docs/tutorial/response-model.md
index 8a7a71248..e3b97b630 100644
--- a/docs/pt/docs/tutorial/response-model.md
+++ b/docs/pt/docs/tutorial/response-model.md
@@ -183,7 +183,7 @@ Pode haver casos em que você retorna algo que não é um campo Pydantic válido
O caso mais comum seria [retornar uma Response diretamente, conforme explicado posteriormente na documentação avançada](../advanced/response-directly.md){.internal-link target=_blank}.
-{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
Este caso simples é tratado automaticamente pelo FastAPI porque a anotação do tipo de retorno é a classe (ou uma subclasse de) `Response`.
@@ -193,7 +193,7 @@ E as ferramentas também ficarão felizes porque `RedirectResponse` e `JSO
Você também pode usar uma subclasse de `Response` na anotação de tipo:
-{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
Isso também funcionará porque `RedirectResponse` é uma subclasse de `Response`, e o FastAPI tratará automaticamente este caso simples.
@@ -201,7 +201,7 @@ Isso também funcionará porque `RedirectResponse` é uma subclasse de `Response
Mas quando você retorna algum outro objeto arbitrário que não é um tipo Pydantic válido (por exemplo, um objeto de banco de dados) e você o anota dessa forma na função, o FastAPI tentará criar um modelo de resposta Pydantic a partir dessa anotação de tipo e falhará.
-O mesmo aconteceria se você tivesse algo como uma união entre tipos diferentes onde um ou mais deles não são tipos Pydantic válidos, por exemplo, isso falharia 💥:
+O mesmo aconteceria se você tivesse algo como uma união entre tipos diferentes onde um ou mais deles não são tipos Pydantic válidos, por exemplo, isso falharia 💥:
{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
@@ -290,7 +290,7 @@ Se os dados tiverem os mesmos valores que os padrões, como o item com ID `baz`:
}
```
-O FastAPI é inteligente o suficiente (na verdade, o Pydantic é inteligente o suficiente) para perceber que, embora `description`, `tax` e `tags` tenham os mesmos valores que os padrões, eles foram definidos explicitamente (em vez de retirados dos padrões).
+O FastAPI é inteligente o suficiente (na verdade, o Pydantic é inteligente o suficiente) para perceber que, embora `description`, `tax` e `tags` tenham os mesmos valores que os padrões, eles foram definidos explícita e diretamente (em vez de retirados dos padrões).
Portanto, eles serão incluídos na resposta JSON.
diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md
index 756c86dad..a3f8d8a56 100644
--- a/docs/pt/docs/tutorial/response-status-code.md
+++ b/docs/pt/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p
* `@app.delete()`
* etc.
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
/// note | Nota
@@ -66,7 +66,7 @@ Resumidamente:
/// tip | Dica
-Para saber mais sobre cada código de status e qual código serve para quê, verifique a documentação do MDN sobre códigos de status HTTP.
+Para saber mais sobre cada código de status e qual código serve para quê, verifique a documentação do MDN sobre códigos de status HTTP.
///
@@ -74,7 +74,7 @@ Para saber mais sobre cada código de status e qual código serve para quê, ver
Vamos ver o exemplo anterior novamente:
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201` é o código de status para "Criado".
@@ -82,7 +82,7 @@ Mas você não precisa memorizar o que cada um desses códigos significa.
Você pode usar as variáveis de conveniência de `fastapi.status`.
-{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa forma você pode usar o preenchimento automático do editor para encontrá-los:
diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md
index 2d62ffd85..560fda908 100644
--- a/docs/pt/docs/tutorial/schema-extra-example.md
+++ b/docs/pt/docs/tutorial/schema-extra-example.md
@@ -74,7 +74,7 @@ Você também pode, é claro, passar vários `examples`:
Quando fizer isso, os exemplos farão parte do **JSON Schema** interno para esses dados do body.
-No entanto, no momento em que isto foi escrito, o Swagger UI, a ferramenta responsável por exibir a UI da documentação, não suporta mostrar vários exemplos para os dados no **JSON Schema**. Mas leia abaixo para uma solução alternativa.
+No entanto, no momento em que isto foi escrito, o Swagger UI, a ferramenta responsável por exibir a UI da documentação, não suporta mostrar vários exemplos para os dados no **JSON Schema**. Mas leia abaixo para uma solução alternativa.
### `examples` específicos do OpenAPI { #openapi-specific-examples }
diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md
index 715a21b6e..f0edd5753 100644
--- a/docs/pt/docs/tutorial/security/first-steps.md
+++ b/docs/pt/docs/tutorial/security/first-steps.md
@@ -20,7 +20,7 @@ Vamos primeiro usar o código e ver como funciona, e depois voltaremos para ente
Copie o exemplo em um arquivo `main.py`:
-{* ../../docs_src/security/tutorial001_an_py39.py *}
+{* ../../docs_src/security/tutorial001_an_py310.py *}
## Execute-o { #run-it }
@@ -132,7 +132,7 @@ Nesse caso, o **FastAPI** também fornece as ferramentas para construí-la.
Quando criamos uma instância da classe `OAuth2PasswordBearer`, passamos o parâmetro `tokenUrl`. Esse parâmetro contém a URL que o client (o frontend rodando no navegador do usuário) usará para enviar o `username` e o `password` para obter um token.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
/// tip | Dica
@@ -156,7 +156,7 @@ Isso ocorre porque ele usa o mesmo nome da especificação do OpenAPI. Assim, se
///
-A variável `oauth2_scheme` é uma instância de `OAuth2PasswordBearer`, mas também é "chamável" (callable).
+A variável `oauth2_scheme` é uma instância de `OAuth2PasswordBearer`, mas também é um "callable".
Ela pode ser chamada como:
@@ -170,7 +170,7 @@ Então, pode ser usada com `Depends`.
Agora você pode passar esse `oauth2_scheme` em uma dependência com `Depends`.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
Essa dependência fornecerá uma `str` que é atribuída ao parâmetro `token` da função de operação de rota.
diff --git a/docs/pt/docs/tutorial/security/get-current-user.md b/docs/pt/docs/tutorial/security/get-current-user.md
index 2135ae236..4c6397c31 100644
--- a/docs/pt/docs/tutorial/security/get-current-user.md
+++ b/docs/pt/docs/tutorial/security/get-current-user.md
@@ -2,7 +2,7 @@
No capítulo anterior, o sistema de segurança (que é baseado no sistema de injeção de dependências) estava fornecendo à *função de operação de rota* um `token` como uma `str`:
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
Mas isso ainda não é tão útil.
diff --git a/docs/pt/docs/tutorial/security/index.md b/docs/pt/docs/tutorial/security/index.md
index d3de3e050..f4c92ea56 100644
--- a/docs/pt/docs/tutorial/security/index.md
+++ b/docs/pt/docs/tutorial/security/index.md
@@ -88,7 +88,6 @@ OpenAPI define os seguintes esquemas de segurança:
* `openIdConnect`: tem uma forma para definir como descobrir automaticamente o dado da autenticação OAuth2.
* Essa descoberta automática é o que é definido na especificação OpenID Connect.
-
/// tip | Dica
Integração com outros provedores de autenticação/autorização como Google, Facebook, X (Twitter), GitHub, etc. é bem possível e relativamente fácil.
@@ -99,7 +98,7 @@ O problema mais complexo é criar um provedor de autenticação/autorização co
## **FastAPI** utilitários { #fastapi-utilities }
-**FastAPI** fornece várias ferramentas para cada um desses esquemas de segurança no módulo `fastapi.security` que simplesmente usa esses mecanismos de segurança.
+**FastAPI** fornece várias ferramentas para cada um desses esquemas de segurança no módulo `fastapi.security` que simplificam o uso desses mecanismos de segurança.
Nos próximos capítulos você irá ver como adicionar segurança à sua API usando essas ferramentas disponibilizadas pelo **FastAPI**.
diff --git a/docs/pt/docs/tutorial/security/oauth2-jwt.md b/docs/pt/docs/tutorial/security/oauth2-jwt.md
index f68b8c39e..4ba38b9f0 100644
--- a/docs/pt/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/pt/docs/tutorial/security/oauth2-jwt.md
@@ -116,7 +116,11 @@ E outra função utilitária para verificar se uma senha recebida corresponde ao
E outra para autenticar e retornar um usuário.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,51,58:59,62:63,72:79] *}
+
+Quando `authenticate_user` é chamado com um nome de usuário que não existe no banco de dados, ainda executamos `verify_password` contra um hash fictício.
+
+Isso garante que o endpoint leve aproximadamente o mesmo tempo para responder, seja o nome de usuário válido ou não, prevenindo **timing attacks** que poderiam ser usados para enumerar nomes de usuário existentes.
/// note | Nota
@@ -152,7 +156,7 @@ Defina um modelo Pydantic que será usado no endpoint de token para a resposta.
Crie uma função utilitária para gerar um novo token de acesso.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,82:90] *}
## Atualize as dependências { #update-the-dependencies }
@@ -162,7 +166,7 @@ Decodifique o token recebido, verifique-o e retorne o usuário atual.
Se o token for inválido, retorne um erro HTTP imediatamente.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[93:110] *}
## Atualize a *operação de rota* `/token` { #update-the-token-path-operation }
@@ -170,7 +174,7 @@ Crie um `timedelta` com o tempo de expiração do token.
Crie um token de acesso JWT real e o retorne.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[121:136] *}
### Detalhes técnicos sobre o "sujeito" `sub` do JWT { #technical-details-about-the-jwt-subject-sub }
diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md
index 04a02c7f9..0b2d0718f 100644
--- a/docs/pt/docs/tutorial/static-files.md
+++ b/docs/pt/docs/tutorial/static-files.md
@@ -7,7 +7,7 @@ Você pode servir arquivos estáticos automaticamente a partir de um diretório
* Importe `StaticFiles`.
* "Monte" uma instância de `StaticFiles()` em um path específico.
-{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py310.py hl[2,6] *}
/// note | Detalhes Técnicos
diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md
index e56edcb8c..44dc2d225 100644
--- a/docs/pt/docs/tutorial/testing.md
+++ b/docs/pt/docs/tutorial/testing.md
@@ -30,7 +30,7 @@ Use o objeto `TestClient` da mesma forma que você faz com `httpx`.
Escreva instruções `assert` simples com as expressões Python padrão que você precisa verificar (novamente, `pytest` padrão).
-{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py310.py hl[2,12,15:18] *}
/// tip | Dica
@@ -76,7 +76,7 @@ Digamos que você tenha uma estrutura de arquivo conforme descrito em [Aplicaç
No arquivo `main.py` você tem sua aplicação **FastAPI**:
-{* ../../docs_src/app_testing/app_a_py39/main.py *}
+{* ../../docs_src/app_testing/app_a_py310/main.py *}
### Arquivo de teste { #testing-file }
@@ -92,7 +92,7 @@ Então você poderia ter um arquivo `test_main.py` com seus testes. Ele poderia
Como esse arquivo está no mesmo pacote, você pode usar importações relativas para importar o objeto `app` do módulo `main` (`main.py`):
-{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py310/test_main.py hl[3] *}
...e ter o código para os testes como antes.
diff --git a/docs/pt/docs/virtual-environments.md b/docs/pt/docs/virtual-environments.md
index 5736f7109..e222c61ad 100644
--- a/docs/pt/docs/virtual-environments.md
+++ b/docs/pt/docs/virtual-environments.md
@@ -1,6 +1,6 @@
# Ambientes Virtuais { #virtual-environments }
-Ao trabalhar em projetos Python, você provavelmente deve usar um **ambiente virtual** (ou um mecanismo similar) para isolar os pacotes que você instala para cada projeto.
+Ao trabalhar em projetos Python, você provavelmente deveria usar um **ambiente virtual** (ou um mecanismo similar) para isolar os pacotes que você instala para cada projeto.
/// info | Informação
@@ -53,7 +53,7 @@ $ cd awesome-project
## Crie um ambiente virtual { #create-a-virtual-environment }
-Ao começar a trabalhar em um projeto Python **pela primeira vez**, crie um ambiente virtual **dentro do seu projeto**.
+Ao começar a trabalhar em um projeto Python **pela primeira vez**, crie um ambiente virtual **dentro do seu projeto**.
/// tip | Dica
@@ -166,7 +166,7 @@ $ source .venv/Scripts/activate
Toda vez que você instalar um **novo pacote** naquele ambiente, **ative** o ambiente novamente.
-Isso garante que, se você usar um **programa de terminal (CLI)** instalado por esse pacote, você usará aquele do seu ambiente virtual e não qualquer outro que possa ser instalado globalmente, provavelmente com uma versão diferente do que você precisa.
+Isso garante que, se você usar um **programa de terminal (CLI)** instalado por esse pacote, você usará aquele do seu ambiente virtual e não qualquer outro que possa ser instalado globalmente, provavelmente com uma versão diferente do que você precisa.
///
@@ -176,7 +176,7 @@ Verifique se o ambiente virtual está ativo (o comando anterior funcionou).
/// tip | Dica
-Isso é **opcional**, mas é uma boa maneira de **verificar** se tudo está funcionando conforme o esperado e se você está usando o ambiente virtual intendido.
+Isso é **opcional**, mas é uma boa maneira de **verificar** se tudo está funcionando conforme o esperado e se você está usando o ambiente virtual pretendido.
///
@@ -220,7 +220,7 @@ Se você usar
From d213dd363d28fcc63ec61b5e206b5a7a71b3337f Mon Sep 17 00:00:00 2001
From: "github-actions[bot]" lt
+* XWT
+* PSGI
+
+### abbr が完全な語句と説明を示す { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | 情報
+
+"abbr" 要素の "title" 属性は特定の指示に従って翻訳します。
+
+翻訳は、英語の語を説明するために独自の "abbr" 要素を追加してもよく、LLM はそれらを削除してはいけません。
+
+`scripts/translate.py` の general プロンプト内「### HTML abbr elements」の節を参照してください。
+
+////
+
+## HTML "dfn" 要素 { #html-dfn-elements }
+
+* クラスター
+* ディープラーニング
+
+## 見出し { #headings }
+
+//// tab | テスト
+
+### Web アプリを開発する - チュートリアル { #develop-a-webapp-a-tutorial }
+
+こんにちは。
+
+### 型ヒントとアノテーション { #type-hints-and-annotations }
+
+またこんにちは。
+
+### スーパークラスとサブクラス { #super-and-subclasses }
+
+またこんにちは。
+
+////
+
+//// tab | 情報
+
+見出しに関する唯一の厳格なルールは、リンクが壊れないように、LLM が中括弧内のハッシュ部分を変更しないことです。
+
+`scripts/translate.py` の general プロンプト内「### Headings」の節を参照してください。
+
+言語固有の指示については、例として `docs/de/llm-prompt.md` の「### Headings」の節を参照してください。
+
+////
+
+## ドキュメントで使う用語 { #terms-used-in-the-docs }
+
+//// tab | テスト
+
+* you
+* your
+
+* e.g.
+* etc.
+
+* `foo` を `int` として
+* `bar` を `str` として
+* `baz` を `list` として
+
+* チュートリアル - ユーザーガイド
+* 上級ユーザーガイド
+* SQLModel ドキュメント
+* API ドキュメント
+* 自動生成ドキュメント
+
+* データサイエンス
+* ディープラーニング
+* 機械学習
+* 依存性注入
+* HTTP Basic 認証
+* HTTP Digest
+* ISO 形式
+* JSON Schema 規格
+* JSON スキーマ
+* スキーマ定義
+* Password Flow
+* モバイル
+
+* 非推奨
+* 設計された
+* 無効
+* オンザフライ
+* 標準
+* デフォルト
+* 大文字小文字を区別
+* 大文字小文字を区別しない
+
+* アプリケーションを提供する
+* ページを配信する
+
+* アプリ
+* アプリケーション
+
+* リクエスト
+* レスポンス
+* エラーレスポンス
+
+* path operation
+* path operation デコレータ
+* path operation 関数
+
+* ボディ
+* リクエストボディ
+* レスポンスボディ
+* JSON ボディ
+* フォームボディ
+* ファイルボディ
+* 関数本体
+
+* パラメータ
+* ボディパラメータ
+* パスパラメータ
+* クエリパラメータ
+* Cookie パラメータ
+* ヘッダーパラメータ
+* フォームパラメータ
+* 関数パラメータ
+
+* イベント
+* 起動イベント
+* サーバーの起動
+* シャットダウンイベント
+* lifespan イベント
+
+* ハンドラ
+* イベントハンドラ
+* 例外ハンドラ
+* 処理する
+
+* モデル
+* Pydantic モデル
+* データモデル
+* データベースモデル
+* フォームモデル
+* モデルオブジェクト
+
+* クラス
+* 基底クラス
+* 親クラス
+* サブクラス
+* 子クラス
+* 兄弟クラス
+* クラスメソッド
+
+* ヘッダー
+* ヘッダー(複数)
+* 認可ヘッダー
+* `Authorization` ヘッダー
+* Forwarded ヘッダー
+
+* 依存性注入システム
+* 依存関係
+* dependable
+* dependant
+
+* I/O バウンド
+* CPU バウンド
+* 同時実行性
+* 並列性
+* マルチプロセッシング
+
+* env var
+* 環境変数
+* `PATH`
+* `PATH` 環境変数
+
+* 認証
+* 認証プロバイダ
+* 認可
+* 認可フォーム
+* 認可プロバイダ
+* ユーザーが認証する
+* システムがユーザーを認証する
+
+* CLI
+* コマンドラインインターフェース
+
+* サーバー
+* クライアント
+
+* クラウドプロバイダ
+* クラウドサービス
+
+* 開発
+* 開発段階
+
+* dict
+* 辞書
+* 列挙型
+* Enum
+* 列挙メンバー
+
+* エンコーダー
+* デコーダー
+* エンコードする
+* デコードする
+
+* 例外
+* 送出する
+
+* 式
+* 文
+
+* フロントエンド
+* バックエンド
+
+* GitHub ディスカッション
+* GitHub Issue
+
+* パフォーマンス
+* パフォーマンス最適化
+
+* 戻り値の型
+* 戻り値
+
+* セキュリティ
+* セキュリティスキーム
+
+* タスク
+* バックグラウンドタスク
+* タスク関数
+
+* テンプレート
+* テンプレートエンジン
+
+* 型アノテーション
+* 型ヒント
+
+* サーバーワーカー
+* Uvicorn ワーカー
+* Gunicorn ワーカー
+* ワーカープロセス
+* ワーカークラス
+* ワークロード
+
+* デプロイ
+* デプロイする
+
+* SDK
+* ソフトウェア開発キット
+
+* `APIRouter`
+* `requirements.txt`
+* Bearer Token
+* 破壊的変更
+* バグ
+* ボタン
+* 呼び出し可能
+* コード
+* コミット
+* コンテキストマネージャ
+* コルーチン
+* データベースセッション
+* ディスク
+* ドメイン
+* エンジン
+* フェイクの X
+* HTTP GET メソッド
+* アイテム
+* ライブラリ
+* ライフスパン
+* ロック
+* ミドルウェア
+* モバイルアプリケーション
+* モジュール
+* マウント
+* ネットワーク
+* オリジン
+* オーバーライド
+* ペイロード
+* プロセッサ
+* プロパティ
+* プロキシ
+* プルリクエスト
+* クエリ
+* RAM
+* リモートマシン
+* ステータスコード
+* 文字列
+* タグ
+* Web フレームワーク
+* ワイルドカード
+* 返す
+* 検証する
+
+////
+
+//// tab | 情報
+
+これはドキュメントで見られる(主に)技術用語の不完全かつ規範的でない一覧です。プロンプト設計者が、LLM がどの用語で手助けを必要としているかを把握するのに役立つかもしれません。例えば、良い翻訳を最適でない翻訳に戻してしまう場合や、あなたの言語での活用・格変化に問題がある場合などです。
+
+`docs/de/llm-prompt.md` の「### List of English terms and their preferred German translations」の節を参照してください。
+
+////
diff --git a/docs/ja/docs/about/index.md b/docs/ja/docs/about/index.md
new file mode 100644
index 000000000..b099df7fa
--- /dev/null
+++ b/docs/ja/docs/about/index.md
@@ -0,0 +1,3 @@
+# 概要 { #about }
+
+FastAPI の概要、その設計やインスピレーションなどについて解説します。🤓
diff --git a/docs/ja/docs/advanced/additional-responses.md b/docs/ja/docs/advanced/additional-responses.md
new file mode 100644
index 000000000..4c4425788
--- /dev/null
+++ b/docs/ja/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# OpenAPI の追加レスポンス { #additional-responses-in-openapi }
+
+/// warning | 注意
+
+これは比較的高度なトピックです。
+
+FastAPI を使い始めたばかりであれば、これは不要かもしれません。
+
+///
+
+追加のステータスコード、メディアタイプ、説明などを伴う追加レスポンスを宣言できます。
+
+それらの追加レスポンスは OpenAPI スキーマに含まれ、API ドキュメントにも表示されます。
+
+ただし、それらの追加レスポンスについては、ステータスコードとコンテンツを指定して `JSONResponse` などの `Response` を直接返す必要があります。
+
+## `model` を使った追加レスポンス { #additional-response-with-model }
+
+*path operation デコレータ*に `responses` パラメータを渡せます。
+
+これは `dict` を受け取り、キーは各レスポンスのステータスコード(例: `200`)、値は各レスポンスの情報を含む別の `dict` です。
+
+それぞれのレスポンス `dict` には、`response_model` と同様に Pydantic モデルを格納する `model` キーを含められます。
+
+FastAPI はそのモデルから JSON Schema を生成し、OpenAPI の適切な場所に含めます。
+
+例えば、ステータスコード `404` と Pydantic モデル `Message` を持つ別のレスポンスを宣言するには、次のように書けます:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | 備考
+
+`JSONResponse` を直接返す必要がある点に注意してください。
+
+///
+
+/// info | 情報
+
+`model` キーは OpenAPI の一部ではありません。
+
+FastAPI はそこから Pydantic モデルを取得して JSON Schema を生成し、適切な場所に配置します。
+
+適切な場所は次のとおりです:
+
+- `content` キーの中。これは値として別の JSON オブジェクト(`dict`)を持ち、その中に次が含まれます:
+ - メディアタイプ(例: `application/json`)をキーとし、値としてさらに別の JSON オブジェクトを持ち、その中に次が含まれます:
+ - `schema` キー。値としてモデル由来の JSON Schema を持ち、ここが正しい配置場所です。
+ - FastAPI はここに、スキーマを直接埋め込む代わりに OpenAPI 内のグローバルな JSON Schema への参照を追加します。これにより、他のアプリケーションやクライアントがそれらの JSON Schema を直接利用し、より良いコード生成ツール等を提供できます。
+
+///
+
+この *path operation* のために OpenAPI に生成されるレスポンスは次のとおりです:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+スキーマは OpenAPI スキーマ内の別の場所への参照になります:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## メインのレスポンスに追加のメディアタイプ { #additional-media-types-for-the-main-response }
+
+同じ `responses` パラメータを使って、同一のメインレスポンスに別のメディアタイプを追加できます。
+
+例えば、`image/png` の追加メディアタイプを加え、あなたの *path operation* が JSON オブジェクト(メディアタイプ `application/json`)または PNG 画像を返せることを宣言できます:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | 備考
+
+画像は `FileResponse` を使って直接返す必要がある点に注意してください。
+
+///
+
+/// info | 情報
+
+`responses` パラメータで明示的に別のメディアタイプを指定しない限り、FastAPI はレスポンスがメインのレスポンスクラスと同じメディアタイプ(デフォルトは `application/json`)であるとみなします。
+
+ただし、メディアタイプが `None` のカスタムレスポンスクラスを指定している場合、モデルが関連付けられた追加レスポンスには FastAPI は `application/json` を使用します。
+
+///
+
+## 情報の結合 { #combining-information }
+
+`response_model`、`status_code`、`responses` パラメータなど、複数の場所からのレスポンス情報を組み合わせることもできます。
+
+`response_model` を宣言し、デフォルトのステータスコード `200`(必要なら任意のコード)を使い、その同じレスポンスに対する追加情報を `responses` で OpenAPI スキーマに直接記述できます。
+
+FastAPI は `responses` にある追加情報を保持し、モデルの JSON Schema と結合します。
+
+例えば、Pydantic モデルを用い、独自の `description` を持つステータスコード `404` のレスポンスを宣言できます。
+
+さらに、`response_model` を使うステータスコード `200` のレスポンスに独自の `example` を含めることもできます:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+これらはすべて結合されて OpenAPI に含まれ、API ドキュメントに表示されます:
+
+
+
+## 事前定義レスポンスとカスタムの組み合わせ { #combine-predefined-responses-and-custom-ones }
+
+多くの *path operations* に適用できる事前定義のレスポンスを用意しつつ、各 *path operation* ごとに必要なカスタムレスポンスと組み合わせたい場合があります。
+
+そのような場合、Python の `**dict_to_unpack` による `dict` の「アンパック」テクニックを使えます:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+ここでは、`new_dict` には `old_dict` のすべてのキーと値に加え、新しいキーと値が含まれます:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+このテクニックを使うと、*path operations* で事前定義レスポンスを再利用し、さらにカスタムのレスポンスを組み合わせられます。
+
+例えば:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## OpenAPI レスポンスの詳細 { #more-information-about-openapi-responses }
+
+レスポンスに正確に何を含められるかは、OpenAPI 仕様の次のセクションを参照してください:
+
+- OpenAPI の Responses Object。ここには `Response Object` が含まれます。
+- OpenAPI の Response Object。`responses` パラメータ内の各レスポンスに、ここで定義されている要素を直接含められます。`description`、`headers`、`content`(ここで異なるメディアタイプや JSON Schema を宣言します)、`links` など。
diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md
index 14b7e8ba8..fdac52e83 100644
--- a/docs/ja/docs/advanced/additional-status-codes.md
+++ b/docs/ja/docs/advanced/additional-status-codes.md
@@ -16,7 +16,7 @@
{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
-/// warning | 注意
+/// warning
上の例のように `Response` を直接返すと、それはそのまま返されます。
@@ -38,4 +38,4 @@
追加のステータスコードとレスポンスを直接返す場合、それらは OpenAPI スキーマ(API ドキュメント)には含まれません。FastAPI には、事前に何が返されるかを知る方法がないからです。
-しかし、[Additional Responses](additional-responses.md){.internal-link target=_blank} を使ってコード内にドキュメント化できます。
+しかし、[追加のレスポンス](additional-responses.md){.internal-link target=_blank} を使ってコード内にドキュメント化できます。
diff --git a/docs/ja/docs/advanced/advanced-dependencies.md b/docs/ja/docs/advanced/advanced-dependencies.md
new file mode 100644
index 000000000..d38ce548d
--- /dev/null
+++ b/docs/ja/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# 高度な依存関係 { #advanced-dependencies }
+
+## パラメータ化された依存関係 { #parameterized-dependencies }
+
+これまで見てきた依存関係は、固定の関数またはクラスでした。
+
+しかし、多くの異なる関数やクラスを宣言せずに、その依存関係にパラメータを設定したい場合があります。
+
+たとえば、クエリパラメータ `q` に、ある固定の内容が含まれているかを検査する依存関係が欲しいとします。
+
+ただし、その固定の内容はパラメータ化できるようにしたいです。
+
+## "callable" なインスタンス { #a-callable-instance }
+
+Python には、クラスのインスタンスを "callable" にする方法があります。
+
+クラス自体(これはすでに callable です)ではなく、そのクラスのインスタンスです。
+
+そのためには、`__call__` メソッドを宣言します:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+この場合、この `__call__` が、**FastAPI** が追加のパラメータやサブ依存関係を確認するために使うものになり、後であなたの *path operation 関数* のパラメータに値を渡すために呼び出されるものになります。
+
+## インスタンスのパラメータ化 { #parameterize-the-instance }
+
+そして、`__init__` を使って、依存関係を「パラメータ化」するために利用できるインスタンスのパラメータを宣言できます:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+この場合、**FastAPI** は `__init__` に触れたり気にかけたりすることはありません。私たちがコード内で直接使います。
+
+## インスタンスの作成 { #create-an-instance }
+
+このクラスのインスタンスは次のように作成できます:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+このようにして依存関係を「パラメータ化」できます。いまや `"bar"` が属性 `checker.fixed_content` として中に保持されています。
+
+## インスタンスを依存関係として使う { #use-the-instance-as-a-dependency }
+
+その後、`Depends(FixedContentQueryChecker)` の代わりに `Depends(checker)` でこの `checker` を使えます。依存関係はクラスそのものではなく、インスタンスである `checker` だからです。
+
+依存関係を解決するとき、**FastAPI** はこの `checker` を次のように呼び出します:
+
+```Python
+checker(q="somequery")
+```
+
+...そして、その戻り値を *path operation 関数* 内の依存関係の値として、パラメータ `fixed_content_included` に渡します:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | 豆知識
+
+ここまでの内容は回りくどく感じられるかもしれません。まだどのように役立つかが明確でないかもしれません。
+
+これらの例は意図的に単純ですが、仕組みを示しています。
+
+セキュリティの章では、同じやり方で実装されたユーティリティ関数があります。
+
+ここまでを理解できていれば、そうしたセキュリティ用ユーティリティが内部でどのように動いているかも理解できています。
+
+///
+
+## `yield`、`HTTPException`、`except` とバックグラウンドタスクを伴う依存関係 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | 注意
+
+これらの技術的詳細は、ほとんどの場合は不要です。
+
+主に、0.121.0 より前の FastAPI アプリケーションがあり、`yield` を使う依存関係で問題が発生している場合に有用です。
+
+///
+
+`yield` を使う依存関係は、さまざまなユースケースに対応し、いくつかの問題を修正するために時間とともに進化してきました。ここでは変更点の概要を説明します。
+
+### `yield` と `scope` を伴う依存関係 { #dependencies-with-yield-and-scope }
+
+バージョン 0.121.0 で、`yield` を使う依存関係に対して `Depends(scope="function")` がサポートされました。
+
+`Depends(scope="function")` を使うと、`yield` の後の終了コードは、クライアントへレスポンスが返される前、*path operation 関数* が終了した直後に実行されます。
+
+そして、`Depends(scope="request")`(デフォルト)を使う場合、`yield` の後の終了コードはレスポンス送信後に実行されます。
+
+詳しくはドキュメント「[`yield` を使う依存関係 - 早期終了と `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope)」を参照してください。
+
+### `yield` と `StreamingResponse` を伴う依存関係、技術詳細 { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+FastAPI 0.118.0 より前では、`yield` を使う依存関係を使用すると、*path operation 関数* が戻ってからレスポンス送信直前に終了コードが実行されていました。
+
+これは、レスポンスがネットワーク上を移動するのを待っている間に、不要にリソースを保持しないようにする意図でした。
+
+この変更により、`StreamingResponse` を返す場合、`yield` を持つ依存関係の終了コードはすでに実行されていることになりました。
+
+たとえば、`yield` を持つ依存関係の中でデータベースセッションを持っていた場合、`StreamingResponse` はデータをストリーミングしている間にそのセッションを使えません。というのも、`yield` の後の終了コードでそのセッションがすでにクローズされているからです。
+
+この挙動は 0.118.0 で元に戻され、`yield` の後の終了コードはレスポンス送信後に実行されるようになりました。
+
+/// info | 情報
+
+以下で見るように、これはバージョン 0.106.0 より前の挙動ととても似ていますが、いくつかのコーナーケースに対する改良とバグ修正が含まれています。
+
+///
+
+#### 早期終了コードのユースケース { #use-cases-with-early-exit-code }
+
+特定の条件では、レスポンス送信前に `yield` を持つ依存関係の終了コードを実行する、古い挙動の恩恵を受けられるユースケースがあります。
+
+例えば、`yield` を持つ依存関係でデータベースセッションを使ってユーザ検証だけを行い、その後は *path operation 関数* 内ではそのデータベースセッションを一切使わない、かつレスポンス送信に長い時間がかかる(例えばデータをゆっくり送る `StreamingResponse`)が、何らかの理由でデータベースは使わない、というケースです。
+
+この場合、レスポンスの送信が終わるまでデータベースセッションが保持されますが、使わないのであれば保持する必要はありません。
+
+次のようになります:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+終了コード、すなわち `Session` の自動クローズは:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...の部分で定義されており、遅いデータ送信が終わった後に実行されます:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+しかし、`generate_stream()` はデータベースセッションを使わないため、レスポンス送信中にセッションを開いたままにしておく必要は実際にはありません。
+
+SQLModel(または SQLAlchemy)でこの特定のユースケースがある場合は、不要になった時点でセッションを明示的にクローズできます:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+このようにすると、セッションはデータベース接続を解放するため、他のリクエストがそれを使えるようになります。
+
+`yield` を持つ依存関係で早期終了が必要な別のユースケースがある場合は、あなたの具体的なユースケースと、なぜ `yield` を持つ依存関係の早期クローズが有益かを説明して、GitHub Discussion の質問を作成してください。
+
+`yield` を持つ依存関係の早期クローズに納得できるユースケースがある場合は、早期クローズにオプトインする新しい方法を追加することを検討します。
+
+### `yield` と `except` を伴う依存関係、技術詳細 { #dependencies-with-yield-and-except-technical-details }
+
+FastAPI 0.110.0 より前では、`yield` を持つ依存関係を使い、その依存関係内で `except` によって例外を捕捉し、再度その例外を送出しなかった場合でも、その例外は自動的に送出(フォワード)され、任意の例外ハンドラまたは内部サーバエラーハンドラに渡されていました。
+
+これは、ハンドラのないフォワードされた例外(内部サーバエラー)による未処理のメモリ消費を修正し、通常の Python コードの挙動と一貫性を持たせるため、バージョン 0.110.0 で変更されました。
+
+### バックグラウンドタスクと `yield` を伴う依存関係、技術詳細 { #background-tasks-and-dependencies-with-yield-technical-details }
+
+FastAPI 0.106.0 より前では、`yield` の後で例外を送出することはできませんでした。`yield` を持つ依存関係の終了コードはレスポンス送信「後」に実行されるため、[例外ハンドラ](../tutorial/handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} はすでに実行済みでした。
+
+これは主に、依存関係が "yield" した同じオブジェクトをバックグラウンドタスク内で利用できるようにするための設計でした。終了コードはバックグラウンドタスク完了後に実行されるからです。
+
+これは、レスポンスがネットワーク上を移動するのを待っている間にリソースを保持しないようにする意図で、FastAPI 0.106.0 で変更されました。
+
+/// tip | 豆知識
+
+加えて、バックグラウンドタスクは通常、独立したロジックの集合であり、(例えば専用のデータベース接続など)それ自身のリソースで個別に扱うべきです。
+
+そのため、このやり方の方がコードはおそらくよりクリーンになります。
+
+///
+
+この挙動に依存していた場合は、バックグラウンドタスク用のリソースをバックグラウンドタスク内部で作成し、`yield` を持つ依存関係のリソースに依存しないデータだけを内部で使用するようにしてください。
+
+例えば、同じデータベースセッションを使うのではなく、バックグラウンドタスク内で新しいデータベースセッションを作成し、この新しいセッションでデータベースからオブジェクトを取得します。そして、バックグラウンドタスク関数の引数としてデータベースのオブジェクト自体を渡すのではなく、そのオブジェクトの ID を渡し、バックグラウンドタスク関数内でもう一度そのオブジェクトを取得します。
diff --git a/docs/ja/docs/advanced/advanced-python-types.md b/docs/ja/docs/advanced/advanced-python-types.md
new file mode 100644
index 000000000..b4409bcf6
--- /dev/null
+++ b/docs/ja/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# 高度な Python の型 { #advanced-python-types }
+
+Python の型を扱うときに役立つ追加のアイデアをいくつか紹介します。
+
+## `Union` または `Optional` の利用 { #using-union-or-optional }
+
+何らかの理由で `|` が使えない場合、たとえば型アノテーションではなく `response_model=` のような場所では、縦棒(`|`)の代わりに `typing` の `Union` を使えます。
+
+例えば、`str` または `None` になり得ることを宣言できます:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing` には、`None` を取り得ることを宣言するための短縮形として `Optional` もあります。
+
+ここからは私のとても主観的な提案です:
+
+- 🚨 `Optional[SomeType]` の使用は避けましょう
+- 代わりに ✨ **`Union[SomeType, None]` を使いましょう** ✨。
+
+どちらも等価で内部的には同一ですが、「optional(任意)」という語が値が任意だと誤解させやすく、実際の意味は「`None` を取り得る」であり、任意ではなく依然として必須である場合でもそうです。そのため `Optional` より `Union` を勧めます。
+
+`Union[SomeType, None]` の方が意味がより明確だと思います。
+
+これは用語や名前付けの話に過ぎませんが、その言葉があなたやチームメイトのコードの捉え方に影響します。
+
+例として次の関数を見てみましょう:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+パラメータ `name` は `Optional[str]` と定義されていますが、任意ではありません。このパラメータなしで関数を呼び出すことはできません:
+
+```Python
+say_hi() # あっ、これはエラーになります!😱
+```
+
+`name` パラメータにはデフォルト値がないため、依然として必須(任意ではない)です。ただし、`name` は値として `None` を受け付けます:
+
+```Python
+say_hi(name=None) # これは動作します。None は有効です 🎉
+```
+
+朗報として、多くの場合は単純に `|` を使って型の Union を定義できます:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+したがって、通常は `Optional` や `Union` といった名前を気にする必要はありません。😎
diff --git a/docs/ja/docs/advanced/async-tests.md b/docs/ja/docs/advanced/async-tests.md
new file mode 100644
index 000000000..067e9cc9a
--- /dev/null
+++ b/docs/ja/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# 非同期テスト { #async-tests }
+
+これまでに、提供されている `TestClient` を使って **FastAPI** アプリケーションをテストする方法を見てきました。ここまでは、`async` 関数を使わない同期テストのみでした。
+
+テストで非同期関数を使えると、たとえばデータベースへ非同期にクエリする場合などに便利です。非同期データベースライブラリを使いながら、FastAPI アプリにリクエストを送り、その後バックエンドが正しいデータをデータベースに書き込めたかを検証したい、といったケースを想像してください。
+
+その方法を見ていきます。
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+テスト内で非同期関数を呼び出したい場合、テスト関数自体も非同期である必要があります。AnyIO はこれを実現するための便利なプラグインを提供しており、特定のテスト関数を非同期で呼び出すことを指定できます。
+
+## HTTPX { #httpx }
+
+**FastAPI** アプリケーションが通常の `def` 関数を使っていても、その内側は依然として `async` アプリケーションです。
+
+`TestClient` は、標準の pytest を使って通常の `def` のテスト関数から非同期の FastAPI アプリを呼び出すための「おまじない」を内部で行います。しかし、その「おまじない」はテスト関数自体が非同期の場合には機能しません。テストを非同期で実行すると、テスト関数内で `TestClient` は使えなくなります。
+
+`TestClient` は HTTPX を基に作られており、幸いなことに API のテストには HTTPX を直接利用できます。
+
+## 例 { #example }
+
+簡単な例として、[大きなアプリケーション](../tutorial/bigger-applications.md){.internal-link target=_blank} と [テスト](../tutorial/testing.md){.internal-link target=_blank} で説明したものに似たファイル構成を考えます:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+`main.py` は次のようになります:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+`test_main.py` は `main.py` のテストを持ち、次のようになります:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## 実行 { #run-it }
+
+テストはいつも通り次で実行できます:
+
+
Host: mysuperapp.com
Path: /items
+
+ Note over Proxy: Proxy adds forwarded headers
+
+ Proxy->>Server: HTTP Request
X-Forwarded-For: [client IP]
X-Forwarded-Proto: https
X-Forwarded-Host: mysuperapp.com
Path: /items
+
+ Note over Server: Server interprets headers
(if --forwarded-allow-ips is set)
+
+ Server->>Proxy: HTTP Response
with correct HTTPS URLs
+
+ Proxy->>Client: HTTPS Response
+```
+
+**プロキシ** は元のクライアントリクエストを受け取り、**アプリケーションサーバー** に渡す前に特別な「転送」ヘッダー(`X-Forwarded-*`)を追加します。
+
+これらのヘッダーは、通常は失われる元のリクエストの情報を保持します:
+
+* **X-Forwarded-For**: 元のクライアントの IP アドレス
+* **X-Forwarded-Proto**: 元のプロトコル(`https`)
+* **X-Forwarded-Host**: 元のホスト(`mysuperapp.com`)
+
+**FastAPI CLI** を `--forwarded-allow-ips` で設定すると、これらのヘッダーを信頼して使用し、たとえばリダイレクトで正しい URL を生成します。
+
+## パスプレフィックスを削除するプロキシ { #proxy-with-a-stripped-path-prefix }
+
+アプリケーションにパスプレフィックスを付与するプロキシを使う場合があります。
+
+そのような場合は `root_path` でアプリケーションを設定できます。
+
+`root_path` は(FastAPI が Starlette を通して基づいている)ASGI 仕様で提供されている仕組みです。
+
+`root_path` はこの種のケースを扱うために使われます。
+
+これはサブアプリケーションをマウントする際にも内部的に使用されます。
+
+ここでいう「パスプレフィックスを削除するプロキシ」とは、コード上では `/app` というパスを宣言していても、その上にプロキシ層を追加して **FastAPI** アプリケーションを `/api/v1` のようなパスの下に配置することを指します。
+
+この場合、元のパス `/app` は実際には `/api/v1/app` で提供されます。
+
+すべてのコードは `/app` だけを前提に書かれているにもかかわらず、です。
+
+{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[6] *}
+
+そしてプロキシは、アプリサーバー(おそらく FastAPI CLI 経由の Uvicorn)に転送する前に、その場で **パスプレフィックス** を**「削除」**し、アプリケーション側には自分が `/app` で提供されているように見せかけます。これにより、コードのすべてを `/api/v1` のプレフィックス付きに書き換える必要がありません。
+
+ここまでは通常どおりに動作します。
+
+しかし、統合ドキュメント UI(フロントエンド)を開くと、OpenAPI スキーマを `/api/v1/openapi.json` ではなく `/openapi.json` から取得しようとします。
+
+そのため、フロントエンド(ブラウザで動作)は `/openapi.json` にアクセスしようとして、OpenAPI スキーマを取得できません。
+
+このアプリには `/api/v1` のパスプレフィックスを付与するプロキシがあるため、フロントエンドは `/api/v1/openapi.json` から取得する必要があります。
+
+```mermaid
+graph LR
+
+browser("Browser")
+proxy["Proxy on http://0.0.0.0:9999/api/v1/app"]
+server["Server on http://127.0.0.1:8000/app"]
+
+browser --> proxy
+proxy --> server
+```
+
+/// tip | 豆知識
+
+IP `0.0.0.0` は、そのマシン/サーバーで利用可能なすべての IP で待ち受けることを意味する表現として一般的に使われます。
+
+///
+
+ドキュメント UI では、この API の `server` が(プロキシの背後で)`/api/v1` にあることを宣言する OpenAPI スキーマも必要です。例えば:
+
+```JSON hl_lines="4-8"
+{
+ "openapi": "3.1.0",
+ // ほかの項目
+ "servers": [
+ {
+ "url": "/api/v1"
+ }
+ ],
+ "paths": {
+ // ほかの項目
+ }
+}
+```
+
+この例では「Proxy」は **Traefik** のようなもの、サーバーは **Uvicorn** と FastAPI CLI で FastAPI アプリケーションを実行しているものを想定しています。
+
+### `root_path` の指定 { #providing-the-root-path }
+
+これを実現するには、次のようにコマンドラインオプション `--root-path` を使用します:
+
+
+
+しかし、プロキシ(ポート `9999`)を使った「公式」URL `/api/v1/docs` でドキュメント UI にアクセスすると、正しく動作します!🎉
+
+http://127.0.0.1:9999/api/v1/docs を確認してください:
+
+
+
+ねらいどおりです。✔️
+
+これは、FastAPI が `root_path` を使って、OpenAPI の既定の `server` を `root_path` の URL で生成するためです。
+
+## 追加のサーバー { #additional-servers }
+
+/// warning | 注意
+
+これは高度なユースケースです。読み飛ばしても構いません。
+
+///
+
+既定では、**FastAPI** は OpenAPI スキーマ内に `root_path` の URL を持つ `server` を作成します。
+
+しかし、ステージングと本番の両方と同じドキュメント UI で対話させたい場合など、別の `servers` を指定することもできます。
+
+カスタムの `servers` リストを渡していて、かつ `root_path`(API がプロキシの背後にあるため)が設定されている場合、**FastAPI** はこの `root_path` を用いた「server」をリストの先頭に挿入します。
+
+例えば:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+次のような OpenAPI スキーマが生成されます:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // ほかの項目
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // ほかの項目
+ }
+}
+```
+
+/// tip | 豆知識
+
+`root_path` から取得した `url` 値 `/api/v1` を持つ server が自動生成されている点に注目してください。
+
+///
+
+ドキュメント UI(http://127.0.0.1:9999/api/v1/docs)では次のように表示されます:
+
+
+
+/// tip | 豆知識
+
+ドキュメント UI は、選択した server と対話します。
+
+///
+
+/// note | 技術詳細
+
+OpenAPI 仕様の `servers` プロパティは任意です。
+
+`servers` パラメータを指定せず、かつ `root_path` が `/` の場合、生成される OpenAPI スキーマからは `servers` プロパティが既定で完全に省略されます。これは、`url` が `/` の server が 1 つあるのと同等です。
+
+///
+
+### `root_path` 由来の自動 server を無効化 { #disable-automatic-server-from-root-path }
+
+`root_path` を用いた自動的な server を **FastAPI** に含めてほしくない場合は、パラメータ `root_path_in_servers=False` を使用します:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+すると、OpenAPI スキーマには含まれません。
+
+## サブアプリケーションのマウント { #mounting-a-sub-application }
+
+`root_path` を伴うプロキシを使用しつつサブアプリケーションをマウントする必要がある場合でも([サブアプリケーション - マウント](sub-applications.md){.internal-link target=_blank} 参照)、通常どおりに行えます。
+
+FastAPI は内部で `root_path` を適切に扱うため、そのまま動作します。✨
diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md
index 9d881c013..50a789165 100644
--- a/docs/ja/docs/advanced/custom-response.md
+++ b/docs/ja/docs/advanced/custom-response.md
@@ -30,7 +30,7 @@
しかし、返そうとしているコンテンツが **JSONでシリアライズ可能**であることが確実なら、それを直接レスポンスクラスに渡して、FastAPIがレスポンスクラスへ渡す前に返却コンテンツを `jsonable_encoder` に通すことで発生する追加のオーバーヘッドを回避できます。
-{* ../../docs_src/custom_response/tutorial001b_py39.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001b_py310.py hl[2,7] *}
/// info | 情報
@@ -55,7 +55,7 @@
* `HTMLResponse` をインポートする。
* *path operation デコレータ* のパラメータ `response_class` に `HTMLResponse` を渡す。
-{* ../../docs_src/custom_response/tutorial002_py39.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
/// info | 情報
@@ -73,7 +73,7 @@
上記と同じ例において、 `HTMLResponse` を返すと、このようになります:
-{* ../../docs_src/custom_response/tutorial003_py39.py hl[2,7,19] *}
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
/// warning | 注意
@@ -97,7 +97,7 @@
例えば、このようになります:
-{* ../../docs_src/custom_response/tutorial004_py39.py hl[7,21,23] *}
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
この例では、関数 `generate_html_response()` は、`str` のHTMLを返すのではなく、`Response` を生成して返しています。
@@ -136,7 +136,7 @@
FastAPI(実際にはStarlette)は自動的にContent-Lengthヘッダーを含みます。また、`media_type` に基づいたContent-Typeヘッダーを含み、テキストタイプのためにcharsetを追加します。
-{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
### `HTMLResponse` { #htmlresponse }
@@ -146,7 +146,7 @@ FastAPI(実際にはStarlette)は自動的にContent-Lengthヘッダーを
テキストやバイトを受け取り、プレーンテキストのレスポンスを返します。
-{* ../../docs_src/custom_response/tutorial005_py39.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
### `JSONResponse` { #jsonresponse }
@@ -180,7 +180,7 @@ FastAPI(実際にはStarlette)は自動的にContent-Lengthヘッダーを
///
-{* ../../docs_src/custom_response/tutorial001_py39.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001_py310.py hl[2,7] *}
/// tip | 豆知識
@@ -194,13 +194,13 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
`RedirectResponse` を直接返せます:
-{* ../../docs_src/custom_response/tutorial006_py39.py hl[2,9] *}
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
---
または、`response_class` パラメータで使用できます:
-{* ../../docs_src/custom_response/tutorial006b_py39.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
その場合、*path operation*関数からURLを直接返せます。
@@ -210,13 +210,13 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
また、`status_code` パラメータを `response_class` パラメータと組み合わせて使うこともできます:
-{* ../../docs_src/custom_response/tutorial006c_py39.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
### `StreamingResponse` { #streamingresponse }
非同期ジェネレータ、または通常のジェネレータ/イテレータを受け取り、レスポンスボディをストリームします。
-{* ../../docs_src/custom_response/tutorial007_py39.py hl[2,14] *}
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[2,14] *}
#### ファイルライクオブジェクトで `StreamingResponse` を使う { #using-streamingresponse-with-file-like-objects }
@@ -226,7 +226,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
これにはクラウドストレージとの連携、映像処理など、多くのライブラリが含まれます。
-{* ../../docs_src/custom_response/tutorial008_py39.py hl[2,10:12,14] *}
+{* ../../docs_src/custom_response/tutorial008_py310.py hl[2,10:12,14] *}
1. これはジェネレータ関数です。内部に `yield` 文を含むため「ジェネレータ関数」です。
2. `with` ブロックを使うことで、ジェネレータ関数が終わった後(つまりレスポンスの送信が完了した後)にfile-likeオブジェクトが確実にクローズされるようにします。
@@ -255,11 +255,11 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
ファイルレスポンスには、適切な `Content-Length`、`Last-Modified`、`ETag` ヘッダーが含まれます。
-{* ../../docs_src/custom_response/tutorial009_py39.py hl[2,10] *}
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
`response_class` パラメータを使うこともできます:
-{* ../../docs_src/custom_response/tutorial009b_py39.py hl[2,8,10] *}
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
この場合、*path operation*関数からファイルパスを直接返せます。
@@ -273,7 +273,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
`CustomORJSONResponse` を作れます。主に必要なのは、コンテンツを `bytes` として返す `Response.render(content)` メソッドを作ることです:
-{* ../../docs_src/custom_response/tutorial009c_py39.py hl[9:14,17] *}
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
これまでは次のように返していたものが:
@@ -299,7 +299,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
以下の例では、**FastAPI** はすべての*path operation*で、`JSONResponse` の代わりに `ORJSONResponse` をデフォルトとして使います。
-{* ../../docs_src/custom_response/tutorial010_py39.py hl[2,4] *}
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
/// tip | 豆知識
diff --git a/docs/ja/docs/advanced/dataclasses.md b/docs/ja/docs/advanced/dataclasses.md
new file mode 100644
index 000000000..74f479f07
--- /dev/null
+++ b/docs/ja/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Dataclasses の使用 { #using-dataclasses }
+
+FastAPI は **Pydantic** の上に構築されており、これまでにリクエストやレスポンスを宣言するために Pydantic モデルを使う方法を紹介してきました。
+
+しかし FastAPI は、同様の方法で `dataclasses` もサポートします:
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+これは **Pydantic** によって引き続きサポートされています。Pydantic には `dataclasses` の内部サポート があるためです。
+
+そのため、上記のように明示的に Pydantic を使っていないコードでも、FastAPI は標準の dataclass を Pydantic 独自の dataclass に変換するために Pydantic を使用しています。
+
+そして当然ながら、次の点も同様にサポートされます:
+
+- データ検証
+- データのシリアライズ
+- データのドキュメント化 など
+
+これは Pydantic モデルの場合と同じように動作します。内部的にも同様に Pydantic を使って実現されています。
+
+/// info | 情報
+
+dataclasses は、Pydantic モデルができることをすべては行えない点に留意してください。
+
+そのため、Pydantic モデルを使う必要がある場合もあります。
+
+しかし既存の dataclass が多数あるなら、FastAPI で Web API を構築する際にそれらを活用するちょっとしたテクニックになります。🤓
+
+///
+
+## `response_model` での dataclasses { #dataclasses-in-response-model }
+
+`response_model` パラメータでも `dataclasses` を使用できます:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+dataclass は自動的に Pydantic の dataclass に変換されます。
+
+このため、そのスキーマは API ドキュメントの UI に表示されます:
+
+
+
+## ネストしたデータ構造での dataclasses { #dataclasses-in-nested-data-structures }
+
+`dataclasses` を他の型注釈と組み合わせて、ネストしたデータ構造を作成できます。
+
+場合によっては、自動生成された API ドキュメントでエラーが発生するなどの理由で、Pydantic 版の `dataclasses` を使う必要があるかもしれません。
+
+その場合は、標準の `dataclasses` を `pydantic.dataclasses` に置き換えるだけで済みます。これはドロップイン置換です:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. 依然として標準の `dataclasses` から `field` をインポートします。
+
+2. `pydantic.dataclasses` は `dataclasses` のドロップイン置換です。
+
+3. `Author` dataclass は `Item` dataclass のリストを含みます。
+
+4. `Author` dataclass を `response_model` パラメータとして使用しています。
+
+5. リクエストボディとしての dataclass と併せて、他の標準の型注釈を使用できます。
+
+ この例では、`Item` dataclass のリストです。
+
+6. ここでは、dataclass のリストである `items` を含む辞書を返しています。
+
+ FastAPI はデータを JSON に シリアライズ できます。
+
+7. ここでは `response_model` に `Author` dataclass のリストという型注釈を使用しています。
+
+ このように、`dataclasses` は標準の型注釈と組み合わせられます。
+
+8. この *path operation 関数* は、`async def` ではなく通常の `def` を使用しています。
+
+ いつもどおり、FastAPI では必要に応じて `def` と `async def` を組み合わせられます。
+
+ どちらをいつ使うかの復習が必要な場合は、[`async` と `await`](../async.md#in-a-hurry){.internal-link target=_blank} に関するドキュメントの _"In a hurry?"_ セクションを参照してください。
+
+9. この *path operation 関数* は(可能ではありますが)dataclass 自体は返さず、内部データを持つ辞書のリストを返しています。
+
+ FastAPI は dataclass を含む `response_model` パラメータを使ってレスポンスを変換します。
+
+`dataclasses` は他の型注釈と多様な組み合わせが可能で、複雑なデータ構造を構成できます。
+
+上記のコード内コメントのヒントを参照して、より具体的な詳細を確認してください。
+
+## さらに学ぶ { #learn-more }
+
+`dataclasses` を他の Pydantic モデルと組み合わせたり、継承したり、自分のモデルに含めたりもできます。
+
+詳しくは、dataclasses に関する Pydantic ドキュメント を参照してください。
+
+## バージョン { #version }
+
+これは FastAPI バージョン `0.67.0` 以降で利用可能です。🔖
diff --git a/docs/ja/docs/advanced/events.md b/docs/ja/docs/advanced/events.md
new file mode 100644
index 000000000..fb79062fa
--- /dev/null
+++ b/docs/ja/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# Lifespan イベント { #lifespan-events }
+
+アプリケーションが起動する前に一度だけ実行すべきロジック(コード)を定義できます。これは、アプリケーションがリクエストを受け取り始める前に、そのコードが一度だけ実行される、という意味です。
+
+同様に、アプリケーションがシャットダウンするときに実行すべきロジック(コード)も定義できます。この場合、そのコードは、(多くのリクエストを処理した)後に一度だけ実行されます。
+
+このコードは、アプリケーションがリクエストの受け付けを「開始」する前、そして処理を「終了」した直後に実行されるため、アプリケーションの全体の「Lifespan」(この「lifespan」という言葉はすぐ後で重要になります 😉)をカバーします。
+
+これは、アプリ全体で使用し、リクエスト間で「共有」し、かつ後で「クリーンアップ」する必要があるような「リソース」をセットアップするのにとても便利です。たとえば、データベース接続プールや、共有の機械学習モデルの読み込みなどです。
+
+## ユースケース { #use-case }
+
+まずはユースケースの例から始めて、これをどのように解決するかを見ていきます。
+
+リクエストを処理するために使用したい「機械学習モデル」がいくつかあると想像してください。🤖
+
+同じモデルをリクエスト間で共有するので、リクエストごとやユーザーごとに別々のモデルを使うわけではありません。
+
+モデルの読み込みにはディスクから大量のデータを読む必要があり、かなり時間がかかるかもしれません。したがって、リクエストごとに読み込みたくはありません。
+
+モジュール/ファイルのトップレベルで読み込むこともできますが、その場合は、たとえ簡単な自動テストを実行するだけでも「モデルを読み込む」ことになり、そのモデルの読み込みを待つ必要があるため、独立したコード部分を走らせるだけのテストでも「遅く」なってしまいます。
+
+これを解決しましょう。リクエストを処理する前にモデルを読み込みますが、コードがロードされている最中ではなく、アプリケーションがリクエストの受け付けを開始する直前だけにします。
+
+## Lifespan { #lifespan }
+
+この「起動時」と「シャットダウン時」のロジックは、`FastAPI` アプリの `lifespan` パラメータと「コンテキストマネージャ」(これが何かはすぐに示します)を使って定義できます。
+
+まずは例を見てから、詳細を説明します。
+
+次のように、`yield` を使う非同期関数 `lifespan()` を作成します:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+ここでは、`yield` の前で機械学習モデルの辞書に(ダミーの)モデル関数を入れることで、高コストな「起動時」のモデル読み込みをシミュレーションしています。このコードは、アプリケーションがリクエストを「受け付け始める前」に、すなわち起動時に実行されます。
+
+そして `yield` の直後でモデルをアンロードします。このコードは、アプリケーションがリクエスト処理を「終了」した後、シャットダウン直前に実行されます。たとえばメモリや GPU のようなリソースを解放できます。
+
+/// tip | 豆知識
+
+`shutdown` は、アプリケーションを「停止」するときに発生します。
+
+新しいバージョンを開始する必要があるか、単に実行をやめたくなったのかもしれません。🤷
+
+///
+
+### Lifespan 関数 { #lifespan-function }
+
+まず注目すべきは、`yield` を使う非同期関数を定義していることです。これは「yield を使う依存関係(Dependencies)」にとてもよく似ています。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+`yield` の前の前半は、アプリケーションが開始される「前」に実行されます。
+
+`yield` の後半は、アプリケーションの処理が「終了」した「後」に実行されます。
+
+### 非同期コンテキストマネージャ { #async-context-manager }
+
+この関数には `@asynccontextmanager` がデコレートされています。
+
+これにより、この関数は「非同期コンテキストマネージャ」になります。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Python の「コンテキストマネージャ」は、`with` 文で使えるものです。たとえば、`open()` はコンテキストマネージャとして使えます:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+最近の Python には「非同期コンテキストマネージャ」もあります。`async with` で使います:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+このようにコンテキストマネージャ(または非同期コンテキストマネージャ)を作ると、`with` ブロックに入る前に `yield` より前のコードが実行され、`with` ブロックを出た後に `yield` より後ろのコードが実行されます。
+
+上のコード例では直接それを使ってはいませんが、FastAPI に渡して内部で使ってもらいます。
+
+`FastAPI` アプリの `lifespan` パラメータは「非同期コンテキストマネージャ」を受け取るので、新しく作った `lifespan` 非同期コンテキストマネージャを渡せます。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## 代替のイベント(非推奨) { #alternative-events-deprecated }
+
+/// warning | 注意
+
+推奨される方法は、上で説明したとおり `FastAPI` アプリの `lifespan` パラメータを使って「起動」と「シャットダウン」を扱うことです。`lifespan` パラメータを指定すると、`startup` と `shutdown` のイベントハンドラは呼び出されなくなります。`lifespan` かイベントか、どちらか一方であり、両方同時ではありません。
+
+この節は読み飛ばしてもかまいません。
+
+///
+
+起動時とシャットダウン時に実行されるロジックを定義する別の方法もあります。
+
+アプリケーションが起動する前、またはシャットダウンするときに実行する必要があるイベントハンドラ(関数)を定義できます。
+
+これらの関数は `async def` でも、通常の `def` でも構いません。
+
+### `startup` イベント { #startup-event }
+
+アプリケーションが開始される前に実行すべき関数を追加するには、イベント `"startup"` で宣言します:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+この場合、`startup` のイベントハンドラ関数は items の「データベース」(単なる `dict`)をいくつかの値で初期化します。
+
+イベントハンドラ関数は複数追加できます。
+
+すべての `startup` イベントハンドラが完了するまで、アプリケーションはリクエストの受け付けを開始しません。
+
+### `shutdown` イベント { #shutdown-event }
+
+アプリケーションがシャットダウンするときに実行すべき関数を追加するには、イベント `"shutdown"` で宣言します:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+ここでは、`shutdown` のイベントハンドラ関数が、テキスト行 `"Application shutdown"` をファイル `log.txt` に書き込みます。
+
+/// info | 情報
+
+`open()` 関数の `mode="a"` は「追加」(append)を意味します。つまり、そのファイルに既にある内容を上書きせず、行が後ろに追記されます。
+
+///
+
+/// tip | 豆知識
+
+この例では、ファイルを扱う標準の Python 関数 `open()` を使っています。
+
+そのため、ディスクへの書き込みを「待つ」必要がある I/O(入力/出力)が関わります。
+
+しかし `open()` 自体は `async` や `await` を使いません。
+
+したがって、イベントハンドラ関数は `async def` ではなく通常の `def` で宣言しています。
+
+///
+
+### `startup` と `shutdown` をまとめて { #startup-and-shutdown-together }
+
+起動時とシャットダウン時のロジックは関連していることが多いです。何かを開始してから終了したい、リソースを獲得してから解放したい、などです.
+
+共有するロジックや変数のない別々の関数でそれを行うのは難しく、グローバル変数などに値を保存する必要が出てきます。
+
+そのため、現在は上で説明したとおり `lifespan` を使うことが推奨されています。
+
+## 技術詳細 { #technical-details }
+
+技術が気になる方への細かな詳細です。🤓
+
+内部的には、ASGI の技術仕様において、これは Lifespan プロトコル の一部であり、`startup` と `shutdown` というイベントが定義されています。
+
+/// info | 情報
+
+Starlette の `lifespan` ハンドラについては、Starlette の Lifespan ドキュメントで詳しく読むことができます。
+
+コードの他の領域で使える lifespan の状態をどのように扱うかも含まれています。
+
+///
+
+## サブアプリケーション { #sub-applications }
+
+🚨 これらの lifespan イベント(startup と shutdown)はメインのアプリケーションに対してのみ実行され、[サブアプリケーション - マウント](sub-applications.md){.internal-link target=_blank} には実行されないことに注意してください。
diff --git a/docs/ja/docs/advanced/generate-clients.md b/docs/ja/docs/advanced/generate-clients.md
new file mode 100644
index 000000000..7b9f82054
--- /dev/null
+++ b/docs/ja/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# SDK の生成 { #generating-sdks }
+
+**FastAPI** は **OpenAPI** 仕様に基づいているため、その API は多くのツールが理解できる標準形式で記述できます。
+
+これにより、最新の**ドキュメント**、複数言語のクライアントライブラリ(**SDKs**)、そしてコードと同期し続ける**テスト**や**自動化ワークフロー**を容易に生成できます。
+
+本ガイドでは、FastAPI バックエンド向けの **TypeScript SDK** を生成する方法を説明します。
+
+## オープソースの SDK ジェネレータ { #open-source-sdk-generators }
+
+多用途な選択肢として OpenAPI Generator があります。これは**多数のプログラミング言語**をサポートし、OpenAPI 仕様から SDK を生成できます。
+
+**TypeScript クライアント**向けには、Hey API が目的特化のソリューションで、TypeScript エコシステムに最適化された体験を提供します。
+
+他の SDK ジェネレータは OpenAPI.Tools でも見つけられます。
+
+/// tip | 豆知識
+
+FastAPI は自動的に **OpenAPI 3.1** の仕様を生成します。したがって、使用するツールはこのバージョンをサポートしている必要があります。
+
+///
+
+## FastAPI スポンサーによる SDK ジェネレータ { #sdk-generators-from-fastapi-sponsors }
+
+このセクションでは、FastAPI をスポンサーしている企業による、**ベンチャー支援**および**企業支援**のソリューションを紹介します。これらの製品は、高品質な生成 SDK に加えて、**追加機能**や**統合**を提供します。
+
+✨ [**FastAPI をスポンサーする**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨ ことで、これらの企業はフレームワークとその**エコシステム**の健全性と**持続可能性**を支援しています。
+
+この支援は、FastAPI の**コミュニティ**(皆さん)への強いコミットメントの表明でもあり、**優れたサービス**の提供だけでなく、堅牢で発展するフレームワーク FastAPI を支える姿勢を示しています。🙇
+
+例えば、次のようなものがあります:
+
+* Speakeasy
+* Stainless
+* liblab
+
+これらのソリューションの中にはオープンソースや無料枠を提供するものもあり、金銭的コミットメントなしで試すことができます。他の商用 SDK ジェネレータも存在し、オンラインで見つけられます。🤓
+
+## TypeScript SDK を作成する { #create-a-typescript-sdk }
+
+まずは簡単な FastAPI アプリから始めます:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+ここで、*path operation* はリクエストとレスポンスのペイロードに使用するモデルを定義しており、`Item` と `ResponseMessage` を使っています。
+
+### API ドキュメント { #api-docs }
+
+`/docs` に移動すると、リクエストで送信・レスポンスで受信するデータの**スキーマ**が表示されます:
+
+
+
+これらのスキーマは、アプリ内でモデルとして宣言されているため表示されます。
+
+その情報はアプリの **OpenAPI スキーマ**に含まれ、API ドキュメントに表示されます。
+
+OpenAPI に含まれるこれらのモデル情報を使って、**クライアントコードを生成**できます。
+
+### Hey API { #hey-api }
+
+モデルを備えた FastAPI アプリがあれば、Hey API で TypeScript クライアントを生成できます。最も手早い方法は npx を使うことです。
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+これで TypeScript SDK が `./src/client` に生成されます。
+
+`@hey-api/openapi-ts` のインストール方法や、生成物の詳細は公式サイトを参照してください。
+
+### SDK の利用 { #using-the-sdk }
+
+これでクライアントコードを import して利用できます。例えば次のようになり、メソッドに対して補完が効きます:
+
+
+
+送信するペイロードにも補完が適用されます:
+
+
+
+/// tip | 豆知識
+
+FastAPI アプリの `Item` モデルで定義した `name` と `price` に補完が効いている点に注目してください。
+
+///
+
+送信データに対するインラインエラーも表示されます:
+
+
+
+レスポンスオブジェクトにも補完があります:
+
+
+
+## タグ付きの FastAPI アプリ { #fastapi-app-with-tags }
+
+実運用ではアプリは大きくなり、*path operation* のグループ分けにタグを使うことが多いでしょう。
+
+例えば **items** 用と **users** 用のセクションがあり、タグで分けられます:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### タグ付き TypeScript クライアントの生成 { #generate-a-typescript-client-with-tags }
+
+タグを用いた FastAPI アプリからクライアントを生成すると、通常クライアント側のコードもタグごとに分割されます。
+
+これにより、クライアントコードも正しく整理・グルーピングされます:
+
+
+
+この例では次のようになります:
+
+* `ItemsService`
+* `UsersService`
+
+### クライアントのメソッド名 { #client-method-names }
+
+現状では、生成されるメソッド名(`createItemItemsPost` など)はあまりきれいではありません:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+これは、クライアントジェネレータが各 *path operation* の OpenAPI 内部の **operation ID** を用いるためです。
+
+OpenAPI では operation ID は全ての *path operation* を通して一意である必要があります。そのため FastAPI は**関数名**、**パス**、**HTTP メソッド/オペレーション**を組み合わせて operation ID を生成し、一意性を保証します。
+
+次にこれを改善する方法を示します。🤓
+
+## カスタム operation ID とより良いメソッド名 { #custom-operation-ids-and-better-method-names }
+
+operation ID の**生成方法**を**変更**して簡潔にし、クライアント側の**メソッド名をシンプル**にできます。
+
+この場合でも各 operation ID が**一意**であることは別の方法で保証する必要があります。
+
+例えば、各 *path operation* にタグを付け、**タグ**と *path operation* の**名前**(関数名)から operation ID を生成できます。
+
+### 一意 ID 生成関数のカスタマイズ { #custom-generate-unique-id-function }
+
+FastAPI は各 *path operation* に**一意 ID**を用いており、これは **operation ID** のほか、必要に応じてリクエストやレスポンスのカスタムモデル名にも使われます。
+
+この関数はカスタマイズ可能です。`APIRoute` を受け取り、文字列を返します。
+
+例えばここでは、最初のタグ(通常は 1 つ)と *path operation* 名(関数名)を使います。
+
+そのカスタム関数を **FastAPI** の `generate_unique_id_function` パラメータに渡します:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### カスタム operation ID で TypeScript クライアントを生成 { #generate-a-typescript-client-with-custom-operation-ids }
+
+この状態でクライアントを再生成すると、メソッド名が改善されています:
+
+
+
+ご覧のとおり、メソッド名はタグ名と関数名のみになり、URL パスや HTTP オペレーションの情報は含まれません。
+
+### クライアント生成向けの OpenAPI 仕様の前処理 { #preprocess-the-openapi-specification-for-the-client-generator }
+
+それでも生成コードには**重複情報**が残っています。
+
+`ItemsService`(タグ由来)から items 関連であることはすでに分かるのに、メソッド名にもタグ名が前置されています。😕
+
+OpenAPI 全体としては operation ID の**一意性**のために、このプレフィックスを維持したい場合があるでしょう。
+
+しかし生成クライアント用には、クライアントを生成する直前に OpenAPI の operation ID を**加工**して、メソッド名をより**見やすく**、**クリーン**にできます。
+
+OpenAPI の JSON を `openapi.json` として保存し、次のようなスクリプトで**そのタグのプレフィックスを除去**できます:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+これにより operation ID は `items-get_items` のような形から単なる `get_items` に置き換わり、クライアントジェネレータはより簡潔なメソッド名を生成できます。
+
+### 前処理済み OpenAPI から TypeScript クライアントを生成 { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+生成元が `openapi.json` になったので、入力の場所を更新します:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+新しいクライアントを生成すると、**クリーンなメソッド名**になり、**補完**や**インラインエラー**などもそのまま利用できます:
+
+
+
+## 利点 { #benefits }
+
+自動生成されたクライアントを使うと、次のような対象で**補完**が得られます:
+
+* メソッド
+* 本体のリクエストペイロード、クエリパラメータ等
+* レスポンスのペイロード
+
+また、あらゆる箇所で**インラインエラー**も得られます。
+
+バックエンドコードを更新してフロントエンドを**再生成**すれば、新しい *path operation* はメソッドとして追加され、古いものは削除され、その他の変更も生成コードに反映されます。🤓
+
+つまり、変更があれば自動的にクライアントコードに**反映**されます。クライアントを**ビルド**すれば、使用データに**不整合**があればエラーになります。
+
+その結果、多くのエラーを開発の初期段階で**早期発見**でき、本番で最終ユーザーに不具合が現れてから原因をデバッグする必要がなくなります。✨
diff --git a/docs/ja/docs/advanced/middleware.md b/docs/ja/docs/advanced/middleware.md
new file mode 100644
index 000000000..2883d53d8
--- /dev/null
+++ b/docs/ja/docs/advanced/middleware.md
@@ -0,0 +1,97 @@
+# 高度なミドルウェア { #advanced-middleware }
+
+メインのチュートリアルでは、アプリケーションに[カスタムミドルウェア](../tutorial/middleware.md){.internal-link target=_blank}を追加する方法を学びました。
+
+そして、[`CORSMiddleware` を使った CORS の扱い方](../tutorial/cors.md){.internal-link target=_blank}も学びました。
+
+このセクションでは、その他のミドルウェアの使い方を見ていきます。
+
+## ASGI ミドルウェアの追加 { #adding-asgi-middlewares }
+
+**FastAPI** は Starlette を基盤としており、ASGI 仕様を実装しているため、任意の ASGI ミドルウェアを利用できます。
+
+ミドルウェアは ASGI 仕様に従っていれば、FastAPI や Starlette 専用に作られていなくても動作します。
+
+一般に、ASGI ミドルウェアは最初の引数として ASGI アプリを受け取るクラスです。
+
+そのため、サードパーティの ASGI ミドルウェアのドキュメントでは、おそらく次のように書かれているでしょう:
+
+```Python
+from unicorn import UnicornMiddleware
+
+app = SomeASGIApp()
+
+new_app = UnicornMiddleware(app, some_config="rainbow")
+```
+
+しかし FastAPI(正確には Starlette)は、内部ミドルウェアがサーバーエラーを処理し、カスタム例外ハンドラが正しく動作することを保証する、より簡単な方法を提供しています。
+
+そのためには(CORS の例と同様に)`app.add_middleware()` を使います。
+
+```Python
+from fastapi import FastAPI
+from unicorn import UnicornMiddleware
+
+app = FastAPI()
+
+app.add_middleware(UnicornMiddleware, some_config="rainbow")
+```
+
+`app.add_middleware()` は、最初の引数にミドルウェアのクラスを取り、それ以外の追加引数はミドルウェアに渡されます。
+
+## 組み込みミドルウェア { #integrated-middlewares }
+
+**FastAPI** は一般的なユースケースに対応するいくつかのミドルウェアを含んでいます。以下でその使い方を見ていきます。
+
+/// note | 技術詳細
+
+以下の例では、`from starlette.middleware.something import SomethingMiddleware` を使うこともできます。
+
+**FastAPI** は開発者であるあなたの便宜のために `fastapi.middleware` にいくつかのミドルウェアを提供しています。しかし、利用可能なミドルウェアの多くは Starlette から直接提供されています。
+
+///
+
+## `HTTPSRedirectMiddleware` { #httpsredirectmiddleware }
+
+すべての受信リクエストが `https` または `wss` でなければならないように強制します。
+
+`http` または `ws` への受信リクエストは、安全なスキームにリダイレクトされます。
+
+{* ../../docs_src/advanced_middleware/tutorial001_py310.py hl[2,6] *}
+
+## `TrustedHostMiddleware` { #trustedhostmiddleware }
+
+HTTP Host Header 攻撃を防ぐため、すべての受信リクエストに正しく設定された `Host` ヘッダーを強制します。
+
+{* ../../docs_src/advanced_middleware/tutorial002_py310.py hl[2,6:8] *}
+
+サポートされる引数は次のとおりです:
+
+- `allowed_hosts` - 許可するホスト名のドメイン名リスト。`*.example.com` のようなワイルドカードドメインでサブドメインのマッチングもサポートします。任意のホスト名を許可するには、`allowed_hosts=["*"]` を使うか、このミドルウェアを省略します。
+- `www_redirect` - True に設定すると、許可されたホストの非 www 版へのリクエストを www 版へリダイレクトします。デフォルトは `True` です。
+
+受信リクエストが正しく検証されない場合、`400` のレスポンスが返されます。
+
+## `GZipMiddleware` { #gzipmiddleware }
+
+`Accept-Encoding` ヘッダーに "gzip" を含むリクエストに対して GZip レスポンスを処理します。
+
+このミドルウェアは、通常のレスポンスとストリーミングレスポンスの両方を処理します。
+
+{* ../../docs_src/advanced_middleware/tutorial003_py310.py hl[2,6] *}
+
+サポートされる引数は次のとおりです:
+
+- `minimum_size` - このバイト数の最小サイズ未満のレスポンスは GZip 圧縮しません。デフォルトは `500` です。
+- `compresslevel` - GZip 圧縮時に使用します。1 から 9 までの整数です。デフォルトは `9`。値が小さいほど圧縮は速くなりますがファイルサイズは大きくなり、値が大きいほど圧縮は遅くなりますがファイルサイズは小さくなります。
+
+## その他のミドルウェア { #other-middlewares }
+
+他にも多くの ASGI ミドルウェアがあります。
+
+例えば:
+
+- Uvicorn の `ProxyHeadersMiddleware`
+- MessagePack
+
+他に利用可能なミドルウェアについては、Starlette のミドルウェアドキュメントや ASGI Awesome List を参照してください。
diff --git a/docs/ja/docs/advanced/openapi-callbacks.md b/docs/ja/docs/advanced/openapi-callbacks.md
new file mode 100644
index 000000000..283a80b21
--- /dev/null
+++ b/docs/ja/docs/advanced/openapi-callbacks.md
@@ -0,0 +1,186 @@
+# OpenAPI コールバック { #openapi-callbacks }
+
+あなたは、*path operation* を持つ API を作成し、他者(多くの場合、あなたの API を「利用する」同一の開発者)が作成した *外部 API* へリクエストをトリガーできるようにできます。
+
+あなたの API アプリが *外部 API* を呼び出すときに起きる処理は「コールバック」と呼ばれます。なぜなら、外部開発者が作成したソフトウェアがあなたの API にリクエストを送り、その後であなたの API が「呼び返し」、*外部 API*(おそらく同じ開発者が作成)へリクエストを送るためです。
+
+この場合、その *外部 API* がどのようである「べき」かをドキュメント化したくなるでしょう。どんな *path operation* を持ち、どんなボディを受け取り、どんなレスポンスを返すか、などです。
+
+## コールバックのあるアプリ { #an-app-with-callbacks }
+
+例で見ていきます。
+
+あなたが請求書を作成できるアプリを開発していると想像してください。
+
+これらの請求書は `id`、`title`(任意)、`customer`、`total` を持ちます。
+
+あなたの API の利用者(外部開発者)は、POST リクエストであなたの API に請求書を作成します。
+
+その後、あなたの API は(仮にこうしましょう):
+
+* 外部開発者の顧客に請求書を送ります。
+* 代金を回収します。
+* API 利用者(外部開発者)に通知を送り返します。
+ * これは(あなたの API から)外部開発者が提供する *外部 API* に POST リクエストを送ることで行われます(これが「コールバック」です)。
+
+## 通常の FastAPI アプリ { #the-normal-fastapi-app }
+
+まず、コールバックを追加する前の通常の API アプリがどうなるか見てみましょう。
+
+`Invoice` ボディを受け取り、クエリパラメータ `callback_url` にコールバック用の URL を含める *path operation* を持ちます。
+
+この部分はとても普通で、ほとんどのコードはすでに見覚えがあるはずです:
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[7:11,34:51] *}
+
+/// tip | 豆知識
+
+`callback_url` クエリパラメータは、Pydantic の Url 型を使用します。
+
+///
+
+唯一の新しい点は、*path operation デコレータ*の引数として `callbacks=invoices_callback_router.routes` を渡すことです。これが何かは次で見ます。
+
+## コールバックのドキュメント化 { #documenting-the-callback }
+
+実際のコールバックのコードは、あなた自身の API アプリに大きく依存します。
+
+そしてアプリごとに大きく異なるでしょう。
+
+それは次のように 1、2 行のコードかもしれません:
+
+```Python
+callback_url = "https://example.com/api/v1/invoices/events/"
+httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
+```
+
+しかし、おそらくコールバックで最も重要な点は、あなたの API 利用者(外部開発者)が、*あなたの API* がコールバックのリクエストボディなどで送るデータに従って、*外部 API* を正しく実装することを確実にすることです。
+
+そこで次に行うのは、*あなたの API* からのコールバックを受け取るために、その *外部 API* がどうあるべきかをドキュメント化するコードを追加することです。
+
+そのドキュメントはあなたの API の `/docs` の Swagger UI に表示され、外部開発者に *外部 API* の作り方を知らせます。
+
+この例ではコールバック自体は実装しません(それは 1 行のコードでもよいでしょう)。ドキュメント部分のみです。
+
+/// tip | 豆知識
+
+実際のコールバックは単なる HTTP リクエストです。
+
+自分でコールバックを実装する場合は、HTTPX や Requests のようなものを使えます。
+
+///
+
+## コールバックのドキュメント用コードを書く { #write-the-callback-documentation-code }
+
+このコードはあなたのアプリで実行されません。*外部 API* がどうあるべきかをドキュメント化するためだけに必要です。
+
+しかし、あなたはすでに **FastAPI** で API の自動ドキュメントを簡単に作る方法を知っています。
+
+その知識を使って、*外部 API* がどうあるべきかをドキュメント化します……つまり、外部 API が実装すべき *path operation(s)*(あなたの API が呼び出すもの)を作成します。
+
+/// tip | 豆知識
+
+コールバックをドキュメント化するコードを書くときは、あなたがその「外部開発者」だと想像するのが役に立つかもしれません。いま実装しているのは「あなたの API」ではなく、*外部 API* です。
+
+この(外部開発者の)視点を一時的に採用すると、その *外部 API* に対してパラメータ、ボディ用の Pydantic モデル、レスポンスなどをどこに置くのが自然かがより明確に感じられるでしょう。
+
+///
+
+### コールバック用 APIRouter を作成 { #create-a-callback-apirouter }
+
+まず、1 つ以上のコールバックを含む新しい `APIRouter` を作成します。
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[1,23] *}
+
+### コールバックの path operation を作成 { #create-the-callback-path-operation }
+
+上で作成したのと同じ `APIRouter` を使って、コールバックの *path operation* を作成します。
+
+見た目は通常の FastAPI の *path operation* と同じです:
+
+* 受け取るボディの宣言(例: `body: InvoiceEvent`)が必要でしょう。
+* 返すレスポンスの宣言(例: `response_model=InvoiceEventReceived`)も持てます。
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[14:16,19:20,26:30] *}
+
+通常の *path operation* と異なる主な点が 2 つあります:
+
+* 実際のコードは不要です。あなたのアプリはこのコードを決して呼びません。これは *外部 API* をドキュメント化するためだけに使われます。したがって、関数本体は `pass` で構いません。
+* *パス* には、*あなたの API* に送られた元のリクエストのパラメータや一部を変数として使える OpenAPI 3 の式(後述)を含められます。
+
+### コールバックのパス式 { #the-callback-path-expression }
+
+コールバックの *パス* には、*あなたの API* に送られた元のリクエストの一部を含められる OpenAPI 3 の式を使用できます。
+
+この例では、`str` は次のとおりです:
+
+```Python
+"{$callback_url}/invoices/{$request.body.id}"
+```
+
+つまり、あなたの API 利用者(外部開発者)が *あなたの API* に次のようにリクエストを送った場合:
+
+```
+https://yourapi.com/invoices/?callback_url=https://www.external.org/events
+```
+
+JSON ボディは:
+
+```JSON
+{
+ "id": "2expen51ve",
+ "customer": "Mr. Richie Rich",
+ "total": "9999"
+}
+```
+
+その後 *あなたの API* は請求書を処理し、のちほど `callback_url`(*外部 API*)へコールバックのリクエストを送ります:
+
+```
+https://www.external.org/events/invoices/2expen51ve
+```
+
+JSON ボディは次のような内容です:
+
+```JSON
+{
+ "description": "Payment celebration",
+ "paid": true
+}
+```
+
+そして *外部 API* からは次のような JSON ボディのレスポンスを期待します:
+
+```JSON
+{
+ "ok": true
+}
+```
+
+/// tip | 豆知識
+
+使用されるコールバック URL には、クエリパラメータ `callback_url`(`https://www.external.org/events`)で受け取った URL と、JSON ボディ内の請求書 `id`(`2expen51ve`)が含まれている点に注目してください。
+
+///
+
+### コールバック用ルーターを追加 { #add-the-callback-router }
+
+これで、上で作成したコールバック用ルーター内に、必要なコールバックの *path operation(s)*(*外部開発者* が *外部 API* に実装すべきもの)が用意できました。
+
+次に、*あなたの API の path operation デコレータ*の `callbacks` パラメータに、そのコールバック用ルーターの属性 `.routes`(実体はルート/*path operations* の `list`)を渡します:
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *}
+
+/// tip | 豆知識
+
+`callback=` に渡すのはルーター本体(`invoices_callback_router`)ではなく、属性 `.routes`(`invoices_callback_router.routes`)である点に注意してください。
+
+///
+
+### ドキュメントを確認 { #check-the-docs }
+
+アプリを起動して http://127.0.0.1:8000/docs にアクセスします。
+
+あなたの *path operation* に「Callbacks」セクションが含まれ、*外部 API* がどうあるべきかが表示されているのが確認できます:
+
+
diff --git a/docs/ja/docs/advanced/openapi-webhooks.md b/docs/ja/docs/advanced/openapi-webhooks.md
new file mode 100644
index 000000000..368cfddd8
--- /dev/null
+++ b/docs/ja/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# OpenAPI の Webhook { #openapi-webhooks }
+
+アプリがある種の**イベント**を**通知**するために、データ付きで相手のアプリ(リクエスト送信)を呼び出す可能性があることを、API の**ユーザー**に伝えたい場合があります。
+
+これは、通常のようにユーザーがあなたの API にリクエストを送るのではなく、**あなたの API(あなたのアプリ)**が**相手のシステム**(相手の API、アプリ)にリクエストを送る、ということです。
+
+これは一般に**Webhook**と呼ばれます。
+
+## Webhook の手順 { #webhooks-steps }
+
+通常の流れとして、まずあなたのコード内で、送信するメッセージ、すなわちリクエストの**本文(ボディ)**を**定義**します。
+
+加えて、アプリがそれらのリクエスト(イベント)を送信する**タイミング**も何らかの形で定義します。
+
+そして**ユーザー**は、アプリがそのリクエストを送るべき**URL**を(たとえばどこかの Web ダッシュボードで)定義します。
+
+Webhook の URL を登録する方法や実際にリクエストを送るコードなど、これらの**ロジック**はすべてあなた次第です。**あなた自身のコード**で好きなように実装します。
+
+## FastAPI と OpenAPI による Webhook のドキュメント化 { #documenting-webhooks-with-fastapi-and-openapi }
+
+**FastAPI** と OpenAPI を使うと、Webhook の名前、アプリが送信できる HTTP の操作(例: `POST`, `PUT` など)、アプリが送るリクエストの**ボディ**を定義できます。
+
+これにより、ユーザーがあなたの **Webhook** リクエストを受け取るための**API を実装**するのが大幅に簡単になります。場合によっては、ユーザーが自分たちの API コードを自動生成できるかもしれません。
+
+/// info | 情報
+
+Webhook は OpenAPI 3.1.0 以上で利用可能で、FastAPI `0.99.0` 以上が対応しています。
+
+///
+
+## Webhook を持つアプリ { #an-app-with-webhooks }
+
+**FastAPI** アプリケーションを作成すると、`webhooks` という属性があり、ここで *path operations* と同様に(例: `@app.webhooks.post()`)*webhook* を定義できます。
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+定義した webhook は **OpenAPI** スキーマおよび自動生成される **ドキュメント UI** に反映されます。
+
+/// info | 情報
+
+`app.webhooks` オブジェクトは実際には単なる `APIRouter` で、複数ファイルでアプリを構成する際に使うものと同じ型です。
+
+///
+
+Webhook では(`/items/` のような)*パス*を宣言しているわけではない点に注意してください。ここで渡す文字列は webhook の**識別子**(イベント名)です。たとえば `@app.webhooks.post("new-subscription")` での webhook 名は `new-subscription` です。
+
+これは、**ユーザー**が実際に Webhook リクエストを受け取りたい**URL パス**を、別の方法(例: Web ダッシュボード)で定義することを想定しているためです。
+
+### ドキュメントの確認 { #check-the-docs }
+
+アプリを起動し、http://127.0.0.1:8000/docs にアクセスします。
+
+ドキュメントには通常の *path operations* に加えて、**webhooks** も表示されます:
+
+
diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md
index a78c3cb02..f7e340617 100644
--- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md
@@ -12,7 +12,7 @@ OpenAPIの「エキスパート」でなければ、これはおそらく必要
各オペレーションで一意になるようにする必要があります。
-{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
### *path operation関数* の名前をoperationIdとして使用する { #using-the-path-operation-function-name-as-the-operationid }
@@ -20,7 +20,7 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP
すべての *path operation* を追加した後に行うべきです。
-{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py39.py hl[2, 12:21, 24] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
/// tip | 豆知識
@@ -40,7 +40,7 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP
生成されるOpenAPIスキーマ(つまり、自動ドキュメント生成の仕組み)から *path operation* を除外するには、`include_in_schema` パラメータを使用して `False` に設定します。
-{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
## docstringによる説明の高度な設定 { #advanced-description-from-docstring }
@@ -92,7 +92,7 @@ OpenAPI仕様では parsed されず、直接 `bytes` として読み取られます。そして `magic_data_reader()` 関数が、何らかの方法でそれをパースする責務を担います。
+この例では、Pydanticモデルを一切宣言していません。実際、リクエストボディはJSONとして パース されず、直接 `bytes` として読み取られます。そして `magic_data_reader()` 関数が、何らかの方法でそれをパースする責務を担います。
それでも、リクエストボディに期待されるスキーマを宣言できます。
@@ -153,7 +153,7 @@ OpenAPI仕様では Starlette のドキュメントを参照してください。
diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md
index 7e83b9ffb..103e84c38 100644
--- a/docs/ja/docs/advanced/response-directly.md
+++ b/docs/ja/docs/advanced/response-directly.md
@@ -54,7 +54,7 @@
XMLを文字列にし、`Response` に含め、それを返します。
-{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
## 備考 { #notes }
diff --git a/docs/ja/docs/advanced/response-headers.md b/docs/ja/docs/advanced/response-headers.md
new file mode 100644
index 000000000..10aec7845
--- /dev/null
+++ b/docs/ja/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# レスポンスヘッダー { #response-headers }
+
+## `Response` パラメータを使う { #use-a-response-parameter }
+
+(Cookie と同様に)*path operation 関数*で `Response` 型のパラメータを宣言できます。
+
+そして、その*一時的*なレスポンスオブジェクトにヘッダーを設定できます。
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+その後は通常どおり、必要な任意のオブジェクト(`dict`、データベースモデルなど)を返せます。
+
+`response_model` を宣言している場合は、返したオブジェクトのフィルタと変換に引き続き使用されます。
+
+**FastAPI** はその*一時的*なレスポンスからヘッダー(Cookie やステータスコードも含む)を取り出し、`response_model` によってフィルタされた返却値を含む最終的なレスポンスに反映します。
+
+また、依存関係の中で `Response` パラメータを宣言し、その中でヘッダー(や Cookie)を設定することもできます。
+
+## `Response` を直接返す { #return-a-response-directly }
+
+`Response` を直接返す場合にもヘッダーを追加できます。
+
+[Response を直接返す](response-directly.md){.internal-link target=_blank} で説明したようにレスポンスを作成し、ヘッダーを追加のパラメータとして渡します:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | 技術詳細
+
+`from starlette.responses import Response` や `from starlette.responses import JSONResponse` を使うこともできます。
+
+**FastAPI** は、開発者であるあなたへの便宜として、`starlette.responses` と同じものを `fastapi.responses` として提供しています。しかし、利用可能なレスポンスの大半は直接 Starlette から来ています。
+
+また、`Response` はヘッダーや Cookie を設定するのによく使われるため、**FastAPI** は `fastapi.Response` でも提供しています。
+
+///
+
+## カスタムヘッダー { #custom-headers }
+
+独自のカスタムヘッダーは、`X-` プレフィックスを使って追加できることに注意してください。
+
+ただし、ブラウザのクライアントに見えるようにしたいカスタムヘッダーがある場合は、CORS 設定にそれらを追加する必要があります([CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank} を参照)。このとき、Starlette の CORS ドキュメントに記載の `expose_headers` パラメータを使用します。
diff --git a/docs/ja/docs/advanced/security/http-basic-auth.md b/docs/ja/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 000000000..7ee56a039
--- /dev/null
+++ b/docs/ja/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP Basic 認証 { #http-basic-auth }
+
+最もシンプルなケースでは、HTTP Basic 認証を利用できます。
+
+HTTP Basic 認証では、アプリケーションはユーザー名とパスワードを含むヘッダーを期待します。
+
+それを受け取れない場合、HTTP 401 "Unauthorized" エラーを返します。
+
+そして、値が `Basic` のヘッダー `WWW-Authenticate` を、任意の `realm` パラメータとともに返します。
+
+これにより、ブラウザは組み込みのユーザー名とパスワード入力プロンプトを表示します。
+
+その後、そのユーザー名とパスワードを入力すると、ブラウザはそれらをヘッダーに自動的に付与して送信します。
+
+## シンプルな HTTP Basic 認証 { #simple-http-basic-auth }
+
+- `HTTPBasic` と `HTTPBasicCredentials` をインポートします。
+- `HTTPBasic` を使って「`security` スキーム」を作成します。
+- その `security` を依存関係として path operation に使用します。
+- `HTTPBasicCredentials` 型のオブジェクトが返ります:
+ - 送信された `username` と `password` を含みます。
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+URL を最初に開こうとしたとき(またはドキュメントで「Execute」ボタンをクリックしたとき)、ブラウザはユーザー名とパスワードの入力を求めます:
+
+
+
+## ユーザー名の確認 { #check-the-username }
+
+より完全な例です。
+
+依存関係を使ってユーザー名とパスワードが正しいかを確認します。
+
+これには、Python 標準モジュール `secrets` を用いてユーザー名とパスワードを検証します。
+
+`secrets.compare_digest()` は `bytes` か、ASCII 文字(英語の文字)のみを含む `str` を受け取る必要があります。つまり、`Sebastián` のように `á` を含む文字ではそのままでは動作しません。
+
+これに対処するため、まず `username` と `password` を UTF-8 でエンコードして `bytes` に変換します。
+
+そのうえで、`secrets.compare_digest()` を使って、`credentials.username` が `"stanleyjobson"` であり、`credentials.password` が `"swordfish"` であることを確認します。
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+これは次のようなコードに相当します:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Return some error
+ ...
+```
+
+しかし `secrets.compare_digest()` を使うことで、「タイミング攻撃」と呼ばれる種類の攻撃に対して安全になります。
+
+### タイミング攻撃 { #timing-attacks }
+
+「タイミング攻撃」とは何でしょうか?
+
+攻撃者がユーザー名とパスワードを推測しようとしていると想像してください。
+
+そして、ユーザー名 `johndoe`、パスワード `love123` を使ってリクエストを送ります。
+
+その場合、アプリケーション内の Python コードは次のようなものと等価になります:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+しかし、Python は `johndoe` の最初の `j` と `stanleyjobson` の最初の `s` を比較した時点で、両者の文字列が同じでないと判断してすぐに `False` を返します。つまり「残りの文字を比較して計算資源を無駄にする必要はない」と考えるわけです。そしてアプリケーションは「ユーザー名またはパスワードが正しくありません」と返します。
+
+次に、攻撃者がユーザー名 `stanleyjobsox`、パスワード `love123` で試すとします。
+
+アプリケーションのコードは次のようになります:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+この場合、Python は `stanleyjobsox` と `stanleyjobson` の両方で `stanleyjobso` 全体を比較してから、文字列が同じでないと気づきます。したがって、「ユーザー名またはパスワードが正しくありません」と応答するまでに余分に数マイクロ秒かかります。
+
+#### 応答時間が攻撃者を助ける { #the-time-to-answer-helps-the-attackers }
+
+ここで、サーバーが「ユーザー名またはパスワードが正しくありません」というレスポンスを返すまでに、わずかに長い時間がかかったことに気づけば、攻撃者は何かしら正解に近づいた、すなわち先頭のいくつかの文字が正しかったことを知ることができます。
+
+すると、`johndoe` よりも `stanleyjobsox` に近いものを狙って再試行できます。
+
+#### 「プロ」レベルの攻撃 { #a-professional-attack }
+
+もちろん、攻撃者はこれらを手作業では行わず、プログラムを書いて、1 秒間に数千〜数百万回のテストを行うでしょう。そして 1 回に 1 文字ずつ正しい文字を見つけていきます。
+
+そうすることで、数分から数時間のうちに、攻撃者は私たちのアプリケーションの「助け」(応答にかかった時間)だけを利用して、正しいユーザー名とパスワードを推測できてしまいます。
+
+#### `secrets.compare_digest()` で対策 { #fix-it-with-secrets-compare-digest }
+
+しかし、私たちのコードでは実際に `secrets.compare_digest()` を使用しています。
+
+要するに、`stanleyjobsox` と `stanleyjobson` を比較するのにかかる時間は、`johndoe` と `stanleyjobson` を比較するのにかかる時間と同じになります。パスワードでも同様です。
+
+このように、アプリケーションコードで `secrets.compare_digest()` を使うと、この種の一連のセキュリティ攻撃に対して安全になります。
+
+### エラーを返す { #return-the-error }
+
+認証情報が不正であることを検出したら、ステータスコード 401(認証情報が提供されない場合と同じ)で `HTTPException` を返し、ブラウザに再度ログインプロンプトを表示させるためにヘッダー `WWW-Authenticate` を追加します:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/ja/docs/advanced/security/index.md b/docs/ja/docs/advanced/security/index.md
new file mode 100644
index 000000000..069e2686c
--- /dev/null
+++ b/docs/ja/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# 高度なセキュリティ { #advanced-security }
+
+## 追加機能 { #additional-features }
+
+[チュートリアル - ユーザーガイド: セキュリティ](../../tutorial/security/index.md){.internal-link target=_blank}で扱ったもの以外にも、セキュリティを扱うための追加機能がいくつかあります。
+
+/// tip | 豆知識
+
+次の節は必ずしも「高度」ではありません。
+
+あなたのユースケースでは、その中のいずれかに解決策があるかもしれません。
+
+///
+
+## まずチュートリアルを読む { #read-the-tutorial-first }
+
+以下の節は、すでにメインの[チュートリアル - ユーザーガイド: セキュリティ](../../tutorial/security/index.md){.internal-link target=_blank}を読んでいることを前提とします。
+
+いずれも同じ概念に基づいていますが、いくつかの追加機能を利用できます。
diff --git a/docs/ja/docs/advanced/security/oauth2-scopes.md b/docs/ja/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 000000000..7c6cfdbf0
--- /dev/null
+++ b/docs/ja/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2 のスコープ { #oauth2-scopes }
+
+OAuth2 のスコープは **FastAPI** で直接利用でき、シームレスに統合されています。
+
+これにより、OAuth2 標準に従った、よりきめ細かな権限システムを、OpenAPI 対応アプリケーション(および API ドキュメント)に統合できます。
+
+スコープ付きの OAuth2 は、Facebook、Google、GitHub、Microsoft、X (Twitter) など、多くの大手認証プロバイダで使われている仕組みです。ユーザーやアプリケーションに特定の権限を付与するために利用されます。
+
+「Facebook でログイン」「Google でログイン」「GitHub でログイン」「Microsoft でログイン」「X (Twitter) でログイン」するたびに、そのアプリケーションはスコープ付きの OAuth2 を使っています。
+
+この節では、同じスコープ付き OAuth2 を使って、**FastAPI** アプリケーションで認証と認可を管理する方法を見ていきます。
+
+/// warning | 注意
+
+これはやや高度な内容です。はじめたばかりであれば読み飛ばしても構いません。
+
+OAuth2 のスコープは必ずしも必要ではなく、認証と認可は好きなやり方で実装できます。
+
+ただし、スコープ付きの OAuth2 は、API(OpenAPI)や API ドキュメントにきれいに統合できます。
+
+とはいえ、これらのスコープやその他のセキュリティ/認可要件の適用は、必要に応じてコードの中で行う必要があります。
+
+多くの場合、スコープ付き OAuth2 はオーバースペックになりえます。
+
+それでも必要だと分かっている場合や、興味がある場合は、このまま読み進めてください。
+
+///
+
+## OAuth2 のスコープと OpenAPI { #oauth2-scopes-and-openapi }
+
+OAuth2 仕様では、「スコープ」は空白で区切られた文字列の一覧として定義されています。
+
+各文字列の内容は任意ですが、空白は含められません。
+
+これらのスコープは「権限」を表します。
+
+OpenAPI(例: API ドキュメント)では、「セキュリティスキーム」を定義できます。
+
+これらのセキュリティスキームの一つが OAuth2 を使う場合、スコープを宣言して利用できます。
+
+各「スコープ」は、ただの文字列(空白なし)です。
+
+通常、特定のセキュリティ権限を宣言するために使われます。例えば:
+
+- `users:read` や `users:write` は一般的な例です。
+- `instagram_basic` は Facebook / Instagram で使われています。
+- `https://www.googleapis.com/auth/drive` は Google で使われています。
+
+/// info | 情報
+
+OAuth2 において「スコープ」は、必要な特定の権限を宣言する単なる文字列です。
+
+`:` のような他の文字が含まれていても、URL であっても問題ありません。
+
+それらの詳細は実装依存です。
+
+OAuth2 にとっては、単に文字列に過ぎません。
+
+///
+
+## 全体像 { #global-view }
+
+まず、メインの**チュートリアル - ユーザーガイド**にある [OAuth2(パスワード[ハッシュ化あり])、Bearer と JWT トークン](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank} の例から変更される部分を、スコープ付き OAuth2 を使って手早く見てみましょう。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+では、これらの変更を一つずつ確認していきます。
+
+## OAuth2 のセキュリティスキーム { #oauth2-security-scheme }
+
+最初の変更点は、`me` と `items` の 2 つのスコープを持つ OAuth2 セキュリティスキームを宣言していることです。
+
+`scopes` パラメータは、各スコープをキー、その説明を値とする `dict` を受け取ります:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+これらのスコープを宣言しているため、ログイン/認可時に API ドキュメントに表示されます。
+
+そして、付与するスコープ(`me`、`items`)を選択できます。
+
+これは、Facebook、Google、GitHub などでログイン時に権限を付与する際と同じ仕組みです:
+
+
+
+## スコープ付きの JWT トークン { #jwt-token-with-scopes }
+
+次に、トークンの path operation を修正して、要求されたスコープを返すようにします。
+
+引き続き同じ `OAuth2PasswordRequestForm` を使用します。これには、リクエストで受け取った各スコープを含む、`str` の `list` である `scopes` プロパティが含まれます。
+
+そして、そのスコープを JWT トークンの一部として返します。
+
+/// danger | 警告
+
+簡単のため、ここでは受け取ったスコープをそのままトークンに追加しています。
+
+しかし、本番アプリケーションではセキュリティのため、ユーザーが実際に持つことができるスコープ、または事前に定義したスコープだけを追加するようにしてください。
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## path operation と依存関係でスコープを宣言 { #declare-scopes-in-path-operations-and-dependencies }
+
+ここでは、`/users/me/items/` の path operation が `items` スコープを必要とするように宣言します。
+
+そのために、`fastapi` から `Security` をインポートして使います。
+
+`Security` は(`Depends` と同様に)依存関係を宣言できますが、さらにスコープ(文字列)のリストを受け取る `scopes` パラメータも持ちます。
+
+この場合、`Security` に依存関数 `get_current_active_user` を渡します(`Depends` と同様です)。
+
+加えて、`items` という 1 つのスコープ(複数でも可)を含む `list` も渡します。
+
+依存関数 `get_current_active_user` は、`Depends` だけでなく `Security` でもサブ依存関係を宣言できます。自身のサブ依存関数(`get_current_user`)を宣言し、さらにスコープ要件を追加します。
+
+この場合、`me` スコープを要求します(複数のスコープも可)。
+
+/// note | 備考
+
+異なる場所で異なるスコープを追加する必要は必ずしもありません。
+
+ここでは、**FastAPI** が異なるレベルで宣言されたスコープをどのように扱うかを示すためにそうしています。
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | 技術詳細
+
+`Security` は実際には `Depends` のサブクラスで、後述する追加パラメータが 1 つあるだけです。
+
+しかし `Depends` の代わりに `Security` を使うことで、**FastAPI** はセキュリティスコープを宣言・内部利用でき、OpenAPI で API をドキュメント化できると判断します。
+
+なお、`fastapi` から `Query`、`Path`、`Depends`、`Security` などをインポートする際、それらは実際には特殊なクラスを返す関数です。
+
+///
+
+## `SecurityScopes` を使う { #use-securityscopes }
+
+次に、依存関数 `get_current_user` を更新します。
+
+これは上記の依存関係から使用されます。
+
+ここで、先ほど作成した同じ OAuth2 スキームを依存関係(`oauth2_scheme`)として宣言して使います。
+
+この依存関数自体はスコープ要件を持たないため、`oauth2_scheme` には `Depends` を使えます。セキュリティスコープを指定する必要がない場合は `Security` を使う必要はありません。
+
+さらに、`fastapi.security` からインポートする特別な型 `SecurityScopes` のパラメータを宣言します。
+
+この `SecurityScopes` クラスは `Request` に似ています(`Request` はリクエストオブジェクトを直接取得するために使いました)。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## `scopes` を使う { #use-the-scopes }
+
+パラメータ `security_scopes` は `SecurityScopes` 型になります。
+
+このオブジェクトは、自身およびこれをサブ依存として使うすべての依存関係で要求されるスコープを含む `scopes` プロパティ(リスト)を持ちます。つまり、すべての「依存元」... 少し分かりにくいかもしれませんが、後で再度説明します。
+
+`security_scopes`(`SecurityScopes` クラスのインスタンス)は、要求されたスコープを空白で連結した 1 つの文字列を返す `scope_str` も提供します(これを使います)。
+
+後で複数箇所で再利用(raise)できるように、`HTTPException` を 1 つ作成します。
+
+この例外には、要求されたスコープがあればそれらを空白区切りの文字列(`scope_str` を使用)として含めます。このスコープ文字列は `WWW-Authenticate` ヘッダに入れます(仕様の一部です)。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## `username` とデータ構造の検証 { #verify-the-username-and-data-shape }
+
+`username` を取得できていることを確認し、スコープを取り出します。
+
+そして、そのデータを Pydantic モデルで検証します(`ValidationError` 例外を捕捉)。JWT トークンの読み取りや Pydantic によるデータ検証でエラーが発生した場合は、先ほど作成した `HTTPException` を送出します。
+
+そのために、Pydantic モデル `TokenData` に新しいプロパティ `scopes` を追加します。
+
+Pydantic でデータを検証することで、例えばスコープは `str` の `list`、`username` は `str` といった、正確な型になっていることを保証できます。
+
+そうしておけば、例えば誤って `dict` などが入って後でアプリケーションを破壊してしまい、セキュリティリスクになる、といった事態を避けられます。
+
+また、その `username` を持つユーザーが存在することも確認し、存在しなければ、やはり先ほどの例外を送出します。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## `scopes` の検証 { #verify-the-scopes }
+
+この依存関数およびすべての依存元(path operation を含む)が要求するすべてのスコープが、受け取ったトークンに含まれていることを検証し、含まれていなければ `HTTPException` を送出します。
+
+そのために、これらすべてのスコープを `str` の `list` として含む `security_scopes.scopes` を使います。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## 依存関係ツリーとスコープ { #dependency-tree-and-scopes }
+
+依存関係ツリーとスコープをもう一度見てみましょう。
+
+`get_current_active_user` 依存関係は `get_current_user` をサブ依存として持つため、`get_current_active_user` で宣言された `"me"` スコープは、`get_current_user` に渡される `security_scopes.scopes` の必須スコープ一覧に含まれます。
+
+path operation 自体も `"items"` スコープを宣言するため、これも `get_current_user` に渡される `security_scopes.scopes` に含まれます。
+
+依存関係とスコープの階層は次のようになります:
+
+- *path operation* `read_own_items` には:
+ - 依存関係に対して必須スコープ `["items"]` がある:
+ - `get_current_active_user`:
+ - 依存関数 `get_current_active_user` には:
+ - 依存関係に対して必須スコープ `["me"]` がある:
+ - `get_current_user`:
+ - 依存関数 `get_current_user` には:
+ - 自身に必須スコープはない。
+ - `oauth2_scheme` を使う依存関係がある。
+ - `SecurityScopes` 型の `security_scopes` パラメータがある:
+ - この `security_scopes` パラメータは、上で宣言されたすべてのスコープを含む `list` を持つ `scopes` プロパティを持つ。したがって:
+ - *path operation* `read_own_items` では、`security_scopes.scopes` は `["me", "items"]` を含む。
+ - *path operation* `read_users_me` では、`security_scopes.scopes` は `["me"]` を含む。これは依存関係 `get_current_active_user` に宣言されているため。
+ - *path operation* `read_system_status` では、`security_scopes.scopes` は `[]`(空)になる。`scopes` を持つ `Security` を宣言しておらず、その依存関係 `get_current_user` も `scopes` を宣言していないため。
+
+/// tip | 豆知識
+
+重要で「魔法のよう」な点は、`get_current_user` が path operation ごとに異なる `scopes` のリストをチェックすることになる、ということです。
+
+それは、それぞれの path operation と、その path operation の依存関係ツリー内の各依存関係で宣言された `scopes` によって決まります。
+
+///
+
+## `SecurityScopes` の詳細 { #more-details-about-securityscopes }
+
+`SecurityScopes` はどの地点でも、複数箇所でも使えます。「ルート」の依存関係である必要はありません。
+
+常に、その時点の `Security` 依存関係と、**その特定の** path operation と **その特定の** 依存関係ツリーにおける、すべての依存元で宣言されたセキュリティスコープを持ちます。
+
+`SecurityScopes` には依存元で宣言されたすべてのスコープが入るため、トークンが必要なスコープを持っているかどうかを中央の依存関数で検証し、path operation ごとに異なるスコープ要件を宣言する、といった使い方ができます。
+
+これらは path operation ごとに独立して検証されます。
+
+## チェック { #check-it }
+
+API ドキュメントを開くと、認証して、許可するスコープを指定できます。
+
+
+
+どのスコープも選択しない場合は「認証済み」にはなりますが、`/users/me/` や `/users/me/items/` にアクセスしようとすると、権限が不足しているというエラーになります。`/status/` には引き続きアクセスできます。
+
+`me` スコープだけを選択し、`items` スコープを選択しない場合は、`/users/me/` にはアクセスできますが、`/users/me/items/` にはアクセスできません。
+
+これは、ユーザーがアプリケーションに与えた権限の範囲に応じて、サードパーティアプリケーションがこれらの path operation のいずれかに、ユーザーから提供されたトークンでアクセスしようとしたときに起こる動作です。
+
+## サードパーティ統合について { #about-third-party-integrations }
+
+この例では、OAuth2 の「password」フローを使用しています。
+
+これは、(おそらく自前のフロントエンドで)自分たちのアプリケーションにログインする場合に適しています。
+
+自分たちで管理しているため、`username` と `password` を受け取る相手を信頼できるからです。
+
+しかし、他者が接続する OAuth2 アプリケーション(Facebook、Google、GitHub などに相当する認証プロバイダ)を構築する場合は、他のいずれかのフローを使用すべきです。
+
+最も一般的なのは implicit フローです。
+
+最も安全なのは code フローですが、手順が多く実装がより複雑です。複雑なため、多くのプロバイダは結局 implicit フローを推奨することがあります。
+
+/// note | 備考
+
+各認証プロバイダがフローに独自の名称を付け、自社のブランドの一部にするのは一般的です。
+
+しかし、最終的には同じ OAuth2 標準を実装しています。
+
+///
+
+**FastAPI** には、これらすべての OAuth2 認証フロー向けのユーティリティが `fastapi.security.oauth2` に含まれています。
+
+## デコレータ `dependencies` での `Security` { #security-in-decorator-dependencies }
+
+デコレータの `dependencies` パラメータに `Depends` の `list` を定義できるのと同様([path operation デコレータでの依存関係](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 参照)、ここで `scopes` を指定した `Security` も使用できます。
diff --git a/docs/ja/docs/advanced/settings.md b/docs/ja/docs/advanced/settings.md
new file mode 100644
index 000000000..5508ad6d9
--- /dev/null
+++ b/docs/ja/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# 設定と環境変数 { #settings-and-environment-variables }
+
+多くの場合、アプリケーションは外部の設定や構成を必要とします。たとえば、シークレットキー、データベース認証情報、メールサービスの認証情報などです。
+
+これらの設定の多くは可変(変更されうる)で、データベースのURLのようなものがあります。また、多くはシークレットのように機微な情報です。
+
+そのため、アプリケーションが読み取る環境変数で提供するのが一般的です。
+
+/// tip | 豆知識
+
+環境変数について理解するには、[環境変数](../environment-variables.md){.internal-link target=_blank}を参照してください。
+
+///
+
+## 型とバリデーション { #types-and-validation }
+
+これらの環境変数は Python の外部にあり、他のプログラムやシステム全体(Linux、Windows、macOS といった異なるOSを含む)と互換性が必要なため、文字列テキストのみを扱えます。
+
+つまり、Python で環境変数から読み取られる値はすべて `str` になり、他の型への変換やバリデーションはコードで行う必要があります。
+
+## Pydantic の `Settings` { #pydantic-settings }
+
+幸いなことに、Pydantic には環境変数から来る設定を扱うための優れたユーティリティがあり、Pydantic: Settings management で提供されています。
+
+### `pydantic-settings` のインストール { #install-pydantic-settings }
+
+まず、[仮想環境](../virtual-environments.md){.internal-link target=_blank}を作成して有効化し、`pydantic-settings` パッケージをインストールします:
+
+
+
+次に、サブアプリケーションのドキュメント http://127.0.0.1:8000/subapi/docs を開きます。
+
+サブアプリケーション用の自動 API ドキュメントが表示され、そのアプリ自身の path operation のみが、正しいサブパス接頭辞 `/subapi` の下で表示されます:
+
+
+
+どちらの UI でも操作すれば正しく動作します。ブラウザがそれぞれのアプリ/サブアプリと通信できるためです。
+
+### 技術詳細: `root_path` { #technical-details-root-path }
+
+上記のようにサブアプリケーションをマウントすると、FastAPI は ASGI 仕様の `root_path` と呼ばれる仕組みを使って、そのサブアプリケーションへのマウントパスを伝播します。
+
+このため、サブアプリケーションはドキュメント UI でそのパス接頭辞を使用すべきことを認識できます。
+
+さらに、サブアプリケーション自身が別のサブアプリケーションをマウントしていても問題ありません。FastAPI がこれらの `root_path` をすべて自動的に処理するためです。
+
+`root_path` の詳細や明示的な指定方法については、[プロキシの背後で](behind-a-proxy.md){.internal-link target=_blank} の節で学べます。
diff --git a/docs/ja/docs/advanced/templates.md b/docs/ja/docs/advanced/templates.md
new file mode 100644
index 000000000..3c4827b88
--- /dev/null
+++ b/docs/ja/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# テンプレート { #templates }
+
+**FastAPI** では任意のテンプレートエンジンを使用できます。
+
+Flask などでも使われている Jinja2 が一般的な選択肢です。
+
+Starlette によって提供され、**FastAPI** アプリで直接使える、簡単に設定できるユーティリティがあります。
+
+## 依存関係のインストール { #install-dependencies }
+
+[仮想環境](../virtual-environments.md){.internal-link target=_blank} を作成して有効化し、`jinja2` をインストールします:
+
+
-料金を支払います💸。
+やがてあなたの番になり、好きな人と自分のために、とても豪華なハンバーガーを2つ注文します。🍔🍔
-レジ係💁はキッチンの男👨🍳に向かって、あなたのハンバーガー🍔を準備しなければならないと伝えるために何か言いました (彼は現在、前のお客さんの商品を準備していますが)。
+
-レジ係💁はあなたに番号札を渡します。
+レジ係はキッチンの料理人に、あなたのハンバーガーを用意するよう声をかけます (料理人はいま前のお客さんの分を作っています)。
-待っている間、好きな人😍と一緒にテーブルを選んで座り、好きな人😍と長い間話をします (注文したハンバーガーは非常に豪華で、準備に少し時間がかかるので✨🍔✨)。
+
-ハンバーガー🍔を待ちながら好きな人😍とテーブルに座っている間、あなたの好きな人がなんて素晴らしく、かわいくて頭がいいんだと✨😍✨惚れ惚れしながら時間を費やすことができます。
+支払いをします。💸
-好きな人😍と話しながら待っている間、ときどき、カウンターに表示されている番号をチェックして、自分の番かどうかを確認します。
+レジ係はあなたに番号札を渡します。
-その後、ついにあなたの番になりました。カウンターに行き、ハンバーガー🍔を手に入れてテーブルに戻ります。
+
-あなたとあなたの好きな人😍はハンバーガー🍔を食べて、楽しい時間を過ごします✨。
+待っている間、好きな人とテーブルに移動して座り、(豪華なハンバーガーは時間がかかるので) しばらく話します。
+
+テーブルで待っている間、好きな人がどれだけ素敵で、かわいくて、頭が良いかを眺めて時間を過ごせます ✨😍✨。
+
+
+
+時々カウンターの表示を見て、自分の番号になっているか確認します。
+
+やがてあなたの番になります。カウンターに行き、ハンバーガーを受け取り、テーブルに戻ります。
+
+
+
+あなたと好きな人はハンバーガーを食べて、楽しい時間を過ごします。✨
+
+
+
+/// info | 情報
+
+美しいイラストは Ketrina Thompson によるものです。🎨
+
+///
---
-上記のストーリーで、あなたがコンピュータ/プログラム🤖だと想像してみてください。
+この物語で、あなた自身がコンピュータ/プログラム 🤖 だと想像してみてください。
-列にいる間、あなたはアイドル状態です😴。何も「生産的」なことをせず、ただ自分の番を待っています。しかし、レジ係💁は注文を受け取るだけなので (商品の準備をしているわけではない)、列は高速です。したがって、何も問題ありません。
+列にいる間は、何も「生産的」なことをせず、自分の番を待つだけのアイドル状態 😴 です。ただしレジ係は注文を取るだけ (作りはしない) なので列は速く進み、問題ありません。
-それから、あなたの番になったら、実に「生産的な」作業を行います🤓、メニューを確認し、欲しいものを決め、好きな人😍の欲しいものを聞き、料金を支払い💸、現金またはカードを正しく渡したか確認し、正しく清算されたことを確認し、注文が正しく通っているかなどを確認します。
+あなたの番になると、実際に「生産的」な作業をします。メニューを見て注文を決め、好きな人の分も確認し、支払い、正しい紙幣/カードを渡したか、正しく決済されたか、注文内容が正しいかなどを確認します。
-しかし、ハンバーガー🍔をまだできていないので、ハンバーガーの準備ができるまで待機🕙する必要があるため、レジ係💁との作業は「一時停止⏸」になります。
+しかし、ハンバーガーはまだ出来上がっていないので、レジ係とのやり取りは「一時停止」⏸ になります。ハンバーガーができるまで待つ 🕙 必要があるからです。
-しかし、カウンターから離れて、番号札を持ってテーブルに座っているときは、注意を好きな人😍に切り替えて🔀、その上で「仕事⏯🤓」を行なえます。その後、好きな人😍といちゃつくかのような、非常に「生産的な🤓」ことを再び行います。
+ただし、番号札を持ってカウンターから離れテーブルに座れば、注意を好きな人に切り替え 🔀、「その作業」⏯ 🤓 に取り組めます。好きな人といちゃつくという、とても「生産的」🤓 なことがまたできます。
-次に、レジ係💁は、「ハンバーガーの準備ができました🍔」と言って、カウンターのディスプレイに番号を表示しますが、表示番号があなたの番号に変わっても、すぐに狂ったように飛んで行くようなことはありません。あなたは自分の番号札を持っていって、他の人も自分の番号札があるので、あなたのハンバーガー🍔を盗む人がいないことは知っています。
+レジ係 💁 がカウンターの表示にあなたの番号を出して「ハンバーガーができました」と知らせても、あなたは表示が切り替わった瞬間に飛び跳ねたりしません。自分の番号札があり、他の人にもそれぞれ番号札があるので、ハンバーガーを盗られることはないと知っているからです。
-なので、あなたは好きな人😍が話し終えるのを待って (現在の仕事⏯ / 処理中のタスクを終了します🤓)、優しく微笑んで、ハンバーガーを貰ってくるねと言います⏸。
+だから、好きな人の話が終わるのを待ち (現在の作業 ⏯ / 処理中のタスクを完了し 🤓)、微笑んで「ハンバーガー取ってくるね」と言います ⏸。
-次に、カウンターへ、いまから完了する最初のタスク⏯へ向かい、ハンバーガー🍔を受け取り、感謝の意を表して、テーブルに持っていきます。これで、カウンターとのやり取りのステップ/タスクが完了しました⏹。これにより、「ハンバーガーを食べる🔀⏯」という新しいタスクが作成されます。しかし、前の「ハンバーガーを取得する」というタスクは終了しました⏹。
+それからカウンターへ行き 🔀、いま完了した初期のタスク ⏯ に戻って、ハンバーガーを受け取り、礼を言ってテーブルに持っていきます。これでカウンターとのやり取りというステップ/タスクは完了 ⏹ です。その結果として「ハンバーガーを食べる」🔀 ⏯ という新しいタスクが生まれますが、先の「ハンバーガーを受け取る」タスクは完了 ⏹ しています。
-### 並列ハンバーガー
+### 並列ハンバーガー { #parallel-burgers }
-これらが「並行ハンバーガー」ではなく、「並列ハンバーガー」であるとしましょう。
+今度は、これが「並行ハンバーガー」ではなく「並列ハンバーガー」だと想像しましょう。
-あなたは好きな人😍と並列ファストフード🍔を買おうとしています。
+あなたは好きな人と「並列」ファストフードを買いに行きます。
-列に並んでいますが、何人かの料理人兼、レジ係 (8人としましょう) 👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳があなたの前にいる人達の注文を受けつけています。
+複数のレジ係 (例えば 8 人) が同時に料理人でもあり、前の人たちの注文を受けています。
-8人のレジ係がそれぞれ自分で注文を受けるや否や、次の注文を受ける前にハンバーガーを準備するので、あなたの前の人達はカウンターを離れずに、ハンバーガー🍔ができるのを待っています🕙。
+8 人のレジ係はそれぞれ、次の注文を取る前にすぐに調理に取りかかるため、あなたの前の人たちはカウンターを離れず、ハンバーガーができるのを待っています。
-それからいよいよあなたの番になり、好きな人😍と自分のために、2つの非常に豪華なハンバーガー🍔を注文します。
+
-料金を支払います💸。
+ようやくあなたの番になり、好きな人と自分のために豪華なハンバーガーを 2 つ注文します。
-レジ係はキッチンに行きます👨🍳。
+支払いをします 💸。
-あなたはカウンターの前に立って待ちます🕙。番号札がないので誰もあなたよりも先にハンバーガー🍔を取らないようにします。
+
-あなたと好きな人😍は忙しいので、誰もあなたの前に来させませんし、あなたのハンバーガーが到着したとき🕙に誰にも取ることを許しません。あなたは好きな人に注意を払えません😞。
+レジ係はキッチンに向かいます。
-これは「同期」作業であり、レジ係/料理人👨🍳と「同期」します。レジ係/料理人👨🍳がハンバーガー🍔を完成させてあなたに渡すまで待つ🕙必要があり、ちょうどその完成の瞬間にそこにいる必要があります。そうでなければ、他の誰かに取られるかもしれません。
+番号札がないため、他の誰かに先に取られないよう、カウンターの前で立って待ちます 🕙。
-その後、カウンターの前で長い時間待ってから🕙、ついにレジ係/料理人👨🍳がハンバーガー🍔を渡しに戻ってきます。
+
-ハンバーガー🍔を取り、好きな人😍とテーブルに行きます。
+あなたと好きな人は、誰にも割り込まれずハンバーガーが来たらすぐ受け取れるよう見張っているので、好きな人に注意を向けられません。😞
-ただ食べるだけ、それでおしまいです。🍔⏹。
+これは「同期」的な作業です。レジ係/料理人 👨🍳 と「同期」しています。レジ係/料理人 👨🍳 がハンバーガーを作り終えて手渡すその瞬間に、待って 🕙 その場にいなければなりません。そうでないと他の誰かに取られるかもしれません。
-ほとんどの時間、カウンターの前で待つのに費やされていたので🕙、あまり話したりいちゃつくことはありませんでした😞。
+
+
+長い時間 🕙 カウンター前で待った後、ようやくレジ係/料理人 👨🍳 がハンバーガーを持って戻ってきます。
+
+
+
+ハンバーガーを受け取り、好きな人とテーブルに行きます。
+
+食べて、おしまいです。⏹
+
+
+
+ほとんどの時間をカウンター前で待つ 🕙 のに費やしたため、あまり話したり、いちゃついたりできませんでした。😞
+
+/// info | 情報
+
+美しいイラストは Ketrina Thompson によるものです。🎨
+
+///
---
-この並列ハンバーガーのシナリオでは、あなたは2つのプロセッサを備えたコンピュータ/プログラム🤖 (あなたとあなたの好きな人😍) であり、両方とも待機🕙していて、彼らは「カウンターで待機🕙」することに専念しています⏯。
+この「並列ハンバーガー」のシナリオでは、あなたは 2 つのプロセッサ (あなたと好きな人) を持つコンピュータ/プログラム 🤖 で、どちらも長い間 🕙「カウンターでの待機」に注意 ⏯ を専念しています。
-ファストフード店には8つのプロセッサ (レジ係/料理人) 👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳があります。一方、並行ハンバーガー店には2人 (レジ係と料理人) 💁👨🍳しかいなかったかもしれません。
+ファストフード店には 8 個のプロセッサ (レジ係/料理人) があります。一方、並行ハンバーガーの店には (レジ係 1、人、料理人 1 人の) 2 個しかなかったかもしれません。
-しかし、それでも、最終的な体験は最高ではありません😞。
+それでも、最終的な体験は最良とは言えません。😞
---
-これは、ハンバーガー🍔の話と同等な話になります。
+これはハンバーガーにおける並列版の物語です。🍔
より「現実的な」例として、銀行を想像してみてください。
-最近まで、ほとんどの銀行は複数の窓口👨💼👨💼👨💼👨💼に、行列🕙🕙🕙🕙🕙🕙🕙🕙ができていました。
+つい最近まで、ほとんどの銀行には複数の窓口係 👨💼👨💼👨💼👨💼 と長い行列 🕙🕙🕙🕙🕙🕙🕙🕙 がありました。
-すべての窓口で、次々と、一人の客とすべての作業を行います👨💼⏯.
+各窓口係が、一人ずつ、すべての作業を順番に行います 👨💼⏯。
-その上、長時間、列に並ばなければいけません🕙。そうしないと、順番が回ってきません。
+そして、長時間 🕙 行列で待たなければ順番を失います。
-銀行🏦での用事にあなたの好きな人😍を連れて行きたくはないでしょう。
+銀行の用事 🏦 に、好きな人 😍 を連れて行きたいとは思わないでしょう。
-### ハンバーガーのまとめ
+### ハンバーガーのまとめ { #burger-conclusion }
-この「好きな人とのファストフードハンバーガー」のシナリオでは、待機🕙が多いため、並行システム⏸🔀⏯を使用する方がはるかに理にかなっています。
+この「好きな人とファストフード」のシナリオでは、待ち時間 🕙 が多いため、並行システム ⏸🔀⏯ を使う方がはるかに理にかなっています。
-これは、ほとんどのWebアプリケーションに当てはまります。
+これは、ほとんどの Web アプリケーションにも当てはまります。
-多くのユーザーがいますが、サーバーは、あまり強くない回線でのリクエストの送信を待機🕙しています。
+とても多くのユーザーがいますが、サーバは彼らのあまり速くない回線からリクエストが届くのを待ち 🕙、
-そして、レスポンスが返ってくるのをもう一度待機🕙します。
+その後、レスポンスが戻ってくるのをまた待ちます 🕙。
-この「待機🕙」はマイクロ秒単位ですが、それでも、すべて合算すると、最終的にはかなり待機することになります。
+この「待ち」🕙 はマイクロ秒単位で測られますが、すべてを合計すると、結局かなりの待ちになります。
-これが、Web APIへの非同期⏸🔀⏯コードの利用が理にかなっている理由です。
+だからこそ、Web API には非同期 ⏸🔀⏯ コードを使うのが理にかなっています。
-ほとんどの既存の人気のあるPythonフレームワーク (FlaskやDjangoを含む) は、Pythonの新しい非同期機能ができる前に作成されました。したがって、それらをデプロイする方法は、並列実行と、新機能ほど強力ではない古い形式の非同期実行をサポートします。
+これが、NodeJS を人気にした要因 (NodeJS 自体は並列ではありません) であり、プログラミング言語としての Go の強みでもあります。
-しかし、WebSocketのサポートを追加するために、非同期Web Python (ASGI) の主な仕様はDjangoで開発されました。
+そして、それが **FastAPI** で得られるパフォーマンスの水準です。
-そのような非同期性がNodeJSを人気にした理由です (NodeJSは並列ではありませんが)。そして、プログラミング言語としてのGoの強みでもあります。
+さらに、並列性と非同期性を同時に活用できるため、テストされた多くの NodeJS フレームワークより高い性能を発揮し、C に近いコンパイル言語である Go と同等の性能になります (すべて Starlette のおかげです)。
-そして、それは**FastAPI**で得られるパフォーマンスと同じレベルです。
+### 並行処理は並列処理より優れている? { #is-concurrency-better-than-parallelism }
-また、並列処理と非同期処理を同時に実行できるため、テスト済みのほとんどのNodeJSフレームワークよりも高く、Goと同等のパフォーマンスが得られます。Goは、Cに近いコンパイル言語です (Starletteに感謝します)。
+いいえ!それがこの話の教訓ではありません。
-### 並行は並列よりも優れていますか?
+並行処理は並列処理とは異なります。そして多くの待ち時間を伴う**特定の**シナリオでは優れています。そのため、一般に Web アプリ開発では並列処理よりはるかに適しています。しかし、すべてに対して最良というわけではありません。
-いや!それはこの話の教訓ではありません。
+バランスを取るために、次の短い物語を想像してください。
-並行処理は並列処理とは異なります。多くの待機を伴う**特定の**シナリオに適しています。そのため、一般に、Webアプリケーション開発では並列処理よりもはるかに優れています。しかし、すべてに対してより良いというわけではありません。
+> 大きくて汚れた家を掃除しなければならない。
-なので、バランスをとるために、次の物語を想像して下さい:
-
-> あなたは大きくて汚れた家を掃除する必要があります。
-
-*はい、以上です*。
+*はい、これで物語は全部です*。
---
-待機🕙せず、家の中の複数の場所でたくさんの仕事をするだけです。
+どこにも待ち 🕙 はなく、家の複数箇所で大量の作業があるだけです。
-あなたはハンバーガーの例のように、最初はリビングルーム、次にキッチンのように順番にやっていくことができますが、何かを待機🕙しているわけではなく、ただひたすらに掃除をするだけで、順番は何にも影響しません。
+ハンバーガーの例のように順番を決めて、まずリビング、次にキッチン、と進めてもよいのですが、何かを待つ 🕙 わけではなく、ひたすら掃除するだけなので、順番は何も影響しません。
-順番の有無に関係なく (並行に) 同じ時間がかかり、同じ量の作業が行われることになるでしょう。
+順番の有無 (並行性の有無) に関係なく、終了までに同じ時間がかかり、同じ作業量をこなすことになります。
-しかし、この場合、8人の元レジ係/料理人/現役清掃員👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳を手配できて、それぞれ (さらにあなたも) が家の別々の場所を掃除できれば、追加の助けを借りて、すべての作業を**並列**に行い、はるかに早く終了できるでしょう。
+しかしこの場合、8 人の元レジ係/料理人/現清掃員を連れてきて、それぞれ (あなたも加えて) 家の別々のエリアを掃除できれば、**並列** に作業でき、より早く終えられます。
-このシナリオでは、清掃員 (あなたを含む) のそれぞれがプロセッサとなり、それぞれの役割を果たします。
+このシナリオでは、各清掃員 (あなたを含む) がプロセッサであり、それぞれが自分の役割を果たします。
-また、実行時間のほとんどは (待機ではなく) 実際の作業に費やされ、コンピュータでの作業はCPUによって行われます。これらの問題は「CPUバウンド」と言います。
+そして実行時間の大半は (待ちではなく) 実作業が占め、コンピュータでの作業は CPU によって行われます。これらの問題は「CPU バウンド」と呼ばれます。
---
-CPUバウンド操作の一般的な例は、複雑な数学処理が必要なものです。
+CPU バウンドな操作の一般的な例は、複雑な数値処理が必要なものです。
例えば:
* **オーディオ** や **画像処理**。
-* **コンピュータビジョン**: 画像は数百万のピクセルで構成され、各ピクセルには3つの値/色があり、通常、これらのピクセルで何かを同時に計算する必要がある処理。
-* **機械学習**: 通常、多くの「行列」と「ベクトル」の乗算が必要です。巨大なスプレッドシートに数字を入れて、それを同時に全部掛け合わせることを考えてみてください。
-* **ディープラーニング**: これは機械学習のサブフィールドであるため、同じことが当てはまります。乗算する数字がある単一のスプレッドシートではなく、それらの膨大な集合で、多くの場合、それらのモデルを構築および/または使用するために特別なプロセッサを使用します。
+* **コンピュータビジョン**: 画像は数百万のピクセルで構成され、各ピクセルには 3 つの値/色があり、通常、それらのピクセル上で同時に何かを計算する必要があります。
+* **機械学習**: 多くの「行列」や「ベクトル」の乗算が必要になります。巨大なスプレッドシートに数字が入っていて、それらを同時にすべて掛け合わせることを想像してください。
+* **ディープラーニング**: 機械学習のサブフィールドなので同様です。掛け合わせる数字が 1 つのスプレッドシートではなく膨大な集合であり、多くの場合、それらのモデルを構築/利用するための特別なプロセッサを使います。
-### 並行処理 + 並列処理: Web + 機械学習
+### 並行処理 + 並列処理: Web + 機械学習 { #concurrency-parallelism-web-machine-learning }
-**FastAPI**を使用すると、Web開発で非常に一般的な並行処理 (NodeJSの主な魅力と同じもの) を利用できます。
+**FastAPI** では、Web 開発で非常に一般的な並行処理 (NodeJS の主な魅力と同じ) を活用できます。
-ただし、機械学習システムのような **CPUバウンド** ワークロードに対して、並列処理とマルチプロセッシング (複数のプロセスが並列で実行される) の利点を活用することもできます。
+同時に、機械学習システムのような **CPU バウンド** なワークロードに対して、並列処理やマルチプロセッシング (複数プロセスの並列実行) の利点も活用できます。
-さらに、Pythonが**データサイエンス**、機械学習、特にディープラーニングの主要言語であるという単純な事実により、FastAPIはデータサイエンス/機械学習のWeb APIおよびアプリケーション (他の多くのアプリケーションとの) に非常によく適合しています。
+さらに、Python が **データサイエンス**、機械学習、特にディープラーニングの主要言語であるという事実も相まって、FastAPI はデータサイエンス/機械学習の Web API やアプリケーション (ほか多数) に非常に適しています。
-本番環境でこの並列処理を実現する方法については、[デプロイ](deployment/index.md){.internal-link target=_blank}に関するセクションを参照してください。
+本番環境でこの並列性を実現する方法は、[デプロイ](deployment/index.md){.internal-link target=_blank} のセクションを参照してください。
-## `async` と `await`
+## `async` と `await` { #async-and-await }
-現代的なバージョンのPythonには、非同期コードを定義する非常に直感的な方法があります。これにより、通常の「シーケンシャル」コードのように見え、適切なタイミングで「待機」します。
+モダンな Python には、非同期コードをとても直感的に定義する方法があります。これにより、通常の「シーケンシャル」なコードのように書けて、適切なタイミングで「待ち」を行ってくれます。
-結果を返す前に待機する必要があり、これらの新しいPython機能をサポートする操作がある場合は、次のようにコーディングできます。
+結果を返す前に待ちが必要で、これらの新しい Python 機能をサポートしている操作がある場合、次のように書けます。
```Python
burgers = await get_burgers(2)
```
-カギは `await` です。結果を `burgers`に保存する前に、`get_burgers(2)`の処理🕙の完了を待つ⏸必要があることをPythonに伝えます。これでPythonは、その間に (別のリクエストを受信するなど) 何か他のことができる🔀⏯ことを知ります。
+ここでの鍵は `await` です。`burgers` に結果を保存する前に、`get_burgers(2)` がやるべきことを終えるのを ⏸ 待つ 🕙 ように Python に伝えます。これにより Python は、その間に (別のリクエストを受け取るなど) ほかのことを 🔀 ⏯ できると分かります。
-`await` が機能するためには、非同期処理をサポートする関数内にある必要があります。これは、`async def` で関数を宣言するだけでよいです:
+`await` が機能するには、この非同期性をサポートする関数の内部でなければなりません。そのためには `async def` で宣言します:
```Python hl_lines="1"
async def get_burgers(number: int):
- # ハンバーガーを作成するために非同期処理を実行
+ # ハンバーガーを作るために非同期の処理を行う
return burgers
```
-...`def` のかわりに:
+...`def` の代わりに:
```Python hl_lines="2"
-# 非同期ではない
+# これは非同期ではない
def get_sequential_burgers(number: int):
- # ハンバーガーを作成するためにシーケンシャルな処理を実行
+ # ハンバーガーを作るためにシーケンシャルな処理を行う
return burgers
```
-`async def` を使用すると、Pythonにその関数内で `await` 式 (その関数の実行を「一時停止⏸」し、結果が戻るまで他の何かを実行🔀する) を認識しなければならないと伝えることができます。
-`async def` 関数を呼び出すときは、「await」しなければなりません。したがって、これは機能しません:
+`async def` を使うと、Python はその関数内で `await` 式に注意し、関数の実行を「一時停止」⏸ してほかのことをしに行き 🔀、戻ってくることができると分かります。
+
+`async def` な関数を呼ぶときは「await」しなければなりません。したがって、次は動きません:
```Python
-# get_burgersはasync defで定義されているので動作しない
+# 動きません。get_burgers は async def で定義されています
burgers = get_burgers(2)
```
---
-したがって、 `await` で呼び出すことができるライブラリを使用している場合は、次のように `async def` を使用して、それを使用する*path operation 関数*を作成する必要があります:
+そのため、`await` で呼べると謳っているライブラリを使っている場合は、それを使う *path operation 関数* を `async def` で作る必要があります。例えば:
```Python hl_lines="2-3"
@app.get('/burgers')
@@ -314,86 +349,96 @@ async def read_burgers():
return burgers
```
-### より発展的な技術詳細
+### より発展的な技術詳細 { #more-technical-details }
-`await` は `async def` で定義された関数内でのみ使用できることがわかったかと思います。
+`await` は `async def` で定義された関数の内部でしか使えないことに気づいたかもしれません。
-しかし同時に、`async def` で定義された関数は「awaitされる」必要があります。なので、`async def` を持つ関数は、`async def` で定義された関数内でのみ呼び出せます。
+同時に、`async def` で定義された関数は「await」される必要があります。つまり、`async def` を持つ関数は、やはり `async def` で定義された関数の内部からしか呼べません。
-では、このニワトリと卵の問題について、最初の `async` 関数をどのように呼び出すのでしょうか?
+では、ニワトリと卵の話のように、最初の `async` 関数はどう呼ぶのでしょうか?
-**FastAPI**を使用している場合、その「最初の」関数が*path operation 関数*であり、FastAPIが正しく実行する方法を知っているので、心配する必要はありません。
+**FastAPI** を使っている場合は心配ありません。その「最初の」関数は *path operation 関数* で、FastAPI が適切に実行してくれます。
-しかし、FastAPI以外で `async` / `await` を使用したい場合は、公式Pythonドキュメントを参照して下さい。
+しかし、FastAPI を使わずに `async` / `await` を使いたい場合もあります。
-### 非同期コードの他の形式
+### 自分で async コードを書く { #write-your-own-async-code }
-`async` と `await` を使用するスタイルは、この言語では比較的新しいものです。
+Starlette (**FastAPI** も) は AnyIO の上に構築されており、標準ライブラリの asyncio と Trio の両方に対応しています。
-非同期コードの操作がはるかに簡単になります。
+特に、あなた自身のコード内で、より高度なパターンを必要とする発展的な並行処理のユースケースに対して、AnyIO を直接使えます。
-等価な (またはほとんど同一の) 構文が、最近のバージョンのJavaScript (ブラウザおよびNodeJS) にも最近組み込まれました。
+仮に FastAPI を使っていなくても、AnyIO で独自の async アプリケーションを書けば、高い互換性と利点 (例: 構造化並行性) を得られます。
-しかし、その前は、非同期コードの処理はかなり複雑で難解でした。
+私は AnyIO の上に薄い層として、型注釈を少し改善し、より良い**補完**や**インラインエラー**などを得るための別ライブラリも作りました。また、**理解**して**自分で async コードを書く**のに役立つフレンドリーなイントロ/チュートリアルもあります: Asyncer。特に、**async コードと通常の** (ブロッキング/同期) **コードを組み合わせる**必要がある場合に有用です。
-以前のバージョンのPythonでは、スレッドやGeventが利用できました。しかし、コードは理解、デバック、そして、考察がはるかに複雑です。
+### 非同期コードの他の形式 { #other-forms-of-asynchronous-code }
-以前のバージョンのNodeJS / ブラウザJavaScriptでは、「コールバック」を使用していました。これは、「コールバック地獄」につながります。
+`async` と `await` を使うこのスタイルは、言語としては比較的新しいものです。
-## コルーチン
+しかし、これにより非同期コードの取り扱いは大幅に簡単になります。
-**コルーチン**は、`async def` 関数によって返されるものを指す非常に洒落た用語です。これは、開始できて、いつか終了する関数のようなものであるが、内部に `await` があるときは内部的に一時停止⏸されることもあるものだとPythonは認識しています。
+同等 (ほぼ同一) の構文が最近の JavaScript (ブラウザと NodeJS) にも導入されました。
-`async` と `await` を用いた非同期コードを使用するすべての機能は、「コルーチン」を使用するものとして何度もまとめられています。Goの主要機能である「ゴルーチン」に相当します。
+それ以前は、非同期コードの扱いはかなり複雑で難解でした。
-## まとめ
+以前の Python ではスレッドや Gevent を使えましたが、コードの理解・デバッグ・思考がはるかに難しくなります。
-上述したフレーズを見てみましょう:
+以前の NodeJS / ブラウザ JavaScript では「コールバック」を使っており、「コールバック地獄」を招きました。
-> 現代版のPythonは「**非同期コード**」を、「**コルーチン**」と称されるものを利用してサポートしています。これは **`async` と `await`** 構文を用います。
+## コルーチン { #coroutines }
-今では、この意味がより理解できるはずです。✨
+**コルーチン**は、`async def` 関数が返すものを指す、ちょっと洒落た用語です。Python はそれを、開始できていつか終了する関数のようなものとして扱いますが、内部に `await` があるたびに内部的に一時停止 ⏸ するかもしれないものとして認識します。
-(Starletteを介して) FastAPIに力を与えて、印象的なパフォーマンスを実現しているものはこれがすべてです。
+`async` と `await` を用いた非同期コードの機能全体は、しばしば「コルーチンを使う」と要約されます。これは Go の主要機能「Goroutines」に相当します。
-## 非常に発展的な技術的詳細
+## まとめ { #conclusion }
+
+上のフレーズをもう一度見てみましょう:
+
+> モダンな Python は **「非同期コード」** を **「コルーチン」** と呼ばれる仕組みでサポートしており、構文は **`async` と `await`** です。
+
+今なら、より意味が分かるはずです。✨
+
+これらすべてが (Starlette を通じて) FastAPI を支え、印象的なパフォーマンスを実現しています。
+
+## 非常に発展的な技術的詳細 { #very-technical-details }
/// warning | 注意
-恐らくスキップしても良いでしょう。
+おそらく読み飛ばしても大丈夫です。
-この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。
+これは **FastAPI** の内部動作に関する、とても技術的な詳細です。
-かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
+(コルーチン、スレッド、ブロッキング等の) 技術知識があり、FastAPI が `async def` と通常の `def` をどう扱うかに興味がある場合は、読み進めてください。
///
-### Path operation 関数
+### Path operation 関数 { #path-operation-functions }
-*path operation 関数*を `async def` の代わりに通常の `def` で宣言すると、(サーバーをブロックするので) 直接呼び出す代わりに外部スレッドプール (awaitされる) で実行されます。
+*path operation 関数* を `async def` ではなく通常の `def` で宣言した場合、(サーバをブロックしてしまうため) 直接呼び出されるのではなく、外部のスレッドプールで実行され、それを待機します。
-上記の方法と違った方法の別の非同期フレームワークから来ており、小さなパフォーマンス向上 (約100ナノ秒) のために通常の `def` を使用して些細な演算のみ行う *path operation 関数* を定義するのに慣れている場合は、**FastAPI**ではまったく逆の効果になることに注意してください。このような場合、*path operation 関数* がブロッキングI/Oを実行しないのであれば、`async def` の使用をお勧めします。
+上記とは異なる動作の別の非同期フレームワークから来ており、ほんのわずかなパフォーマンス向上 (約 100 ナノ秒) を狙って、計算のみの些細な *path operation 関数* を素の `def` で定義することに慣れている場合、**FastAPI** では効果がまったく逆になる点に注意してください。これらの場合、*path operation 関数* がブロッキングな I/O を行うコードを使っていない限り、`async def` を使った方が良いです。
-それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](index.md#_10){.internal-link target=_blank}可能性があります。
+それでも、どちらの状況でも、**FastAPI** はあなたが以前使っていたフレームワークよりも (少なくとも同等に) [高速である](index.md#performance){.internal-link target=_blank} 可能性が高いです。
-### 依存関係
+### 依存関係 { #dependencies }
-依存関係についても同様です。依存関係が `async def` ではなく標準の `def` 関数である場合、外部スレッドプールで実行されます。
+[依存関係](tutorial/dependencies/index.md){.internal-link target=_blank} についても同様です。依存関係が `async def` ではなく標準の `def` 関数である場合、外部のスレッドプールで実行されます。
-### サブ依存関係
+### サブ依存関係 { #sub-dependencies }
-(関数定義のパラメーターとして) 相互に必要な複数の依存関係とサブ依存関係を設定できます。一部は `async def` で作成され、他の一部は通常の `def` で作成されます。それでも動作し、通常の `def`で作成されたものは、「awaitされる」代わりに (スレッドプールから) 外部スレッドで呼び出されます。
+複数の依存関係や [サブ依存関係](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} を (関数定義のパラメータとして) 相互に要求させられます。その一部は `async def`、他は通常の `def` で作られていても動作します。通常の `def` で作られたものは「await」される代わりに、外部スレッドプールからスレッド上で呼び出されます。
-### その他のユーティリティ関数
+### その他のユーティリティ関数 { #other-utility-functions }
-あなたが直接呼び出すユーティリティ関数は通常の `def` または `async def` で作成でき、FastAPIは呼び出す方法に影響を与えません。
+あなたが直接呼び出すユーティリティ関数は、通常の `def` でも `async def` でも構いません。FastAPI はその呼び出し方に影響を与えません。
-これは、FastAPIが呼び出す関数と対照的です: *path operation 関数*と依存関係。
+これは、FastAPI があなたの代わりに呼び出す関数 (すなわち *path operation 関数* と依存関係) とは対照的です。
-ユーティリティ関数が `def` を使用した通常の関数である場合、スレッドプールではなく直接 (コードで記述したとおりに) 呼び出されます。関数が `async def` を使用して作成されている場合は、呼び出す際に `await` する必要があります。
+ユーティリティ関数が `def` の通常関数であれば、(あなたのコードに書いたとおりに) 直接呼び出され、スレッドプールでは実行されません。関数が `async def` で作られている場合は、その関数を呼ぶときに `await` すべきです。
---
-繰り返しになりますが、これらは非常に技術的な詳細であり、検索して辿り着いた場合は役立つでしょう。
+繰り返しになりますが、これらは非常に技術的な詳細で、該当事項を検索してここにたどり着いた場合には役立つでしょう。
-それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: 急いでいますか?。
+それ以外の場合は、上のセクションのガイドラインに従えば十分です: 急いでいますか?。
diff --git a/docs/ja/docs/deployment/cloud.md b/docs/ja/docs/deployment/cloud.md
new file mode 100644
index 000000000..17699cdca
--- /dev/null
+++ b/docs/ja/docs/deployment/cloud.md
@@ -0,0 +1,24 @@
+# クラウドプロバイダへの FastAPI デプロイ { #deploy-fastapi-on-cloud-providers }
+
+FastAPI アプリケーションは、実質的にどのようなクラウドプロバイダでもデプロイできます。
+
+多くの場合、主要なクラウドプロバイダは FastAPI をデプロイするためのガイドを提供しています。
+
+## FastAPI Cloud { #fastapi-cloud }
+
+**FastAPI Cloud** は、**FastAPI** の作者と同じチームによって作られています。
+
+API の**構築**、**デプロイ**、**アクセス**までのプロセスを、最小限の手間で効率化します。
+
+FastAPI でアプリを開発するときと同じ**開発者体験**を、クラウドへの**デプロイ**にももたらします。🎉
+
+FastAPI Cloud は、*FastAPI and friends* オープンソースプロジェクトの主要なスポンサーかつ資金提供元です。✨
+
+## クラウドプロバイダ - スポンサー { #cloud-providers-sponsors }
+
+他にもいくつかのクラウドプロバイダが ✨ [**FastAPI をスポンサーしています**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨。🙇
+
+それらのガイドを参考にし、サービスを試してみるのもよいでしょう:
+
+* Render
+* Railway
diff --git a/docs/ja/docs/deployment/concepts.md b/docs/ja/docs/deployment/concepts.md
index 787eb2e73..501a90bc9 100644
--- a/docs/ja/docs/deployment/concepts.md
+++ b/docs/ja/docs/deployment/concepts.md
@@ -29,7 +29,6 @@
## セキュリティ - HTTPS { #security-https }
-
[前チャプターのHTTPSについて](https.md){.internal-link target=_blank}では、HTTPSがどのようにAPIを暗号化するのかについて学びました。
通常、アプリケーションサーバにとって**外部の**コンポーネントである**TLS Termination Proxy**によって提供されることが一般的です。このプロキシは通信の暗号化を担当します。
@@ -193,7 +192,6 @@ FastAPI アプリケーションでは、Uvicorn を実行する `fastapi` コ
同じAPIプログラムの**複数のプロセス**を実行する場合、それらは一般的に**Worker/ワーカー**と呼ばれます。
### ワーカー・プロセス と ポート { #worker-processes-and-ports }
-
[HTTPSについて](https.md){.internal-link target=_blank}のドキュメントで、1つのサーバーで1つのポートとIPアドレスの組み合わせでリッスンできるのは1つのプロセスだけであることを覚えていますでしょうか?
diff --git a/docs/ja/docs/deployment/docker.md b/docs/ja/docs/deployment/docker.md
index 6c182448c..883f98c98 100644
--- a/docs/ja/docs/deployment/docker.md
+++ b/docs/ja/docs/deployment/docker.md
@@ -14,7 +14,7 @@ Linuxコンテナの使用には、**セキュリティ**、**反復可能性(
-**FastAPI**は、代替ツールのこれまでの働きがなければ存在しなかったでしょう。
+**FastAPI**は、他の人々のこれまでの働きがなければ存在しなかったでしょう。
以前に作られた多くのツールが、作成における刺激として役立ってきました。
@@ -29,7 +28,7 @@
-## 調査
+## 調査 { #investigation }
すべて既存の代替手段を使うことで、そのすべてを学び、アイデアを得て、自分や一緒に仕事をしてきた開発者のチームにとって最良の方法で組み合わせる機会を得ました。
@@ -39,7 +38,7 @@
そこで、**FastAPI**のコードを書き始める前に、OpenAPI、JSON Schema、OAuth2などの仕様を数ヶ月かけて勉強し、それらの関係、重複する箇所、相違点を理解しました。
-## 設計
+## 設計 { #design }
その後、 (FastAPIを使う開発者として) ユーザーが欲しい「API」の設計に時間を費やしました。
@@ -53,19 +52,19 @@
すべての箇所で、すべての開発者に最高の開発体験を提供しました。
-## 要件
+## 要件 { #requirements }
いくつかの代替手法を試したあと、私は**Pydantic**の強みを利用することを決めました。
そして、JSON Schemaに完全に準拠するようにしたり、制約宣言を定義するさまざまな方法をサポートしたり、いくつかのエディターでのテストに基づいてエディターのサポート (型チェック、自動補完) を改善するために貢献しました。
-開発中、もう1つの重要な鍵となる**Starlette**、にも貢献しました。
+開発中、もう1つの重要な鍵となる**Starlette**にも貢献しました。
-## 開発
+## 開発 { #development }
私が**FastAPI**自体の作成を開始した時には、ほとんどの部分がすでに準備されており、設計が定義され、必要な条件とツールの準備ができていました。そして規格や仕様に関する知識が、明確になり、更新されていました。
-## これから
+## これから { #future }
この時点ですでに、これらのアイデアを持った**FastAPI**が多くの人の役に立っていることは明らかです。
diff --git a/docs/ja/docs/how-to/authentication-error-status-code.md b/docs/ja/docs/how-to/authentication-error-status-code.md
new file mode 100644
index 000000000..9bef47644
--- /dev/null
+++ b/docs/ja/docs/how-to/authentication-error-status-code.md
@@ -0,0 +1,17 @@
+# 古い 403 認証エラーのステータスコードを使う { #use-old-403-authentication-error-status-codes }
+
+FastAPI バージョン `0.122.0` より前は、統合されたセキュリティユーティリティが認証に失敗してクライアントへエラーを返す際、HTTP ステータスコード `403 Forbidden` を使用していました。
+
+FastAPI バージョン `0.122.0` 以降では、より適切な HTTP ステータスコード `401 Unauthorized` を使用し、HTTP 仕様に従ってレスポンスに妥当な `WWW-Authenticate` ヘッダーを含めます。RFC 7235、RFC 9110。
+
+しかし、何らかの理由でクライアントが従来の挙動に依存している場合は、セキュリティクラスでメソッド `make_not_authenticated_error` をオーバーライドすることで、その挙動に戻せます。
+
+たとえば、既定の `401 Unauthorized` エラーの代わりに `403 Forbidden` エラーを返す `HTTPBearer` のサブクラスを作成できます:
+
+{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *}
+
+/// tip | 豆知識
+
+この関数は例外インスタンスを返す点に注意してください。ここでは例外を送出しません。送出は内部の他のコードで行われます。
+
+///
diff --git a/docs/ja/docs/how-to/conditional-openapi.md b/docs/ja/docs/how-to/conditional-openapi.md
index 9478f5c03..0febe1ef6 100644
--- a/docs/ja/docs/how-to/conditional-openapi.md
+++ b/docs/ja/docs/how-to/conditional-openapi.md
@@ -10,7 +10,7 @@
もしセキュリティ上の欠陥がソースコードにあるならば、それは存在したままです。
-ドキュメンテーションを非表示にするのは、単にあなたのAPIへのアクセス方法を難解にするだけでなく、同時にあなた自身の本番環境でのAPIのデバッグを困難にしてしまう可能性があります。単純に、 Security through obscurity の一つの形態として考えられるでしょう。
+ドキュメンテーションを非表示にするのは、単にあなたのAPIへのアクセス方法を難解にするだけでなく、同時にあなた自身の本番環境でのAPIのデバッグを困難にしてしまう可能性があります。単純に、 秘匿によるセキュリティ の一つの形態として考えられるでしょう。
もしあなたのAPIのセキュリティを強化したいなら、いくつかのよりよい方法があります。例を示すと、
@@ -29,7 +29,7 @@
例えば、
-{* ../../docs_src/conditional_openapi/tutorial001_py39.py hl[6,11] *}
+{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *}
ここでは `openapi_url` の設定を、デフォルトの `"/openapi.json"` のまま宣言しています。
diff --git a/docs/ja/docs/how-to/configure-swagger-ui.md b/docs/ja/docs/how-to/configure-swagger-ui.md
new file mode 100644
index 000000000..8be7adc84
--- /dev/null
+++ b/docs/ja/docs/how-to/configure-swagger-ui.md
@@ -0,0 +1,70 @@
+# Swagger UI の設定 { #configure-swagger-ui }
+
+いくつかの追加の Swagger UI パラメータを設定できます。
+
+設定するには、`FastAPI()` のアプリオブジェクトを作成するとき、または `get_swagger_ui_html()` 関数に `swagger_ui_parameters` 引数を渡します。
+
+`swagger_ui_parameters` は、Swagger UI に直接渡される設定を含む辞書を受け取ります。
+
+FastAPI はそれらの設定を **JSON** に変換し、JavaScript と互換にします。Swagger UI が必要とするのはこの形式です。
+
+## シンタックスハイライトを無効化 { #disable-syntax-highlighting }
+
+例えば、Swagger UI のシンタックスハイライトを無効化できます。
+
+設定を変更しなければ、シンタックスハイライトはデフォルトで有効です:
+
+
+
+しかし、`syntaxHighlight` を `False` に設定すると無効化できます:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+...その場合、Swagger UI ではシンタックスハイライトが表示されなくなります:
+
+
+
+## テーマの変更 { #change-the-theme }
+
+同様に、キー `"syntaxHighlight.theme"`(途中にドットが含まれている点に注意)でシンタックスハイライトのテーマを設定できます:
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+この設定により、シンタックスハイライトの配色テーマが変わります:
+
+
+
+## 既定の Swagger UI パラメータの変更 { #change-default-swagger-ui-parameters }
+
+FastAPI には、多くのユースケースに適した既定の設定パラメータが含まれています。
+
+既定では次の設定が含まれます:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+引数 `swagger_ui_parameters` に別の値を指定することで、これらを上書きできます。
+
+例えば、`deepLinking` を無効化するには、次の設定を `swagger_ui_parameters` に渡します:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## その他の Swagger UI パラメータ { #other-swagger-ui-parameters }
+
+利用可能な他のすべての設定については、公式の Swagger UI パラメータのドキュメントを参照してください。
+
+## JavaScript 専用の設定 { #javascript-only-settings }
+
+Swagger UI では、他にも **JavaScript 専用** のオブジェクト(例: JavaScript の関数)による設定が可能です。
+
+FastAPI には、次の JavaScript 専用の `presets` 設定も含まれています:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+これらは文字列ではなく **JavaScript** のオブジェクトであるため、Python のコードから直接渡すことはできません。
+
+そのような JavaScript 専用の設定を使う必要がある場合は、上記のいずれかの方法を使用し、Swagger UI の path operation をオーバーライドして、必要な JavaScript を手動で記述してください。
diff --git a/docs/ja/docs/how-to/custom-docs-ui-assets.md b/docs/ja/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 000000000..c0c9745b2
--- /dev/null
+++ b/docs/ja/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# カスタムドキュメント UI の静的アセット(セルフホスティング) { #custom-docs-ui-static-assets-self-hosting }
+
+API ドキュメントは **Swagger UI** と **ReDoc** を使用しており、それぞれにいくつかの JavaScript と CSS ファイルが必要です。
+
+既定では、これらのファイルは CDN から配信されます。
+
+しかし、カスタマイズすることも可能で、特定の CDN を指定したり、自分でファイルを配信したりできます。
+
+## JavaScript と CSS のカスタム CDN { #custom-cdn-for-javascript-and-css }
+
+別の CDN を使いたいとします。例えば `https://unpkg.com/` を使いたい場合です。
+
+例えば、一部の URL が制限されている国に住んでいる場合に役立ちます。
+
+### 自動ドキュメントの無効化 { #disable-the-automatic-docs }
+
+最初の手順は自動ドキュメントを無効化することです。デフォルトではそれらは既定の CDN を使用します。
+
+無効化するには、`FastAPI` アプリ作成時にそれらの URL を `None` に設定します:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### カスタムドキュメントの追加 { #include-the-custom-docs }
+
+これで、カスタムドキュメント用の *path operations* を作成できます。
+
+FastAPI の内部関数を再利用してドキュメント用の HTML ページを生成し、必要な引数を渡せます:
+
+- `openapi_url`: ドキュメントの HTML ページが API の OpenAPI スキーマを取得する URL。ここでは属性 `app.openapi_url` を使用できます。
+- `title`: API のタイトル。
+- `oauth2_redirect_url`: 既定値を使うにはここで `app.swagger_ui_oauth2_redirect_url` を使用できます。
+- `swagger_js_url`: Swagger UI ドキュメント用の HTML が取得する JavaScript ファイルの URL。これはカスタム CDN の URL です。
+- `swagger_css_url`: Swagger UI ドキュメント用の HTML が取得する CSS ファイルの URL。これはカスタム CDN の URL です。
+
+ReDoc についても同様です...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | 豆知識
+
+`swagger_ui_redirect` 用の *path operation* は、OAuth2 を使用する場合の補助です。
+
+API を OAuth2 プロバイダと統合すると、認証を実行して取得したクレデンシャルを持った状態で API ドキュメントに戻れます。そして実際の OAuth2 認証を用いてドキュメント上から API と対話できます。
+
+Swagger UI がこの処理を裏側で行いますが、そのためにこの「redirect」の補助が必要です。
+
+///
+
+### テスト用の *path operation* を作成 { #create-a-path-operation-to-test-it }
+
+すべてが動作するかをテストできるように、*path operation* を作成します:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### テスト { #test-it }
+
+これで、http://127.0.0.1:8000/docs にアクセスしてページを再読み込みすると、新しい CDN からそれらのアセットが読み込まれるはずです。
+
+## ドキュメント用 JavaScript と CSS のセルフホスティング { #self-hosting-javascript-and-css-for-docs }
+
+オフライン(インターネット非接続)でも、あるいはローカルネットワークで、アプリを動作させたい場合などには、JavaScript と CSS をセルフホストするのが有用です。
+
+ここでは、同じ FastAPI アプリ内でそれらのファイルを配信し、ドキュメントでそれらを使用するように設定する方法を示します。
+
+### プロジェクトのファイル構成 { #project-file-structure }
+
+プロジェクトのファイル構成が次のようになっているとします:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+これらの静的ファイルを保存するためのディレクトリを作成します。
+
+新しいファイル構成は次のようになります:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### ファイルのダウンロード { #download-the-files }
+
+ドキュメントに必要な静的ファイルをダウンロードし、`static/` ディレクトリに配置します。
+
+各リンクを右クリックして「リンク先を別名で保存...」のようなオプションを選べます。
+
+**Swagger UI** では次のファイルを使用します:
+
+- `swagger-ui-bundle.js`
+- `swagger-ui.css`
+
+そして **ReDoc** では次のファイルを使用します:
+
+- `redoc.standalone.js`
+
+その後、ファイル構成は次のようになります:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### 静的ファイルの配信 { #serve-the-static-files }
+
+- `StaticFiles` をインポートします。
+- 特定のパスに `StaticFiles()` インスタンスを「マウント」します。
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### 静的ファイルのテスト { #test-the-static-files }
+
+アプリケーションを起動し、http://127.0.0.1:8000/static/redoc.standalone.js にアクセスします。
+
+**ReDoc** 用の非常に長い JavaScript ファイルが表示されるはずです。
+
+先頭は次のようになっているかもしれません:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+これで、アプリから静的ファイルを配信できていること、そしてドキュメント用の静的ファイルを正しい場所に配置できていることが確認できます。
+
+次に、ドキュメントでそれらの静的ファイルを使用するようにアプリを設定します。
+
+### 静的ファイル用に自動ドキュメントを無効化 { #disable-the-automatic-docs-for-static-files }
+
+カスタム CDN を使う場合と同様、最初の手順は自動ドキュメントを無効化することです。既定では CDN を使用します。
+
+無効化するには、`FastAPI` アプリ作成時にそれらの URL を `None` に設定します:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### 静的ファイル用のカスタムドキュメントを追加 { #include-the-custom-docs-for-static-files }
+
+カスタム CDN と同様の方法で、カスタムドキュメント用の *path operations* を作成できます。
+
+再び、FastAPI の内部関数を再利用してドキュメント用の HTML ページを生成し、必要な引数を渡します:
+
+- `openapi_url`: ドキュメントの HTML ページが API の OpenAPI スキーマを取得する URL。ここでは属性 `app.openapi_url` を使用できます。
+- `title`: API のタイトル。
+- `oauth2_redirect_url`: 既定値を使うにはここで `app.swagger_ui_oauth2_redirect_url` を使用できます。
+- `swagger_js_url`: Swagger UI ドキュメント用の HTML が取得する **JavaScript** ファイルの URL。**これはあなたのアプリ自身がいま配信しているものです**。
+- `swagger_css_url`: Swagger UI ドキュメント用の HTML が取得する **CSS** ファイルの URL。**これはあなたのアプリ自身がいま配信しているものです**。
+
+ReDoc についても同様です...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | 豆知識
+
+`swagger_ui_redirect` 用の *path operation* は、OAuth2 を使用する場合の補助です。
+
+API を OAuth2 プロバイダと統合すると、認証を実行して取得したクレデンシャルを持った状態で API ドキュメントに戻れます。そして実際の OAuth2 認証を用いてドキュメント上から API と対話できます。
+
+Swagger UI がこの処理を裏側で行いますが、そのためにこの「redirect」の補助が必要です。
+
+///
+
+### 静的ファイルをテストするための *path operation* を作成 { #create-a-path-operation-to-test-static-files }
+
+すべてが動作するかをテストできるように、*path operation* を作成します:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### 静的ファイル UI のテスト { #test-static-files-ui }
+
+これで、WiFi を切断して http://127.0.0.1:8000/docs にアクセスし、ページを再読み込みできるはずです。
+
+インターネットに接続していなくても、API のドキュメントを表示し、API と対話できます。
diff --git a/docs/ja/docs/how-to/custom-request-and-route.md b/docs/ja/docs/how-to/custom-request-and-route.md
new file mode 100644
index 000000000..ae64f3109
--- /dev/null
+++ b/docs/ja/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# カスタム Request と APIRoute クラス { #custom-request-and-apiroute-class }
+
+場合によっては、`Request` や `APIRoute` クラスで使われるロジックを上書きしたいことがあります。
+
+特に、ミドルウェアでのロジックの代替として有効な場合があります。
+
+たとえば、アプリケーションで処理される前にリクエストボディを読み取ったり操作したりしたい場合です。
+
+/// danger | 警告
+
+これは「上級」機能です。
+
+FastAPI を始めたばかりの場合は、このセクションは読み飛ばしてもよいでしょう。
+
+///
+
+## ユースケース { #use-cases }
+
+ユースケースの例:
+
+* JSON ではないリクエストボディを JSON に変換する(例: `msgpack`)。
+* gzip 圧縮されたリクエストボディの解凍。
+* すべてのリクエストボディの自動ロギング。
+
+## カスタムリクエストボディのエンコーディングの処理 { #handling-custom-request-body-encodings }
+
+gzip のリクエストを解凍するために、カスタムの `Request` サブクラスを使う方法を見ていきます。
+
+そして、そのカスタムリクエストクラスを使うための `APIRoute` サブクラスを用意します。
+
+### カスタム `GzipRequest` クラスの作成 { #create-a-custom-gziprequest-class }
+
+/// tip | 豆知識
+
+これは仕組みを示すためのサンプルです。Gzip 対応が必要な場合は、用意されている [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} を使用できます。
+
+///
+
+まず、`GzipRequest` クラスを作成します。これは適切なヘッダーがある場合に本体を解凍するよう、`Request.body()` メソッドを上書きします。
+
+ヘッダーに `gzip` がなければ、解凍は試みません。
+
+この方法により、同じルートクラスで gzip 圧縮済み/未圧縮のリクエストの両方を扱えます。
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### カスタム `GzipRoute` クラスの作成 { #create-a-custom-gziproute-class }
+
+次に、`GzipRequest` を利用する `fastapi.routing.APIRoute` のカスタムサブクラスを作成します。
+
+ここでは `APIRoute.get_route_handler()` メソッドを上書きします。
+
+このメソッドは関数を返します。そしてその関数がリクエストを受け取り、レスポンスを返します。
+
+ここでは、元のリクエストから `GzipRequest` を作成するために利用します。
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | 技術詳細
+
+`Request` には `request.scope` 属性があり、これはリクエストに関するメタデータを含む Python の `dict` です。
+
+`Request` には `request.receive` もあり、これはリクエストの本体を「受信」するための関数です。
+
+`scope` の `dict` と `receive` 関数はいずれも ASGI 仕様の一部です。
+
+そしてこの 2 つ(`scope` と `receive`)が、新しい `Request` インスタンスを作成するために必要なものです。
+
+`Request` について詳しくは、Starlette の Requests に関するドキュメント を参照してください。
+
+///
+
+`GzipRequest.get_route_handler` が返す関数が異なるのは、`Request` を `GzipRequest` に変換する点だけです。
+
+これにより、`GzipRequest` は必要に応じてデータを解凍してから *path operations* に渡します。
+
+それ以降の処理ロジックはすべて同じです。
+
+ただし、`GzipRequest.body` を変更しているため、必要に応じて **FastAPI** によって読み込まれる際にリクエストボディが自動的に解凍されます。
+
+## 例外ハンドラでのリクエストボディへのアクセス { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | 豆知識
+
+同じ問題を解決するには、`RequestValidationError` 用のカスタムハンドラで `body` を使う方がずっと簡単でしょう([エラー処理](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank})。
+
+ただし、この例も有効で、内部コンポーネントとどのようにやり取りするかを示しています。
+
+///
+
+同じアプローチを使って、例外ハンドラ内でリクエストボディにアクセスすることもできます。
+
+やることは、`try`/`except` ブロックの中でリクエストを処理するだけです:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+例外が発生しても、`Request` インスタンスはスコープ内に残るため、エラー処理時にリクエストボディを読み取り、活用できます:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## ルーターでのカスタム `APIRoute` クラス { #custom-apiroute-class-in-a-router }
+
+`APIRouter` の `route_class` パラメータを設定することもできます:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+この例では、`router` 配下の *path operations* はカスタムの `TimedRoute` クラスを使用し、レスポンスの生成にかかった時間を示す追加の `X-Response-Time` ヘッダーがレスポンスに含まれます:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/ja/docs/how-to/extending-openapi.md b/docs/ja/docs/how-to/extending-openapi.md
new file mode 100644
index 000000000..df5b3cd35
--- /dev/null
+++ b/docs/ja/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# OpenAPI の拡張 { #extending-openapi }
+
+生成された OpenAPI スキーマを変更する必要がある場合があります。
+
+このセクションではその方法を説明します。
+
+## 通常のプロセス { #the-normal-process }
+
+通常(デフォルト)のプロセスは次のとおりです。
+
+`FastAPI` アプリケーション(インスタンス)には、OpenAPI スキーマを返すことが期待される `.openapi()` メソッドがあります。
+
+アプリケーションオブジェクトの作成時に、`/openapi.json`(または `openapi_url` に設定したパス)への path operation が登録されます。
+
+これは単に、アプリケーションの `.openapi()` メソッドの結果を含む JSON レスポンスを返します。
+
+デフォルトでは、`.openapi()` メソッドはプロパティ `.openapi_schema` に内容があるかを確認し、あればそれを返します。
+
+なければ、`fastapi.openapi.utils.get_openapi` にあるユーティリティ関数を使って生成します。
+
+この関数 `get_openapi()` は次の引数を受け取ります:
+
+- `title`: ドキュメントに表示される OpenAPI のタイトル。
+- `version`: API のバージョン。例: `2.5.0`。
+- `openapi_version`: 使用する OpenAPI 仕様のバージョン。デフォルトは最新の `3.1.0`。
+- `summary`: API の短い概要。
+- `description`: API の説明。Markdown を含めることができ、ドキュメントに表示されます。
+- `routes`: ルートのリスト。登録済みの各 path operation です。`app.routes` から取得されます。
+
+/// info | 情報
+
+パラメータ `summary` は OpenAPI 3.1.0 以降で利用可能で、FastAPI 0.99.0 以降が対応しています。
+
+///
+
+## デフォルトの上書き { #overriding-the-defaults }
+
+上記の情報を使って、同じユーティリティ関数で OpenAPI スキーマを生成し、必要な部分を上書きできます。
+
+たとえば、カスタムロゴを含めるための ReDoc の OpenAPI 拡張を追加してみましょう。
+
+### 通常の **FastAPI** { #normal-fastapi }
+
+まず、通常どおりに **FastAPI** アプリケーションを実装します:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### OpenAPI スキーマの生成 { #generate-the-openapi-schema }
+
+次に、`custom_openapi()` 関数内で同じユーティリティ関数を使って OpenAPI スキーマを生成します:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### OpenAPI スキーマの変更 { #modify-the-openapi-schema }
+
+OpenAPI スキーマの `info`「オブジェクト」にカスタムの `x-logo` を追加して、ReDoc 拡張を加えます:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### OpenAPI スキーマのキャッシュ { #cache-the-openapi-schema }
+
+生成したスキーマを保持する「キャッシュ」として `.openapi_schema` プロパティを利用できます。
+
+こうすることで、ユーザーが API ドキュメントを開くたびにスキーマを生成する必要がなくなります。
+
+最初の1回だけ生成され、その後は同じキャッシュ済みスキーマが以降のリクエストで使われます。
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### メソッドの上書き { #override-the-method }
+
+これで、`.openapi()` メソッドを新しい関数に置き換えられます。
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### 確認 { #check-it }
+
+http://127.0.0.1:8000/redoc にアクセスすると、カスタムロゴ(この例では **FastAPI** のロゴ)が使われていることが確認できます:
+
+
diff --git a/docs/ja/docs/how-to/general.md b/docs/ja/docs/how-to/general.md
new file mode 100644
index 000000000..8879c68eb
--- /dev/null
+++ b/docs/ja/docs/how-to/general.md
@@ -0,0 +1,39 @@
+# 一般 - ハウツー - レシピ { #general-how-to-recipes }
+
+ここでは、一般的またはよくある質問に対して、ドキュメント内の他の箇所への参照をいくつか示します。
+
+## データのフィルタリング - セキュリティ { #filter-data-security }
+
+返すべき以上のデータを返さないようにするには、[チュートリアル - レスポンスモデル - 戻り値の型](../tutorial/response-model.md){.internal-link target=_blank} を参照してください。
+
+## ドキュメントのタグ - OpenAPI { #documentation-tags-openapi }
+
+*path operations* にタグを追加し、ドキュメント UI でグループ化するには、[チュートリアル - path operation の設定 - タグ](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank} を参照してください。
+
+## ドキュメントの概要と説明 - OpenAPI { #documentation-summary-and-description-openapi }
+
+*path operations* に概要と説明を追加し、ドキュメント UI に表示するには、[チュートリアル - path operation の設定 - 概要と説明](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank} を参照してください。
+
+## ドキュメントのレスポンス説明 - OpenAPI { #documentation-response-description-openapi }
+
+ドキュメント UI に表示されるレスポンスの説明を定義するには、[チュートリアル - path operation の設定 - レスポンスの説明](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank} を参照してください。
+
+## *Path Operation* の非推奨化 - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+*path operation* を非推奨にし、ドキュメント UI に表示するには、[チュートリアル - path operation の設定 - 非推奨](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank} を参照してください。
+
+## 任意のデータを JSON 互換に変換 { #convert-any-data-to-json-compatible }
+
+任意のデータを JSON 互換に変換するには、[チュートリアル - JSON 互換エンコーダ](../tutorial/encoder.md){.internal-link target=_blank} を参照してください。
+
+## OpenAPI メタデータ - ドキュメント { #openapi-metadata-docs }
+
+ライセンス、バージョン、連絡先などを含むメタデータを OpenAPI スキーマに追加するには、[チュートリアル - メタデータとドキュメントの URL](../tutorial/metadata.md){.internal-link target=_blank} を参照してください。
+
+## OpenAPI のカスタム URL { #openapi-custom-url }
+
+OpenAPI の URL をカスタマイズ(または削除)するには、[チュートリアル - メタデータとドキュメントの URL](../tutorial/metadata.md#openapi-url){.internal-link target=_blank} を参照してください。
+
+## OpenAPI ドキュメントの URL { #openapi-docs-urls }
+
+自動生成されるドキュメント UI が使用する URL を変更するには、[チュートリアル - メタデータとドキュメントの URL](../tutorial/metadata.md#docs-urls){.internal-link target=_blank} を参照してください。
diff --git a/docs/ja/docs/how-to/graphql.md b/docs/ja/docs/how-to/graphql.md
new file mode 100644
index 000000000..bd0d22349
--- /dev/null
+++ b/docs/ja/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+**FastAPI** は **ASGI** 標準に基づいているため、ASGI に対応した任意の **GraphQL** ライブラリを簡単に統合できます。
+
+同じアプリケーション内で通常の FastAPI の *path operation* と GraphQL を組み合わせて使えます。
+
+/// tip | 豆知識
+
+**GraphQL** は非常に特定のユースケースを解決します。
+
+一般的な **Web API** と比べると、**長所** と **短所** があります。
+
+ご自身のユースケースで得られる **利点** が **欠点** を補うかどうかを評価してください。 🤓
+
+///
+
+## GraphQL ライブラリ { #graphql-libraries }
+
+**ASGI** をサポートする **GraphQL** ライブラリの一部を以下に示します。**FastAPI** と組み合わせて使用できます:
+
+* Strawberry 🍓
+ * FastAPI 向けドキュメントあり
+* Ariadne
+ * FastAPI 向けドキュメントあり
+* Tartiflette
+ * ASGI 連携用の Tartiflette ASGI あり
+* Graphene
+ * starlette-graphene3 あり
+
+## Strawberry で GraphQL { #graphql-with-strawberry }
+
+**GraphQL** が必要、または利用したい場合は、**Strawberry** を**推奨**します。**FastAPI** の設計に最も近く、すべてが**型アノテーション**に基づいています。
+
+ユースケースによっては他のライブラリを選ぶ方がよい場合もありますが、私に尋ねられれば、おそらく **Strawberry** を試すことを勧めるでしょう。
+
+FastAPI と Strawberry を統合する方法の簡単なプレビューです:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+詳細は Strawberry のドキュメントをご覧ください。
+
+また、Strawberry と FastAPI の連携に関するドキュメントもあります。
+
+## Starlette の旧 `GraphQLApp` { #older-graphqlapp-from-starlette }
+
+以前の Starlette には、Graphene と統合するための `GraphQLApp` クラスが含まれていました。
+
+これは Starlette からは非推奨になりましたが、もしそれを使用しているコードがある場合は、同じユースケースをカバーし、**ほぼ同一のインターフェース**を持つ starlette-graphene3 へ容易に**移行**できます。
+
+/// tip | 豆知識
+
+GraphQL が必要であれば、依然として Strawberry の利用を推奨します。独自のクラスや型ではなく、型アノテーションに基づいているためです。
+
+///
+
+## さらに学ぶ { #learn-more }
+
+**GraphQL** については、公式 GraphQL ドキュメントでさらに学べます。
+
+上記の各ライブラリについては、リンク先のドキュメントをご参照ください。
diff --git a/docs/ja/docs/how-to/index.md b/docs/ja/docs/how-to/index.md
new file mode 100644
index 000000000..b1cd17785
--- /dev/null
+++ b/docs/ja/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# ハウツー - レシピ { #how-to-recipes }
+
+ここでは、**複数のトピック**に関するさまざまなレシピや「ハウツー」ガイドを紹介します。
+
+これらのアイデアの多くはおおむね**独立**しており、ほとんどの場合、**あなたのプロジェクト**に直接当てはまるものだけを読めば十分です。
+
+プロジェクトにとって興味深く有用だと思うものがあれば、ぜひ確認してください。そうでなければ、読み飛ばしても問題ありません。
+
+/// tip | 豆知識
+
+**FastAPI を学ぶ**ことを体系的に進めたい場合(推奨)、代わりに [チュートリアル - ユーザーガイド](../tutorial/index.md){.internal-link target=_blank} を章ごとに読んでください。
+
+///
diff --git a/docs/ja/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/ja/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 000000000..f1414ac28
--- /dev/null
+++ b/docs/ja/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Pydantic v1 から Pydantic v2 への移行 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+古い FastAPI アプリがある場合、Pydantic v1 を使っているかもしれません。
+
+FastAPI 0.100.0 は Pydantic v1 / v2 のどちらにも対応しており、インストールされている方を使用しました。
+
+FastAPI 0.119.0 では、Pydantic v2 内からの Pydantic v1 の部分的サポート(`pydantic.v1`)が導入され、v2 への移行が容易になりました。
+
+FastAPI 0.126.0 で Pydantic v1 のサポートは終了しましたが、しばらくの間は `pydantic.v1` は利用可能でした。
+
+/// warning | 注意
+
+Pydantic チームは Python の最新バージョン、つまり **Python 3.14** から、Pydantic v1 のサポートを終了しました。
+
+これには `pydantic.v1` も含まれ、Python 3.14 以上ではサポートされません。
+
+Python の最新機能を使いたい場合は、Pydantic v2 を使用していることを確認する必要があります。
+
+///
+
+古い FastAPI アプリで Pydantic v1 を使っている場合、ここでは Pydantic v2 への移行方法と、段階的移行を助ける **FastAPI 0.119.0 の機能** を紹介します。
+
+## 公式ガイド { #official-guide }
+
+Pydantic には v1 から v2 への公式の 移行ガイド があります。
+
+変更点、検証がより正確で厳密になった点、注意事項などが含まれます。
+
+何が変わったかをよりよく理解するために参照してください。
+
+## テスト { #tests }
+
+アプリに対する[テスト](../tutorial/testing.md){.internal-link target=_blank}を用意し、継続的インテグレーション(CI)で実行するようにしてください。
+
+これにより、アップグレード後も期待どおり動作していることを確認できます。
+
+## `bump-pydantic` { #bump-pydantic }
+
+多くの場合、カスタマイズのない通常の Pydantic モデルを使っていれば、v1 から v2 への移行作業の大半を自動化できます。
+
+同じ Pydantic チームが提供する `bump-pydantic` を使用できます。
+
+このツールは必要なコード変更のほとんどを自動で行います。
+
+その後テストを実行し、問題なければ完了です。😎
+
+## v2 における Pydantic v1 { #pydantic-v1-in-v2 }
+
+Pydantic v2 には、Pydantic v1 がサブモジュール `pydantic.v1` として同梱されています。ただし、これは Python 3.13 を超えるバージョンではサポートされません。
+
+つまり、Pydantic v2 の最新バージョンをインストールし、このサブモジュールから旧 Pydantic v1 のコンポーネントをインポートして、あたかも v1 をインストールしているかのように使用できます。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### v2 内の Pydantic v1 に対する FastAPI のサポート { #fastapi-support-for-pydantic-v1-in-v2 }
+
+FastAPI 0.119.0 以降では、移行を容易にするため、Pydantic v2 内の Pydantic v1 に対する部分的サポートもあります。
+
+そのため、Pydantic を v2 の最新に上げ、インポートを `pydantic.v1` サブモジュールに切り替えるだけで、多くの場合そのまま動作します。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | 注意
+
+前述のとおり、Python の最近のバージョン(Python 3.14 以降)では Pydantic v1 がサポートされないため、`pydantic.v1` の使用も Python 3.14 以上ではサポートされません。
+
+///
+
+### 同一アプリでの Pydantic v1 と v2 { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic v2 のモデルのフィールドに Pydantic v1 のモデルを(またはその逆を)埋め込むことは、Pydantic では「サポートされていません」。
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...but, you can have separated models using Pydantic v1 and v2 in the same app.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+場合によっては、同じ FastAPI の path operation 内で、Pydantic v1 と v2 の両方のモデルを扱うことも可能です:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+上の例では、入力モデルは Pydantic v1、出力モデル(`response_model=ItemV2` で定義)は Pydantic v2 です。
+
+### Pydantic v1 のパラメータ { #pydantic-v1-parameters }
+
+Pydantic v1 のモデルで `Body`、`Query`、`Form` などの FastAPI 固有のパラメータユーティリティを使う必要がある場合、v2 への移行が完了するまでの間は `fastapi.temp_pydantic_v1_params` からインポートできます:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### 段階的に移行 { #migrate-in-steps }
+
+/// tip | 豆知識
+
+まずは `bump-pydantic` を試してください。テストが通り、問題なければコマンド一発で完了です。✨
+
+///
+
+`bump-pydantic` が適用できない場合は、同一アプリで v1 と v2 のモデルを併用できるサポートを利用して、徐々に v2 へ移行できます。
+
+まず Pydantic を v2 の最新にアップグレードし、すべてのモデルのインポートを `pydantic.v1` に切り替えます。
+
+その後、モデルをグループごとに少しずつ Pydantic v1 から v2 へ移行していきます。🚶
diff --git a/docs/ja/docs/how-to/separate-openapi-schemas.md b/docs/ja/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 000000000..46df2aafb
--- /dev/null
+++ b/docs/ja/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# 入力と出力でOpenAPIのスキーマを分けるかどうか { #separate-openapi-schemas-for-input-and-output-or-not }
+
+**Pydantic v2** のリリース以降、生成される OpenAPI は以前より少し正確で、より正しいものになりました。😎
+
+実際には、場合によっては同じ Pydantic モデルに対して、入力用と出力用で OpenAPI に **2 つの JSON Schema** が含まれることがあります。これは **デフォルト値** の有無に依存します。
+
+その動作と、必要に応じての変更方法を見ていきます。
+
+## 入出力のPydanticモデル { #pydantic-models-for-input-and-output }
+
+次のようにデフォルト値を持つ Pydantic モデルがあるとします。
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### 入力用モデル { #model-for-input }
+
+このモデルを次のように入力として使うと:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+...`description` フィールドは **必須ではありません**。デフォルト値が `None` だからです。
+
+### ドキュメントでの入力モデル { #input-model-in-docs }
+
+ドキュメントで確認すると、`description` フィールドには **赤いアスタリスク** が付いておらず、必須としてはマークされていません:
+
+
+
+
+
+
+
-Web API の代わりにターミナルで使用する CLI アプリを構築する場合は、**Typer** を確認してください。
+Web API の代わりにターミナルで使用する CLI アプリを構築する場合は、**Typer** を確認してください。
**Typer** は FastAPI の弟分です。そして、**CLI 版 FastAPI** を意図しています。 ⌨️ 🚀
@@ -368,7 +368,7 @@ item: Item
* データの検証:
* データが無効な場合に自動で明確なエラーを返します。
* 深い入れ子になった JSON オブジェクトでも検証が可能です。
-* 入力データの 変換: ネットワークから Python のデータや型へ。以下から読み取ります:
+* 入力データの 変換: ネットワークから Python のデータや型へ。以下から読み取ります:
* JSON。
* パスパラメータ。
* クエリパラメータ。
@@ -376,7 +376,7 @@ item: Item
* ヘッダー。
* フォーム。
* ファイル。
-* 出力データの 変換: Python のデータや型からネットワークデータへ(JSON として)変換します:
+* 出力データの 変換: Python のデータや型からネットワークデータへ(JSON として)変換します:
* Python の型(`str`、`int`、`float`、`bool`、`list` など)の変換。
* `datetime` オブジェクト。
* `UUID` オブジェクト。
@@ -439,7 +439,7 @@ item: Item
* **ヘッダー**、**Cookie**、**フォームフィールド**、**ファイル**など、他のさまざまな場所からの **パラメータ** 宣言。
* `maximum_length` や `regex` のような **検証制約** を設定する方法。
-* 非常に強力で使いやすい **依存性注入** システム。
+* 非常に強力で使いやすい **依存性注入** システム。
* **JWT トークン**を用いた **OAuth2** や **HTTP Basic** 認証のサポートを含む、セキュリティと認証。
* **深くネストされた JSON モデル**を宣言するための、より高度な(しかし同様に簡単な)手法(Pydantic のおかげです)。
* Strawberry および他のライブラリによる **GraphQL** 統合。
@@ -524,7 +524,7 @@ Starlette によって使用されるもの:
*
httpx - `TestClient` を使用したい場合に必要です。
* jinja2 - デフォルトのテンプレート設定を使用したい場合に必要です。
-* python-multipart - `request.form()` とともに、フォームの 「parsing」 をサポートしたい場合に必要です。
+* python-multipart - `request.form()` とともに、フォームの 「parsing」 をサポートしたい場合に必要です。
FastAPI によって使用されるもの:
diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md
index 26a9e2193..a6b46c256 100644
--- a/docs/ja/docs/python-types.md
+++ b/docs/ja/docs/python-types.md
@@ -1,12 +1,12 @@
# Pythonの型の紹介 { #python-types-intro }
-Pythonではオプションの「型ヒント」(「型アノテーション」とも呼ばれます)がサポートされています。
+Python にはオプションの「型ヒント」(「型アノテーション」とも呼ばれます)がサポートされています。
-これらの **「型ヒント」** またはアノテーションは、変数の型を宣言できる特別な構文です。
+これらの **「型ヒント」** やアノテーションは、変数の型を宣言できる特別な構文です。
変数に型を宣言することで、エディターやツールがより良いサポートを提供できます。
-これはPythonの型ヒントについての **クイックチュートリアル/リフレッシュ** にすぎません。**FastAPI** で使用するために必要な最低限のことだけをカバーしています。...実際には本当に少ないです。
+これは Python の型ヒントについての **クイックチュートリアル/リフレッシュ** にすぎません。**FastAPI** で使うために必要な最低限のことだけをカバーしています。...実際には本当に少ないです。
**FastAPI** はすべてこれらの型ヒントに基づいており、多くの強みと利点を与えてくれます。
@@ -14,7 +14,7 @@ Pythonではオプションの「型ヒント」(「型アノテーション
/// note | 備考
-もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
+もしあなたが Python の専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
///
@@ -22,7 +22,7 @@ Pythonではオプションの「型ヒント」(「型アノテーション
簡単な例から始めてみましょう:
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
このプログラムを呼び出すと、以下が出力されます:
@@ -32,11 +32,11 @@ John Doe
この関数は以下のようなことを行います:
-* `first_name`と`last_name`を取得します。
-* `title()`を用いて、それぞれの最初の文字を大文字に変換します。
-* 真ん中にスペースを入れて連結します。
+* `first_name` と `last_name` を取得します。
+* `title()` を用いて、それぞれの最初の文字を大文字に変換します。
+* 真ん中にスペースを入れて連結します。
-{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
### 編集 { #edit-it }
@@ -48,11 +48,11 @@ John Doe
しかし、そうすると「最初の文字を大文字に変換するあのメソッド」を呼び出す必要があります。
-それは`upper`でしたか?`uppercase`でしたか?`first_uppercase`?`capitalize`?
+それは `upper` でしたか?`uppercase` でしたか?`first_uppercase`?`capitalize`?
そして、古くからプログラマーの友人であるエディタで自動補完を試してみます。
-関数の最初のパラメータ`first_name`を入力し、ドット(`.`)を入力してから、`Ctrl+Space`を押すと補完が実行されます。
+関数の最初のパラメータ `first_name` を入力し、ドット(`.`)を入力してから、`Ctrl+Space` を押すと補完が実行されます。
しかし、悲しいことに、これはなんの役にも立ちません:
@@ -78,7 +78,7 @@ John Doe
それが「型ヒント」です:
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
これは、以下のようにデフォルト値を宣言するのと同じではありません:
@@ -94,7 +94,7 @@ John Doe
しかし今、あなたが再びその関数を作成している最中に、型ヒントを使っていると想像してみてください。
-同じタイミングで`Ctrl+Space`で自動補完を実行すると、以下のようになります:
+同じタイミングで `Ctrl+Space` で自動補完を実行すると、以下のようになります:
@@ -106,15 +106,15 @@ John Doe
この関数を見てください。すでに型ヒントを持っています:
-{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます:
-これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります:
+これで `age` を `str(age)` で文字列に変換して修正する必要があることがわかります:
-{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
## 型の宣言 { #declaring-types }
@@ -124,7 +124,7 @@ John Doe
### 単純な型 { #simple-types }
-`str`だけでなく、Pythonの標準的な型すべてを宣言できます。
+`str` だけでなく、Python の標準的な型すべてを宣言できます。
例えば、以下を使用可能です:
@@ -133,51 +133,54 @@ John Doe
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### 型パラメータを持つジェネリック型 { #generic-types-with-type-parameters }
+### `typing` モジュール { #typing-module }
-データ構造の中には、`dict`、`list`、`set`、`tuple`のように他の値を含むことができるものがあります。また内部の値も独自の型を持つことができます。
+いくつかの追加のユースケースでは、標準ライブラリの `typing` モジュールから何かをインポートする必要があるかもしれません。例えば「任意の型」を受け付けることを宣言したい場合、`typing` の `Any` を使えます:
-内部の型を持つこれらの型は「**generic**」型と呼ばれます。そして、内部の型も含めて宣言することが可能です。
+```python
+from typing import Any
-これらの型や内部の型を宣言するには、Pythonの標準モジュール`typing`を使用できます。これらの型ヒントをサポートするために特別に存在しています。
-#### 新しいPythonバージョン { #newer-versions-of-python }
+def some_function(data: Any):
+ print(data)
+```
-`typing`を使う構文は、Python 3.6から最新バージョンまで(Python 3.9、Python 3.10などを含む)すべてのバージョンと **互換性** があります。
+### ジェネリック型 { #generic-types }
-Pythonが進化するにつれ、**新しいバージョン** ではこれらの型アノテーションへのサポートが改善され、多くの場合、型アノテーションを宣言するために`typing`モジュールをインポートして使う必要すらなくなります。
+一部の型は、角括弧内で「型パラメータ」を受け取り、内部の型を定義できます。例えば「文字列のリスト」は `list[str]` として宣言します。
-プロジェクトでより新しいPythonバージョンを選べるなら、その追加のシンプルさを活用できます。
+このように型パラメータを取れる型は **Generic types**(ジェネリクス)と呼ばれます。
-ドキュメント全体で、Pythonの各バージョンと互換性のある例(差分がある場合)を示しています。
+次の組み込み型をジェネリクスとして(角括弧と内部の型で)使えます:
-例えば「**Python 3.6+**」はPython 3.6以上(3.7、3.8、3.9、3.10などを含む)と互換性があることを意味します。また「**Python 3.9+**」はPython 3.9以上(3.10などを含む)と互換性があることを意味します。
-
-**最新のPythonバージョン** を使えるなら、最新バージョン向けの例を使ってください。例えば「**Python 3.10+**」のように、それらは **最良かつ最もシンプルな構文** になります。
+* `list`
+* `tuple`
+* `set`
+* `dict`
#### List { #list }
-例えば、`str`の`list`の変数を定義してみましょう。
+例えば、`str` の `list` の変数を定義してみましょう。
同じコロン(`:`)の構文で変数を宣言します。
-型として、`list`を指定します。
+型として、`list` を指定します。
リストはいくつかの内部の型を含む型なので、それらを角括弧で囲みます:
-{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
/// info | 情報
角括弧内の内部の型は「型パラメータ」と呼ばれています。
-この場合、`str`は`list`に渡される型パラメータです。
+この場合、`str` は `list` に渡される型パラメータです。
///
-つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。
+つまり: 変数 `items` は `list` であり、このリストの各項目は `str` です。
そうすることで、エディタはリストの項目を処理している間にもサポートを提供できます。
@@ -185,78 +188,54 @@ Pythonが進化するにつれ、**新しいバージョン** ではこれらの
型がなければ、それはほぼ不可能です。
-変数`item`はリスト`items`の要素の一つであることに注意してください。
+変数 `item` はリスト `items` の要素の一つであることに注意してください。
-それでも、エディタはそれが`str`であることを知っていて、そのためのサポートを提供しています。
+それでも、エディタはそれが `str` であることを知っていて、そのためのサポートを提供しています。
#### Tuple と Set { #tuple-and-set }
-`tuple`と`set`の宣言も同様です:
+`tuple` と `set` の宣言も同様です:
-{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
つまり:
-* 変数`items_t`は`int`、別の`int`、`str`の3つの項目を持つ`tuple`です。
-* 変数`items_s`は`set`であり、その各項目は`bytes`型です。
+* 変数 `items_t` は `int`、別の `int`、`str` の 3 つの項目を持つ `tuple` です。
+* 変数 `items_s` は `set` であり、その各項目は `bytes` 型です。
#### Dict { #dict }
-`dict`を定義するには、カンマ区切りで2つの型パラメータを渡します。
+`dict` を定義するには、カンマ区切りで 2 つの型パラメータを渡します。
-最初の型パラメータは`dict`のキーです。
+最初の型パラメータは `dict` のキーです。
-2番目の型パラメータは`dict`の値です:
+2 番目の型パラメータは `dict` の値です:
-{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
つまり:
-* 変数`prices`は`dict`です:
- * この`dict`のキーは`str`型です(例えば、各項目の名前)。
- * この`dict`の値は`float`型です(例えば、各項目の価格)。
+* 変数 `prices` は `dict` です:
+ * この `dict` のキーは `str` 型です(例えば、各項目の名前)。
+ * この `dict` の値は `float` 型です(例えば、各項目の価格)。
#### Union { #union }
-変数が**複数の型のいずれか**になり得ることを宣言できます。例えば、`int`または`str`です。
+変数が **複数の型のいずれか** になり得ることを宣言できます。例えば、`int` または `str` です。
-Python 3.6以上(Python 3.10を含む)では、`typing`の`Union`型を使い、角括弧の中に受け付ける可能性のある型を入れられます。
+それを定義するには、両方の型を区切るために 縦棒(`|`) を使います。
-Python 3.10では、受け付ける可能性のある型を縦棒(`|`)で区切って書ける **新しい構文** もあります。
-
-//// tab | Python 3.10+
+これは「ユニオン(union)」と呼ばれます。変数がそれら 2 つの型の集合の和集合のいずれかになり得るからです。
```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-////
+これは `item` が `int` または `str` になり得ることを意味します.
-//// tab | Python 3.9+
+#### `None` の可能性 { #possibly-none }
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b_py39.py!}
-```
-
-////
-
-どちらの場合も、`item`は`int`または`str`になり得ることを意味します。
-
-#### `None`の可能性 { #possibly-none }
-
-値が`str`のような型を持つ可能性がある一方で、`None`にもなり得ることを宣言できます。
-
-Python 3.6以上(Python 3.10を含む)では、`typing`モジュールから`Optional`をインポートして使うことで宣言できます。
-
-```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-ただの`str`の代わりに`Optional[str]`を使用することで、値が常に`str`であると仮定しているときに、実際には`None`である可能性もあるというエラーをエディタが検出するのに役立ちます。
-
-`Optional[Something]`は実際には`Union[Something, None]`のショートカットで、両者は等価です。
-
-これは、Python 3.10では`Something | None`も使えることを意味します:
+値が `str` のような型を持つ可能性がある一方で、`None` にもなり得ることを宣言できます。
//// tab | Python 3.10+
@@ -266,120 +245,31 @@ Python 3.6以上(Python 3.10を含む)では、`typing`モジュールから
////
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-////
-
-//// tab | Python 3.9+ alternative
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b_py39.py!}
-```
-
-////
-
-#### `Union`または`Optional`の使用 { #using-union-or-optional }
-
-Python 3.10未満のバージョンを使っている場合、これは私のとても **主観的** な観点からのヒントです:
-
-* 🚨 `Optional[SomeType]`は避けてください
-* 代わりに ✨ **`Union[SomeType, None]`を使ってください** ✨
-
-どちらも等価で、内部的には同じですが、`Optional`より`Union`をおすすめします。というのも「**optional**」という単語は値がオプションであることを示唆するように見えますが、実際には「`None`になり得る」という意味であり、オプションではなく必須である場合でもそうだからです。
-
-`Union[SomeType, None]`のほうが意味がより明示的だと思います。
-
-これは言葉や名前の話にすぎません。しかし、その言葉はあなたやチームメイトがコードをどう考えるかに影響し得ます。
-
-例として、この関数を見てみましょう:
-
-{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
-
-パラメータ`name`は`Optional[str]`として定義されていますが、**オプションではありません**。そのパラメータなしで関数を呼び出せません:
-
-```Python
-say_hi() # Oh, no, this throws an error! 😱
-```
-
-`name`パラメータはデフォルト値がないため、**依然として必須**(*optional*ではない)です。それでも、`name`は値として`None`を受け付けます:
-
-```Python
-say_hi(name=None) # This works, None is valid 🎉
-```
-
-良い知らせとして、Python 3.10になればその心配は不要です。型のユニオンを定義するために`|`を単純に使えるからです:
-
-{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
-
-そして、`Optional`や`Union`のような名前について心配する必要もなくなります。😎
-
-#### ジェネリック型 { #generic-types }
-
-角括弧で型パラメータを取るこれらの型は、例えば次のように **Generic types** または **Generics** と呼ばれます:
-
-//// tab | Python 3.10+
-
-同じ組み込み型をジェネリクスとして(角括弧と内部の型で)使えます:
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-また、これまでのPythonバージョンと同様に、`typing`モジュールから:
-
-* `Union`
-* `Optional`
-* ...and others.
-
-Python 3.10では、ジェネリクスの`Union`や`Optional`を使う代替として、型のユニオンを宣言するために縦棒(`|`)を使えます。これはずっと良く、よりシンプルです。
-
-////
-
-//// tab | Python 3.9+
-
-同じ組み込み型をジェネリクスとして(角括弧と内部の型で)使えます:
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-そして`typing`モジュールのジェネリクス:
-
-* `Union`
-* `Optional`
-* ...and others.
-
-////
+ただの `str` の代わりに `str | None` を使用することで、値が常に `str` であると仮定しているときに、実際には `None` である可能性もあるというエラーをエディタが検出するのに役立ちます。
### 型としてのクラス { #classes-as-types }
変数の型としてクラスを宣言することもできます。
-名前を持つ`Person`クラスがあるとしましょう:
+名前を持つ `Person` クラスがあるとしましょう:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
-変数を`Person`型として宣言できます:
+変数を `Person` 型として宣言できます:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
そして、再び、すべてのエディタのサポートを得ることができます:
-これは「`one_person`はクラス`Person`の**インスタンス**である」ことを意味します。
+これは「`one_person` はクラス `Person` の **インスタンス** である」ことを意味します。
-「`one_person`は`Person`という名前の**クラス**である」という意味ではありません。
+「`one_person` は `Person` という名前の **クラス** である」という意味ではありません。
-## Pydanticのモデル { #pydantic-models }
+## Pydantic のモデル { #pydantic-models }
-Pydantic はデータ検証を行うためのPythonライブラリです。
+Pydantic はデータ検証を行うための Python ライブラリです。
データの「形」を属性付きのクラスとして宣言します。
@@ -389,53 +279,47 @@ Python 3.10では、ジェネリクスの`Union`や`Optional`を使う代替と
また、その結果のオブジェクトですべてのエディタのサポートを受けることができます。
-Pydanticの公式ドキュメントからの例:
+Pydantic の公式ドキュメントからの例:
{* ../../docs_src/python_types/tutorial011_py310.py *}
/// info | 情報
-Pydanticの詳細はドキュメントを参照してください。
+Pydantic の詳細はドキュメントを参照してください。
///
-**FastAPI** はすべてPydanticをベースにしています。
+**FastAPI** はすべて Pydantic をベースにしています。
-すべてのことは[チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で実際に見ることができます。
-
-/// tip | 豆知識
-
-Pydanticには、デフォルト値なしで`Optional`または`Union[Something, None]`を使った場合の特別な挙動があります。詳細はPydanticドキュメントのRequired Optional fieldsを参照してください。
-
-///
+すべてのことは [チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank} で実際に見ることができます。
## メタデータアノテーション付き型ヒント { #type-hints-with-metadata-annotations }
-Pythonには、`Annotated`を使って型ヒントに**追加のメタデータ**を付与できる機能もあります。
+Python には、`Annotated` を使って型ヒントに **追加の メタデータ** を付与できる機能もあります。
-Python 3.9以降、`Annotated`は標準ライブラリの一部なので、`typing`からインポートできます。
+`Annotated` は `typing` からインポートできます。
-{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
-Python自体は、この`Annotated`で何かをするわけではありません。また、エディタや他のツールにとっても、型は依然として`str`です。
+Python 自体は、この `Annotated` で何かをするわけではありません。また、エディタや他のツールにとっても、型は依然として `str` です。
-しかし、`Annotated`内のこのスペースを使って、アプリケーションをどのように動作させたいかについての追加メタデータを **FastAPI** に提供できます。
+しかし、`Annotated` 内のこのスペースを使って、アプリケーションをどのように動作させたいかについての追加メタデータを **FastAPI** に提供できます。
-覚えておくべき重要な点は、`Annotated`に渡す**最初の*型パラメータ***が**実際の型**であることです。残りは、他のツール向けのメタデータにすぎません。
+覚えておくべき重要な点は、`Annotated` に渡す **最初の「型パラメータ」** が **実際の型** であることです。残りは、他のツール向けのメタデータにすぎません。
-今のところは、`Annotated`が存在し、それが標準のPythonであることを知っておけば十分です。😎
+今のところは、`Annotated` が存在し、それが標準の Python であることを知っておけば十分です。😎
-後で、これがどれほど**強力**になり得るかを見ることになります。
+後で、これがどれほど **強力** になり得るかを見ることになります。
/// tip | 豆知識
-これが **標準のPython** であるという事実は、エディタで、使用しているツール(コードの解析やリファクタリングなど)とともに、**可能な限り最高の開発体験**が得られることを意味します。 ✨
+これが **標準の Python** であるという事実は、エディタで、使用しているツール(コードの解析やリファクタリングなど)とともに、**可能な限り最高の開発体験** が得られることを意味します。 ✨
-また、あなたのコードが他の多くのPythonツールやライブラリとも非常に互換性が高いことも意味します。 🚀
+また、あなたのコードが他の多くの Python ツールやライブラリとも非常に互換性が高いことも意味します。 🚀
///
-## **FastAPI**での型ヒント { #type-hints-in-fastapi }
+## **FastAPI** での型ヒント { #type-hints-in-fastapi }
**FastAPI** はこれらの型ヒントを利用していくつかのことを行います。
@@ -450,15 +334,15 @@ Python自体は、この`Annotated`で何かをするわけではありません
* **データの変換**: リクエストから必要な型にデータを変換します。
* **データの検証**: 各リクエストから来るデータについて:
* データが無効な場合にクライアントに返される **自動エラー** を生成します。
-* OpenAPIを使用してAPIを**ドキュメント化**します:
+* OpenAPI を使用して API を **ドキュメント化** します:
* これは自動の対話型ドキュメントのユーザーインターフェイスで使われます。
-すべてが抽象的に聞こえるかもしれません。心配しないでください。 この全ての動作は [チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で見ることができます。
+すべてが抽象的に聞こえるかもしれません。心配しないでください。 この全ての動作は [チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank} で見ることができます。
-重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。
+重要なのは、Python の標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1 つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。
/// info | 情報
-すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、良いリソースとして`mypy`の「チートシート」があります。
+すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、良いリソースとして `mypy` の「チートシート」 があります。
///
diff --git a/docs/ja/docs/resources/index.md b/docs/ja/docs/resources/index.md
new file mode 100644
index 000000000..15a949e01
--- /dev/null
+++ b/docs/ja/docs/resources/index.md
@@ -0,0 +1,3 @@
+# リソース { #resources }
+
+追加リソース、外部リンクなど。✈️
diff --git a/docs/ja/docs/translation-banner.md b/docs/ja/docs/translation-banner.md
new file mode 100644
index 000000000..351a82a35
--- /dev/null
+++ b/docs/ja/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 AI と人間による翻訳
+
+この翻訳は、人間のガイドに基づいて AI によって作成されました。🤝
+
+原文の意図を取り違えていたり、不自然な表現になっている可能性があります。🤖
+
+[AI LLM をより適切に誘導するのを手伝う](https://fastapi.tiangolo.com/ja/contributing/#translations) ことで、この翻訳を改善できます。
+
+[英語版](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md
index 0ed41ce11..d32c141b5 100644
--- a/docs/ja/docs/tutorial/background-tasks.md
+++ b/docs/ja/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@
まず初めに、`BackgroundTasks` をインポートし、`BackgroundTasks` の型宣言と共に、*path operation function* のパラメーターを定義します:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。
@@ -31,13 +31,13 @@
また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
## バックグラウンドタスクの追加 { #add-the-background-task }
*path operation function* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` は以下の引数を受け取ります:
diff --git a/docs/ja/docs/tutorial/bigger-applications.md b/docs/ja/docs/tutorial/bigger-applications.md
new file mode 100644
index 000000000..9c1cc0fe6
--- /dev/null
+++ b/docs/ja/docs/tutorial/bigger-applications.md
@@ -0,0 +1,504 @@
+# 大規模アプリケーション - 複数ファイル { #bigger-applications-multiple-files }
+
+アプリケーションや Web API を作る場合、すべてを1つのファイルに収められることはほとんどありません。
+
+**FastAPI** は、柔軟性を保ったままアプリケーションを構造化できる便利なツールを提供します。
+
+/// info | 情報
+
+Flask 出身であれば、Flask の Blueprint に相当します。
+
+///
+
+## 例のファイル構成 { #an-example-file-structure }
+
+次のようなファイル構成があるとします:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | 豆知識
+
+複数の `__init__.py` ファイルがあります: 各ディレクトリやサブディレクトリに1つずつです。
+
+これにより、あるファイルから別のファイルへコードをインポートできます。
+
+例えば、`app/main.py` では次のように書けます:
+
+```
+from app.routers import items
+```
+
+///
+
+* `app` ディレクトリはすべてを含みます。そして空のファイル `app/__init__.py` があり、「Python パッケージ」(「Python モジュール」の集合): `app` です。
+* `app/main.py` ファイルがあります。Python パッケージ(`__init__.py` のあるディレクトリ)の中にあるため、そのパッケージの「モジュール」: `app.main` です。
+* `app/dependencies.py` ファイルもあり、`app/main.py` と同様に「モジュール」: `app.dependencies` です。
+* `app/routers/` サブディレクトリに別の `__init__.py` があるので、「Python サブパッケージ」: `app.routers` です。
+* `app/routers/items.py` はパッケージ `app/routers/` 内のファイルなので、サブモジュール: `app.routers.items` です。
+* `app/routers/users.py` も同様で、別のサブモジュール: `app.routers.users` です。
+* `app/internal/` サブディレクトリにも `__init__.py` があるので、別の「Python サブパッケージ」: `app.internal` です。
+* `app/internal/admin.py` は別のサブモジュール: `app.internal.admin` です。
+
+
+
+同じファイル構成にコメントを付けると次のとおりです:
+
+```bash
+.
+├── app # "app" is a Python package
+│ ├── __init__.py # this file makes "app" a "Python package"
+│ ├── main.py # "main" module, e.g. import app.main
+│ ├── dependencies.py # "dependencies" module, e.g. import app.dependencies
+│ └── routers # "routers" is a "Python subpackage"
+│ │ ├── __init__.py # makes "routers" a "Python subpackage"
+│ │ ├── items.py # "items" submodule, e.g. import app.routers.items
+│ │ └── users.py # "users" submodule, e.g. import app.routers.users
+│ └── internal # "internal" is a "Python subpackage"
+│ ├── __init__.py # makes "internal" a "Python subpackage"
+│ └── admin.py # "admin" submodule, e.g. import app.internal.admin
+```
+
+## `APIRouter` { #apirouter }
+
+ユーザーだけを扱うファイルが `/app/routers/users.py` のサブモジュールだとします。
+
+ユーザーに関連する *path operations* をほかのコードから分離して整理したいはずです。
+
+ただし、同じ **FastAPI** アプリケーション / Web API(同じ「Python パッケージ」の一部)である点は変わりません。
+
+そのモジュールで `APIRouter` を使って *path operations* を作成できます。
+
+### `APIRouter` のインポート { #import-apirouter }
+
+クラス `FastAPI` と同様にインポートし、「インスタンス」を作成します:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+
+### `APIRouter` での *path operations* { #path-operations-with-apirouter }
+
+これを使って *path operations* を宣言します。
+
+使い方は `FastAPI` クラスと同じです:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+
+`APIRouter` は「ミニ `FastAPI`」のようなクラスと考えられます。
+
+同じオプションがすべてサポートされています。
+
+同じ `parameters`、`responses`、`dependencies`、`tags` などが使えます。
+
+/// tip | 豆知識
+
+この例では変数名は `router` ですが、任意の名前を付けられます。
+
+///
+
+この `APIRouter` をメインの `FastAPI` アプリに取り込みますが、その前に依存関係と別の `APIRouter` を確認します。
+
+## 依存関係 { #dependencies }
+
+アプリケーションの複数箇所で使う依存関係が必要になります。
+
+そのため、専用の `dependencies` モジュール(`app/dependencies.py`)に置きます。
+
+ここではカスタムヘッダー `X-Token` を読む簡単な依存関係を使います:
+
+{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+
+/// tip | 豆知識
+
+この例を簡単にするために架空のヘッダーを使っています。
+
+しかし実際には、組み込みの [Security utilities](security/index.md){.internal-link target=_blank} を使う方が良い結果になります。
+
+///
+
+## 別モジュールでの `APIRouter` { #another-module-with-apirouter }
+
+アプリケーションの「items」を扱うエンドポイントが `app/routers/items.py` のモジュールにあるとします。
+
+次の *path operations* があります:
+
+* `/items/`
+* `/items/{item_id}`
+
+構造は `app/routers/users.py` と同じです。
+
+しかし、もう少し賢くしてコードを少し簡潔にしたいところです。
+
+このモジュールのすべての *path operations* には同じものがあると分かっています:
+
+* パスの `prefix`: `/items`
+* `tags`(1つのタグ: `items`)
+* 追加の `responses`
+* `dependencies`: 先ほど作成した `X-Token` の依存関係が必要
+
+そこで、各 *path operation* に個別に追加する代わりに、これらを `APIRouter` に追加できます。
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+
+各 *path operation* のパスは次のように `/` で始める必要があるため:
+
+```Python hl_lines="1"
+@router.get("/{item_id}")
+async def read_item(item_id: str):
+ ...
+```
+
+...prefix の末尾に `/` を含めてはいけません。
+
+この場合の prefix は `/items` です。
+
+また、`tags` のリストや追加の `responses` を、このルーターに含まれるすべての *path operations* に適用するよう追加できます。
+
+さらに `dependencies` のリストを追加できます。これはこのルーター内のすべての *path operations* に追加され、それらへの各リクエストごとに実行・解決されます。
+
+/// tip | 豆知識
+
+[*path operation デコレータ*の依存関係](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} と同様に、*path operation 関数*には値は渡されない点に注意してください。
+
+///
+
+最終的に、item のパスは次のとおりになります:
+
+* `/items/`
+* `/items/{item_id}`
+
+...意図したとおりです。
+
+* これらには、文字列 `"items"` を1つ含むタグのリストが付きます。
+ * これらの「タグ」は、(OpenAPI を使う)自動インタラクティブドキュメントで特に有用です。
+* すべてに事前定義した `responses` が含まれます。
+* これらすべての *path operations* では、実行前に `dependencies` のリストが評価・実行されます。
+ * 特定の *path operation* に依存関係を宣言した場合は、**それらも実行されます**。
+ * ルーターの依存関係が先に実行され、その後に[デコレータ内の `dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}、次に通常のパラメータ依存関係が続きます。
+ * [`scopes` を伴う `Security` 依存関係](../advanced/security/oauth2-scopes.md){.internal-link target=_blank} を追加することもできます。
+
+/// tip | 豆知識
+
+`APIRouter` に `dependencies` を置くことで、*path operations* のグループ全体に認証を要求する、といった用途に使えます。個々の *path operation* に依存関係を追加していなくても構いません。
+
+///
+
+/// check | 確認
+
+`prefix`、`tags`、`responses`、`dependencies` の各パラメータは(ほかの多くのケースと同様に)コード重複を避けるための **FastAPI** の機能です。
+
+///
+
+### 依存関係をインポート { #import-the-dependencies }
+
+このコードはモジュール `app.routers.items`(ファイル `app/routers/items.py`)内にあります。
+
+そして依存関係の関数はモジュール `app.dependencies`(ファイル `app/dependencies.py`)から取得する必要があります。
+
+そこで、依存関係には `..` を使った相対インポートを使います:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}
+
+#### 相対インポートの仕組み { #how-relative-imports-work }
+
+/// tip | 豆知識
+
+インポートの仕組みを十分理解している場合は、次の節に進んでください。
+
+///
+
+ドット1つ `.` を使うと、次のような意味になります:
+
+```Python
+from .dependencies import get_token_header
+```
+
+意味:
+
+* このモジュール(`app/routers/items.py`)が存在する同じパッケージ(ディレクトリ `app/routers/`)から開始し...
+* モジュール `dependencies`(仮想的には `app/routers/dependencies.py`)を探し...
+* そこから関数 `get_token_header` をインポートする。
+
+しかしそのファイルは存在せず、実際の依存関係は `app/dependencies.py` にあります。
+
+アプリ/ファイル構成がどうなっていたかを思い出してください:
+
+
+
+---
+
+ドット2つ `..` を使うと、次のようになります:
+
+```Python
+from ..dependencies import get_token_header
+```
+
+意味:
+
+* このモジュール(`app/routers/items.py`)が存在する同じパッケージ(ディレクトリ `app/routers/`)から開始し...
+* 親パッケージ(ディレクトリ `app/`)に移動し...
+* そこでモジュール `dependencies`(ファイル `app/dependencies.py`)を探し...
+* そこから関数 `get_token_header` をインポートする。
+
+これは正しく動作します! 🎉
+
+---
+
+同様に、ドット3つ `...` を使うと:
+
+```Python
+from ...dependencies import get_token_header
+```
+
+意味:
+
+* このモジュール(`app/routers/items.py`)が存在する同じパッケージ(ディレクトリ `app/routers/`)から開始し...
+* 親パッケージ(ディレクトリ `app/`)に移動し...
+* さらにその親パッケージに移動しようとします(`app` は最上位なので親パッケージはありません 😱)...
+* そこでモジュール `dependencies`(ファイル `app/dependencies.py`)を探し...
+* そこから関数 `get_token_header` をインポートする。
+
+これは `app/` より上位のパッケージ(独自の `__init__.py` を持つ)を参照することになります。しかしそのようなものはありません。そのため、この例ではエラーになります。🚨
+
+これで仕組みが分かったので、どれほど複雑でも自分のアプリで相対インポートを使えます。🤓
+
+### カスタムの `tags`、`responses`、`dependencies` を追加 { #add-some-custom-tags-responses-and-dependencies }
+
+`APIRouter` に追加済みなので、各 *path operation* に `/items` の prefix や `tags=["items"]` を付けていません。
+
+しかし、特定の *path operation* に適用される _追加の_ `tags` や、その *path operation* 固有の追加の `responses` を加えることはできます:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+
+/// tip | 豆知識
+
+この最後の *path operation* は、`["items", "custom"]` のタグの組み合わせを持ちます。
+
+またドキュメントには `404` と `403` の両方のレスポンスが表示されます。
+
+///
+
+## メインの `FastAPI` { #the-main-fastapi }
+
+次に、`app/main.py` のモジュールを見ていきます。
+
+ここでクラス `FastAPI` をインポートして使用します。
+
+これはすべてをまとめるアプリケーションのメインファイルになります。
+
+そして大部分のロジックはそれぞれの専用モジュールに置かれるため、メインファイルはかなりシンプルになります。
+
+### `FastAPI` のインポート { #import-fastapi }
+
+通常どおり `FastAPI` クラスをインポートして作成します。
+
+さらに、各 `APIRouter` の依存関係と組み合わされる[グローバル依存関係](dependencies/global-dependencies.md){.internal-link target=_blank}も宣言できます:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
+
+### `APIRouter` のインポート { #import-the-apirouter }
+
+次に、`APIRouter` を持つ他のサブモジュールをインポートします:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}
+
+`app/routers/users.py` と `app/routers/items.py` は同じ Python パッケージ `app` のサブモジュールなので、1つのドット `.` を使った「相対インポート」でインポートできます。
+
+### インポートの動作 { #how-the-importing-works }
+
+次の部分:
+
+```Python
+from .routers import items, users
+```
+
+は次の意味です:
+
+* このモジュール(`app/main.py`)が存在する同じパッケージ(ディレクトリ `app/`)から開始し...
+* サブパッケージ `routers`(ディレクトリ `app/routers/`)を探し...
+* そこからサブモジュール `items`(ファイル `app/routers/items.py`)と `users`(ファイル `app/routers/users.py`)をインポートする...
+
+モジュール `items` には変数 `router`(`items.router`)があります。これは `app/routers/items.py` で作成した `APIRouter` オブジェクトと同じものです。
+
+モジュール `users` についても同様です。
+
+次のようにインポートすることもできます:
+
+```Python
+from app.routers import items, users
+```
+
+/// info | 情報
+
+最初のバージョンは「相対インポート」です:
+
+```Python
+from .routers import items, users
+```
+
+2つ目のバージョンは「絶対インポート」です:
+
+```Python
+from app.routers import items, users
+```
+
+Python のパッケージとモジュールについて詳しくは、公式の Python モジュールに関するドキュメントをご覧ください。
+
+///
+
+### 名前衝突の回避 { #avoid-name-collisions }
+
+サブモジュール `items` の変数 `router` だけをインポートするのではなく、サブモジュール自体を直接インポートしています。
+
+これは、サブモジュール `users` にも `router` という変数があるためです。
+
+もし次のように続けてインポートした場合:
+
+```Python
+from .routers.items import router
+from .routers.users import router
+```
+
+`users` の `router` が `items` のものを上書きしてしまい、同時に両方を使えなくなります。
+
+同じファイルで両方を使えるようにするため、サブモジュールを直接インポートします:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}
+
+### `users` と `items` の `APIRouter` を取り込む { #include-the-apirouters-for-users-and-items }
+
+では、サブモジュール `users` と `items` から `router` を取り込みます:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}
+
+/// info | 情報
+
+`users.router` は、ファイル `app/routers/users.py` 内の `APIRouter` を含みます。
+
+`items.router` は、ファイル `app/routers/items.py` 内の `APIRouter` を含みます。
+
+///
+
+`app.include_router()` を使って、各 `APIRouter` をメインの `FastAPI` アプリケーションに追加できます。
+
+そのルーターのすべてのルートがアプリに含まれます。
+
+/// note | 技術詳細
+
+実際には、`APIRouter` で宣言された各 *path operation* ごとに内部的に *path operation* が作成されます。
+
+つまり裏側では、すべてが同じ単一のアプリであるかのように動作します。
+
+///
+
+/// check | 確認
+
+ルーターを取り込んでもパフォーマンスを心配する必要はありません。
+
+これは起動時にマイクロ秒で行われます。
+
+したがってパフォーマンスには影響しません。⚡
+
+///
+
+### カスタムの `prefix`、`tags`、`responses`、`dependencies` 付きで `APIRouter` を取り込む { #include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies }
+
+あなたの組織から `app/internal/admin.py` ファイルが提供されたとしましょう。
+
+そこには、組織が複数プロジェクトで共有している管理用の *path operations* を持つ `APIRouter` が含まれています。
+
+この例ではとてもシンプルですが、組織内の他プロジェクトと共有しているため、`APIRouter` 自体を直接変更して `prefix`、`dependencies`、`tags` などを追加できないとします:
+
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+
+それでも、`APIRouter` を取り込む際にカスタムの `prefix` を設定してすべての *path operations* を `/admin` で始めたい、既存の `dependencies` で保護したい、さらに `tags` と `responses` も含めたいとします。
+
+元の `APIRouter` を変更することなく、`app.include_router()` にこれらのパラメータを渡すことで宣言できます:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}
+
+このようにすると、元の `APIRouter` は未変更のままなので、同じ `app/internal/admin.py` ファイルを組織内の他プロジェクトとも引き続き共有できます。
+
+結果として、このアプリ内では `admin` モジュールの各 *path operation* が次のようになります:
+
+* prefix は `/admin`
+* タグは `admin`
+* 依存関係は `get_token_header`
+* レスポンスは `418` 🍵
+
+ただし、これはこのアプリ内のその `APIRouter` にのみ影響し、それを使用する他のコードには影響しません。
+
+例えば、他のプロジェクトでは同じ `APIRouter` を別の認証方式で使うこともできます。
+
+### *path operation* を追加 { #include-a-path-operation }
+
+`FastAPI` アプリに *path operations* を直接追加することもできます。
+
+ここでは(できることを示すためだけに)追加します 🤷:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}
+
+そして、`app.include_router()` で追加したほかの *path operations* と一緒に正しく動作します。
+
+/// info | 非常に技術的な詳細
+
+注記: これは非常に技術的な詳細で、**読み飛ばして構いません**。
+
+---
+
+`APIRouter` は「マウント」されておらず、アプリケーションの他部分から分離されていません。
+
+これは、それらの *path operations* を OpenAPI スキーマやユーザーインターフェースに含めたいからです。
+
+完全に分離して独立に「マウント」できないため、*path operations* は直接取り込まれるのではなく「クローン(再作成)」されます。
+
+///
+
+## 自動APIドキュメントの確認 { #check-the-automatic-api-docs }
+
+アプリを実行します:
+
+
+
+## 同じルーターを異なる `prefix` で複数回取り込む { #include-the-same-router-multiple-times-with-different-prefix }
+
+同じルーターに対して、異なる prefix で `.include_router()` を複数回使うこともできます。
+
+例えば、同じ API を `/api/v1` と `/api/latest` のように異なる prefix で公開する場合に役立ちます。
+
+高度な使い方なので不要かもしれませんが、必要な場合に備えて用意されています。
+
+## `APIRouter` を別の `APIRouter` に取り込む { #include-an-apirouter-in-another }
+
+`APIRouter` を `FastAPI` アプリケーションに取り込めるのと同じように、`APIRouter` を別の `APIRouter` に取り込むこともできます:
+
+```Python
+router.include_router(other_router)
+```
+
+`router` を `FastAPI` アプリに取り込む前にこれを実行して、`other_router` の *path operations* も含まれるようにしてください。
diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md
index 4ce77cc0d..0f81f4c46 100644
--- a/docs/ja/docs/tutorial/body-multiple-params.md
+++ b/docs/ja/docs/tutorial/body-multiple-params.md
@@ -106,12 +106,6 @@
q: str | None = None
```
-またはPython 3.10以上では:
-
-```Python
-q: Union[str, None] = None
-```
-
例えば:
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md
index 24eb30208..ab78b8f86 100644
--- a/docs/ja/docs/tutorial/body-nested-models.md
+++ b/docs/ja/docs/tutorial/body-nested-models.md
@@ -164,7 +164,7 @@ images: list[Image]
以下のように:
-{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
## あらゆる場所でのエディタサポート { #editor-support-everywhere }
@@ -194,7 +194,7 @@ Pydanticモデルではなく、`dict`を直接使用している場合はこの
この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます:
-{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
/// tip | 豆知識
diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md
index e888d5a0d..310530c69 100644
--- a/docs/ja/docs/tutorial/body-updates.md
+++ b/docs/ja/docs/tutorial/body-updates.md
@@ -68,7 +68,7 @@
まとめると、部分的な更新を適用するには、次のようにします:
-* (オプションで)`PUT`の代わりに`PATCH`を使用します。
+* (オプションで)`PATCH`の代わりに`PUT`を使用します。
* 保存されているデータを取得します。
* そのデータをPydanticモデルにいれます。
* 入力モデルからデフォルト値を含まない`dict`を生成します(`exclude_unset`を使用します)。
diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md
index a219faed0..7c939bdfa 100644
--- a/docs/ja/docs/tutorial/body.md
+++ b/docs/ja/docs/tutorial/body.md
@@ -74,7 +74,7 @@ APIはほとんどの場合 **レスポンス** ボディを送信する必要
* 受け取ったデータをパラメータ `item` に渡します。
* 関数内で `Item` 型として宣言したため、すべての属性とその型について、エディタサポート(補完など)も利用できます。
* モデル向けの JSON Schema 定義を生成します。プロジェクトにとって意味があるなら、他の場所でも好きなように利用できます。
-* それらのスキーマは生成されるOpenAPIスキーマの一部となり、自動ドキュメントの UIs で使用されます。
+* それらのスキーマは生成されるOpenAPIスキーマの一部となり、自動ドキュメントの UIs で使用されます。
## 自動ドキュメント { #automatic-docs }
@@ -155,7 +155,7 @@ APIはほとんどの場合 **レスポンス** ボディを送信する必要
FastAPIは、デフォルト値 `= None` があるため、`q` の値が必須ではないことを認識します。
-`str | None`(Python 3.10+)や `Union[str, None]`(Python 3.9+)の `Union` は、値が必須ではないことを判断するためにFastAPIでは使用されません。`= None` というデフォルト値があるため、必須ではないことを認識します。
+`str | None` は、値が必須ではないことを判断するためにFastAPIでは使用されません。`= None` というデフォルト値があるため、必須ではないことを認識します。
しかし、型アノテーションを追加すると、エディタがより良いサポートを提供し、エラーを検出できるようになります。
diff --git a/docs/ja/docs/tutorial/cookie-param-models.md b/docs/ja/docs/tutorial/cookie-param-models.md
index 10ffb2566..89ae42438 100644
--- a/docs/ja/docs/tutorial/cookie-param-models.md
+++ b/docs/ja/docs/tutorial/cookie-param-models.md
@@ -46,7 +46,7 @@
特定の(あまり一般的ではないかもしれない)ケースで、受け付けるクッキーを**制限**する必要があるかもしれません。
-あなたのAPIは独自の クッキー同意 を管理する能力を持っています。 🤪🍪
+あなたのAPIは独自の クッキー同意 を管理する能力を持っています。 🤪🍪
Pydanticのモデルの Configuration を利用して、 `extra` フィールドを `forbid` とすることができます。
@@ -54,9 +54,9 @@ Pydanticのモデルの Configuration を利用して、 `extra` フィールド
もしクライアントが**余分なクッキー**を送ろうとすると、**エラー**レスポンスが返されます。
-どうせAPIに拒否されるのにあなたの同意を得ようと精一杯努力する可哀想なクッキーバナーたち... 🍪
+どうせAPIに拒否されるのにあなたの同意を得ようと精一杯努力する可哀想なクッキーバナーたち... 🍪
-例えば、クライアントがクッキー `santa_tracker` を `good-list-please` という値で送ろうとすると、`santa_tracker` という クッキーが許可されていない ことを通知する**エラー**レスポンスが返されます:
+例えば、クライアントがクッキー `santa_tracker` を `good-list-please` という値で送ろうとすると、`santa_tracker` という クッキーが許可されていない ことを通知する**エラー**レスポンスが返されます:
```json
{
@@ -73,4 +73,4 @@ Pydanticのモデルの Configuration を利用して、 `extra` フィールド
## まとめ { #summary }
-**FastAPI**では、**クッキー**を宣言するために、**Pydanticモデル**を使用できます。😎
+**FastAPI**では、**クッキー**を宣言するために、**Pydanticモデル**を使用できます。😎
diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md
index a1dfe8e62..5136a7fd5 100644
--- a/docs/ja/docs/tutorial/cors.md
+++ b/docs/ja/docs/tutorial/cors.md
@@ -46,7 +46,7 @@
* 特定のHTTPメソッド (`POST`、`PUT`) またはワイルドカード `"*"` を使用してすべて許可。
* 特定のHTTPヘッダー、またはワイルドカード `"*"`を使用してすべて許可。
-{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *}
`CORSMiddleware` 実装で使用されるデフォルトのパラメータはデフォルトで制限が厳しいため、ブラウザがクロスドメインのコンテキストでそれらを使用できるようにするには、特定のオリジン、メソッド、またはヘッダーを明示的に有効にする必要があります。
diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md
index 8fe5b2d5d..9d88ba42b 100644
--- a/docs/ja/docs/tutorial/debugging.md
+++ b/docs/ja/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@ Visual Studio CodeやPyCharmなどを使用して、エディター上でデバ
FastAPIアプリケーション上で、`uvicorn` を直接インポートして実行します:
-{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *}
### `__name__ == "__main__"` について { #about-name-main }
diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md
index 3cb1fe73d..21de5b978 100644
--- a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -101,7 +101,7 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可
上のコードでは`CommonQueryParams`を2回書いていることに注目してください:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ 注釈なし
+//// tab | Python 3.10+ 注釈なし
/// tip | 豆知識
@@ -137,7 +137,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
この場合、以下にある最初の`CommonQueryParams`:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.9+ 注釈なし
+//// tab | Python 3.10+ 注釈なし
/// tip | 豆知識
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
実際には以下のように書けばいいだけです:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ 注釈なし
+//// tab | Python 3.10+ 注釈なし
/// tip | 豆知識
@@ -197,7 +197,7 @@ commons = Depends(CommonQueryParams)
しかし、ここでは`CommonQueryParams`を2回書くというコードの繰り返しが発生していることがわかります:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ 注釈なし
+//// tab | Python 3.10+ 注釈なし
/// tip | 豆知識
@@ -225,7 +225,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
以下のように書く代わりに:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ 注釈なし
+//// tab | Python 3.10+ 注釈なし
/// tip | 豆知識
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
...以下のように書きます:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.9+ 注釈なし
+//// tab | Python 3.10+ 注釈なし
/// tip | 豆知識
diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 2051afc05..d0a2b1672 100644
--- a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -14,7 +14,7 @@
それは`Depends()`の`list`であるべきです:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation 関数*には渡されません。
@@ -44,13 +44,13 @@
これらはリクエストの要件(ヘッダーのようなもの)やその他のサブ依存関係を宣言できます:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
### 例外の発生 { #raise-exceptions }
これらの依存関係は、通常の依存関係と同じように例外を`raise`できます:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
### 戻り値 { #return-values }
@@ -58,7 +58,7 @@
つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用でき、値は使われなくても依存関係は実行されます:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
## *path operation*のグループに対する依存関係 { #dependencies-for-a-group-of-path-operations }
diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md
index 8095114c3..380dcb536 100644
--- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,6 +1,6 @@
# `yield`を持つ依存関係 { #dependencies-with-yield }
-FastAPIは、いくつかの終了後の追加のステップを行う依存関係をサポートしています。
+FastAPIは、いくつかの終了後の追加のステップを行う依存関係をサポートしています。
これを行うには、`return`の代わりに`yield`を使い、その後に追加のステップ(コード)を書きます。
@@ -29,15 +29,15 @@ FastAPIは、いくつかの
+
+kwargsとしても知られています。たとえデフォルト値がなくても。
+Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。
-{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
### `Annotated`のほうがよい { #better-with-annotated }
`Annotated`を使う場合は、関数パラメータのデフォルト値を使わないため、この問題は起きず、おそらく`*`を使う必要もありません。
-{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
## 数値の検証: 以上 { #number-validations-greater-than-or-equal }
@@ -97,7 +97,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降
ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなければなりません。
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
## 数値の検証: より大きいと小なりイコール { #number-validations-greater-than-and-less-than-or-equal }
@@ -106,7 +106,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
## 数値の検証: 浮動小数点、 大なり小なり { #number-validations-floats-greater-than-and-less-than }
@@ -118,7 +118,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降
これはltも同じです。
-{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
## まとめ { #recap }
diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md
index 96a1fe9d1..5b78eb7b1 100644
--- a/docs/ja/docs/tutorial/path-params.md
+++ b/docs/ja/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Pythonのformat文字列と同様のシンタックスで「パスパラメータ」や「パス変数」を宣言できます:
-{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
パスパラメータ `item_id` の値は、引数 `item_id` として関数に渡されます。
@@ -16,7 +16,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
標準のPythonの型アノテーションを使用して、関数内のパスパラメータの型を宣言できます:
-{* ../../docs_src/path_params/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
ここでは、 `item_id` は `int` として宣言されています。
@@ -26,7 +26,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
///
-## データ変換 { #data-conversion }
+## データ変換 { #data-conversion }
この例を実行し、ブラウザで http://127.0.0.1:8000/items/3 を開くと、次のレスポンスが表示されます:
@@ -38,7 +38,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
-したがって、その型宣言を使うと、**FastAPI**は自動リクエスト "解析" を行います。
+したがって、その型宣言を使うと、**FastAPI**は自動リクエスト "解析" を行います。
///
@@ -118,13 +118,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
*path operations* は順に評価されるので、 `/users/me` が `/users/{user_id}` よりも先に宣言されているか確認する必要があります:
-{* ../../docs_src/path_params/tutorial003_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
それ以外の場合、 `/users/{user_id}` は `/users/me` としてもマッチします。値が `"me"` であるパラメータ `user_id` を受け取ると「考え」ます。
同様に、path operation を再定義することはできません:
-{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
パスは最初にマッチしたものが常に使われるため、最初のものが常に使用されます。
@@ -140,11 +140,11 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
そして、固定値のクラス属性を作ります。すると、その値が使用可能な値となります:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
/// tip | 豆知識
-"AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。
+"AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。
///
@@ -152,7 +152,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
次に、作成したenumクラスである`ModelName`を使用した型アノテーションをもつ*パスパラメータ*を作成します:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
### ドキュメントの確認 { #check-the-docs }
@@ -168,13 +168,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
これは、作成した列挙型 `ModelName` の*列挙型メンバ*と比較できます:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[17] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
#### *列挙値*の取得 { #get-the-enumeration-value }
`model_name.value` 、もしくは一般に、 `your_enum_member.value` を使用して実際の値 (この場合は `str`) を取得できます。
-{* ../../docs_src/path_params/tutorial005_py39.py hl[20] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
/// tip | 豆知識
@@ -188,7 +188,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
それらはクライアントに返される前に適切な値 (この場合は文字列) に変換されます。
-{* ../../docs_src/path_params/tutorial005_py39.py hl[18,21,23] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
クライアントは以下の様なJSONレスポンスを得ます:
@@ -227,7 +227,7 @@ Starletteのオプションを直接使用することで、以下のURLの様
したがって、以下の様に使用できます:
-{* ../../docs_src/path_params/tutorial004_py39.py hl[6] *}
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
/// tip | 豆知識
@@ -242,7 +242,7 @@ Starletteのオプションを直接使用することで、以下のURLの様
簡潔で、本質的で、標準的なPythonの型宣言を使用することで、**FastAPI**は以下を行います:
* エディターサポート: エラーチェック、自動補完、など
-* データ「解析」
+* データ「解析」
* データバリデーション
* APIアノテーションと自動ドキュメント生成
diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md
index e230ef29a..dda4e120b 100644
--- a/docs/ja/docs/tutorial/query-params-str-validations.md
+++ b/docs/ja/docs/tutorial/query-params-str-validations.md
@@ -47,40 +47,16 @@ FastAPI はバージョン 0.95.0 で `Annotated` のサポートを追加し(
次の型アノテーションがありました:
-//// tab | Python 3.10+
-
```Python
q: str | None = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Union[str, None] = None
-```
-
-////
-
これを `Annotated` で包んで、次のようにします:
-//// tab | Python 3.10+
-
```Python
q: Annotated[str | None] = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Annotated[Union[str, None]] = None
-```
-
-////
-
どちらも同じ意味で、`q` は `str` または `None` になり得るパラメータで、デフォルトでは `None` です。
では、面白いところに進みましょう。 🎉
@@ -109,7 +85,7 @@ FastAPI は次を行います:
## 代替(古い方法): デフォルト値としての `Query` { #alternative-old-query-as-the-default-value }
-FastAPI の以前のバージョン(0.95.0 より前)では、パラメータのデフォルト値として `Query` を使う必要があり、`Annotated` の中に入れるのではありませんでした。これを使ったコードを見かける可能性が高いので、説明します。
+FastAPI の以前のバージョン(0.95.0 より前)では、パラメータのデフォルト値として `Query` を使う必要があり、`Annotated` の中に入れるのではありませんでした。これを使ったコードを見かける可能性が高いので、説明します。
/// tip | 豆知識
@@ -192,7 +168,7 @@ FastAPI なしで同じ関数を **別の場所** から **呼び出しても**
## 正規表現の追加 { #add-regular-expressions }
-パラメータが一致するべき 正規表現 `pattern` を定義することができます:
+パラメータが一致するべき 正規表現 `pattern` を定義することができます:
{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
@@ -212,7 +188,7 @@ FastAPI なしで同じ関数を **別の場所** から **呼び出しても**
クエリパラメータ `q` の `min_length` を `3` とし、デフォルト値を `"fixedquery"` として宣言したいとします:
-{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial005_an_py310.py hl[9] *}
/// note | 備考
@@ -242,7 +218,7 @@ q: Annotated[str | None, Query(min_length=3)] = None
そのため、`Query` を使いながら値を必須として宣言したい場合は、単にデフォルト値を宣言しません:
-{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial006_an_py310.py hl[9] *}
### 必須、`None` にできる { #required-can-be-none }
@@ -293,7 +269,7 @@ http://localhost:8000/items/?q=foo&q=bar
また、値が指定されていない場合はデフォルトの `list` を定義することもできます。
-{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
以下にアクセスすると:
@@ -316,7 +292,7 @@ http://localhost:8000/items/
`list[str]` の代わりに直接 `list` を使うこともできます:
-{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
/// note | 備考
@@ -372,7 +348,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
さて、このパラメータが気に入らなくなったとしましょう。
-それを使っているクライアントがいるので、しばらくは残しておく必要がありますが、ドキュメントにはdeprecatedと明記しておきたいです。
+それを使っているクライアントがいるので、しばらくは残しておく必要がありますが、ドキュメントにはdeprecatedと明記しておきたいです。
その場合、`Query`にパラメータ`deprecated=True`を渡します:
@@ -402,7 +378,7 @@ Pydantic には ISBN の書籍番号なら item ID が `isbn-` で始まること、IMDB の movie URL ID なら `imdb-` で始まることをチェックします:
+例えば、このカスタムバリデータは、ISBN の書籍番号なら item ID が `isbn-` で始まること、IMDB の movie URL ID なら `imdb-` で始まることをチェックします:
{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
@@ -436,7 +412,7 @@ Pydantic には 反復可能オブジェクト を取得します。
+`data.items()` で、辞書の各アイテムのキーと値を含むタプルを持つ 反復可能オブジェクト を取得します。
この反復可能オブジェクトを `list(data.items())` で適切な `list` に変換します。
diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md
index 41e51ed78..d32c9822b 100644
--- a/docs/ja/docs/tutorial/query-params.md
+++ b/docs/ja/docs/tutorial/query-params.md
@@ -2,7 +2,7 @@
パスパラメータではない関数パラメータを宣言すると、それらは自動的に「クエリ」パラメータとして解釈されます。
-{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
クエリはURL内で `?` の後に続くキーとバリューの組で、 `&` で区切られています。
@@ -24,7 +24,7 @@ http://127.0.0.1:8000/items/?skip=0&limit=10
パスパラメータに適用される処理と完全に同様な処理がクエリパラメータにも施されます:
* エディターサポート (明らかに)
-* データ 「解析」
+* データ 「解析」
* データバリデーション
* 自動ドキュメント生成
@@ -128,7 +128,7 @@ http://127.0.0.1:8000/items/foo?short=yes
しかしクエリパラメータを必須にしたい場合は、ただデフォルト値を宣言しなければよいです:
-{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
ここで、クエリパラメータ `needy` は `str` 型の必須のクエリパラメータです。
diff --git a/docs/ja/docs/tutorial/request-files.md b/docs/ja/docs/tutorial/request-files.md
new file mode 100644
index 000000000..538cf6474
--- /dev/null
+++ b/docs/ja/docs/tutorial/request-files.md
@@ -0,0 +1,176 @@
+# リクエストファイル { #request-files }
+
+`File` を使って、クライアントがアップロードするファイルを定義できます。
+
+/// info | 情報
+
+アップロードされたファイルを受け取るには、まず `python-multipart` をインストールします。
+
+[仮想環境](../virtual-environments.md){.internal-link target=_blank}を作成して有効化し、次のようにインストールしてください:
+
+```console
+$ pip install python-multipart
+```
+
+アップロードされたファイルは「form data」として送信されるためです。
+
+///
+
+## `File` をインポート { #import-file }
+
+`fastapi` から `File` と `UploadFile` をインポートします:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
+
+## `File` パラメータの定義 { #define-file-parameters }
+
+`Body` や `Form` と同様の方法でファイルのパラメータを作成します:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info | 情報
+
+`File` は `Form` を直接継承したクラスです。
+
+ただし、`fastapi` から `Query`、`Path`、`File` などをインポートするとき、それらは実際には特殊なクラスを返す関数であることに注意してください。
+
+///
+
+/// tip | 豆知識
+
+ファイルのボディを宣言するには `File` を使う必要があります。そうしないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されます。
+
+///
+
+ファイルは「form data」としてアップロードされます。
+
+*path operation 関数* のパラメータの型を `bytes` として宣言すると、**FastAPI** がファイルを読み取り、内容を `bytes` として受け取ります。
+
+これは内容全体がメモリに保持されることを意味します。小さなファイルには有効です。
+
+しかし、多くの場合は `UploadFile` を使う方が有利です。
+
+## `UploadFile` によるファイルパラメータ { #file-parameters-with-uploadfile }
+
+型を `UploadFile` にしてファイルパラメータを定義します:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
+
+`UploadFile` を使うことには `bytes` に対する次の利点があります:
+
+- パラメータのデフォルト値に `File()` を使う必要がありません。
+- 「spooled」ファイルを使います:
+ - 最大サイズまではメモリに保持し、それを超えるとディスクに格納されるファイルです。
+- そのため、画像・動画・大きなバイナリなどの大きなファイルでも、メモリを使い果たすことなくうまく動作します。
+- アップロードされたファイルからメタデータを取得できます。
+- file-like な `async` インターフェースを持ちます。
+- 実際の Python の `SpooledTemporaryFile` オブジェクトを公開しており、file-like オブジェクトを期待する他のライブラリにそのまま渡せます。
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` には次の属性があります:
+
+- `filename`: アップロード時の元のファイル名を表す `str`(例: `myimage.jpg`)
+- `content_type`: コンテントタイプ(MIME タイプ / メディアタイプ)を表す `str`(例: `image/jpeg`)
+- `file`: `SpooledTemporaryFile`(file-like なオブジェクト)。これは実際の Python のファイルオブジェクトで、「file-like」オブジェクトを期待する関数やライブラリに直接渡せます。
+
+`UploadFile` には次の `async` メソッドがあります。いずれも内部で対応するファイルメソッド(内部の `SpooledTemporaryFile`)を呼び出します。
+
+- `write(data)`: `data`(`str` または `bytes`)を書き込みます。
+- `read(size)`: `size`(`int`)バイト/文字を読み込みます。
+- `seek(offset)`: ファイル内のバイト位置 `offset`(`int`)に移動します。
+ - 例: `await myfile.seek(0)` はファイルの先頭に移動します。
+ - 一度 `await myfile.read()` を実行して、もう一度内容を読みたい場合に特に便利です。
+- `close()`: ファイルを閉じます。
+
+これらはすべて `async` メソッドなので、`await` する必要があります。
+
+例えば、`async` の *path operation 関数* 内では次のように内容を取得できます:
+
+```Python
+contents = await myfile.read()
+```
+
+通常の `def` の *path operation 関数* 内にいる場合は、`UploadFile.file` に直接アクセスできます。例えば:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | `async` の技術詳細
+
+`async` メソッドを使うと、**FastAPI** はファイルメソッドをスレッドプールで実行し、その完了を待機します。
+
+///
+
+/// note | Starlette の技術詳細
+
+**FastAPI** の `UploadFile` は **Starlette** の `UploadFile` を直接継承していますが、**Pydantic** や FastAPI の他の部分と互換にするために必要な要素を追加しています。
+
+///
+
+## 「Form Data」とは { #what-is-form-data }
+
+HTML フォーム(``)がサーバーにデータを送る方法は、そのデータに対して通常「特別な」エンコーディングを用い、JSON とは異なります。
+
+**FastAPI** は JSON ではなく、適切な場所からそのデータを読み取るようにします。
+
+/// note | 技術詳細
+
+ファイルを含まない場合、フォームからのデータは通常「メディアタイプ」`application/x-www-form-urlencoded` でエンコードされます。
+
+ただしフォームにファイルが含まれる場合は、`multipart/form-data` としてエンコードされます。`File` を使うと、**FastAPI** はボディ内の正しい部分からファイルを取得すべきであると認識します。
+
+これらのエンコーディングやフォームフィールドの詳細は、MDN Web Docs の POST を参照してください。
+
+///
+
+/// warning | 注意
+
+1 つの *path operation* に複数の `File` および `Form` パラメータを宣言できますが、同時に JSON として受け取ることを期待する `Body` フィールドを宣言することはできません。リクエストのボディは `application/json` ではなく `multipart/form-data` でエンコードされるためです。
+
+これは **FastAPI** の制限ではなく、HTTP プロトコルの仕様です。
+
+///
+
+## 任意のファイルアップロード { #optional-file-upload }
+
+標準の型アノテーションを使い、デフォルト値を `None` に設定することで、ファイルを任意にできます:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## 追加メタデータつきの `UploadFile` { #uploadfile-with-additional-metadata }
+
+例えば追加のメタデータを設定するために、`UploadFile` と併せて `File()` を使うこともできます:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## 複数ファイルのアップロード { #multiple-file-uploads }
+
+同時に複数のファイルをアップロードできます。
+
+それらは「form data」で送信される同じ「フォームフィールド」に関連付けられます。
+
+そのためには、`bytes` または `UploadFile` のリストを宣言します:
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+宣言どおり、`bytes` または `UploadFile` の `list` を受け取ります。
+
+/// note | 技術詳細
+
+`from starlette.responses import HTMLResponse` を使うこともできます。
+
+**FastAPI** は利便性のため、`starlette.responses` と同じものを `fastapi.responses` として提供しています。ただし、利用可能なレスポンスの多くは Starlette から直接提供されています。
+
+///
+
+### 追加メタデータつきの複数ファイルアップロード { #multiple-file-uploads-with-additional-metadata }
+
+先ほどと同様に、`UploadFile` に対しても `File()` を使って追加のパラメータを設定できます:
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## まとめ { #recap }
+
+リクエストでフォームデータとして送信されるアップロードファイルを宣言するには、`File`、`bytes`、`UploadFile` を使います。
diff --git a/docs/ja/docs/tutorial/request-form-models.md b/docs/ja/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..071867964
--- /dev/null
+++ b/docs/ja/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# フォームモデル { #form-models }
+
+FastAPI では、フォームフィールドを宣言するために Pydantic モデルを使用できます。
+
+/// info | 情報
+
+フォームを使うには、まず `python-multipart` をインストールします。
+
+まず [仮想環境](../virtual-environments.md){.internal-link target=_blank} を作成して有効化し、そのうえでインストールしてください。例えば:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | 備考
+
+これは FastAPI バージョン `0.113.0` 以降でサポートされています。🤓
+
+///
+
+## フォーム用の Pydantic モデル { #pydantic-models-for-forms }
+
+受け取りたいフィールドを **フォームフィールド** として持つ **Pydantic モデル** を宣言し、パラメータを `Form` として宣言するだけです:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** はリクエストの **フォームデータ** から **各フィールド** のデータを **抽出** し、定義した Pydantic モデルとして渡します。
+
+## ドキュメントで確認 { #check-the-docs }
+
+`/docs` のドキュメント UI で確認できます:
+
+
+POSTのウェブドキュメントを参照してください。
+これらのエンコーディングやフォームフィールドの詳細については、MDNのPOSTのウェブドキュメントを参照してください。
///
/// warning | 注意
-*path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。
+*path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/x-www-form-urlencoded`の代わりに`application/json`を使ってボディをエンコードするからです。
これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。
diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md
index 258eac8e6..07dc20123 100644
--- a/docs/ja/docs/tutorial/response-model.md
+++ b/docs/ja/docs/tutorial/response-model.md
@@ -41,7 +41,7 @@ FastAPIはこの戻り値の型を使って以下を行います:
/// note | 備考
-`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation 関数* のパラメータではありません。
+`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータです。関数のパラメータやボディなどとは違い、*path operation 関数*のパラメータではありません。
///
@@ -183,7 +183,7 @@ Pydanticフィールドとして有効ではないものを返し、ツール(
最も一般的なケースは、[高度なドキュメントで後述する「Responseを直接返す」](../advanced/response-directly.md){.internal-link target=_blank}場合です。
-{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
このシンプルなケースは、戻り値の型アノテーションが `Response` のクラス(またはサブクラス)であるため、FastAPIが自動的に処理します。
@@ -193,7 +193,7 @@ Pydanticフィールドとして有効ではないものを返し、ツール(
型アノテーションで `Response` のサブクラスを使うこともできます:
-{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
これは `RedirectResponse` が `Response` のサブクラスであり、FastAPIがこのシンプルなケースを自動処理するため、同様に動作します。
@@ -201,7 +201,7 @@ Pydanticフィールドとして有効ではないものを返し、ツール(
しかし、Pydantic型として有効ではない別の任意のオブジェクト(例: データベースオブジェクト)を返し、関数でそのようにアノテーションすると、FastAPIはその型アノテーションからPydanticレスポンスモデルを作成しようとして失敗します。
-同様に、unionのように、複数の型のうち1つ以上がPydantic型として有効でないものを含む場合も起こります。例えば次は失敗します 💥:
+同様に、ユニオンのように、複数の型のうち1つ以上がPydantic型として有効でないものを含む場合も起こります。例えば次は失敗します 💥:
{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md
index d3c219416..d4ac45da6 100644
--- a/docs/ja/docs/tutorial/response-status-code.md
+++ b/docs/ja/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@
* `@app.delete()`
* etc.
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
/// note | 備考
@@ -74,7 +74,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータスコ
先ほどの例をもう一度見てみましょう:
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201`は「作成完了」のためのステータスコードです。
@@ -82,7 +82,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータスコ
`fastapi.status`の便利な変数を利用することができます。
-{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
それらは単なる便利なものであり、同じ番号を保持しています。しかし、その方法ではエディタの自動補完を使用してそれらを見つけることができます。
diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md
index e526685c2..76a6b0f94 100644
--- a/docs/ja/docs/tutorial/schema-extra-example.md
+++ b/docs/ja/docs/tutorial/schema-extra-example.md
@@ -74,7 +74,7 @@ Pydanticモデルで`Field()`を使う場合、追加の`examples`も宣言で
この場合、examplesはそのボディデータの内部**JSON Schema**の一部になります。
-それでも、執筆時点では、ドキュメントUIの表示を担当するツールであるSwagger UIは、**JSON Schema**内のデータに対して複数の例を表示することをサポートしていません。しかし、回避策については以下を読んでください。
+それでも、執筆時点では、ドキュメントUIの表示を担当するツールであるSwagger UIは、**JSON Schema**内のデータに対して複数の例を表示することをサポートしていません。しかし、回避策については以下を読んでください。
### OpenAPI固有の`examples` { #openapi-specific-examples }
diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md
index 76ef04db8..5bf04386a 100644
--- a/docs/ja/docs/tutorial/security/first-steps.md
+++ b/docs/ja/docs/tutorial/security/first-steps.md
@@ -20,7 +20,7 @@
`main.py`に、下記の例をコピーします:
-{* ../../docs_src/security/tutorial001_an_py39.py *}
+{* ../../docs_src/security/tutorial001_an_py310.py *}
## 実行 { #run-it }
@@ -132,7 +132,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー
`OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`username`と`password`を送信するURLを指定します。
-{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
/// tip | 豆知識
@@ -150,7 +150,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー
/// info | 情報
-非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。
+非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`tokenUrl`ではなく`token_url`であることを気に入らないかもしれません。
それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。
@@ -170,7 +170,7 @@ oauth2_scheme(some, parameters)
これで`oauth2_scheme`を`Depends`で依存関係に渡すことができます。
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
この依存関係は、*path operation 関数*のパラメーター`token`に代入される`str`を提供します。
diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md
index 39b97cca5..60378fd98 100644
--- a/docs/ja/docs/tutorial/security/get-current-user.md
+++ b/docs/ja/docs/tutorial/security/get-current-user.md
@@ -2,7 +2,7 @@
一つ前の章では、(依存性注入システムに基づいた)セキュリティシステムは、 *path operation 関数* に `str` として `token` を与えていました:
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
しかし、それはまだそんなに有用ではありません。
diff --git a/docs/ja/docs/tutorial/security/index.md b/docs/ja/docs/tutorial/security/index.md
index 14f2c8f44..b96021b7f 100644
--- a/docs/ja/docs/tutorial/security/index.md
+++ b/docs/ja/docs/tutorial/security/index.md
@@ -1,4 +1,4 @@
-# セキュリティ入門
+# セキュリティ入門 { #security }
セキュリティ、認証、認可を扱うには多くの方法があります。
@@ -10,11 +10,11 @@
しかし、その前に、いくつかの小さな概念を確認しましょう。
-## お急ぎですか?
+## お急ぎですか? { #in-a-hurry }
もし、これらの用語に興味がなく、ユーザー名とパスワードに基づく認証でセキュリティを**今すぐ**確保する必要がある場合は、次の章に進んでください。
-## OAuth2
+## OAuth2 { #oauth2 }
OAuth2は、認証と認可を処理するためのいくつかの方法を定義した仕様です。
@@ -24,7 +24,7 @@ OAuth2は、認証と認可を処理するためのいくつかの方法を定
これが、「Facebook、Google、X (Twitter)、GitHubを使ってログイン」を使用したすべてのシステムの背後で使われている仕組みです。
-### OAuth 1
+### OAuth 1 { #oauth-1 }
OAuth 1というものもありましたが、これはOAuth2とは全く異なり、通信をどのように暗号化するかという仕様が直接的に含まれており、より複雑なものとなっています。
@@ -38,7 +38,7 @@ OAuth2は、通信を暗号化する方法を指定せず、アプリケーシ
///
-## OpenID Connect
+## OpenID Connect { #openid-connect }
OpenID Connectは、**OAuth2**をベースにした別の仕様です。
@@ -48,7 +48,7 @@ OpenID Connectは、**OAuth2**をベースにした別の仕様です。
しかし、FacebookのログインはOpenID Connectをサポートしていません。OAuth2を独自にアレンジしています。
-### OpenID (「OpenID Connect」ではない)
+### OpenID (「OpenID Connect」ではない) { #openid-not-openid-connect }
また、「OpenID」という仕様もありました。それは、**OpenID Connect**と同じことを解決しようとしたものですが、OAuth2に基づいているわけではありませんでした。
@@ -56,7 +56,7 @@ OpenID Connectは、**OAuth2**をベースにした別の仕様です。
現在ではあまり普及していませんし、使われてもいません。
-## OpenAPI
+## OpenAPI { #openapi }
OpenAPI(以前はSwaggerとして知られていました)は、APIを構築するためのオープンな仕様です(現在はLinux Foundationの一部になっています)。
@@ -97,7 +97,7 @@ Google、Facebook、X (Twitter)、GitHubなど、他の認証/認可プロバイ
///
-## **FastAPI** ユーティリティ
+## **FastAPI** ユーティリティ { #fastapi-utilities }
FastAPIは `fastapi.security` モジュールの中で、これらのセキュリティスキームごとにいくつかのツールを提供し、これらのセキュリティメカニズムを簡単に使用できるようにします。
diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md
index 186936f1b..0d6be90a2 100644
--- a/docs/ja/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md
@@ -1,6 +1,6 @@
# パスワード(およびハッシュ化)によるOAuth2、JWTトークンによるBearer { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
-これでセキュリティの流れが全てわかったので、JWTトークンと安全なパスワードのハッシュ化を使用して、実際にアプリケーションを安全にしてみましょう。
+これでセキュリティの流れが全てわかったので、JWTトークンと安全なパスワードのハッシュ化を使用して、実際にアプリケーションを安全にしてみましょう。
このコードは、アプリケーションで実際に使用したり、パスワードハッシュをデータベースに保存するといった用途に利用できます。
@@ -116,7 +116,11 @@ pwdlibはbcryptハッシュアルゴリズムもサポートしていますが
さらに、ユーザーを認証して返す関数も作成します。
-{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,51,58:59,62:63,72:79] *}
+
+`authenticate_user` がデータベースに存在しないユーザー名で呼び出された場合でも、ダミーのハッシュを使って `verify_password` を実行します。
+
+これにより、ユーザー名が有効かどうかに関わらずエンドポイントの応答時間がおおよそ同じになり、既存のユーザー名を列挙するために悪用されうる「タイミング攻撃」を防止できます。
/// note | 備考
@@ -152,7 +156,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し
新しいアクセストークンを生成するユーティリティ関数を作成します。
-{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,82:90] *}
## 依存関係の更新 { #update-the-dependencies }
@@ -162,7 +166,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し
トークンが無効な場合は、すぐにHTTPエラーを返します。
-{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[93:110] *}
## `/token` *path operation* の更新 { #update-the-token-path-operation }
@@ -170,7 +174,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し
実際のJWTアクセストークンを作成し、それを返します。
-{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[121:136] *}
### JWTの「subject」`sub` についての技術的な詳細 { #technical-details-about-the-jwt-subject-sub }
diff --git a/docs/ja/docs/tutorial/security/simple-oauth2.md b/docs/ja/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 000000000..c371b0acf
--- /dev/null
+++ b/docs/ja/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# パスワードとBearerによるシンプルなOAuth2 { #simple-oauth2-with-password-and-bearer }
+
+前章から発展させて、完全なセキュリティフローに必要な不足部分を追加していきます。
+
+## `username` と `password` を取得する { #get-the-username-and-password }
+
+`username` と `password` を取得するために **FastAPI** のセキュリティユーティリティを使います。
+
+OAuth2 では、「password flow」(ここで使用するフロー)を使う場合、クライアント/ユーザーはフォームデータとして `username` と `password` フィールドを送信する必要があります。
+
+しかも、フィールド名はこの通りでなければなりません。つまり、`user-name` や `email` では動作しません。
+
+ただし、フロントエンドで最終ユーザーにどう表示するかは自由です。
+
+また、データベースのモデルでは任意の別名を使って構いません。
+
+しかし、ログイン用の path operation では、仕様との互換性を保つ(たとえば組み込みのAPIドキュメントシステムを使えるようにする)ために、これらの名前を使う必要があります。
+
+また、仕様では `username` と `password` はフォームデータとして送らなければならない(つまり、ここではJSONは使わない)ことも定められています。
+
+### `scope` { #scope }
+
+仕様では、クライアントは追加のフォームフィールド「`scope`」を送ることができるとも書かれています。
+
+フォームフィールド名は `scope`(単数形)ですが、実態はスペース区切りの「スコープ」文字列を並べた長い文字列です。
+
+各「スコープ」は(スペースを含まない)単なる文字列です。
+
+通常、特定のセキュリティ権限を宣言するために使われます。例えば:
+
+- `users:read` や `users:write` はよくある例です。
+- `instagram_basic` は Facebook / Instagram で使われます。
+- `https://www.googleapis.com/auth/drive` は Google で使われます。
+
+/// info | 情報
+
+OAuth2 における「スコープ」は、要求される特定の権限を表す単なる文字列です。
+
+`:` のような他の文字を含んでいても、URL であっても構いません。
+
+それらの詳細は実装依存です。
+
+OAuth2 にとっては単なる文字列です。
+
+///
+
+## `username` と `password` を取得するコード { #code-to-get-the-username-and-password }
+
+では、これを処理するために **FastAPI** が提供するユーティリティを使いましょう。
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+まず、`OAuth2PasswordRequestForm` をインポートし、`/token` の path operation に `Depends` で依存関係として使います:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` は次のフォームボディを宣言するクラス依存関係です:
+
+- `username`
+- `password`
+- スペース区切りの文字列で構成される、オプションの `scope` フィールド
+- オプションの `grant_type`
+
+/// tip | 豆知識
+
+OAuth2 の仕様では、固定値 `password` を持つフィールド `grant_type` が実際には必須ですが、`OAuth2PasswordRequestForm` はそれを強制しません。
+
+強制したい場合は、`OAuth2PasswordRequestForm` の代わりに `OAuth2PasswordRequestFormStrict` を使ってください。
+
+///
+
+- オプションの `client_id`(この例では不要)
+- オプションの `client_secret`(この例では不要)
+
+/// info | 情報
+
+`OAuth2PasswordRequestForm` は、`OAuth2PasswordBearer` のように **FastAPI** にとって特別なクラスではありません。
+
+`OAuth2PasswordBearer` は **FastAPI** にセキュリティスキームであることを認識させます。そのため OpenAPI にそのように追加されます。
+
+一方、`OAuth2PasswordRequestForm` は、あなた自身でも書けるような単なるクラス依存関係であり、直接 `Form` パラメータを宣言することもできます。
+
+ただし一般的なユースケースなので、簡単に使えるよう **FastAPI** が直接提供しています。
+
+///
+
+### フォームデータの利用 { #use-the-form-data }
+
+/// tip | 豆知識
+
+依存関係クラス `OAuth2PasswordRequestForm` のインスタンスは、スペース区切りの長い文字列を持つ `scope` 属性は持ちません。代わりに、送られてきた各スコープの実際の文字列リストを格納する `scopes` 属性を持ちます。
+
+この例では `scopes` は使いませんが、必要ならその機能が利用できます。
+
+///
+
+次に、フォームフィールドの `username` を使って(疑似の)データベースからユーザーデータを取得します。
+
+そのユーザーが存在しない場合は、「Incorrect username or password」というエラーを返します。
+
+エラーには `HTTPException` 例外を使います:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### パスワードのチェック { #check-the-password }
+
+この時点でデータベースからユーザーデータは取得できましたが、まだパスワードを確認していません。
+
+まず、そのデータを Pydantic の `UserInDB` モデルに入れます。
+
+プレーンテキストのパスワードを保存してはいけないので、(疑似の)パスワードハッシュ化システムを使います。
+
+パスワードが一致しなければ、同じエラーを返します。
+
+#### パスワードハッシュ化 { #password-hashing }
+
+「ハッシュ化」とは、ある内容(ここではパスワード)を、乱雑に見えるバイト列(単なる文字列)に変換することを指します。
+
+まったく同じ内容(まったく同じパスワード)を渡すと、毎回まったく同じ乱雑な文字列が得られます。
+
+しかし、その乱雑な文字列から元のパスワードに戻すことはできません。
+
+##### なぜパスワードをハッシュ化するのか { #why-use-password-hashing }
+
+もしデータベースが盗まれても、盗んだ側が手にするのはユーザーのプレーンテキストのパスワードではなく、ハッシュだけです。
+
+したがって、盗んだ側は同じパスワードを別のシステムで試すことができません(多くのユーザーがあらゆる場所で同じパスワードを使っているため、これは危険になり得ます)。
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### `**user_dict` について { #about-user-dict }
+
+`UserInDB(**user_dict)` は次を意味します:
+
+`user_dict` のキーと値を、そのままキーワード引数として渡します。つまり次と同等です:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info | 情報
+
+`**user_dict` のより完全な解説は、[**追加モデル**のドキュメント](../extra-models.md#about-user-in-dict){.internal-link target=_blank}を参照してください。
+
+///
+
+## トークンを返す { #return-the-token }
+
+`token` エンドポイントのレスポンスは JSON オブジェクトでなければなりません。
+
+`token_type` を含める必要があります。ここでは「Bearer」トークンを使うので、トークンタイプは「`bearer`」です。
+
+そして `access_token` を含め、その中にアクセストークンの文字列を入れます。
+
+この単純な例では、完全に安全ではありませんが、トークンとして同じ `username` をそのまま返します。
+
+/// tip | 豆知識
+
+次の章では、パスワードハッシュ化と JWT トークンを使った本当に安全な実装を見ます。
+
+しかし今は、必要な特定の詳細に集中しましょう。
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | 豆知識
+
+仕様に従うと、この例と同じく `access_token` と `token_type` を含む JSON を返す必要があります。
+
+これはあなた自身のコードで実装する必要があり、これらのJSONキーを使っていることを確認してください。
+
+仕様に準拠するために、あなた自身が正しく覚えて実装すべきことは、ほぼこれだけです。
+
+それ以外は **FastAPI** が面倒を見てくれます。
+
+///
+
+## 依存関係の更新 { #update-the-dependencies }
+
+ここで依存関係を更新します。
+
+アクティブなユーザーの場合にのみ `current_user` を取得したいとします。
+
+そこで、`get_current_user` を依存関係として利用する追加の依存関係 `get_current_active_user` を作成します。
+
+これら2つの依存関係は、ユーザーが存在しない、または非アクティブである場合に、HTTPエラーを返すだけです。
+
+したがって、エンドポイントでは、ユーザーが存在し、正しく認証され、かつアクティブである場合にのみ、ユーザーを取得します:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | 情報
+
+ここで返している値が `Bearer` の追加ヘッダー `WWW-Authenticate` も仕様の一部です。
+
+HTTP(エラー)ステータスコード 401「UNAUTHORIZED」は、`WWW-Authenticate` ヘッダーも返すことになっています。
+
+ベアラートークン(今回のケース)の場合、そのヘッダーの値は `Bearer` であるべきです。
+
+実際のところ、この追加ヘッダーを省略しても動作はします。
+
+しかし、仕様に準拠するためにここでは付与しています。
+
+また、(今または将来)それを想定して利用するツールがあるかもしれず、あなたやユーザーにとって有用になる可能性があります。
+
+これが標準の利点です…。
+
+///
+
+## 動作確認 { #see-it-in-action }
+
+インタラクティブドキュメントを開きます: http://127.0.0.1:8000/docs。
+
+### 認証 { #authenticate }
+
+「Authorize」ボタンをクリックします。
+
+次の認証情報を使います:
+
+User: `johndoe`
+
+Password: `secret`
+
+
+
+システムで認証されると、次のように表示されます:
+
+
+
+### 自分のユーザーデータを取得 { #get-your-own-user-data }
+
+`GET` の path `/users/me` を使います。
+
+次のようなユーザーデータが取得できます:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+錠前アイコンをクリックしてログアウトし、同じ操作を再度試すと、次のような HTTP 401 エラーになります:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### 非アクティブユーザー { #inactive-user }
+
+今度は非アクティブなユーザーで試してみます。次で認証してください:
+
+User: `alice`
+
+Password: `secret2`
+
+そして `GET` の path `/users/me` を使います。
+
+次のような「Inactive user」エラーになります:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## まとめ { #recap }
+
+これで、API のために `username` と `password` に基づく完全なセキュリティシステムを実装するための道具が揃いました。
+
+これらの道具を使えば、任意のデータベース、任意のユーザー/データモデルと互換性のあるセキュリティシステムを構築できます。
+
+ただし、実際にはまだ「安全」ではありません。
+
+次の章では、安全なパスワードハッシュライブラリと JWT トークンの使い方を見ていきます。
diff --git a/docs/ja/docs/tutorial/sql-databases.md b/docs/ja/docs/tutorial/sql-databases.md
new file mode 100644
index 000000000..930e433de
--- /dev/null
+++ b/docs/ja/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# SQL(リレーショナル)データベース { #sql-relational-databases }
+
+FastAPI は SQL(リレーショナル)データベースの使用を必須にはしません。必要であれば、任意のデータベースを使用できます。
+
+ここでは SQLModel を使った例を見ていきます。
+
+SQLModel は SQLAlchemy と Pydantic の上に構築されています。FastAPI と同じ作者により、SQL データベースを使う必要がある FastAPI アプリに最適になるように作られています。
+
+/// tip | 豆知識
+
+他の任意の SQL あるいは NoSQL のデータベースライブラリ(場合によっては "ORMs" と呼ばれます)を使うこともできます。FastAPI は何も強制しません。😎
+
+///
+
+SQLModel は SQLAlchemy をベースにしているため、SQLAlchemy がサポートする任意のデータベース(SQLModel からもサポートされます)を簡単に使えます。例えば:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server など
+
+この例では、単一ファイルで動作し、Python に統合サポートがあるため、SQLite を使います。つまり、この例をそのままコピーして実行できます。
+
+本番アプリでは、PostgreSQL のようなデータベースサーバーを使いたくなるかもしれません。
+
+/// tip | 豆知識
+
+フロントエンドやその他のツールを含む、FastAPI と PostgreSQL の公式プロジェクトジェネレーターがあります: https://github.com/fastapi/full-stack-fastapi-template
+
+///
+
+これはとてもシンプルで短いチュートリアルです。データベースや SQL、より高度な機能について学びたい場合は、SQLModel のドキュメントをご覧ください。
+
+## `SQLModel` のインストール { #install-sqlmodel }
+
+まずは [仮想環境](../virtual-environments.md){.internal-link target=_blank} を作成・有効化し、`sqlmodel` をインストールします:
+
+
+
+httpx – erforderlich, wenn Sie den `TestClient` verwenden möchten.
* jinja2 – erforderlich, wenn Sie die Default-Template-Konfiguration verwenden möchten.
-* python-multipart – erforderlich, wenn Sie Formulare mittels `request.form()` „parsen“ möchten.
+* python-multipart – erforderlich, wenn Sie Formulare mittels `request.form()` „parsen“ möchten.
Verwendet von FastAPI:
diff --git a/docs/de/docs/project-generation.md b/docs/de/docs/project-generation.md
index 62702d852..2c252933d 100644
--- a/docs/de/docs/project-generation.md
+++ b/docs/de/docs/project-generation.md
@@ -20,7 +20,7 @@ GitHub-Repository: „Typhinweise“ (auch „Typannotationen“ genannt).
+Python hat Unterstützung für optionale „Typhinweise“ (auch „Typannotationen“ genannt).
-Diese **„Typhinweise“** oder -Annotationen sind eine spezielle Syntax, die es erlaubt, den Typ einer Variablen zu deklarieren.
+Diese **„Typhinweise“** oder -Annotationen sind eine spezielle Syntax, die es erlaubt, den Typ einer Variablen zu deklarieren.
Durch das Deklarieren von Typen für Ihre Variablen können Editoren und Tools bessere Unterstützung bieten.
@@ -22,7 +22,7 @@ Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, üb
Fangen wir mit einem einfachen Beispiel an:
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
Dieses Programm gibt aus:
@@ -34,9 +34,9 @@ Die Funktion macht Folgendes:
* Nimmt einen `first_name` und `last_name`.
* Schreibt den ersten Buchstaben eines jeden Wortes groß, mithilfe von `title()`.
-* Verkettet sie mit einem Leerzeichen in der Mitte.
+* Verkettet sie mit einem Leerzeichen in der Mitte.
-{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
### Es bearbeiten { #edit-it }
@@ -78,7 +78,7 @@ Das war's.
Das sind die „Typhinweise“:
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist:
@@ -106,7 +106,7 @@ Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der
Sehen Sie sich diese Funktion an, sie hat bereits Typhinweise:
-{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung:
@@ -114,7 +114,7 @@ Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervoll
Jetzt, da Sie wissen, dass Sie das reparieren müssen, konvertieren Sie `age` mittels `str(age)` in einen String:
-{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
## Deklarieren von Typen { #declaring-types }
@@ -133,29 +133,32 @@ Zum Beispiel diese:
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### Generische Typen mit Typ-Parametern { #generic-types-with-type-parameters }
+### `typing`-Modul { #typing-module }
-Es gibt Datenstrukturen, die andere Werte enthalten können, wie etwa `dict`, `list`, `set` und `tuple`. Die inneren Werte können auch ihren eigenen Typ haben.
+Für einige zusätzliche Anwendungsfälle müssen Sie möglicherweise Dinge aus dem Standardmodul `typing` importieren. Zum Beispiel, wenn Sie deklarieren möchten, dass etwas „jeden Typ“ haben kann, können Sie `Any` aus `typing` verwenden:
-Diese Typen mit inneren Typen werden „**generische**“ Typen genannt. Es ist möglich, sie mit ihren inneren Typen zu deklarieren.
+```python
+from typing import Any
-Um diese Typen und die inneren Typen zu deklarieren, können Sie Pythons Standardmodul `typing` verwenden. Es existiert speziell für die Unterstützung dieser Typhinweise.
-#### Neuere Python-Versionen { #newer-versions-of-python }
+def some_function(data: Any):
+ print(data)
+```
-Die Syntax, welche `typing` verwendet, ist **kompatibel** mit allen Versionen, von Python 3.6 aufwärts zu den neuesten, inklusive Python 3.9, Python 3.10, usw.
+### Generische Typen { #generic-types }
-Mit der Weiterentwicklung von Python kommen **neuere Versionen** heraus, mit verbesserter Unterstützung für Typannotationen, und in vielen Fällen müssen Sie gar nicht mehr das `typing`-Modul importieren, um Typannotationen zu schreiben.
+Einige Typen können „Typ-Parameter“ in eckigen Klammern annehmen, um ihre inneren Typen zu definieren, z. B. eine „Liste von Strings“ würde als `list[str]` deklariert.
-Wenn Sie eine neuere Python-Version für Ihr Projekt wählen können, werden Sie aus dieser zusätzlichen Vereinfachung Nutzen ziehen können.
+Diese Typen, die Typ-Parameter annehmen können, werden **generische Typen** oder **Generics** genannt.
-In der gesamten Dokumentation gibt es Beispiele, welche kompatibel mit unterschiedlichen Python-Versionen sind (wenn es Unterschiede gibt).
+Sie können dieselben eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
-Zum Beispiel bedeutet „**Python 3.6+**“, dass das Beispiel kompatibel mit Python 3.6 oder höher ist (inklusive 3.7, 3.8, 3.9, 3.10, usw.). Und „**Python 3.9+**“ bedeutet, es ist kompatibel mit Python 3.9 oder höher (inklusive 3.10, usw.).
-
-Wenn Sie über die **neueste Version von Python** verfügen, verwenden Sie die Beispiele für die neueste Version, diese werden die **beste und einfachste Syntax** haben, zum Beispiel, „**Python 3.10+**“.
+* `list`
+* `tuple`
+* `set`
+* `dict`
#### Liste { #list }
@@ -167,7 +170,7 @@ Als Typ nehmen Sie `list`.
Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
-{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
/// info | Info
@@ -193,7 +196,7 @@ Und trotzdem weiß der Editor, dass es sich um ein `str` handelt, und bietet ent
Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Menge – `set`:
-{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
Das bedeutet:
@@ -208,7 +211,7 @@ Der erste Typ-Parameter ist für die Schlüssel des `dict`.
Der zweite Typ-Parameter ist für die Werte des `dict`:
-{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Das bedeutet:
@@ -216,47 +219,23 @@ Das bedeutet:
* Die Schlüssel dieses `dict` sind vom Typ `str` (z. B. die Namen der einzelnen Artikel).
* Die Werte dieses `dict` sind vom Typ `float` (z. B. der Preis jedes Artikels).
-#### Union { #union }
+#### Union { #union }
Sie können deklarieren, dass eine Variable einer von **verschiedenen Typen** sein kann, zum Beispiel ein `int` oder ein `str`.
-In Python 3.6 und höher (inklusive Python 3.10) können Sie den `Union`-Typ von `typing` verwenden und die möglichen Typen innerhalb der eckigen Klammern auflisten.
+Um das zu definieren, verwenden Sie den vertikalen Balken (`|`), um beide Typen zu trennen.
-In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die möglichen Typen getrennt von einem vertikalen Balken (`|`) aufzulisten.
-
-//// tab | Python 3.10+
+Das wird „Union“ genannt, weil die Variable etwas aus der Vereinigung dieser beiden Typmengen sein kann.
```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-////
-
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b_py39.py!}
-```
-
-////
-
-In beiden Fällen bedeutet das, dass `item` ein `int` oder ein `str` sein kann.
+Das bedeutet, dass `item` ein `int` oder ein `str` sein könnte.
#### Vielleicht `None` { #possibly-none }
-Sie können deklarieren, dass ein Wert ein `str`, aber vielleicht auch `None` sein kann.
-
-In Python 3.6 und darüber (inklusive Python 3.10) können Sie das deklarieren, indem Sie `Optional` vom `typing` Modul importieren und verwenden.
-
-```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer eine String (`str`) ist, obwohl er auch `None` sein könnte.
-
-`Optional[Something]` ist tatsächlich eine Abkürzung für `Union[Something, None]`, diese beiden sind äquivalent.
-
-Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können:
+Sie können deklarieren, dass ein Wert einen Typ haben könnte, wie `str`, dass er aber auch `None` sein könnte.
//// tab | Python 3.10+
@@ -266,96 +245,7 @@ Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können:
////
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-////
-
-//// tab | Python 3.9+ Alternative
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b_py39.py!}
-```
-
-////
-
-#### `Union` oder `Optional` verwenden? { #using-union-or-optional }
-
-Wenn Sie eine Python-Version unterhalb 3.10 verwenden, hier ist mein sehr **subjektiver** Standpunkt dazu:
-
-* 🚨 Vermeiden Sie `Optional[SomeType]`
-* Stattdessen ✨ **verwenden Sie `Union[SomeType, None]`** ✨.
-
-Beide sind äquivalent und im Hintergrund dasselbe, aber ich empfehle `Union` statt `Optional`, weil das Wort „**optional**“ impliziert, dass dieser Wert, zum Beispiel als Funktionsparameter, optional ist. Tatsächlich bedeutet es aber nur „Der Wert kann `None` sein“, selbst wenn der Wert nicht optional ist und benötigt wird.
-
-Ich denke, `Union[SomeType, None]` ist expliziter bezüglich seiner Bedeutung.
-
-Es geht nur um Worte und Namen. Aber diese Worte können beeinflussen, wie Sie und Ihre Teamkollegen über den Code denken.
-
-Nehmen wir zum Beispiel diese Funktion:
-
-{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
-
-Der Parameter `name` ist definiert als `Optional[str]`, aber er ist **nicht optional**, Sie können die Funktion nicht ohne diesen Parameter aufrufen:
-
-```Python
-say_hi() # Oh, nein, das löst einen Fehler aus! 😱
-```
-
-Der `name` Parameter wird **immer noch benötigt** (nicht *optional*), weil er keinen Default-Wert hat. `name` akzeptiert aber dennoch `None` als Wert:
-
-```Python
-say_hi(name=None) # Das funktioniert, None ist gültig 🎉
-```
-
-Die gute Nachricht ist, dass Sie sich darüber keine Sorgen mehr machen müssen, wenn Sie Python 3.10 verwenden, da Sie einfach `|` verwenden können, um Vereinigungen von Typen zu definieren:
-
-{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
-
-Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmern. 😎
-
-#### Generische Typen { #generic-types }
-
-Diese Typen, die Typ-Parameter in eckigen Klammern akzeptieren, werden **generische Typen** oder **Generics** genannt.
-
-//// tab | Python 3.10+
-
-Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-Und ebenso wie bei früheren Python-Versionen, aus dem `typing`-Modul:
-
-* `Union`
-* `Optional`
-* ... und andere.
-
-In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher.
-
-////
-
-//// tab | Python 3.9+
-
-Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-Und Generics aus dem `typing`-Modul:
-
-* `Union`
-* `Optional`
-* ... und andere.
-
-////
+Wenn Sie `str | None` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer ein `str` ist, obwohl er auch `None` sein könnte.
### Klassen als Typen { #classes-as-types }
@@ -363,11 +253,11 @@ Sie können auch eine Klasse als Typ einer Variablen deklarieren.
Nehmen wir an, Sie haben eine Klasse `Person`, mit einem Namen:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
Dann können Sie eine Variable vom Typ `Person` deklarieren:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
Und wiederum bekommen Sie die volle Editor-Unterstützung:
@@ -403,19 +293,13 @@ Um mehr über Erforderliche optionale Felder mehr erfahren.
-
-///
-
## Typhinweise mit Metadaten-Annotationen { #type-hints-with-metadata-annotations }
-Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`.
+Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`.
-Seit Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren.
+Sie können `Annotated` von `typing` importieren.
-{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
Python selbst macht nichts mit `Annotated`. Für Editoren und andere Tools ist der Typ immer noch `str`.
diff --git a/docs/de/docs/translation-banner.md b/docs/de/docs/translation-banner.md
new file mode 100644
index 000000000..1801a0190
--- /dev/null
+++ b/docs/de/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Übersetzung durch KI und Menschen
+
+Diese Übersetzung wurde von KI erstellt, angeleitet von Menschen. 🤝
+
+Sie könnte Fehler enthalten, etwa Missverständnisse des ursprünglichen Sinns oder unnatürliche Formulierungen, usw. 🤖
+
+Sie können diese Übersetzung verbessern, indem Sie [uns helfen, die KI-LLM besser anzuleiten](https://fastapi.tiangolo.com/de/contributing/#translations).
+
+[Englische Version](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md
index 1d34430dc..950174d9c 100644
--- a/docs/de/docs/tutorial/background-tasks.md
+++ b/docs/de/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@ Hierzu zählen beispielsweise:
Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter.
@@ -31,13 +31,13 @@ In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail
Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
## Den Hintergrundtask hinzufügen { #add-the-background-task }
Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` erhält als Argumente:
diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md
index d478d77c2..97fa9b81a 100644
--- a/docs/de/docs/tutorial/bigger-applications.md
+++ b/docs/de/docs/tutorial/bigger-applications.md
@@ -85,7 +85,7 @@ Sie können die *Pfadoperationen* für dieses Modul mit `APIRouter` erstellen.
Sie importieren ihn und erstellen eine „Instanz“ auf die gleiche Weise wie mit der Klasse `FastAPI`:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
### *Pfadoperationen* mit `APIRouter` { #path-operations-with-apirouter }
@@ -93,7 +93,7 @@ Und dann verwenden Sie ihn, um Ihre *Pfadoperationen* zu deklarieren.
Verwenden Sie ihn auf die gleiche Weise wie die Klasse `FastAPI`:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
Sie können sich `APIRouter` als eine „Mini-`FastAPI`“-Klasse vorstellen.
@@ -117,7 +117,7 @@ Also fügen wir sie in ihr eigenes `dependencies`-Modul (`app/dependencies.py`)
Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefinierten `X-Token`-Header zu lesen:
-{* ../../docs_src/bigger_applications/app_an_py39/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
/// tip | Tipp
@@ -149,7 +149,7 @@ Wir wissen, dass alle *Pfadoperationen* in diesem Modul folgendes haben:
Anstatt also alles zu jeder *Pfadoperation* hinzuzufügen, können wir es dem `APIRouter` hinzufügen.
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
Da der Pfad jeder *Pfadoperation* mit `/` beginnen muss, wie in:
@@ -208,7 +208,7 @@ Und wir müssen die Abhängigkeitsfunktion aus dem Modul `app.dependencies` impo
Daher verwenden wir einen relativen Import mit `..` für die Abhängigkeiten:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[3] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}
#### Wie relative Importe funktionieren { #how-relative-imports-work }
@@ -279,7 +279,7 @@ Wir fügen weder das Präfix `/items` noch `tags=["items"]` zu jeder *Pfadoperat
Aber wir können immer noch _mehr_ `tags` hinzufügen, die auf eine bestimmte *Pfadoperation* angewendet werden, sowie einige zusätzliche `responses`, die speziell für diese *Pfadoperation* gelten:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}
/// tip | Tipp
@@ -305,13 +305,13 @@ Sie importieren und erstellen wie gewohnt eine `FastAPI`-Klasse.
Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies.md){.internal-link target=_blank} deklarieren, die mit den Abhängigkeiten für jeden `APIRouter` kombiniert werden:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[1,3,7] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
### Den `APIRouter` importieren { #import-the-apirouter }
Jetzt importieren wir die anderen Submodule, die `APIRouter` haben:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[4:5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}
Da es sich bei den Dateien `app/routers/users.py` und `app/routers/items.py` um Submodule handelt, die Teil desselben Python-Packages `app` sind, können wir einen einzelnen Punkt `.` verwenden, um sie mit „relativen Imports“ zu importieren.
@@ -374,13 +374,13 @@ würde der `router` von `users` den von `items` überschreiben und wir könnten
Um also beide in derselben Datei verwenden zu können, importieren wir die Submodule direkt:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}
### Die `APIRouter` für `users` und `items` inkludieren { #include-the-apirouters-for-users-and-items }
Inkludieren wir nun die `router` aus diesen Submodulen `users` und `items`:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[10:11] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}
/// info | Info
@@ -420,13 +420,13 @@ Sie enthält einen `APIRouter` mit einigen administrativen *Pfadoperationen*, di
In diesem Beispiel wird es ganz einfach sein. Nehmen wir jedoch an, dass wir, da sie mit anderen Projekten in der Organisation geteilt wird, sie nicht ändern und kein `prefix`, `dependencies`, `tags`, usw. direkt zum `APIRouter` hinzufügen können:
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wir den `APIRouter` einbinden, sodass alle seine *Pfadoperationen* mit `/admin` beginnen, wir möchten es mit den `dependencies` sichern, die wir bereits für dieses Projekt haben, und wir möchten `tags` und `responses` hinzufügen.
Wir können das alles deklarieren, ohne den ursprünglichen `APIRouter` ändern zu müssen, indem wir diese Parameter an `app.include_router()` übergeben:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[14:17] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}
Auf diese Weise bleibt der ursprüngliche `APIRouter` unverändert, sodass wir dieselbe `app/internal/admin.py`-Datei weiterhin mit anderen Projekten in der Organisation teilen können.
@@ -447,7 +447,7 @@ Wir können *Pfadoperationen* auch direkt zur `FastAPI`-App hinzufügen.
Hier machen wir es ... nur um zu zeigen, dass wir es können 🤷:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[21:23] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}
und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden.
diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md
index b73d57d2d..4edb22478 100644
--- a/docs/de/docs/tutorial/body-fields.md
+++ b/docs/de/docs/tutorial/body-fields.md
@@ -44,7 +44,7 @@ Beachten Sie, wie jedes Attribut eines Modells mit einem Typ, Defaultwert und `F
Sie können zusätzliche Information in `Field`, `Query`, `Body`, usw. deklarieren. Und es wird im generierten JSON-Schema untergebracht.
-Sie werden später mehr darüber lernen, wie man zusätzliche Information unterbringt, wenn Sie lernen, Beispiele zu deklarieren.
+Sie werden später in der Dokumentation mehr darüber lernen, wie man zusätzliche Information unterbringt, wenn Sie lernen, Beispiele zu deklarieren.
/// warning | Achtung
diff --git a/docs/de/docs/tutorial/body-multiple-params.md b/docs/de/docs/tutorial/body-multiple-params.md
index daa48f23d..60a0ceefe 100644
--- a/docs/de/docs/tutorial/body-multiple-params.md
+++ b/docs/de/docs/tutorial/body-multiple-params.md
@@ -104,12 +104,6 @@ Da einfache Werte standardmäßig als Query-Parameter interpretiert werden, müs
q: str | None = None
```
-Oder in Python 3.9:
-
-```Python
-q: Union[str, None] = None
-```
-
Zum Beispiel:
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md
index 65a5d7c1d..52b00e036 100644
--- a/docs/de/docs/tutorial/body-nested-models.md
+++ b/docs/de/docs/tutorial/body-nested-models.md
@@ -163,7 +163,7 @@ images: list[Image]
so wie in:
-{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
## Editor-Unterstützung überall { #editor-support-everywhere }
@@ -193,7 +193,7 @@ Das schauen wir uns mal an.
Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüssel und `float`-Werte hat:
-{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
/// tip | Tipp
diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md
index cdf3122f2..e1214bc53 100644
--- a/docs/de/docs/tutorial/body.md
+++ b/docs/de/docs/tutorial/body.md
@@ -154,7 +154,7 @@ Die Funktionsparameter werden wie folgt erkannt:
FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, aufgrund des definierten Defaultwertes `= None`.
-Das `str | None` (Python 3.10+) oder `Union` in `Union[str, None]` (Python 3.9+) wird von FastAPI nicht verwendet, um zu bestimmen, dass der Wert nicht erforderlich ist. FastAPI weiß, dass er nicht erforderlich ist, weil er einen Defaultwert von `= None` hat.
+Das `str | None` wird von FastAPI nicht verwendet, um zu bestimmen, dass der Wert nicht erforderlich ist. FastAPI weiß, dass er nicht erforderlich ist, weil er einen Defaultwert von `= None` hat.
Das Hinzufügen der Typannotationen ermöglicht jedoch Ihrem Editor, Ihnen eine bessere Unterstützung zu bieten und Fehler zu erkennen.
diff --git a/docs/de/docs/tutorial/cookie-param-models.md b/docs/de/docs/tutorial/cookie-param-models.md
index 25718bd33..81f7abb7d 100644
--- a/docs/de/docs/tutorial/cookie-param-models.md
+++ b/docs/de/docs/tutorial/cookie-param-models.md
@@ -46,7 +46,7 @@ Aber selbst wenn Sie die **Daten ausfüllen** und auf „Ausführen“ klicken,
In einigen speziellen Anwendungsfällen (wahrscheinlich nicht sehr häufig) möchten Sie möglicherweise die Cookies, die Sie empfangen möchten, **einschränken**.
-Ihre API hat jetzt die Macht, ihre eigene Cookie-Einwilligung zu kontrollieren. 🤪🍪
+Ihre API hat jetzt die Macht, ihre eigene Cookie-Einwilligung zu kontrollieren. 🤪🍪
Sie können die Modellkonfiguration von Pydantic verwenden, um `extra` Felder zu verbieten (`forbid`):
@@ -54,9 +54,9 @@ Sie können die Modellkonfiguration von Pydantic verwenden, um `extra` Felder zu
Wenn ein Client versucht, einige **zusätzliche Cookies** zu senden, erhält er eine **Error-Response**.
-Arme Cookie-Banner, wie sie sich mühen, Ihre Einwilligung zu erhalten, dass die API sie ablehnen darf. 🍪
+Arme Cookie-Banner, wie sie sich mühen, Ihre Einwilligung zu erhalten, dass die API sie ablehnen darf. 🍪
-Wenn der Client beispielsweise versucht, ein `santa_tracker`-Cookie mit einem Wert von `good-list-please` zu senden, erhält der Client eine **Error-Response**, die ihm mitteilt, dass das `santa_tracker` Cookie nicht erlaubt ist:
+Wenn der Client beispielsweise versucht, ein `santa_tracker`-Cookie mit einem Wert von `good-list-please` zu senden, erhält der Client eine **Error-Response**, die ihm mitteilt, dass das `santa_tracker` Cookie nicht erlaubt ist:
```json
{
@@ -73,4 +73,4 @@ Wenn der Client beispielsweise versucht, ein `santa_tracker`-Cookie mit einem We
## Zusammenfassung { #summary }
-Sie können **Pydantic-Modelle** verwenden, um **Cookies** in **FastAPI** zu deklarieren. 😎
+Sie können **Pydantic-Modelle** verwenden, um **Cookies** in **FastAPI** zu deklarieren. 😎
diff --git a/docs/de/docs/tutorial/cors.md b/docs/de/docs/tutorial/cors.md
index 81f0f3605..4e714f215 100644
--- a/docs/de/docs/tutorial/cors.md
+++ b/docs/de/docs/tutorial/cors.md
@@ -46,7 +46,7 @@ Sie können auch angeben, ob Ihr Backend erlaubt:
* Bestimmte HTTP-Methoden (`POST`, `PUT`) oder alle mit der Wildcard `"*"`.
* Bestimmte HTTP-Header oder alle mit der Wildcard `"*"`.
-{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *}
Die von der `CORSMiddleware`-Implementierung verwendeten Defaultparameter sind standardmäßig restriktiv, daher müssen Sie bestimmte Origins, Methoden oder Header ausdrücklich aktivieren, damit Browser sie in einem Cross-Domain-Kontext verwenden dürfen.
diff --git a/docs/de/docs/tutorial/debugging.md b/docs/de/docs/tutorial/debugging.md
index 0d12877c1..cabaf5a3a 100644
--- a/docs/de/docs/tutorial/debugging.md
+++ b/docs/de/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@ Sie können den Debugger in Ihrem Editor verbinden, zum Beispiel mit Visual Stud
Importieren und führen Sie `uvicorn` direkt in Ihrer FastAPI-Anwendung aus:
-{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *}
### Über `__name__ == "__main__"` { #about-name-main }
diff --git a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md
index 7df0842eb..4fd8d092f 100644
--- a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -101,7 +101,7 @@ Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren.
Beachten Sie, wie wir `CommonQueryParams` im obigen Code zweimal schreiben:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ nicht annotiert
+//// tab | Python 3.10+ nicht annotiert
/// tip | Tipp
@@ -137,7 +137,7 @@ Aus diesem extrahiert FastAPI die deklarierten Parameter, und dieses ist es, was
In diesem Fall hat das erste `CommonQueryParams` in:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.9+ nicht annotiert
+//// tab | Python 3.10+ nicht annotiert
/// tip | Tipp
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
Sie könnten tatsächlich einfach schreiben:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ nicht annotiert
+//// tab | Python 3.10+ nicht annotiert
/// tip | Tipp
@@ -197,7 +197,7 @@ Es wird jedoch empfohlen, den Typ zu deklarieren, da Ihr Editor so weiß, was al
Aber Sie sehen, dass wir hier etwas Codeduplizierung haben, indem wir `CommonQueryParams` zweimal schreiben:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ nicht annotiert
+//// tab | Python 3.10+ nicht annotiert
/// tip | Tipp
@@ -225,7 +225,7 @@ In diesem speziellen Fall können Sie Folgendes tun:
Anstatt zu schreiben:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ nicht annotiert
+//// tab | Python 3.10+ nicht annotiert
/// tip | Tipp
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
... schreiben Sie:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.9+ nicht annotiert
+//// tab | Python 3.10+ nicht annotiert
/// tip | Tipp
diff --git a/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 59c9fcf48..f63273f16 100644
--- a/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -6,15 +6,15 @@ Oder die Abhängigkeit gibt keinen Wert zurück.
Aber Sie müssen sie trotzdem ausführen/auflösen.
-In diesen Fällen können Sie, anstatt einen Parameter der *Pfadoperation-Funktion* mit `Depends` zu deklarieren, eine `list`e von `dependencies` zum *Pfadoperation-Dekorator* hinzufügen.
+In diesen Fällen können Sie, anstatt einen Parameter der *Pfadoperation-Funktion* mit `Depends` zu deklarieren, eine `list` von `dependencies` zum *Pfadoperation-Dekorator* hinzufügen.
## `dependencies` zum *Pfadoperation-Dekorator* hinzufügen { #add-dependencies-to-the-path-operation-decorator }
Der *Pfadoperation-Dekorator* erhält ein optionales Argument `dependencies`.
-Es sollte eine `list`e von `Depends()` sein:
+Es sollte eine `list` von `Depends()` sein:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
Diese Abhängigkeiten werden auf die gleiche Weise wie normale Abhängigkeiten ausgeführt/aufgelöst. Aber ihr Wert (falls sie einen zurückgeben) wird nicht an Ihre *Pfadoperation-Funktion* übergeben.
@@ -44,13 +44,13 @@ Sie können dieselben Abhängigkeits-*Funktionen* verwenden, die Sie normalerwei
Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhängigkeiten deklarieren:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
### Exceptions auslösen { #raise-exceptions }
Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeiten:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
### Rückgabewerte { #return-values }
@@ -58,7 +58,7 @@ Und sie können Werte zurückgeben oder nicht, die Werte werden nicht verwendet.
Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Sie bereits an anderer Stelle verwenden, wiederverwenden, und auch wenn der Wert nicht verwendet wird, wird die Abhängigkeit ausgeführt:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
## Abhängigkeiten für eine Gruppe von *Pfadoperationen* { #dependencies-for-a-group-of-path-operations }
diff --git a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md
index 0083e7e7e..c5f2acbae 100644
--- a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,6 +1,6 @@
# Abhängigkeiten mit `yield` { #dependencies-with-yield }
-FastAPI unterstützt Abhängigkeiten, die nach Abschluss einige zusätzliche Schritte ausführen.
+FastAPI unterstützt Abhängigkeiten, die einige zusätzliche Schritte nach Abschluss ausführen.
Verwenden Sie dazu `yield` statt `return` und schreiben Sie die zusätzlichen Schritte / den zusätzlichen Code danach.
@@ -29,15 +29,15 @@ Sie könnten damit beispielsweise eine Datenbanksession erstellen und diese nach
Nur der Code vor und einschließlich der `yield`-Anweisung wird ausgeführt, bevor eine Response erzeugt wird:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
Der ge`yield`ete Wert ist das, was in *Pfadoperationen* und andere Abhängigkeiten eingefügt wird:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
Der auf die `yield`-Anweisung folgende Code wird nach der Response ausgeführt:
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
/// tip | Tipp
@@ -57,7 +57,7 @@ Sie können also mit `except SomeException` diese bestimmte Exception innerhalb
Auf die gleiche Weise können Sie `finally` verwenden, um sicherzustellen, dass die Exit-Schritte ausgeführt werden, unabhängig davon, ob eine Exception geworfen wurde oder nicht.
-{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
## Unterabhängigkeiten mit `yield` { #sub-dependencies-with-yield }
@@ -67,7 +67,7 @@ Sie können Unterabhängigkeiten und „Bäume“ von Unterabhängigkeiten belie
Beispielsweise kann `dependency_c` von `dependency_b` und `dependency_b` von `dependency_a` abhängen:
-{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *}
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
Und alle können `yield` verwenden.
@@ -75,7 +75,7 @@ In diesem Fall benötigt `dependency_c` zum Ausführen seines Exit-Codes, dass d
Und wiederum benötigt `dependency_b` den Wert von `dependency_a` (hier `dep_a` genannt) für seinen Exit-Code.
-{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *}
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
Auf die gleiche Weise könnten Sie einige Abhängigkeiten mit `yield` und einige andere Abhängigkeiten mit `return` haben, und alle können beliebig voneinander abhängen.
@@ -109,7 +109,7 @@ Aber es ist für Sie da, wenn Sie es brauchen. 🤓
///
-{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *}
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
Wenn Sie Exceptions abfangen und darauf basierend eine benutzerdefinierte Response erstellen möchten, erstellen Sie einen [benutzerdefinierten Exceptionhandler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
@@ -117,7 +117,7 @@ Wenn Sie Exceptions abfangen und darauf basierend eine benutzerdefinierte Respon
Wenn Sie eine Exception mit `except` in einer Abhängigkeit mit `yield` abfangen und sie nicht erneut auslösen (oder eine neue Exception auslösen), kann FastAPI nicht feststellen, dass es eine Exception gab, genau so wie es bei normalem Python der Fall wäre:
-{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *}
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
In diesem Fall sieht der Client eine *HTTP 500 Internal Server Error*-Response, wie es sein sollte, da wir keine `HTTPException` oder Ähnliches auslösen, aber der Server hat **keine Logs** oder einen anderen Hinweis darauf, was der Fehler war. 😱
@@ -127,7 +127,7 @@ Wenn Sie eine Exception in einer Abhängigkeit mit `yield` abfangen, sollten Sie
Sie können dieselbe Exception mit `raise` erneut auslösen:
-{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *}
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
Jetzt erhält der Client dieselbe *HTTP 500 Internal Server Error*-Response, aber der Server enthält unseren benutzerdefinierten `InternalError` in den Logs. 😎
@@ -190,7 +190,7 @@ Normalerweise wird der Exit-Code von Abhängigkeiten mit `yield` ausgeführt **n
Wenn Sie aber wissen, dass Sie die Abhängigkeit nach der Rückkehr aus der *Pfadoperation-Funktion* nicht mehr benötigen, können Sie `Depends(scope="function")` verwenden, um FastAPI mitzuteilen, dass es die Abhängigkeit nach der Rückkehr aus der *Pfadoperation-Funktion* schließen soll, jedoch **bevor** die **Response gesendet wird**.
-{* ../../docs_src/dependencies/tutorial008e_an_py39.py hl[12,16] *}
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
`Depends()` erhält einen `scope`-Parameter, der sein kann:
@@ -268,7 +268,7 @@ In Python können Sie Kontextmanager erstellen, indem Sie Dependency Injection** System.
+**FastAPI** hat ein sehr mächtiges, aber intuitives **Abhängigkeitsinjektion** System.
Es ist so konzipiert, sehr einfach zu verwenden zu sein und es jedem Entwickler sehr leicht zu machen, andere Komponenten mit **FastAPI** zu integrieren.
diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md
index d72f820dc..b01cc80a7 100644
--- a/docs/de/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md
@@ -58,11 +58,11 @@ query_extractor --> query_or_cookie_extractor --> read_query
Wenn eine Ihrer Abhängigkeiten mehrmals für dieselbe *Pfadoperation* deklariert wird, beispielsweise wenn mehrere Abhängigkeiten eine gemeinsame Unterabhängigkeit haben, wird **FastAPI** diese Unterabhängigkeit nur einmal pro Request aufrufen.
-Und es speichert den zurückgegebenen Wert in einem „Cache“ und übergibt diesen gecachten Wert an alle „Dependanten“, die ihn in diesem spezifischen Request benötigen, anstatt die Abhängigkeit mehrmals für denselben Request aufzurufen.
+Und es speichert den zurückgegebenen Wert in einem „Cache“ und übergibt diesen gecachten Wert an alle „Dependanten“, die ihn in diesem spezifischen Request benötigen, anstatt die Abhängigkeit mehrmals für denselben Request aufzurufen.
In einem fortgeschrittenen Szenario, bei dem Sie wissen, dass die Abhängigkeit bei jedem Schritt (möglicherweise mehrmals) in demselben Request aufgerufen werden muss, anstatt den zwischengespeicherten Wert zu verwenden, können Sie den Parameter `use_cache=False` festlegen, wenn Sie `Depends` verwenden:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python hl_lines="1"
async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
@@ -71,7 +71,7 @@ async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_ca
////
-//// tab | Python 3.9+ nicht annotiert
+//// tab | Python 3.10+ nicht annotiert
/// tip | Tipp
diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md
index 889fdb9a3..4f55f2428 100644
--- a/docs/de/docs/tutorial/extra-models.md
+++ b/docs/de/docs/tutorial/extra-models.md
@@ -190,9 +190,9 @@ Aber wenn wir das in der Zuweisung `response_model=PlaneItem | CarItem` machen,
Auf die gleiche Weise können Sie Responses von Listen von Objekten deklarieren.
-Dafür verwenden Sie Pythons Standard-`typing.List` (oder nur `list` in Python 3.9 und höher):
+Dafür verwenden Sie Pythons Standard-`list`:
-{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *}
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
## Response mit beliebigem `dict` { #response-with-arbitrary-dict }
@@ -200,9 +200,9 @@ Sie können auch eine Response deklarieren, die ein beliebiges `dict` zurückgib
Dies ist nützlich, wenn Sie die gültigen Feld-/Attributnamen nicht im Voraus kennen (die für ein Pydantic-Modell benötigt werden würden).
-In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und höher):
+In diesem Fall können Sie `dict` verwenden:
-{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *}
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
## Zusammenfassung { #recap }
diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md
index 9505a0bdb..f02fb3d43 100644
--- a/docs/de/docs/tutorial/first-steps.md
+++ b/docs/de/docs/tutorial/first-steps.md
@@ -2,7 +2,7 @@
Die einfachste FastAPI-Datei könnte wie folgt aussehen:
-{* ../../docs_src/first_steps/tutorial001_py39.py *}
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
Kopieren Sie das in eine Datei `main.py`.
@@ -183,7 +183,7 @@ Das war's! Jetzt können Sie Ihre App unter dieser URL aufrufen. ✨
### Schritt 1: `FastAPI` importieren { #step-1-import-fastapi }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[1] *}
`FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt.
@@ -197,7 +197,7 @@ Sie können alle Requests zuständig ist, die an:
* den Pfad `/`
-* unter der Verwendung der get-Operation gehen
+* unter der Verwendung der get-Operation gehen
/// info | `@decorator` Info
@@ -320,7 +320,7 @@ Das ist unsere „**Pfadoperation-Funktion**“:
* **Operation**: ist `get`.
* **Funktion**: ist die Funktion direkt unter dem „Dekorator“ (unter `@app.get("/")`).
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
Dies ist eine Python-Funktion.
@@ -332,7 +332,7 @@ In diesem Fall handelt es sich um eine `async`-Funktion.
Sie könnten sie auch als normale Funktion anstelle von `async def` definieren:
-{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
/// note | Hinweis
@@ -342,7 +342,7 @@ Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../as
### Schritt 5: den Inhalt zurückgeben { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
Sie können ein `dict`, eine `list`, einzelne Werte wie `str`, `int`, usw. zurückgeben.
diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md
index d890b4462..0cb0de2ca 100644
--- a/docs/de/docs/tutorial/handling-errors.md
+++ b/docs/de/docs/tutorial/handling-errors.md
@@ -25,7 +25,7 @@ Um HTTP-Exceptionhandler mit den gleichen Exception-Werkzeugen von Starlette hinzufügen.
+Sie können benutzerdefinierte Exceptionhandler mit den gleichen Exception-Werkzeugen von Starlette hinzufügen.
Angenommen, Sie haben eine benutzerdefinierte Exception `UnicornException`, die Sie (oder eine Bibliothek, die Sie verwenden) `raise`n könnten.
@@ -89,7 +89,7 @@ Und Sie möchten diese Exception global mit FastAPI handhaben.
Sie könnten einen benutzerdefinierten Exceptionhandler mit `@app.exception_handler()` hinzufügen:
-{* ../../docs_src/handling_errors/tutorial003_py39.py hl[5:7,13:18,24] *}
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
Hier, wenn Sie `/unicorns/yolo` anfordern, wird die *Pfadoperation* eine `UnicornException` `raise`n.
@@ -127,7 +127,7 @@ Um diesen zu überschreiben, importieren Sie den `RequestValidationError` und ve
Der Exceptionhandler erhält einen `Request` und die Exception.
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[2,14:19] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
Wenn Sie nun zu `/items/foo` gehen, erhalten Sie anstelle des standardmäßigen JSON-Fehlers mit:
@@ -159,7 +159,7 @@ Auf die gleiche Weise können Sie den `HTTPException`-Handler überschreiben.
Zum Beispiel könnten Sie eine Klartext-Response statt JSON für diese Fehler zurückgeben wollen:
-{* ../../docs_src/handling_errors/tutorial004_py39.py hl[3:4,9:11,25] *}
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
/// note | Technische Details
@@ -183,7 +183,7 @@ Der `RequestValidationError` enthält den empfangenen `body` mit den ungültigen
Sie könnten diesen während der Entwicklung Ihrer Anwendung verwenden, um den Body zu loggen und zu debuggen, ihn an den Benutzer zurückzugeben usw.
-{* ../../docs_src/handling_errors/tutorial005_py39.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
Versuchen Sie nun, einen ungültigen Artikel zu senden:
@@ -239,6 +239,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
Wenn Sie die Exception zusammen mit den gleichen Default-Exceptionhandlern von **FastAPI** verwenden möchten, können Sie die Default-Exceptionhandler aus `fastapi.exception_handlers` importieren und wiederverwenden:
-{* ../../docs_src/handling_errors/tutorial006_py39.py hl[2:5,15,21] *}
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
In diesem Beispiel geben Sie nur den Fehler mit einer sehr ausdrucksstarken Nachricht aus, aber Sie verstehen das Prinzip. Sie können die Exception verwenden und dann einfach die Default-Exceptionhandler wiederverwenden.
diff --git a/docs/de/docs/tutorial/metadata.md b/docs/de/docs/tutorial/metadata.md
index ee88a21d6..f5999a667 100644
--- a/docs/de/docs/tutorial/metadata.md
+++ b/docs/de/docs/tutorial/metadata.md
@@ -18,7 +18,7 @@ Sie können die folgenden Felder festlegen, die in der OpenAPI-Spezifikation und
Sie können diese wie folgt setzen:
-{* ../../docs_src/metadata/tutorial001_py39.py hl[3:16, 19:32] *}
+{* ../../docs_src/metadata/tutorial001_py310.py hl[3:16, 19:32] *}
/// tip | Tipp
@@ -36,7 +36,7 @@ Seit OpenAPI 3.1.0 und FastAPI 0.99.0 können Sie die `license_info` auch mit ei
Zum Beispiel:
-{* ../../docs_src/metadata/tutorial001_1_py39.py hl[31] *}
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
## Metadaten für Tags { #metadata-for-tags }
@@ -58,7 +58,7 @@ Versuchen wir es mit einem Beispiel mit Tags für `users` und `items`.
Erstellen Sie Metadaten für Ihre Tags und übergeben Sie diese an den Parameter `openapi_tags`:
-{* ../../docs_src/metadata/tutorial004_py39.py hl[3:16,18] *}
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
Beachten Sie, dass Sie Markdown innerhalb der Beschreibungen verwenden können. Zum Beispiel wird „login“ in Fettschrift (**login**) und „fancy“ in Kursivschrift (_fancy_) angezeigt.
@@ -72,7 +72,7 @@ Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen.
Verwenden Sie den Parameter `tags` mit Ihren *Pfadoperationen* (und `APIRouter`n), um diese verschiedenen Tags zuzuweisen:
-{* ../../docs_src/metadata/tutorial004_py39.py hl[21,26] *}
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
/// info | Info
@@ -100,7 +100,7 @@ Sie können das aber mit dem Parameter `openapi_url` konfigurieren.
Um beispielsweise festzulegen, dass es unter `/api/v1/openapi.json` bereitgestellt wird:
-{* ../../docs_src/metadata/tutorial002_py39.py hl[3] *}
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
Wenn Sie das OpenAPI-Schema vollständig deaktivieren möchten, können Sie `openapi_url=None` festlegen, wodurch auch die Dokumentationsbenutzeroberflächen deaktiviert werden, die es verwenden.
@@ -117,4 +117,4 @@ Sie können die beiden enthaltenen Dokumentationsbenutzeroberflächen konfigurie
Um beispielsweise Swagger UI so einzustellen, dass sie unter `/documentation` bereitgestellt wird, und ReDoc zu deaktivieren:
-{* ../../docs_src/metadata/tutorial003_py39.py hl[3] *}
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/de/docs/tutorial/middleware.md b/docs/de/docs/tutorial/middleware.md
index 540a18c4d..116f87d23 100644
--- a/docs/de/docs/tutorial/middleware.md
+++ b/docs/de/docs/tutorial/middleware.md
@@ -31,7 +31,7 @@ Die Middleware-Funktion erhält:
* Dann gibt es die von der entsprechenden *Pfadoperation* generierte `response` zurück.
* Sie können die `response` dann weiter modifizieren, bevor Sie sie zurückgeben.
-{* ../../docs_src/middleware/tutorial001_py39.py hl[8:9,11,14] *}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
/// tip | Tipp
@@ -57,7 +57,7 @@ Und auch nachdem die `response` generiert wurde, bevor sie zurückgegeben wird.
Sie könnten beispielsweise einen benutzerdefinierten Header `X-Process-Time` hinzufügen, der die Zeit in Sekunden enthält, die benötigt wurde, um den Request zu verarbeiten und eine Response zu generieren:
-{* ../../docs_src/middleware/tutorial001_py39.py hl[10,12:13] *}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
/// tip | Tipp
diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md
index a06c85e57..48d6d6603 100644
--- a/docs/de/docs/tutorial/path-operation-configuration.md
+++ b/docs/de/docs/tutorial/path-operation-configuration.md
@@ -46,7 +46,7 @@ In diesem Fall macht es Sinn, die Tags in einem `Enum` zu speichern.
**FastAPI** unterstützt das auf die gleiche Weise wie einfache Strings:
-{* ../../docs_src/path_operation_configuration/tutorial002b_py39.py hl[1,8:10,13,18] *}
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
## Zusammenfassung und Beschreibung { #summary-and-description }
@@ -56,7 +56,7 @@ Sie können eine `summary` und eine Docstring der Funktion deklarieren, und **FastAPI** wird sie daraus auslesen.
+Da Beschreibungen oft mehrere Zeilen lang sind, können Sie die Beschreibung der *Pfadoperation* im Docstring der Funktion deklarieren, und **FastAPI** wird sie daraus auslesen.
Sie können Markdown im Docstring schreiben, es wird korrekt interpretiert und angezeigt (unter Berücksichtigung der Einrückung des Docstring).
@@ -90,9 +90,9 @@ Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolg
## Eine *Pfadoperation* deprecaten { #deprecate-a-path-operation }
-Wenn Sie eine *Pfadoperation* als deprecatet kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu:
+Wenn Sie eine *Pfadoperation* als deprecatet kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu:
-{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
Sie wird in der interaktiven Dokumentation gut sichtbar als deprecatet markiert werden:
diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md
index 8b52e8b42..5147a7fbc 100644
--- a/docs/de/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/de/docs/tutorial/path-params-numeric-validations.md
@@ -54,11 +54,11 @@ Für **FastAPI** spielt es keine Rolle. Es erkennt die Parameter anhand ihrer Na
Sie können Ihre Funktion also so deklarieren:
-{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da es nicht darauf ankommt, dass Sie keine Funktionsparameter-Defaultwerte für `Query()` oder `Path()` verwenden.
-{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
## Die Parameter sortieren, wie Sie möchten: Tricks { #order-the-parameters-as-you-need-tricks }
@@ -83,13 +83,13 @@ Wenn Sie:
Python wird nichts mit diesem `*` machen, aber es wird wissen, dass alle folgenden Parameter als Schlüsselwortargumente (Schlüssel-Wert-Paare) verwendet werden sollen, auch bekannt als kwargs. Selbst wenn diese keinen Defaultwert haben.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
### Besser mit `Annotated` { #better-with-annotated }
Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, da Sie keine Funktionsparameter-Defaultwerte verwenden, dieses Problem nicht haben werden und wahrscheinlich nicht `*` verwenden müssen.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
## Validierung von Zahlen: Größer oder gleich { #number-validations-greater-than-or-equal }
@@ -97,7 +97,7 @@ Mit `Query` und `Path` (und anderen, die Sie später sehen werden) können Sie Z
Hier, mit `ge=1`, muss `item_id` eine ganze Zahl sein, die „`g`reater than or `e`qual to“ (größer oder gleich) `1` ist.
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
## Validierung von Zahlen: Größer und kleiner oder gleich { #number-validations-greater-than-and-less-than-or-equal }
@@ -106,7 +106,7 @@ Das Gleiche gilt für:
* `gt`: `g`reater `t`han (größer als)
* `le`: `l`ess than or `e`qual (kleiner oder gleich)
-{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
## Validierung von Zahlen: Floats, größer und kleiner { #number-validations-floats-greater-than-and-less-than }
@@ -118,7 +118,7 @@ Also wäre `0.5` ein gültiger Wert. Aber `0.0` oder `0` nicht.
Und das Gleiche gilt für lt.
-{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
## Zusammenfassung { #recap }
diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md
index 1de497315..41f6aea55 100644
--- a/docs/de/docs/tutorial/path-params.md
+++ b/docs/de/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Sie können Pfad-„Parameter“ oder -„Variablen“ mit der gleichen Syntax deklarieren, welche in Python-Formatstrings verwendet wird:
-{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben.
@@ -16,7 +16,7 @@ Wenn Sie dieses Beispiel ausführen und auf Konversion { #data-conversion }
+## Daten-Konversion { #data-conversion }
Wenn Sie dieses Beispiel ausführen und Ihren Browser unter http://127.0.0.1:8000/items/3 öffnen, sehen Sie als Response:
@@ -38,7 +38,7 @@ Wenn Sie dieses Beispiel ausführen und Ihren Browser unter Request automatisch „parsen“.
+Sprich, mit dieser Typdeklaration wird **FastAPI** den „parsen“.
///
@@ -118,13 +118,13 @@ Und Sie haben auch einen Pfad `/users/{user_id}`, um Daten über einen spezifisc
Weil *Pfadoperationen* in ihrer Reihenfolge ausgewertet werden, müssen Sie sicherstellen, dass der Pfad `/users/me` vor `/users/{user_id}` deklariert wurde:
-{* ../../docs_src/path_params/tutorial003_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
Ansonsten würde der Pfad für `/users/{user_id}` auch `/users/me` auswerten, und annehmen, dass ein Parameter `user_id` mit dem Wert `"me"` übergeben wurde.
Sie können eine Pfadoperation auch nicht erneut definieren:
-{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
Die erste Definition wird immer verwendet werden, da ihr Pfad zuerst übereinstimmt.
@@ -140,12 +140,11 @@ Indem Sie von `str` erben, weiß die API-Dokumentation, dass die Werte vom Typ `
Erstellen Sie dann Klassen-Attribute mit festgelegten Werten, welches die erlaubten Werte sein werden:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
-
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
/// tip | Tipp
-Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von Modellen für maschinelles Lernen.
+Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von Modellen für maschinelles Lernen.
///
@@ -153,7 +152,7 @@ Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das
Dann erstellen Sie einen *Pfad-Parameter*, der als Typ die gerade erstellte Enum-Klasse hat (`ModelName`):
-{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
### Die API-Dokumentation testen { #check-the-docs }
@@ -169,13 +168,13 @@ Der *Pfad-Parameter* wird ein *parsen"
+* Daten „parsen“
* Datenvalidierung
* API-Annotationen und automatische Dokumentation
diff --git a/docs/de/docs/tutorial/query-params-str-validations.md b/docs/de/docs/tutorial/query-params-str-validations.md
index 8977dbcd5..865d10d13 100644
--- a/docs/de/docs/tutorial/query-params-str-validations.md
+++ b/docs/de/docs/tutorial/query-params-str-validations.md
@@ -39,7 +39,7 @@ Stellen Sie sicher, dass Sie [die FastAPI-Version aktualisieren](../deployment/v
///
-## Verwenden von `Annotated` im Typ für den `q`-Parameter { #use-annotated-in-the-type-for-the-q-parameter }
+## `Annotated` im Typ für den `q`-Parameter verwenden { #use-annotated-in-the-type-for-the-q-parameter }
Erinnern Sie sich, dass ich Ihnen zuvor in [Python-Typen-Intro](../python-types.md#type-hints-with-metadata-annotations){.internal-link target=_blank} gesagt habe, dass `Annotated` verwendet werden kann, um Metadaten zu Ihren Parametern hinzuzufügen?
@@ -47,40 +47,16 @@ Jetzt ist es soweit, dies mit FastAPI zu verwenden. 🚀
Wir hatten diese Typannotation:
-//// tab | Python 3.10+
-
```Python
q: str | None = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Union[str, None] = None
-```
-
-////
-
Was wir tun werden, ist, dies mit `Annotated` zu wrappen, sodass es zu:
-//// tab | Python 3.10+
-
```Python
q: Annotated[str | None] = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Annotated[Union[str, None]] = None
-```
-
-////
-
Beide dieser Versionen bedeuten dasselbe: `q` ist ein Parameter, der ein `str` oder `None` sein kann, und standardmäßig ist er `None`.
Jetzt springen wir zu den spannenden Dingen. 🎉
@@ -109,7 +85,7 @@ FastAPI wird nun:
## Alternative (alt): `Query` als Defaultwert { #alternative-old-query-as-the-default-value }
-Frühere Versionen von FastAPI (vor 0.95.0) erforderten, dass Sie `Query` als den Defaultwert Ihres Parameters verwendeten, anstatt es innerhalb von `Annotated` zu platzieren. Es besteht eine hohe Wahrscheinlichkeit, dass Sie Code sehen, der es so verwendet, also werde ich es Ihnen erklären.
+Frühere Versionen von FastAPI (vor 0.95.0) erforderten, dass Sie `Query` als den Defaultwert Ihres Parameters verwendeten, anstatt es innerhalb von `Annotated` zu platzieren. Es besteht eine hohe Wahrscheinlichkeit, dass Sie Code sehen, der es so verwendet, also werde ich es Ihnen erklären.
/// tip | Tipp
@@ -191,7 +167,7 @@ Sie können auch einen `min_length`-Parameter hinzufügen:
## Reguläre Ausdrücke hinzufügen { #add-regular-expressions }
-Sie können einen regulären Ausdruck `pattern` definieren, mit dem der Parameter übereinstimmen muss:
+Sie können einen regulären Ausdruck `pattern` definieren, mit dem der Parameter übereinstimmen muss:
{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
@@ -211,7 +187,7 @@ Natürlich können Sie Defaultwerte verwenden, die nicht `None` sind.
Nehmen wir an, Sie möchten, dass der `q` Query-Parameter eine `min_length` von `3` hat und einen Defaultwert von `"fixedquery"`:
-{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial005_an_py310.py hl[9] *}
/// note | Hinweis
@@ -241,7 +217,7 @@ q: Annotated[str | None, Query(min_length=3)] = None
Wenn Sie einen Wert als erforderlich deklarieren müssen, während Sie `Query` verwenden, deklarieren Sie einfach keinen Defaultwert:
-{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial006_an_py310.py hl[9] *}
### Erforderlich, kann `None` sein { #required-can-be-none }
@@ -292,7 +268,7 @@ Die interaktive API-Dokumentation wird entsprechend aktualisiert, um mehrere Wer
Sie können auch eine Default-`list` von Werten definieren, wenn keine bereitgestellt werden:
-{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
Wenn Sie zu:
@@ -315,7 +291,7 @@ gehen, wird der Default für `q` sein: `["foo", "bar"]`, und Ihre Response wird
Sie können auch `list` direkt verwenden, anstelle von `list[str]`:
-{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
/// note | Hinweis
@@ -371,7 +347,7 @@ Dann können Sie ein `alias` deklarieren, und dieser Alias wird verwendet, um de
Nehmen wir an, Ihnen gefällt dieser Parameter nicht mehr.
-Sie müssen ihn eine Weile dort belassen, da es Clients gibt, die ihn verwenden, aber Sie möchten, dass die Dokumentation ihn klar als deprecatet anzeigt.
+Sie müssen ihn eine Weile dort belassen, da es Clients gibt, die ihn verwenden, aber Sie möchten, dass die Dokumentation ihn klar als deprecatet anzeigt.
Dann übergeben Sie den Parameter `deprecated=True` an `Query`:
@@ -393,7 +369,7 @@ Es kann Fälle geben, in denen Sie eine **benutzerdefinierte Validierung** durch
In diesen Fällen können Sie eine **benutzerdefinierte Validierungsfunktion** verwenden, die nach der normalen Validierung angewendet wird (z. B. nach der Validierung, dass der Wert ein `str` ist).
-Sie können dies mit Pydantic's `AfterValidator` innerhalb von `Annotated` erreichen.
+Sie können dies mit Pydantics `AfterValidator` innerhalb von `Annotated` erreichen.
/// tip | Tipp
@@ -401,7 +377,7 @@ Pydantic unterstützt auch ISBN-Buchnummer oder mit `imdb-` für eine IMDB-Film-URL-ID beginnt:
+Zum Beispiel überprüft dieser benutzerdefinierte Validator, ob die Artikel-ID mit `isbn-` für eine ISBN-Buchnummer oder mit `imdb-` für eine IMDB-Film-URL-ID beginnt:
{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
@@ -435,7 +411,7 @@ Haben Sie bemerkt? Eine Zeichenkette mit `value.startswith()` kann ein Tuple üb
#### Ein zufälliges Item { #a-random-item }
-Mit `data.items()` erhalten wir ein iterierbares Objekt mit Tupeln, die Schlüssel und Wert für jedes Dictionary-Element enthalten.
+Mit `data.items()` erhalten wir ein iterierbares Objekt mit Tupeln, die Schlüssel und Wert für jedes Dictionary-Element enthalten.
Wir konvertieren dieses iterierbare Objekt mit `list(data.items())` in eine richtige `list`.
diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md
index 05ed3bc83..5a2a2a012 100644
--- a/docs/de/docs/tutorial/query-params.md
+++ b/docs/de/docs/tutorial/query-params.md
@@ -2,7 +2,7 @@
Wenn Sie in Ihrer Funktion andere Parameter deklarieren, die nicht Teil der Pfad-Parameter sind, dann werden diese automatisch als „Query“-Parameter interpretiert.
-{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
Die Query ist die Menge von Schlüssel-Wert-Paaren, die nach dem `?` in einer URL folgen und durch `&`-Zeichen getrennt sind.
@@ -24,7 +24,7 @@ Aber wenn Sie sie mit Python-Typen deklarieren (im obigen Beispiel als `int`), w
Die gleichen Prozesse, die für Pfad-Parameter gelten, werden auch auf Query-Parameter angewendet:
* Editor Unterstützung (natürlich)
-* Daten-„Parsen“
+* Daten-„Parsen“
* Datenvalidierung
* Automatische Dokumentation
@@ -127,7 +127,7 @@ Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach op
Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert:
-{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`.
diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md
index 0aee898b9..5b5f72d6d 100644
--- a/docs/de/docs/tutorial/request-files.md
+++ b/docs/de/docs/tutorial/request-files.md
@@ -20,13 +20,13 @@ Das liegt daran, dass hochgeladene Dateien als „Formulardaten“ gesendet werd
Importieren Sie `File` und `UploadFile` von `fastapi`:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
## `File`-Parameter definieren { #define-file-parameters }
Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
/// info | Info
@@ -54,7 +54,7 @@ Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwe
Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
`UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`:
@@ -143,7 +143,7 @@ Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwe
Sie können auch `File()` mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen:
-{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
## Mehrere Datei-Uploads { #multiple-file-uploads }
@@ -153,7 +153,7 @@ Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten ge
Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s:
-{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
Sie erhalten, wie deklariert, eine `list` von `bytes` oder `UploadFile`s.
@@ -169,7 +169,7 @@ Sie können auch `from starlette.responses import HTMLResponse` verwenden.
Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`:
-{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
## Zusammenfassung { #recap }
diff --git a/docs/de/docs/tutorial/request-form-models.md b/docs/de/docs/tutorial/request-form-models.md
index fbc6c094c..262a14d6d 100644
--- a/docs/de/docs/tutorial/request-form-models.md
+++ b/docs/de/docs/tutorial/request-form-models.md
@@ -24,7 +24,7 @@ Dies wird seit FastAPI Version `0.113.0` unterstützt. 🤓
Sie müssen nur ein **Pydantic-Modell** mit den Feldern deklarieren, die Sie als **Formularfelder** erhalten möchten, und dann den Parameter als `Form` deklarieren:
-{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
**FastAPI** wird die Daten für **jedes Feld** aus den **Formulardaten** im Request **extrahieren** und Ihnen das von Ihnen definierte Pydantic-Modell übergeben.
@@ -48,7 +48,7 @@ Dies wird seit FastAPI Version `0.114.0` unterstützt. 🤓
Sie können die Modellkonfiguration von Pydantic verwenden, um jegliche `extra` Felder zu `verbieten`:
-{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *}
+{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *}
Wenn ein Client versucht, einige zusätzliche Daten zu senden, erhält er eine **Error-Response**.
diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md
index cda38bcc2..f779ff509 100644
--- a/docs/de/docs/tutorial/request-forms-and-files.md
+++ b/docs/de/docs/tutorial/request-forms-and-files.md
@@ -16,13 +16,13 @@ $ pip install python-multipart
## `File` und `Form` importieren { #import-file-and-form }
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[3] *}
## `File` und `Form`-Parameter definieren { #define-file-and-form-parameters }
Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` oder `Query` machen würden:
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[10:12] *}
Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder.
diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md
index 5c2ace67b..4a36dba72 100644
--- a/docs/de/docs/tutorial/request-forms.md
+++ b/docs/de/docs/tutorial/request-forms.md
@@ -18,17 +18,17 @@ $ pip install python-multipart
Importieren Sie `Form` von `fastapi`:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[3] *}
## `Form`-Parameter definieren { #define-form-parameters }
Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[9] *}
Zum Beispiel stellt eine der Möglichkeiten, die OAuth2-Spezifikation zu verwenden (genannt „password flow“), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden.
-Die Spec erfordert, dass die Felder exakt `username` und `password` genannt werden und als Formularfelder, nicht JSON, gesendet werden.
+Die Spezifikation erfordert, dass die Felder exakt `username` und `password` genannt werden und als Formularfelder, nicht JSON, gesendet werden.
Mit `Form` haben Sie die gleichen Konfigurationsmöglichkeiten wie mit `Body` (und `Query`, `Path`, `Cookie`), inklusive Validierung, Beispielen, einem Alias (z. B. `user-name` statt `username`), usw.
diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md
index f759bb257..99d194fe1 100644
--- a/docs/de/docs/tutorial/response-model.md
+++ b/docs/de/docs/tutorial/response-model.md
@@ -183,7 +183,7 @@ Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydan
Der häufigste Anwendungsfall ist, wenn Sie [eine Response direkt zurückgeben, wie es später im Handbuch für fortgeschrittene Benutzer erläutert wird](../advanced/response-directly.md){.internal-link target=_blank}.
-{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist.
@@ -193,7 +193,7 @@ Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch `
Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden.
-{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert.
@@ -201,7 +201,7 @@ Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `
Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pydantic-Typ ist (z. B. ein Datenbank-Objekt), und Sie annotieren es so in der Funktion, wird FastAPI versuchen, ein Pydantic-Responsemodell von dieser Typannotation zu erstellen, und scheitern.
-Das gleiche wird passieren, wenn Sie eine Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥:
+Das gleiche wird passieren, wenn Sie eine Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥:
{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md
index fd17c9933..2ed74f590 100644
--- a/docs/de/docs/tutorial/response-status-code.md
+++ b/docs/de/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@ Genauso wie Sie ein Responsemodell angeben können, können Sie auch den HTTP-St
* `@app.delete()`
* usw.
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
/// note | Hinweis
@@ -66,7 +66,7 @@ Kurz gefasst:
/// tip | Tipp
-Um mehr über die einzelnen Statuscodes zu erfahren und welcher wofür verwendet wird, sehen Sie sich die MDN Dokumentation über HTTP-Statuscodes an.
+Um mehr über die einzelnen Statuscodes zu erfahren und welcher wofür verwendet wird, sehen Sie sich die MDN Dokumentation über HTTP-Statuscodes an.
///
@@ -74,7 +74,7 @@ Um mehr über die einzelnen Statuscodes zu erfahren und welcher wofür verwendet
Lassen Sie uns das vorherige Beispiel noch einmal anschauen:
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201` ist der Statuscode für „Created“ („Erzeugt“).
@@ -82,7 +82,7 @@ Aber Sie müssen sich nicht merken, was jeder dieser Codes bedeutet.
Sie können die Annehmlichkeit von Variablen aus `fastapi.status` nutzen.
-{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
Diese sind nur eine Annehmlichkeit, sie enthalten dieselbe Zahl, aber so können Sie die Autovervollständigung Ihres Editors verwenden, um sie zu finden:
diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md
index 07fe8c5d9..c7b1c2b9e 100644
--- a/docs/de/docs/tutorial/schema-extra-example.md
+++ b/docs/de/docs/tutorial/schema-extra-example.md
@@ -74,7 +74,7 @@ Sie können natürlich auch mehrere `examples` übergeben:
Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten.
-Während dies geschrieben wird, unterstützt Swagger UI, das für die Anzeige der Dokumentations-Benutzeroberfläche zuständige Tool, jedoch nicht die Anzeige mehrerer Beispiele für die Daten in **JSON Schema**. Aber lesen Sie unten für einen Workaround weiter.
+Nichtsdestotrotz unterstützt Swagger UI, das für die Anzeige der Dokumentations-Benutzeroberfläche zuständige Tool, zum Zeitpunkt der Erstellung nicht die Anzeige mehrerer Beispiele für die Daten in **JSON Schema**. Aber lesen Sie unten für einen Workaround weiter.
### OpenAPI-spezifische `examples` { #openapi-specific-examples }
diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md
index 20fcd0c00..5806a8ea0 100644
--- a/docs/de/docs/tutorial/security/first-steps.md
+++ b/docs/de/docs/tutorial/security/first-steps.md
@@ -20,7 +20,7 @@ Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktionie
Kopieren Sie das Beispiel in eine Datei `main.py`:
-{* ../../docs_src/security/tutorial001_an_py39.py *}
+{* ../../docs_src/security/tutorial001_an_py310.py *}
## Ausführen { #run-it }
@@ -111,7 +111,7 @@ Betrachten wir es also aus dieser vereinfachten Sicht:
* Der Benutzer klickt im Frontend, um zu einem anderen Abschnitt der Frontend-Web-Anwendung zu gelangen.
* Das Frontend muss weitere Daten von der API abrufen.
* Es benötigt jedoch eine Authentifizierung für diesen bestimmten Endpunkt.
- * Um sich also bei unserer API zu authentifizieren, sendet es einen Header `Authorization` mit dem Wert `Bearer ` plus dem Token.
+ * Um sich also bei unserer API zu authentifizieren, sendet es einen `Authorization`-Header mit dem Wert `Bearer ` plus dem Token.
* Wenn der Token `foobar` enthielte, wäre der Inhalt des `Authorization`-Headers: `Bearer foobar`.
## **FastAPI**s `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }
@@ -134,7 +134,7 @@ In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen br
Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
/// tip | Tipp
@@ -172,7 +172,7 @@ Es kann also mit `Depends` verwendet werden.
Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird.
diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md
index e32e36669..cfb59ff12 100644
--- a/docs/de/docs/tutorial/security/get-current-user.md
+++ b/docs/de/docs/tutorial/security/get-current-user.md
@@ -2,7 +2,7 @@
Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht:
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
Aber das ist immer noch nicht so nützlich.
diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md
index 39b0b93c9..6330d3d9d 100644
--- a/docs/de/docs/tutorial/security/index.md
+++ b/docs/de/docs/tutorial/security/index.md
@@ -20,7 +20,7 @@ OAuth2 ist eine Spezifikation, die verschiedene Möglichkeiten zur Handhabung vo
Es handelt sich um eine recht umfangreiche Spezifikation, und sie deckt mehrere komplexe Anwendungsfälle ab.
-Sie umfasst Möglichkeiten zur Authentifizierung mithilfe eines „Dritten“ („third party“).
+Sie umfasst Möglichkeiten zur Authentifizierung mithilfe eines „Dritten“.
Das ist es, was alle diese „Login mit Facebook, Google, X (Twitter), GitHub“-Systeme unter der Haube verwenden.
diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md
index 0d5ce587b..6d35a1436 100644
--- a/docs/de/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/de/docs/tutorial/security/oauth2-jwt.md
@@ -116,7 +116,11 @@ Und eine weitere, um zu überprüfen, ob ein empfangenes Passwort mit dem gespei
Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,51,58:59,62:63,72:79] *}
+
+Wenn `authenticate_user` mit einem Benutzernamen aufgerufen wird, der in der Datenbank nicht existiert, führen wir dennoch `verify_password` gegen einen Dummy-Hash aus.
+
+So stellt man sicher, dass der Endpunkt ungefähr gleich viel Zeit für die Antwort benötigt, unabhängig davon, ob der Benutzername gültig ist oder nicht. Dadurch werden Timing-Angriffe verhindert, mit denen vorhandene Benutzernamen ermittelt werden könnten.
/// note | Hinweis
@@ -152,7 +156,7 @@ Definieren Sie ein Pydantic-Modell, das im Token-Endpunkt für die `timedelta` mit der Ablaufz
Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück.
-{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *}
+{* ../../docs_src/security/tutorial004_an_py310.py hl[121:136] *}
### Technische Details zum JWT-„Subjekt“ `sub` { #technical-details-about-the-jwt-subject-sub }
diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md
index 28cb83ba9..ae631f8b7 100644
--- a/docs/de/docs/tutorial/security/simple-oauth2.md
+++ b/docs/de/docs/tutorial/security/simple-oauth2.md
@@ -18,7 +18,7 @@ Aber für die Login-*Pfadoperation* müssen wir diese Namen verwenden, um mit de
Die Spezifikation besagt auch, dass `username` und `password` als Formulardaten gesendet werden müssen (hier also kein JSON).
-### `scope` { #scope }
+### `scope` { #scope }
Ferner sagt die Spezifikation, dass der Client ein weiteres Formularfeld "`scope`" („Geltungsbereich“) senden kann.
diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md
index 9ba250175..26e385316 100644
--- a/docs/de/docs/tutorial/static-files.md
+++ b/docs/de/docs/tutorial/static-files.md
@@ -7,7 +7,7 @@ Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisc
* Importieren Sie `StaticFiles`.
* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad.
-{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py310.py hl[2,6] *}
/// note | Technische Details
diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md
index d889b1e1f..4fbe37279 100644
--- a/docs/de/docs/tutorial/testing.md
+++ b/docs/de/docs/tutorial/testing.md
@@ -30,7 +30,7 @@ Verwenden Sie das `TestClient`-Objekt auf die gleiche Weise wie `httpx`.
Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, die Sie überprüfen müssen (wiederum, Standard-`pytest`).
-{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py310.py hl[2,12,15:18] *}
/// tip | Tipp
@@ -76,7 +76,7 @@ Nehmen wir an, Sie haben eine Dateistruktur wie in [Größere Anwendungen](bigge
In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung:
-{* ../../docs_src/app_testing/app_a_py39/main.py *}
+{* ../../docs_src/app_testing/app_a_py310/main.py *}
### Testdatei { #testing-file }
@@ -93,7 +93,7 @@ Dann könnten Sie eine Datei `test_main.py` mit Ihren Tests haben. Sie könnte s
Da sich diese Datei im selben Package befindet, können Sie relative Importe verwenden, um das Objekt `app` aus dem `main`-Modul (`main.py`) zu importieren:
-{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py310/test_main.py hl[3] *}
... und haben den Code für die Tests wie zuvor.
diff --git a/docs/de/docs/virtual-environments.md b/docs/de/docs/virtual-environments.md
index 11da496c5..621b4b111 100644
--- a/docs/de/docs/virtual-environments.md
+++ b/docs/de/docs/virtual-environments.md
@@ -53,7 +53,7 @@ $ cd awesome-project
## Eine virtuelle Umgebung erstellen { #create-a-virtual-environment }
-Wenn Sie zum **ersten Mal** an einem Python-Projekt arbeiten, erstellen Sie eine virtuelle Umgebung **innerhalb Ihres Projekts**.
+Wenn Sie zum **ersten Mal** an einem Python-Projekt arbeiten, erstellen Sie eine virtuelle Umgebung **innerhalb Ihres Projekts**.
/// tip | Tipp
@@ -166,7 +166,7 @@ $ source .venv/Scripts/activate
Jedes Mal, wenn Sie ein **neues Paket** in dieser Umgebung installieren, aktivieren Sie die Umgebung erneut.
-So stellen Sie sicher, dass, wenn Sie ein **Terminalprogramm (CLI)** verwenden, das durch dieses Paket installiert wurde, Sie das aus Ihrer virtuellen Umgebung verwenden und nicht eines, das global installiert ist, wahrscheinlich mit einer anderen Version als der, die Sie benötigen.
+So stellen Sie sicher, dass, wenn Sie ein **Terminalprogramm (CLI)** verwenden, das durch dieses Paket installiert wurde, Sie das aus Ihrer virtuellen Umgebung verwenden und nicht eines, das global installiert ist, wahrscheinlich mit einer anderen Version als der, die Sie benötigen.
///
@@ -639,7 +639,7 @@ $ source .venv/Scripts/activate
Dieser Befehl erstellt oder ändert einige [Umgebungsvariablen](environment-variables.md){.internal-link target=_blank}, die für die nächsten Befehle verfügbar sein werden.
-Eine dieser Variablen ist die `PATH`-Variable.
+Eine dieser Variablen ist die `PATH`-Umgebungsvariable.
/// tip | Tipp
@@ -649,7 +649,7 @@ Sie können mehr über die `PATH`-Umgebungsvariable im Abschnitt [Umgebungsvaria
Das Aktivieren einer virtuellen Umgebung fügt deren Pfad `.venv/bin` (auf Linux und macOS) oder `.venv\Scripts` (auf Windows) zur `PATH`-Umgebungsvariable hinzu.
-Angenommen, die `PATH`-Variable sah vor dem Aktivieren der Umgebung so aus:
+Angenommen, die `PATH`-Umgebungsvariable sah vor dem Aktivieren der Umgebung so aus:
//// tab | Linux, macOS
@@ -678,7 +678,7 @@ Das bedeutet, dass das System nach Programmen sucht in:
////
-Nach dem Aktivieren der virtuellen Umgebung würde die `PATH`-Variable folgendermaßen aussehen:
+Nach dem Aktivieren der virtuellen Umgebung würde die `PATH`-Umgebungsvariable folgendermaßen aussehen:
//// tab | Linux, macOS
@@ -728,7 +728,7 @@ finden und dieses verwenden.
////
-Ein wichtiger Punkt ist, dass es den Pfad der virtuellen Umgebung am **Anfang** der `PATH`-Variable platziert. Das System wird es **vor** allen anderen verfügbaren Pythons finden. Auf diese Weise, wenn Sie `python` ausführen, wird das Python **aus der virtuellen Umgebung** verwendet anstelle eines anderen `python` (zum Beispiel, einem `python` aus einer globalen Umgebung).
+Ein wichtiger Punkt ist, dass es den Pfad der virtuellen Umgebung am **Anfang** der `PATH`-Umgebungsvariable platziert. Das System wird es **vor** allen anderen verfügbaren Pythons finden. Auf diese Weise, wenn Sie `python` ausführen, wird das Python **aus der virtuellen Umgebung** verwendet anstelle eines anderen `python` (zum Beispiel, einem `python` aus einer globalen Umgebung).
Das Aktivieren einer virtuellen Umgebung ändert auch ein paar andere Dinge, aber dies ist eines der wichtigsten Dinge, die es tut.
From 417990fcb7d933a87117878e131056e76edf969c Mon Sep 17 00:00:00 2001
From: "github-actions[bot]" lt
+* XWT
+* PSGI
+
+### L’abbr donne une expression complète et une explication { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | Info
+
+Les attributs « title » des éléments « abbr » sont traduits en suivant des consignes spécifiques.
+
+Les traductions peuvent ajouter leurs propres éléments « abbr » que le LLM ne doit pas supprimer. Par exemple pour expliquer des mots anglais.
+
+Voir la section `### HTML abbr elements` dans l’invite générale dans `scripts/translate.py`.
+
+////
+
+## Éléments HTML « dfn » { #html-dfn-elements }
+
+* grappe
+* Apprentissage profond
+
+## Titres { #headings }
+
+//// tab | Test
+
+### Créer une application Web - un tutoriel { #develop-a-webapp-a-tutorial }
+
+Bonjour.
+
+### Annotations de type et indications de type { #type-hints-and-annotations }
+
+Rebonjour.
+
+### Superclasses et sous-classes { #super-and-subclasses }
+
+Rebonjour.
+
+////
+
+//// tab | Info
+
+La seule règle stricte pour les titres est que le LLM laisse la partie hachage entre accolades inchangée, ce qui garantit que les liens ne se rompent pas.
+
+Voir la section `### Headings` dans l’invite générale dans `scripts/translate.py`.
+
+Pour certaines consignes spécifiques à la langue, voir par exemple la section `### Headings` dans `docs/de/llm-prompt.md`.
+
+////
+
+## Termes utilisés dans les documents { #terms-used-in-the-docs }
+
+//// tab | Test
+
+* vous
+* votre
+
+* p. ex.
+* etc.
+
+* `foo` en tant que `int`
+* `bar` en tant que `str`
+* `baz` en tant que `list`
+
+* le Tutoriel - Guide utilisateur
+* le Guide utilisateur avancé
+* la documentation SQLModel
+* la documentation de l’API
+* la documentation automatique
+
+* Data Science
+* Apprentissage profond
+* Apprentissage automatique
+* Injection de dépendances
+* authentification HTTP Basic
+* HTTP Digest
+* format ISO
+* la norme JSON Schema
+* le schéma JSON
+* la définition de schéma
+* Flux Password
+* Mobile
+
+* déprécié
+* conçu
+* invalide
+* à la volée
+* standard
+* par défaut
+* sensible à la casse
+* insensible à la casse
+
+* servir l’application
+* servir la page
+
+* l’app
+* l’application
+
+* la requête
+* la réponse
+* la réponse d’erreur
+
+* le chemin d’accès
+* le décorateur de chemin d’accès
+* la fonction de chemin d’accès
+
+* le corps
+* le corps de la requête
+* le corps de la réponse
+* le corps JSON
+* le corps de formulaire
+* le corps de fichier
+* le corps de la fonction
+
+* le paramètre
+* le paramètre de corps
+* le paramètre de chemin
+* le paramètre de requête
+* le paramètre de cookie
+* le paramètre d’en-tête
+* le paramètre de formulaire
+* le paramètre de fonction
+
+* l’événement
+* l’événement de démarrage
+* le démarrage du serveur
+* l’événement d’arrêt
+* l’événement de cycle de vie
+
+* le gestionnaire
+* le gestionnaire d’événements
+* le gestionnaire d’exceptions
+* gérer
+
+* le modèle
+* le modèle Pydantic
+* le modèle de données
+* le modèle de base de données
+* le modèle de formulaire
+* l’objet modèle
+
+* la classe
+* la classe de base
+* la classe parente
+* la sous-classe
+* la classe enfant
+* la classe sœur
+* la méthode de classe
+
+* l’en-tête
+* les en-têtes
+* l’en-tête d’autorisation
+* l’en-tête `Authorization`
+* l’en-tête transféré
+
+* le système d’injection de dépendances
+* la dépendance
+* l’élément dépendable
+* le dépendant
+
+* lié aux E/S
+* lié au processeur
+* concurrence
+* parallélisme
+* multi-traitement
+
+* la variable d’env
+* la variable d’environnement
+* le `PATH`
+* la variable `PATH`
+
+* l’authentification
+* le fournisseur d’authentification
+* l’autorisation
+* le formulaire d’autorisation
+* le fournisseur d’autorisation
+* l’utilisateur s’authentifie
+* le système authentifie l’utilisateur
+
+* la CLI
+* l’interface en ligne de commande
+
+* le serveur
+* le client
+
+* le fournisseur cloud
+* le service cloud
+
+* le développement
+* les étapes de développement
+
+* le dict
+* le dictionnaire
+* l’énumération
+* l’enum
+* le membre d’enum
+
+* l’encodeur
+* le décodeur
+* encoder
+* décoder
+
+* l’exception
+* lever
+
+* l’expression
+* l’instruction
+
+* le frontend
+* le backend
+
+* la discussion GitHub
+* le ticket GitHub
+
+* la performance
+* l’optimisation des performances
+
+* le type de retour
+* la valeur de retour
+
+* la sécurité
+* le schéma de sécurité
+
+* la tâche
+* la tâche d’arrière-plan
+* la fonction de tâche
+
+* le template
+* le moteur de templates
+
+* l’annotation de type
+* l’annotation de type
+
+* le worker du serveur
+* le worker Uvicorn
+* le Worker Gunicorn
+* le processus worker
+* la classe de worker
+* la charge de travail
+
+* le déploiement
+* déployer
+
+* le SDK
+* le kit de développement logiciel
+
+* le `APIRouter`
+* le `requirements.txt`
+* le jeton Bearer
+* le changement majeur incompatible
+* le bogue
+* le bouton
+* l’appelable
+* le code
+* le commit
+* le gestionnaire de contexte
+* la coroutine
+* la session de base de données
+* le disque
+* le domaine
+* le moteur
+* le faux X
+* la méthode HTTP GET
+* l’élément
+* la bibliothèque
+* le cycle de vie
+* le verrou
+* le middleware
+* l’application mobile
+* le module
+* le montage
+* le réseau
+* l’origine
+* la surcharge
+* le payload
+* le processeur
+* la propriété
+* le proxy
+* la pull request
+* la requête
+* la RAM
+* la machine distante
+* le code d’état
+* la chaîne
+* l’étiquette
+* le framework Web
+* le joker
+* retourner
+* valider
+
+////
+
+//// tab | Info
+
+Il s’agit d’une liste non exhaustive et non normative de termes (principalement) techniques présents dans les documents. Elle peut aider le concepteur de l’invite à déterminer pour quels termes le LLM a besoin d’un coup de main. Par exemple, lorsqu’il continue de remplacer une bonne traduction par une traduction sous-optimale. Ou lorsqu’il a des difficultés à conjuguer/décliner un terme dans votre langue.
+
+Voir par exemple la section `### List of English terms and their preferred German translations` dans `docs/de/llm-prompt.md`.
+
+////
diff --git a/docs/fr/docs/about/index.md b/docs/fr/docs/about/index.md
new file mode 100644
index 000000000..f6ec12a4f
--- /dev/null
+++ b/docs/fr/docs/about/index.md
@@ -0,0 +1,3 @@
+# À propos { #about }
+
+À propos de FastAPI, de sa conception, de ses sources d'inspiration et plus encore. 🤓
diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md
index dabcded52..a073dec69 100644
--- a/docs/fr/docs/advanced/additional-responses.md
+++ b/docs/fr/docs/advanced/additional-responses.md
@@ -8,7 +8,7 @@ Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin.
///
-Vous pouvez déclarer des réponses supplémentaires, avec des codes HTTP, des types de médias, des descriptions, etc.
+Vous pouvez déclarer des réponses supplémentaires, avec des codes d'état supplémentaires, des types de médias, des descriptions, etc.
Ces réponses supplémentaires seront incluses dans le schéma OpenAPI, elles apparaîtront donc également dans la documentation de l'API.
@@ -26,7 +26,7 @@ Chacun de ces `dict` de réponse peut avoir une clé `model`, contenant un modè
Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un modèle Pydantic `Message`, vous pouvez écrire :
-{* ../../docs_src/additional_responses/tutorial001_py39.py hl[18,22] *}
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
/// note | Remarque
@@ -203,7 +203,7 @@ Par exemple, vous pouvez déclarer une réponse avec un code HTTP `404` qui util
Et une réponse avec un code HTTP `200` qui utilise votre `response_model`, mais inclut un `example` personnalisé :
-{* ../../docs_src/additional_responses/tutorial003_py39.py hl[20:31] *}
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
Tout sera combiné et inclus dans votre OpenAPI, et affiché dans la documentation de l'API :
diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md
index b2befffa8..b9c8ab113 100644
--- a/docs/fr/docs/advanced/additional-status-codes.md
+++ b/docs/fr/docs/advanced/additional-status-codes.md
@@ -36,6 +36,6 @@ Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` s
## Documents OpenAPI et API { #openapi-and-api-docs }
-Si vous renvoyez directement des codes HTTP et des réponses supplémentaires, ils ne seront pas inclus dans le schéma OpenAPI (la documentation de l'API), car FastAPI n'a aucun moyen de savoir à l'avance ce que vous allez renvoyer.
+Si vous renvoyez directement des codes HTTP et des réponses supplémentaires, ils ne seront pas inclus dans le schéma OpenAPI (les documents de l'API), car FastAPI n'a aucun moyen de savoir à l'avance ce que vous allez renvoyer.
Mais vous pouvez documenter cela dans votre code, en utilisant : [Réponses supplémentaires](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/fr/docs/advanced/advanced-dependencies.md b/docs/fr/docs/advanced/advanced-dependencies.md
new file mode 100644
index 000000000..8afd58b48
--- /dev/null
+++ b/docs/fr/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# Dépendances avancées { #advanced-dependencies }
+
+## Dépendances paramétrées { #parameterized-dependencies }
+
+Toutes les dépendances que nous avons vues étaient des fonctions ou des classes fixes.
+
+Mais il peut y avoir des cas où vous souhaitez pouvoir définir des paramètres sur la dépendance, sans devoir déclarer de nombreuses fonctions ou classes différentes.
+
+Imaginons que nous voulions avoir une dépendance qui vérifie si le paramètre de requête `q` contient un contenu fixe.
+
+Mais nous voulons pouvoir paramétrer ce contenu fixe.
+
+## Une instance « callable » { #a-callable-instance }
+
+En Python, il existe un moyen de rendre une instance de classe « callable ».
+
+Pas la classe elle‑même (qui est déjà un callable), mais une instance de cette classe.
+
+Pour cela, nous déclarons une méthode `__call__` :
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+Dans ce cas, ce `__call__` est ce que **FastAPI** utilisera pour détecter des paramètres supplémentaires et des sous‑dépendances, et c’est ce qui sera appelé pour transmettre ensuite une valeur au paramètre dans votre *fonction de chemin d'accès*.
+
+## Paramétrer l'instance { #parameterize-the-instance }
+
+Et maintenant, nous pouvons utiliser `__init__` pour déclarer les paramètres de l’instance, que nous utiliserons pour « paramétrer » la dépendance :
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+Dans ce cas, **FastAPI** n’accèdera pas à `__init__` et ne s’en souciera pas ; nous l’utiliserons directement dans notre code.
+
+## Créer une instance { #create-an-instance }
+
+Nous pouvons créer une instance de cette classe avec :
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+Et de cette façon, nous pouvons « paramétrer » notre dépendance, qui contient maintenant « bar », en tant qu’attribut `checker.fixed_content`.
+
+## Utiliser l'instance comme dépendance { #use-the-instance-as-a-dependency }
+
+Ensuite, nous pourrions utiliser ce `checker` dans un `Depends(checker)`, au lieu de `Depends(FixedContentQueryChecker)`, car la dépendance est l’instance, `checker`, et non la classe elle‑même.
+
+Et lors de la résolution de la dépendance, **FastAPI** appellera ce `checker` comme ceci :
+
+```Python
+checker(q="somequery")
+```
+
+... et passera ce que cela renvoie comme valeur de la dépendance à notre *fonction de chemin d'accès*, en tant que paramètre `fixed_content_included` :
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | Astuce
+
+Tout cela peut sembler artificiel. Et il n’est peut‑être pas encore très clair en quoi c’est utile.
+
+Ces exemples sont volontairement simples, mais ils montrent comment tout cela fonctionne.
+
+Dans les chapitres sur la sécurité, il existe des fonctions utilitaires implémentées de la même manière.
+
+Si vous avez compris tout cela, vous savez déjà comment ces outils utilitaires pour la sécurité fonctionnent en interne.
+
+///
+
+## Dépendances avec `yield`, `HTTPException`, `except` et tâches d'arrière‑plan { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | Alertes
+
+Vous n’avez très probablement pas besoin de ces détails techniques.
+
+Ces détails sont utiles principalement si vous aviez une application FastAPI antérieure à la version 0.121.0 et que vous rencontrez des problèmes avec des dépendances utilisant `yield`.
+
+///
+
+Les dépendances avec `yield` ont évolué au fil du temps pour couvrir différents cas d’utilisation et corriger certains problèmes ; voici un résumé de ce qui a changé.
+
+### Dépendances avec `yield` et `scope` { #dependencies-with-yield-and-scope }
+
+Dans la version 0.121.0, **FastAPI** a ajouté la prise en charge de `Depends(scope="function")` pour les dépendances avec `yield`.
+
+Avec `Depends(scope="function")`, le code d’arrêt après `yield` s’exécute immédiatement après la fin de la *fonction de chemin d'accès*, avant que la réponse ne soit renvoyée au client.
+
+Et lorsque vous utilisez `Depends(scope="request")` (valeur par défaut), le code d’arrêt après `yield` s’exécute après l’envoi de la réponse.
+
+Vous pouvez en lire davantage dans les documents pour [Dépendances avec `yield` - Sortie anticipée et `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope).
+
+### Dépendances avec `yield` et `StreamingResponse`, Détails techniques { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+Avant FastAPI 0.118.0, si vous utilisiez une dépendance avec `yield`, elle exécutait le code d’arrêt après que la *fonction de chemin d'accès* a retourné, mais juste avant d’envoyer la réponse.
+
+L’objectif était d’éviter de conserver des ressources plus longtemps que nécessaire pendant que la réponse transitait sur le réseau.
+
+Ce changement impliquait aussi que si vous retourniez une `StreamingResponse`, le code d’arrêt de la dépendance avec `yield` aurait déjà été exécuté.
+
+Par exemple, si vous aviez une session de base de données dans une dépendance avec `yield`, la `StreamingResponse` ne pourrait pas utiliser cette session pendant le streaming des données, car la session aurait déjà été fermée dans le code d’arrêt après `yield`.
+
+Ce comportement a été annulé en 0.118.0, afin que le code d’arrêt après `yield` s’exécute après l’envoi de la réponse.
+
+/// info
+
+Comme vous le verrez ci‑dessous, c’est très similaire au comportement avant la version 0.106.0, mais avec plusieurs améliorations et corrections de bogues pour des cas limites.
+
+///
+
+#### Cas d’utilisation avec sortie anticipée du code { #use-cases-with-early-exit-code }
+
+Il existe certains cas d’utilisation avec des conditions spécifiques qui pourraient bénéficier de l’ancien comportement, où le code d’arrêt des dépendances avec `yield` s’exécute avant l’envoi de la réponse.
+
+Par exemple, imaginez que vous ayez du code qui utilise une session de base de données dans une dépendance avec `yield` uniquement pour vérifier un utilisateur, mais que la session de base de données ne soit plus jamais utilisée dans la *fonction de chemin d'accès*, seulement dans la dépendance, et que la réponse mette longtemps à être envoyée, comme une `StreamingResponse` qui envoie les données lentement mais qui, pour une raison quelconque, n’utilise pas la base de données.
+
+Dans ce cas, la session de base de données serait conservée jusqu’à la fin de l’envoi de la réponse, mais si vous ne l’utilisez pas, il ne serait pas nécessaire de la conserver.
+
+Voici à quoi cela pourrait ressembler :
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+Le code d’arrêt, la fermeture automatique de la `Session` dans :
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+... serait exécuté après que la réponse a fini d’envoyer les données lentes :
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+Mais comme `generate_stream()` n’utilise pas la session de base de données, il n’est pas vraiment nécessaire de garder la session ouverte pendant l’envoi de la réponse.
+
+Si vous avez ce cas d’utilisation spécifique avec SQLModel (ou SQLAlchemy), vous pouvez fermer explicitement la session dès que vous n’en avez plus besoin :
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+De cette manière, la session libérera la connexion à la base de données, afin que d’autres requêtes puissent l’utiliser.
+
+Si vous avez un autre cas d’utilisation qui nécessite une sortie anticipée depuis une dépendance avec `yield`, veuillez créer une Question de discussion GitHub avec votre cas spécifique et pourquoi vous bénéficieriez d’une fermeture anticipée pour les dépendances avec `yield`.
+
+S’il existe des cas d’utilisation convaincants pour une fermeture anticipée dans les dépendances avec `yield`, j’envisagerai d’ajouter une nouvelle façon d’y opter.
+
+### Dépendances avec `yield` et `except`, Détails techniques { #dependencies-with-yield-and-except-technical-details }
+
+Avant FastAPI 0.110.0, si vous utilisiez une dépendance avec `yield`, puis capturiez une exception avec `except` dans cette dépendance, et que vous ne relanciez pas l’exception, l’exception était automatiquement levée/transmise à tout gestionnaire d’exceptions ou au gestionnaire d’erreur interne du serveur.
+
+Cela a été modifié dans la version 0.110.0 pour corriger une consommation de mémoire non gérée due aux exceptions transmises sans gestionnaire (erreurs internes du serveur), et pour rendre le comportement cohérent avec celui du code Python classique.
+
+### Tâches d'arrière‑plan et dépendances avec `yield`, Détails techniques { #background-tasks-and-dependencies-with-yield-technical-details }
+
+Avant FastAPI 0.106.0, lever des exceptions après `yield` n’était pas possible, le code d’arrêt dans les dépendances avec `yield` s’exécutait après l’envoi de la réponse, donc les [Gestionnaires d'exceptions](../tutorial/handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} avaient déjà été exécutés.
+
+Cela avait été conçu ainsi principalement pour permettre d’utiliser les mêmes objets « générés par yield » par les dépendances à l’intérieur de tâches d’arrière‑plan, car le code d’arrêt s’exécutait après la fin des tâches d’arrière‑plan.
+
+Cela a été modifié dans FastAPI 0.106.0 afin de ne pas conserver des ressources pendant l’attente de la transmission de la réponse sur le réseau.
+
+/// tip | Astuce
+
+De plus, une tâche d’arrière‑plan est normalement un ensemble de logique indépendant qui devrait être géré séparément, avec ses propres ressources (par ex. sa propre connexion à la base de données).
+
+Ainsi, vous aurez probablement un code plus propre.
+
+///
+
+Si vous comptiez sur ce comportement, vous devez désormais créer les ressources pour les tâches d’arrière‑plan à l’intérieur de la tâche elle‑même, et n’utiliser en interne que des données qui ne dépendent pas des ressources des dépendances avec `yield`.
+
+Par exemple, au lieu d’utiliser la même session de base de données, vous créeriez une nouvelle session de base de données à l’intérieur de la tâche d’arrière‑plan, et vous obtiendriez les objets depuis la base de données en utilisant cette nouvelle session. Puis, au lieu de passer l’objet obtenu depuis la base de données en paramètre à la fonction de tâche d’arrière‑plan, vous passeriez l’identifiant (ID) de cet objet et vous obtiendriez à nouveau l’objet à l’intérieur de la fonction de la tâche d’arrière‑plan.
diff --git a/docs/fr/docs/advanced/advanced-python-types.md b/docs/fr/docs/advanced/advanced-python-types.md
new file mode 100644
index 000000000..3e2d9453b
--- /dev/null
+++ b/docs/fr/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# Types Python avancés { #advanced-python-types }
+
+Voici quelques idées supplémentaires qui peuvent être utiles lorsque vous travaillez avec les types Python.
+
+## Utiliser `Union` ou `Optional` { #using-union-or-optional }
+
+Si votre code ne peut pas utiliser `|` pour une raison quelconque, par exemple si ce n'est pas dans une annotation de type mais dans quelque chose comme `response_model=`, au lieu d'utiliser la barre verticale (`|`) vous pouvez utiliser `Union` de `typing`.
+
+Par exemple, vous pourriez déclarer que quelque chose peut être un `str` ou `None` :
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing` propose également un raccourci pour déclarer que quelque chose peut être `None`, avec `Optional`.
+
+Voici un conseil issu de mon point de vue très subjectif :
+
+- 🚨 Évitez d'utiliser `Optional[SomeType]`
+- À la place ✨ **utilisez `Union[SomeType, None]`** ✨.
+
+Les deux sont équivalents et, en interne, identiques, mais je recommande `Union` plutôt que `Optional` parce que le mot « optional » semble impliquer que la valeur est facultative, alors qu'il signifie en réalité « elle peut être `None` », même si elle n'est pas facultative et reste requise.
+
+Je pense que `Union[SomeType, None]` est plus explicite quant à sa signification.
+
+Il ne s'agit que des mots et des noms. Mais ces mots peuvent influencer la manière dont vous et vos coéquipiers pensez au code.
+
+À titre d'exemple, prenons cette fonction :
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+Le paramètre `name` est défini comme `Optional[str]`, mais il n'est pas facultatif, vous ne pouvez pas appeler la fonction sans le paramètre :
+
+```Python
+say_hi() # Oh non, cela lève une erreur ! 😱
+```
+
+Le paramètre `name` est toujours requis (pas facultatif) car il n'a pas de valeur par défaut. En revanche, `name` accepte `None` comme valeur :
+
+```Python
+say_hi(name=None) # Ceci fonctionne, None est valide 🎉
+```
+
+La bonne nouvelle, c'est que, dans la plupart des cas, vous pourrez simplement utiliser `|` pour définir des unions de types :
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+Ainsi, normalement, vous n'avez pas à vous préoccuper de noms comme `Optional` et `Union`. 😎
diff --git a/docs/fr/docs/advanced/async-tests.md b/docs/fr/docs/advanced/async-tests.md
new file mode 100644
index 000000000..f9cea0ad1
--- /dev/null
+++ b/docs/fr/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# Tests asynchrones { #async-tests }
+
+Vous avez déjà vu comment tester vos applications **FastAPI** en utilisant le `TestClient` fourni. Jusqu'à présent, vous n'avez vu que comment écrire des tests synchrones, sans utiliser de fonctions `async`.
+
+Pouvoir utiliser des fonctions asynchrones dans vos tests peut être utile, par exemple lorsque vous interrogez votre base de données de manière asynchrone. Imaginez que vous vouliez tester l'envoi de requêtes à votre application FastAPI puis vérifier que votre backend a bien écrit les bonnes données dans la base, tout en utilisant une bibliothèque de base de données asynchrone.
+
+Voyons comment procéder.
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+Si nous voulons appeler des fonctions asynchrones dans nos tests, nos fonctions de test doivent être asynchrones. AnyIO fournit un plug-in pratique qui nous permet d'indiquer que certaines fonctions de test doivent être appelées de manière asynchrone.
+
+## HTTPX { #httpx }
+
+Même si votre application **FastAPI** utilise des fonctions `def` normales au lieu de `async def`, c'est toujours une application `async` en interne.
+
+Le `TestClient` fait un peu de magie pour appeler l'application FastAPI asynchrone depuis vos fonctions de test `def` normales, en utilisant pytest standard. Mais cette magie ne fonctionne plus lorsque nous l'utilisons dans des fonctions asynchrones. En exécutant nos tests de manière asynchrone, nous ne pouvons plus utiliser le `TestClient` dans nos fonctions de test.
+
+Le `TestClient` est basé sur HTTPX et, heureusement, nous pouvons l'utiliser directement pour tester l'API.
+
+## Exemple { #example }
+
+Pour un exemple simple, considérons une structure de fichiers similaire à celle décrite dans [Applications plus grandes](../tutorial/bigger-applications.md){.internal-link target=_blank} et [Tests](../tutorial/testing.md){.internal-link target=_blank} :
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+Le fichier `main.py` contiendrait :
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+Le fichier `test_main.py` contiendrait les tests pour `main.py`, il pourrait maintenant ressembler à ceci :
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## Exécuter { #run-it }
+
+Vous pouvez lancer vos tests comme d'habitude via :
+
+
Host: mysuperapp.com
Path: /items
+
+ Note over Proxy: Proxy adds forwarded headers
+
+ Proxy->>Server: HTTP Request
X-Forwarded-For: [client IP]
X-Forwarded-Proto: https
X-Forwarded-Host: mysuperapp.com
Path: /items
+
+ Note over Server: Server interprets headers
(if --forwarded-allow-ips is set)
+
+ Server->>Proxy: HTTP Response
with correct HTTPS URLs
+
+ Proxy->>Client: HTTPS Response
+```
+
+Le **proxy** intercepte la requête client d'origine et ajoute les en-têtes spéciaux *forwarded* (`X-Forwarded-*`) avant de transmettre la requête au **serveur d'application**.
+
+Ces en‑têtes conservent des informations sur la requête d'origine qui seraient autrement perdues :
+
+* **X-Forwarded-For** : l'adresse IP du client d'origine
+* **X-Forwarded-Proto** : le protocole d'origine (`https`)
+* **X-Forwarded-Host** : l'hôte d'origine (`mysuperapp.com`)
+
+Lorsque **FastAPI CLI** est configurée avec `--forwarded-allow-ips`, elle fait confiance à ces en‑têtes et les utilise, par exemple pour générer les bonnes URL dans les redirections.
+
+## Proxy avec un préfixe de chemin supprimé { #proxy-with-a-stripped-path-prefix }
+
+Vous pouvez avoir un proxy qui ajoute un préfixe de chemin à votre application.
+
+Dans ces cas, vous pouvez utiliser `root_path` pour configurer votre application.
+
+Le `root_path` est un mécanisme fourni par la spécification ASGI (sur laquelle FastAPI est construit, via Starlette).
+
+Le `root_path` est utilisé pour gérer ces cas spécifiques.
+
+Et il est également utilisé en interne lors du montage de sous‑applications.
+
+Avoir un proxy avec un préfixe de chemin supprimé, dans ce cas, signifie que vous pourriez déclarer un chemin à `/app` dans votre code, mais ensuite, vous ajoutez une couche au‑dessus (le proxy) qui place votre application **FastAPI** sous un chemin comme `/api/v1`.
+
+Dans ce cas, le chemin original `/app` serait en réalité servi à `/api/v1/app`.
+
+Même si tout votre code est écrit en supposant qu'il n'y a que `/app`.
+
+{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[6] *}
+
+Et le proxy **« stripping »** le **préfixe de chemin** à la volée avant de transmettre la requête au serveur de l'application (probablement Uvicorn via FastAPI CLI), en gardant votre application convaincue qu'elle est servie à `/app`, afin que vous n'ayez pas à mettre à jour tout votre code pour inclure le préfixe `/api/v1`.
+
+Jusqu'ici, tout fonctionnerait normalement.
+
+Mais ensuite, lorsque vous ouvrez l'interface de documentation intégrée (le frontend), elle s'attendra à obtenir le schéma OpenAPI à `/openapi.json`, au lieu de `/api/v1/openapi.json`.
+
+Ainsi, le frontend (qui s'exécute dans le navigateur) essaiera d'atteindre `/openapi.json` et ne pourra pas obtenir le schéma OpenAPI.
+
+Parce que nous avons un proxy avec un préfixe de chemin `/api/v1` pour notre application, le frontend doit récupérer le schéma OpenAPI à `/api/v1/openapi.json`.
+
+```mermaid
+graph LR
+
+browser("Browser")
+proxy["Proxy on http://0.0.0.0:9999/api/v1/app"]
+server["Server on http://127.0.0.1:8000/app"]
+
+browser --> proxy
+proxy --> server
+```
+
+/// tip | Astuce
+
+L'IP `0.0.0.0` est couramment utilisée pour signifier que le programme écoute sur toutes les IP disponibles de cette machine/serveur.
+
+///
+
+L'interface de documents doit également indiquer dans le schéma OpenAPI que ce `server` d'API se trouve à `/api/v1` (derrière le proxy). Par exemple :
+
+```JSON hl_lines="4-8"
+{
+ "openapi": "3.1.0",
+ // Plus d'éléments ici
+ "servers": [
+ {
+ "url": "/api/v1"
+ }
+ ],
+ "paths": {
+ // Plus d'éléments ici
+ }
+}
+```
+
+Dans cet exemple, le « Proxy » pourrait être quelque chose comme **Traefik**. Et le serveur serait quelque chose comme FastAPI CLI avec **Uvicorn**, exécutant votre application FastAPI.
+
+### Fournir le `root_path` { #providing-the-root-path }
+
+Pour y parvenir, vous pouvez utiliser l'option de ligne de commande `--root-path` comme suit :
+
+
+
+Mais si nous accédons à l'interface de documents à l'URL « officielle » en utilisant le proxy avec le port `9999`, à `/api/v1/docs`, cela fonctionne correctement ! 🎉
+
+Vous pouvez le vérifier sur http://127.0.0.1:9999/api/v1/docs :
+
+
+
+Exactement comme nous le voulions. ✔️
+
+C'est parce que FastAPI utilise ce `root_path` pour créer le `server` par défaut dans OpenAPI avec l'URL fournie par `root_path`.
+
+## Serveurs supplémentaires { #additional-servers }
+
+/// warning | Alertes
+
+Ceci est un cas d'utilisation plus avancé. N'hésitez pas à l'ignorer.
+
+///
+
+Par défaut, **FastAPI** créera un `server` dans le schéma OpenAPI avec l'URL correspondant au `root_path`.
+
+Mais vous pouvez aussi fournir d'autres `servers` alternatifs, par exemple si vous voulez que la même interface de documents interagisse avec un environnement de staging et un environnement de production.
+
+Si vous passez une liste personnalisée de `servers` et qu'il y a un `root_path` (parce que votre API vit derrière un proxy), **FastAPI** insérera un « server » avec ce `root_path` au début de la liste.
+
+Par exemple :
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+Générera un schéma OpenAPI comme :
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // Plus d'éléments ici
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // Plus d'éléments ici
+ }
+}
+```
+
+/// tip | Astuce
+
+Remarquez le serveur généré automatiquement avec une valeur `url` de `/api/v1`, reprise depuis le `root_path`.
+
+///
+
+Dans l'interface de documents sur http://127.0.0.1:9999/api/v1/docs, cela ressemblera à ceci :
+
+
+
+/// tip | Astuce
+
+L'interface de documents interagit avec le serveur que vous sélectionnez.
+
+///
+
+/// note | Détails techniques
+
+La propriété `servers` dans la spécification OpenAPI est facultative.
+
+Si vous ne spécifiez pas le paramètre `servers` et que `root_path` est égal à `/`, la propriété `servers` dans le schéma OpenAPI généré sera entièrement omise par défaut, ce qui équivaut à un seul serveur avec une valeur `url` de `/`.
+
+///
+
+### Désactiver le serveur automatique issu de `root_path` { #disable-automatic-server-from-root-path }
+
+Si vous ne voulez pas que **FastAPI** inclue un serveur automatique utilisant le `root_path`, vous pouvez utiliser le paramètre `root_path_in_servers=False` :
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+et il ne l'inclura alors pas dans le schéma OpenAPI.
+
+## Monter une sous-application { #mounting-a-sub-application }
+
+Si vous avez besoin de monter une sous‑application (comme décrit dans [Sous‑applications - montages](sub-applications.md){.internal-link target=_blank}) tout en utilisant un proxy avec `root_path`, vous pouvez le faire normalement, comme vous vous y attendez.
+
+FastAPI utilisera intelligemment le `root_path` en interne, donc cela fonctionnera simplement. ✨
diff --git a/docs/fr/docs/advanced/custom-response.md b/docs/fr/docs/advanced/custom-response.md
new file mode 100644
index 000000000..7eab5b53f
--- /dev/null
+++ b/docs/fr/docs/advanced/custom-response.md
@@ -0,0 +1,312 @@
+# Réponse personnalisée - HTML, flux, fichier, autres { #custom-response-html-stream-file-others }
+
+Par défaut, **FastAPI** renverra les réponses en utilisant `JSONResponse`.
+
+Vous pouvez le remplacer en renvoyant directement une `Response` comme expliqué dans [Renvoyer directement une Response](response-directly.md){.internal-link target=_blank}.
+
+Mais si vous renvoyez directement une `Response` (ou n'importe quelle sous-classe, comme `JSONResponse`), les données ne seront pas automatiquement converties (même si vous déclarez un `response_model`), et la documentation ne sera pas générée automatiquement (par exemple, l'inclusion du « media type » dans l'en-tête HTTP `Content-Type` comme partie de l'OpenAPI généré).
+
+Vous pouvez aussi déclarer la `Response` que vous voulez utiliser (par ex. toute sous-classe de `Response`), dans le décorateur de chemin d'accès en utilisant le paramètre `response_class`.
+
+Le contenu que vous renvoyez depuis votre fonction de chemin d'accès sera placé à l'intérieur de cette `Response`.
+
+Et si cette `Response` a un « media type » JSON (`application/json`), comme c'est le cas avec `JSONResponse` et `UJSONResponse`, les données que vous renvoyez seront automatiquement converties (et filtrées) avec tout `response_model` Pydantic que vous avez déclaré dans le décorateur de chemin d'accès.
+
+/// note | Remarque
+
+Si vous utilisez une classe de réponse sans « media type », FastAPI s'attendra à ce que votre réponse n'ait pas de contenu ; il ne documentera donc pas le format de la réponse dans les documents OpenAPI générés.
+
+///
+
+## Utiliser `ORJSONResponse` { #use-orjsonresponse }
+
+Par exemple, si vous cherchez à maximiser la performance, vous pouvez installer et utiliser `orjson` et définir la réponse sur `ORJSONResponse`.
+
+Importez la classe (sous-classe) `Response` que vous voulez utiliser et déclarez-la dans le décorateur de chemin d'accès.
+
+Pour de grandes réponses, renvoyer directement une `Response` est bien plus rapide que de renvoyer un dictionnaire.
+
+Cela vient du fait que, par défaut, FastAPI inspectera chaque élément et s'assurera qu'il est sérialisable en JSON, en utilisant le même [Encodeur compatible JSON](../tutorial/encoder.md){.internal-link target=_blank} expliqué dans le didacticiel. C'est ce qui vous permet de renvoyer des objets arbitraires, par exemple des modèles de base de données.
+
+Mais si vous êtes certain que le contenu que vous renvoyez est sérialisable en JSON, vous pouvez le passer directement à la classe de réponse et éviter le surcoût supplémentaire qu'aurait FastAPI en faisant passer votre contenu de retour par le `jsonable_encoder` avant de le transmettre à la classe de réponse.
+
+{* ../../docs_src/custom_response/tutorial001b_py310.py hl[2,7] *}
+
+/// info
+
+Le paramètre `response_class` sera aussi utilisé pour définir le « media type » de la réponse.
+
+Dans ce cas, l'en-tête HTTP `Content-Type` sera défini à `application/json`.
+
+Et il sera documenté comme tel dans OpenAPI.
+
+///
+
+/// tip | Astuce
+
+`ORJSONResponse` est disponible uniquement dans FastAPI, pas dans Starlette.
+
+///
+
+## Réponse HTML { #html-response }
+
+Pour renvoyer une réponse avec du HTML directement depuis **FastAPI**, utilisez `HTMLResponse`.
+
+- Importez `HTMLResponse`.
+- Passez `HTMLResponse` comme paramètre `response_class` de votre décorateur de chemin d'accès.
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info
+
+Le paramètre `response_class` sera aussi utilisé pour définir le « media type » de la réponse.
+
+Dans ce cas, l'en-tête HTTP `Content-Type` sera défini à `text/html`.
+
+Et il sera documenté comme tel dans OpenAPI.
+
+///
+
+### Renvoyer une `Response` { #return-a-response }
+
+Comme vu dans [Renvoyer directement une Response](response-directly.md){.internal-link target=_blank}, vous pouvez aussi remplacer la réponse directement dans votre chemin d'accès, en la renvoyant.
+
+Le même exemple ci-dessus, renvoyant une `HTMLResponse`, pourrait ressembler à :
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning | Alertes
+
+Une `Response` renvoyée directement par votre fonction de chemin d'accès ne sera pas documentée dans OpenAPI (par exemple, le `Content-Type` ne sera pas documenté) et ne sera pas visible dans les documents interactifs automatiques.
+
+///
+
+/// info
+
+Bien sûr, l'en-tête `Content-Type` réel, le code d'état, etc., proviendront de l'objet `Response` que vous avez renvoyé.
+
+///
+
+### Documenter dans OpenAPI et remplacer `Response` { #document-in-openapi-and-override-response }
+
+Si vous voulez remplacer la réponse depuis l'intérieur de la fonction mais en même temps documenter le « media type » dans OpenAPI, vous pouvez utiliser le paramètre `response_class` ET renvoyer un objet `Response`.
+
+`response_class` sera alors utilisé uniquement pour documenter l'opération de chemin d'accès OpenAPI, mais votre `Response` sera utilisée telle quelle.
+
+#### Renvoyer directement une `HTMLResponse` { #return-an-htmlresponse-directly }
+
+Par exemple, cela pourrait être quelque chose comme :
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+Dans cet exemple, la fonction `generate_html_response()` génère déjà et renvoie une `Response` au lieu de renvoyer le HTML dans une `str`.
+
+En renvoyant le résultat de l'appel à `generate_html_response()`, vous renvoyez déjà une `Response` qui remplacera le comportement par défaut de **FastAPI**.
+
+Mais comme vous avez aussi passé `HTMLResponse` dans `response_class`, **FastAPI** saura comment la documenter dans OpenAPI et les documents interactifs comme HTML avec `text/html` :
+
+
+
+## Réponses disponibles { #available-responses }
+
+Voici certaines des réponses disponibles.
+
+Gardez à l'esprit que vous pouvez utiliser `Response` pour renvoyer autre chose, ou même créer une sous-classe personnalisée.
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette.responses import HTMLResponse`.
+
+**FastAPI** fournit les mêmes `starlette.responses` sous `fastapi.responses` simplement pour votre confort de développement. Mais la plupart des réponses disponibles viennent directement de Starlette.
+
+///
+
+### `Response` { #response }
+
+La classe principale `Response`, toutes les autres réponses en héritent.
+
+Vous pouvez la renvoyer directement.
+
+Elle accepte les paramètres suivants :
+
+- `content` - Une `str` ou des `bytes`.
+- `status_code` - Un code d'état HTTP de type `int`.
+- `headers` - Un `dict` de chaînes.
+- `media_type` - Une `str` donnant le media type. Par exemple « text/html ».
+
+FastAPI (en fait Starlette) inclura automatiquement un en-tête Content-Length. Il inclura aussi un en-tête Content-Type, basé sur `media_type` et en ajoutant un charset pour les types textuels.
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+Prend du texte ou des octets et renvoie une réponse HTML, comme vous l'avez lu ci-dessus.
+
+### `PlainTextResponse` { #plaintextresponse }
+
+Prend du texte ou des octets et renvoie une réponse en texte brut.
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+Prend des données et renvoie une réponse encodée en `application/json`.
+
+C'est la réponse par défaut utilisée dans **FastAPI**, comme vous l'avez lu ci-dessus.
+
+### `ORJSONResponse` { #orjsonresponse }
+
+Une réponse JSON alternative rapide utilisant `orjson`, comme vous l'avez lu ci-dessus.
+
+/// info
+
+Cela nécessite l'installation de `orjson`, par exemple avec `pip install orjson`.
+
+///
+
+### `UJSONResponse` { #ujsonresponse }
+
+Une réponse JSON alternative utilisant `ujson`.
+
+/// info
+
+Cela nécessite l'installation de `ujson`, par exemple avec `pip install ujson`.
+
+///
+
+/// warning | Alertes
+
+`ujson` est moins rigoureux que l'implémentation intégrée de Python dans sa gestion de certains cas limites.
+
+///
+
+{* ../../docs_src/custom_response/tutorial001_py310.py hl[2,7] *}
+
+/// tip | Astuce
+
+Il est possible que `ORJSONResponse` soit une alternative plus rapide.
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+Renvoie une redirection HTTP. Utilise par défaut un code d'état 307 (Temporary Redirect).
+
+Vous pouvez renvoyer directement une `RedirectResponse` :
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+Ou vous pouvez l'utiliser dans le paramètre `response_class` :
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+Si vous faites cela, vous pouvez alors renvoyer directement l'URL depuis votre fonction de chemin d'accès.
+
+Dans ce cas, le `status_code` utilisé sera celui par défaut pour `RedirectResponse`, c'est-à-dire `307`.
+
+---
+
+Vous pouvez aussi utiliser le paramètre `status_code` combiné avec le paramètre `response_class` :
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+Prend un générateur async ou un générateur/itérateur normal et diffuse le corps de la réponse.
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[2,14] *}
+
+#### Utiliser `StreamingResponse` avec des objets de type fichier { #using-streamingresponse-with-file-like-objects }
+
+Si vous avez un objet de type fichier (par ex. l'objet renvoyé par `open()`), vous pouvez créer une fonction génératrice pour itérer sur cet objet de type fichier.
+
+De cette façon, vous n'avez pas à tout lire en mémoire au préalable, et vous pouvez passer cette fonction génératrice à `StreamingResponse`, puis la renvoyer.
+
+Cela inclut de nombreuses bibliothèques pour interagir avec du stockage cloud, du traitement vidéo, et autres.
+
+{* ../../docs_src/custom_response/tutorial008_py310.py hl[2,10:12,14] *}
+
+1. C'est la fonction génératrice. C'est une « fonction génératrice » parce qu'elle contient des instructions `yield` à l'intérieur.
+2. En utilisant un bloc `with`, nous nous assurons que l'objet de type fichier est fermé après l'exécution de la fonction génératrice. Donc, après qu'elle a fini d'envoyer la réponse.
+3. Ce `yield from` indique à la fonction d'itérer sur l'objet nommé `file_like`. Puis, pour chaque partie itérée, de produire cette partie comme provenant de cette fonction génératrice (`iterfile`).
+
+ Ainsi, c'est une fonction génératrice qui transfère le travail de « génération » à autre chose en interne.
+
+ En procédant ainsi, nous pouvons la placer dans un bloc `with` et, de cette façon, garantir que l'objet de type fichier est fermé après la fin.
+
+/// tip | Astuce
+
+Remarquez qu'ici, comme nous utilisons le `open()` standard qui ne prend pas en charge `async` et `await`, nous déclarons le chemin d'accès avec un `def` normal.
+
+///
+
+### `FileResponse` { #fileresponse }
+
+Diffuse de façon asynchrone un fichier comme réponse.
+
+Prend un ensemble de paramètres différent à l'instanciation par rapport aux autres types de réponse :
+
+- `path` - Le chemin du fichier à diffuser.
+- `headers` - D'éventuels en-têtes personnalisés à inclure, sous forme de dictionnaire.
+- `media_type` - Une chaîne donnant le media type. Si non défini, le nom du fichier ou le chemin sera utilisé pour en déduire un media type.
+- `filename` - Si défini, sera inclus dans l'en-tête `Content-Disposition` de la réponse.
+
+Les réponses de type fichier incluront les en-têtes appropriés `Content-Length`, `Last-Modified` et `ETag`.
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+Vous pouvez aussi utiliser le paramètre `response_class` :
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+Dans ce cas, vous pouvez renvoyer directement le chemin du fichier depuis votre fonction de chemin d'accès.
+
+## Classe de réponse personnalisée { #custom-response-class }
+
+Vous pouvez créer votre propre classe de réponse personnalisée, héritant de `Response`, et l'utiliser.
+
+Par exemple, disons que vous voulez utiliser `orjson`, mais avec certains réglages personnalisés non utilisés dans la classe `ORJSONResponse` incluse.
+
+Disons que vous voulez renvoyer du JSON indenté et formaté, donc vous voulez utiliser l'option orjson `orjson.OPT_INDENT_2`.
+
+Vous pourriez créer une `CustomORJSONResponse`. L'essentiel est de créer une méthode `Response.render(content)` qui renvoie le contenu en `bytes` :
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+Maintenant, au lieu de renvoyer :
+
+```json
+{"message": "Hello World"}
+```
+
+... cette réponse renverra :
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+Bien sûr, vous trouverez probablement des moyens bien meilleurs de tirer parti de cela que de formater du JSON. 😉
+
+## Classe de réponse par défaut { #default-response-class }
+
+Lors de la création d'une instance de classe **FastAPI** ou d'un `APIRouter`, vous pouvez spécifier quelle classe de réponse utiliser par défaut.
+
+Le paramètre qui le définit est `default_response_class`.
+
+Dans l'exemple ci-dessous, **FastAPI** utilisera `ORJSONResponse` par défaut, dans tous les chemins d'accès, au lieu de `JSONResponse`.
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | Astuce
+
+Vous pouvez toujours remplacer `response_class` dans les chemins d'accès comme auparavant.
+
+///
+
+## Documentation supplémentaire { #additional-documentation }
+
+Vous pouvez aussi déclarer le media type et de nombreux autres détails dans OpenAPI en utilisant `responses` : [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/fr/docs/advanced/dataclasses.md b/docs/fr/docs/advanced/dataclasses.md
new file mode 100644
index 000000000..2bd77157e
--- /dev/null
+++ b/docs/fr/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Utiliser des dataclasses { #using-dataclasses }
+
+FastAPI est construit au‑dessus de **Pydantic**, et je vous ai montré comment utiliser des modèles Pydantic pour déclarer les requêtes et les réponses.
+
+Mais FastAPI prend aussi en charge l'utilisation de `dataclasses` de la même manière :
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+Cela fonctionne grâce à **Pydantic**, qui offre une prise en charge interne des `dataclasses`.
+
+Ainsi, même avec le code ci‑dessus qui n'emploie pas explicitement Pydantic, FastAPI utilise Pydantic pour convertir ces dataclasses standard en la variante de dataclasses de Pydantic.
+
+Et bien sûr, cela prend en charge la même chose :
+
+* validation des données
+* sérialisation des données
+* documentation des données, etc.
+
+Cela fonctionne de la même manière qu'avec les modèles Pydantic. Et, en réalité, c'est mis en œuvre de la même façon en interne, en utilisant Pydantic.
+
+/// info | Info
+
+Gardez à l'esprit que les dataclasses ne peuvent pas tout ce que peuvent faire les modèles Pydantic.
+
+Vous pourriez donc avoir encore besoin d'utiliser des modèles Pydantic.
+
+Mais si vous avez déjà un ensemble de dataclasses sous la main, c'est une astuce pratique pour les utiliser afin d'alimenter une API Web avec FastAPI. 🤓
+
+///
+
+## Utiliser des dataclasses dans `response_model` { #dataclasses-in-response-model }
+
+Vous pouvez aussi utiliser `dataclasses` dans le paramètre `response_model` :
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+La dataclass sera automatiquement convertie en dataclass Pydantic.
+
+Ainsi, son schéma apparaîtra dans l'interface utilisateur de la documentation de l'API :
+
+
+
+## Utiliser des dataclasses dans des structures de données imbriquées { #dataclasses-in-nested-data-structures }
+
+Vous pouvez aussi combiner `dataclasses` avec d'autres annotations de type pour créer des structures de données imbriquées.
+
+Dans certains cas, vous devrez peut‑être encore utiliser la version `dataclasses` de Pydantic. Par exemple, si vous rencontrez des erreurs avec la documentation d'API générée automatiquement.
+
+Dans ce cas, vous pouvez simplement remplacer les `dataclasses` standard par `pydantic.dataclasses`, qui est un remplacement drop‑in :
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. Nous continuons à importer `field` depuis les `dataclasses` standard.
+
+2. `pydantic.dataclasses` est un remplacement drop‑in pour `dataclasses`.
+
+3. La dataclass `Author` inclut une liste de dataclasses `Item`.
+
+4. La dataclass `Author` est utilisée comme paramètre `response_model`.
+
+5. Vous pouvez utiliser d'autres annotations de type standard avec des dataclasses comme corps de la requête.
+
+ Dans ce cas, il s'agit d'une liste de dataclasses `Item`.
+
+6. Ici, nous renvoyons un dictionnaire qui contient `items`, qui est une liste de dataclasses.
+
+ FastAPI est toujours capable de sérialiser les données en JSON.
+
+7. Ici, `response_model` utilise une annotation de type correspondant à une liste de dataclasses `Author`.
+
+ Là encore, vous pouvez combiner `dataclasses` avec des annotations de type standard.
+
+8. Notez que cette *fonction de chemin d'accès* utilise un `def` classique au lieu de `async def`.
+
+ Comme toujours, avec FastAPI vous pouvez combiner `def` et `async def` selon vos besoins.
+
+ Si vous avez besoin d'un rappel sur quand utiliser l'un ou l'autre, consultez la section _« In a hurry? »_ dans la documentation à propos de [`async` et `await`](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+9. Cette *fonction de chemin d'accès* ne renvoie pas des dataclasses (même si elle le pourrait), mais une liste de dictionnaires contenant des données internes.
+
+ FastAPI utilisera le paramètre `response_model` (qui inclut des dataclasses) pour convertir la réponse.
+
+Vous pouvez combiner `dataclasses` avec d'autres annotations de type, selon de nombreuses combinaisons, pour former des structures de données complexes.
+
+Reportez‑vous aux annotations dans le code ci‑dessus pour voir plus de détails spécifiques.
+
+## En savoir plus { #learn-more }
+
+Vous pouvez aussi combiner `dataclasses` avec d'autres modèles Pydantic, en hériter, les inclure dans vos propres modèles, etc.
+
+Pour en savoir plus, consultez la documentation Pydantic sur les dataclasses.
+
+## Version { #version }
+
+C'est disponible depuis FastAPI version `0.67.0`. 🔖
diff --git a/docs/fr/docs/advanced/events.md b/docs/fr/docs/advanced/events.md
new file mode 100644
index 000000000..6d0907a8b
--- /dev/null
+++ b/docs/fr/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# Événements de cycle de vie { #lifespan-events }
+
+Vous pouvez définir une logique (du code) qui doit être exécutée avant que l'application ne **démarre**. Cela signifie que ce code sera exécuté **une seule fois**, **avant** que l'application ne **commence à recevoir des requêtes**.
+
+De la même manière, vous pouvez définir une logique (du code) qui doit être exécutée lorsque l'application **s'arrête**. Dans ce cas, ce code sera exécuté **une seule fois**, **après** avoir traité potentiellement **de nombreuses requêtes**.
+
+Comme ce code est exécuté avant que l'application ne **commence** à recevoir des requêtes, et juste après qu'elle **termine** de les traiter, il couvre tout le **cycle de vie** de l'application (le mot « lifespan » va être important dans un instant 😉).
+
+Cela peut être très utile pour configurer des **ressources** dont vous avez besoin pour l'ensemble de l'application, qui sont **partagées** entre les requêtes, et/ou que vous devez **nettoyer** ensuite. Par exemple, un pool de connexions à une base de données, ou le chargement d'un modèle d'apprentissage automatique partagé.
+
+## Cas d'utilisation { #use-case }
+
+Commençons par un exemple de **cas d'utilisation**, puis voyons comment le résoudre avec ceci.
+
+Imaginons que vous ayez des **modèles d'apprentissage automatique** que vous souhaitez utiliser pour traiter des requêtes. 🤖
+
+Les mêmes modèles sont partagés entre les requêtes, ce n'est donc pas un modèle par requête, ni un par utilisateur, ou quelque chose de similaire.
+
+Imaginons que le chargement du modèle puisse **prendre pas mal de temps**, car il doit lire beaucoup de **données depuis le disque**. Vous ne voulez donc pas le faire pour chaque requête.
+
+Vous pourriez le charger au niveau supérieur du module/fichier, mais cela signifierait aussi qu'il **chargerait le modèle** même si vous exécutez simplement un test automatisé simple ; ce test serait alors **lent** car il devrait attendre le chargement du modèle avant de pouvoir exécuter une partie indépendante du code.
+
+C'est ce que nous allons résoudre : chargeons le modèle avant que les requêtes ne soient traitées, mais seulement juste avant que l'application ne commence à recevoir des requêtes, pas pendant le chargement du code.
+
+## Cycle de vie { #lifespan }
+
+Vous pouvez définir cette logique de *démarrage* et d'*arrêt* en utilisant le paramètre `lifespan` de l'application `FastAPI`, et un « gestionnaire de contexte » (je vais vous montrer ce que c'est dans un instant).
+
+Commençons par un exemple, puis voyons-le en détail.
+
+Nous créons une fonction async `lifespan()` avec `yield` comme ceci :
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+Ici, nous simulons l'opération de *démarrage* coûteuse de chargement du modèle en plaçant la fonction (factice) du modèle dans le dictionnaire avec les modèles d'apprentissage automatique avant le `yield`. Ce code sera exécuté **avant** que l'application ne **commence à recevoir des requêtes**, pendant le *démarrage*.
+
+Puis, juste après le `yield`, nous déchargeons le modèle. Ce code sera exécuté **après** que l'application **a fini de traiter les requêtes**, juste avant l'*arrêt*. Cela pourrait, par exemple, libérer des ressources comme la mémoire ou un GPU.
+
+/// tip | Astuce
+
+L’« arrêt » se produit lorsque vous **arrêtez** l'application.
+
+Peut-être devez-vous démarrer une nouvelle version, ou vous en avez simplement assez de l'exécuter. 🤷
+
+///
+
+### Fonction de cycle de vie { #lifespan-function }
+
+La première chose à remarquer est que nous définissons une fonction async avec `yield`. C'est très similaire aux Dépendances avec `yield`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+La première partie de la fonction, avant le `yield`, sera exécutée **avant** le démarrage de l'application.
+
+Et la partie après le `yield` sera exécutée **après** que l'application a terminé.
+
+### Gestionnaire de contexte asynchrone { #async-context-manager }
+
+Si vous regardez, la fonction est décorée avec `@asynccontextmanager`.
+
+Cela convertit la fonction en quelque chose appelé un « **gestionnaire de contexte asynchrone** ».
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Un **gestionnaire de contexte** en Python est quelque chose que vous pouvez utiliser dans une instruction `with`. Par exemple, `open()` peut être utilisé comme gestionnaire de contexte :
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+Dans les versions récentes de Python, il existe aussi un **gestionnaire de contexte asynchrone**. Vous l'utiliseriez avec `async with` :
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+Quand vous créez un gestionnaire de contexte ou un gestionnaire de contexte asynchrone comme ci-dessus, ce qu'il fait, c'est qu'avant d'entrer dans le bloc `with`, il exécute le code avant le `yield`, et après être sorti du bloc `with`, il exécute le code après le `yield`.
+
+Dans notre exemple de code ci-dessus, nous ne l'utilisons pas directement, mais nous le transmettons à FastAPI pour qu'il l'utilise.
+
+Le paramètre `lifespan` de l'application `FastAPI` accepte un **gestionnaire de contexte asynchrone**, nous pouvons donc lui passer notre nouveau gestionnaire de contexte asynchrone `lifespan`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## Événements alternatifs (déprécié) { #alternative-events-deprecated }
+
+/// warning | Alertes
+
+La méthode recommandée pour gérer le *démarrage* et l'*arrêt* est d'utiliser le paramètre `lifespan` de l'application `FastAPI` comme décrit ci-dessus. Si vous fournissez un paramètre `lifespan`, les gestionnaires d'événements `startup` et `shutdown` ne seront plus appelés. C'est soit tout en `lifespan`, soit tout en événements, pas les deux.
+
+Vous pouvez probablement passer cette partie.
+
+///
+
+Il existe une autre manière de définir cette logique à exécuter au *démarrage* et à l'*arrêt*.
+
+Vous pouvez définir des gestionnaires d'événements (fonctions) qui doivent être exécutés avant le démarrage de l'application, ou lorsque l'application s'arrête.
+
+Ces fonctions peuvent être déclarées avec `async def` ou un `def` normal.
+
+### Événement `startup` { #startup-event }
+
+Pour ajouter une fonction qui doit être exécutée avant le démarrage de l'application, déclarez-la avec l'événement « startup » :
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+Dans ce cas, la fonction gestionnaire de l'événement `startup` initialisera la « base de données » des items (juste un `dict`) avec quelques valeurs.
+
+Vous pouvez ajouter plusieurs fonctions de gestion d'événements.
+
+Et votre application ne commencera pas à recevoir des requêtes avant que tous les gestionnaires de l'événement `startup` aient terminé.
+
+### Événement `shutdown` { #shutdown-event }
+
+Pour ajouter une fonction qui doit être exécutée lorsque l'application s'arrête, déclarez-la avec l'événement « shutdown » :
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+Ici, la fonction gestionnaire de l'événement `shutdown` écrira une ligne de texte « Application shutdown » dans un fichier `log.txt`.
+
+/// info
+
+Dans la fonction `open()`, le `mode="a"` signifie « append » (ajouter) ; la ligne sera donc ajoutée après ce qui se trouve déjà dans ce fichier, sans écraser le contenu précédent.
+
+///
+
+/// tip | Astuce
+
+Notez que dans ce cas, nous utilisons une fonction Python standard `open()` qui interagit avec un fichier.
+
+Cela implique des E/S (input/output), qui nécessitent « d'attendre » que des choses soient écrites sur le disque.
+
+Mais `open()` n'utilise pas `async` et `await`.
+
+Nous déclarons donc la fonction gestionnaire d'événement avec un `def` standard plutôt qu'avec `async def`.
+
+///
+
+### `startup` et `shutdown` ensemble { #startup-and-shutdown-together }
+
+Il y a de fortes chances que la logique de votre *démarrage* et de votre *arrêt* soit liée : vous pourriez vouloir démarrer quelque chose puis le terminer, acquérir une ressource puis la libérer, etc.
+
+Faire cela dans des fonctions séparées qui ne partagent pas de logique ni de variables est plus difficile, car vous devriez stocker des valeurs dans des variables globales ou recourir à des astuces similaires.
+
+Pour cette raison, il est désormais recommandé d'utiliser plutôt le `lifespan` comme expliqué ci-dessus.
+
+## Détails techniques { #technical-details }
+
+Juste un détail technique pour les nerds curieux. 🤓
+
+Sous le capot, dans la spécification technique ASGI, cela fait partie du protocole Lifespan, et il y définit des événements appelés `startup` et `shutdown`.
+
+/// info
+
+Vous pouvez en lire plus sur les gestionnaires `lifespan` de Starlette dans la documentation « Lifespan » de Starlette.
+
+Y compris comment gérer l'état de cycle de vie qui peut être utilisé dans d'autres parties de votre code.
+
+///
+
+## Sous-applications { #sub-applications }
+
+🚨 Gardez à l'esprit que ces événements de cycle de vie (démarrage et arrêt) ne seront exécutés que pour l'application principale, pas pour [Sous-applications - Montages](sub-applications.md){.internal-link target=_blank}.
diff --git a/docs/fr/docs/advanced/generate-clients.md b/docs/fr/docs/advanced/generate-clients.md
new file mode 100644
index 000000000..6f51ac7be
--- /dev/null
+++ b/docs/fr/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# Générer des SDK { #generating-sdks }
+
+Parce que **FastAPI** est basé sur la spécification **OpenAPI**, ses API peuvent être décrites dans un format standard compris par de nombreux outils.
+
+Cela facilite la génération de **documentation** à jour, de bibliothèques clientes (**SDKs**) dans plusieurs langages, ainsi que de **tests** ou de **workflows d’automatisation** qui restent synchronisés avec votre code.
+
+Dans ce guide, vous apprendrez à générer un **SDK TypeScript** pour votre backend FastAPI.
+
+## Générateurs de SDK open source { #open-source-sdk-generators }
+
+Une option polyvalente est OpenAPI Generator, qui prend en charge **de nombreux langages de programmation** et peut générer des SDK à partir de votre spécification OpenAPI.
+
+Pour les **clients TypeScript**, Hey API est une solution dédiée, offrant une expérience optimisée pour l’écosystème TypeScript.
+
+Vous pouvez découvrir davantage de générateurs de SDK sur OpenAPI.Tools.
+
+/// tip | Astuce
+
+FastAPI génère automatiquement des spécifications **OpenAPI 3.1**, donc tout outil que vous utilisez doit prendre en charge cette version.
+
+///
+
+## Générateurs de SDK par les sponsors de FastAPI { #sdk-generators-from-fastapi-sponsors }
+
+Cette section met en avant des solutions **soutenues par des fonds** et **par des entreprises** qui sponsorisent FastAPI. Ces produits offrent **des fonctionnalités supplémentaires** et **des intégrations** en plus de SDK de haute qualité générés.
+
+En ✨ [**sponsorisant FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, ces entreprises contribuent à garantir que le framework et son **écosystème** restent sains et **durables**.
+
+Leur sponsoring démontre également un fort engagement envers la **communauté** FastAPI (vous), montrant qu’elles se soucient non seulement d’offrir un **excellent service**, mais aussi de soutenir un **framework robuste et florissant**, FastAPI. 🙇
+
+Par exemple, vous pourriez essayer :
+
+* Speakeasy
+* Stainless
+* liblab
+
+Certaines de ces solutions peuvent aussi être open source ou proposer des niveaux gratuits, afin que vous puissiez les essayer sans engagement financier. D’autres générateurs de SDK commerciaux existent et peuvent être trouvés en ligne. 🤓
+
+## Créer un SDK TypeScript { #create-a-typescript-sdk }
+
+Commençons par une application FastAPI simple :
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+Remarquez que les *chemins d'accès* définissent les modèles qu’ils utilisent pour le payload de requête et le payload de réponse, en utilisant les modèles `Item` et `ResponseMessage`.
+
+### Documentation de l’API { #api-docs }
+
+Si vous allez sur `/docs`, vous verrez qu’elle contient les **schémas** pour les données à envoyer dans les requêtes et reçues dans les réponses :
+
+
+
+Vous voyez ces schémas parce qu’ils ont été déclarés avec les modèles dans l’application.
+
+Ces informations sont disponibles dans le **schéma OpenAPI** de l’application, puis affichées dans la documentation de l’API.
+
+Ces mêmes informations issues des modèles, incluses dans OpenAPI, peuvent être utilisées pour **générer le code client**.
+
+### Hey API { #hey-api }
+
+Une fois que vous avez une application FastAPI avec les modèles, vous pouvez utiliser Hey API pour générer un client TypeScript. Le moyen le plus rapide de le faire est via npx.
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+Cela générera un SDK TypeScript dans `./src/client`.
+
+Vous pouvez apprendre à installer `@hey-api/openapi-ts` et lire à propos du résultat généré sur leur site.
+
+### Utiliser le SDK { #using-the-sdk }
+
+Vous pouvez maintenant importer et utiliser le code client. Cela pourrait ressembler à ceci, remarquez que vous obtenez l’autocomplétion pour les méthodes :
+
+
+
+Vous obtiendrez également l’autocomplétion pour le payload à envoyer :
+
+
+
+/// tip | Astuce
+
+Remarquez l’autocomplétion pour `name` et `price`, qui a été définie dans l’application FastAPI, dans le modèle `Item`.
+
+///
+
+Vous aurez des erreurs en ligne pour les données que vous envoyez :
+
+
+
+L’objet de réponse aura également l’autocomplétion :
+
+
+
+## Application FastAPI avec des tags { #fastapi-app-with-tags }
+
+Dans de nombreux cas, votre application FastAPI sera plus grande, et vous utiliserez probablement des tags pour séparer différents groupes de *chemins d'accès*.
+
+Par exemple, vous pourriez avoir une section pour les **items** et une autre section pour les **users**, et elles pourraient être séparées par des tags :
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### Générer un client TypeScript avec des tags { #generate-a-typescript-client-with-tags }
+
+Si vous générez un client pour une application FastAPI utilisant des tags, il séparera normalement aussi le code client en fonction des tags.
+
+De cette façon, vous pourrez avoir les éléments ordonnés et correctement groupés côté client :
+
+
+
+Dans ce cas, vous avez :
+
+* `ItemsService`
+* `UsersService`
+
+### Noms des méthodes du client { #client-method-names }
+
+À l’heure actuelle, les noms de méthodes générés comme `createItemItemsPost` ne sont pas très propres :
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+... c’est parce que le générateur de client utilise l’**operation ID** interne OpenAPI pour chaque *chemin d'accès*.
+
+OpenAPI exige que chaque operation ID soit unique parmi tous les *chemins d'accès*, donc FastAPI utilise le **nom de la fonction**, le **chemin**, et la **méthode/opération HTTP** pour générer cet operation ID, car de cette façon il peut s’assurer que les operation IDs sont uniques.
+
+Mais je vais vous montrer comment améliorer cela ensuite. 🤓
+
+## IDs d’opération personnalisés et meilleurs noms de méthodes { #custom-operation-ids-and-better-method-names }
+
+Vous pouvez **modifier** la façon dont ces operation IDs sont **générés** pour les simplifier et obtenir des **noms de méthodes plus simples** dans les clients.
+
+Dans ce cas, vous devez vous assurer que chaque operation ID est **unique** d’une autre manière.
+
+Par exemple, vous pouvez vous assurer que chaque *chemin d'accès* a un tag, puis générer l’operation ID à partir du **tag** et du **nom** du *chemin d'accès* (le nom de la fonction).
+
+### Fonction personnalisée de génération d’ID unique { #custom-generate-unique-id-function }
+
+FastAPI utilise un **ID unique** pour chaque *chemin d'accès*, qui est utilisé pour l’**operation ID** et également pour les noms des modèles personnalisés nécessaires, pour les requêtes ou les réponses.
+
+Vous pouvez personnaliser cette fonction. Elle prend un `APIRoute` et retourne une chaîne.
+
+Par exemple, ici elle utilise le premier tag (vous n’en aurez probablement qu’un) et le nom du *chemin d'accès* (le nom de la fonction).
+
+Vous pouvez ensuite passer cette fonction personnalisée à **FastAPI** via le paramètre `generate_unique_id_function` :
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### Générer un client TypeScript avec des IDs d’opération personnalisés { #generate-a-typescript-client-with-custom-operation-ids }
+
+Maintenant, si vous régénérez le client, vous verrez qu’il possède des noms de méthodes améliorés :
+
+
+
+Comme vous le voyez, les noms de méthodes contiennent maintenant le tag puis le nom de la fonction ; ils n’incluent plus d’informations provenant du chemin d’URL et de l’opération HTTP.
+
+### Prétraiter la spécification OpenAPI pour le générateur de client { #preprocess-the-openapi-specification-for-the-client-generator }
+
+Le code généré contient encore des **informations dupliquées**.
+
+Nous savons déjà que cette méthode est liée aux **items** parce que ce mot figure dans `ItemsService` (issu du tag), mais nous avons encore le nom du tag préfixé dans le nom de la méthode. 😕
+
+Nous voudrons probablement le conserver pour OpenAPI en général, car cela garantira que les operation IDs sont **uniques**.
+
+Mais pour le client généré, nous pourrions **modifier** les operation IDs d’OpenAPI juste avant de générer les clients, simplement pour rendre ces noms de méthodes plus agréables et **plus clairs**.
+
+Nous pourrions télécharger le JSON OpenAPI dans un fichier `openapi.json` puis **supprimer ce tag préfixé** avec un script comme celui-ci :
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+Avec cela, les operation IDs seraient renommés de `items-get_items` en simplement `get_items`, de sorte que le générateur de client puisse produire des noms de méthodes plus simples.
+
+### Générer un client TypeScript avec l’OpenAPI prétraité { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Puisque le résultat final se trouve maintenant dans un fichier `openapi.json`, vous devez mettre à jour l’emplacement d’entrée :
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+Après avoir généré le nouveau client, vous aurez désormais des **noms de méthodes propres**, avec toute l’**autocomplétion**, les **erreurs en ligne**, etc. :
+
+
+
+## Avantages { #benefits }
+
+En utilisant les clients générés automatiquement, vous obtiendrez de l’**autocomplétion** pour :
+
+* Méthodes.
+* Payloads de requête dans le corps, paramètres de requête, etc.
+* Payloads de réponse.
+
+Vous auriez également des **erreurs en ligne** pour tout.
+
+Et chaque fois que vous mettez à jour le code du backend et **régénérez** le frontend, il inclura les nouveaux *chemins d'accès* disponibles en tant que méthodes, supprimera les anciens, et tout autre changement sera reflété dans le code généré. 🤓
+
+Cela signifie aussi que si quelque chose change, cela sera **reflété** automatiquement dans le code client. Et si vous **bâtissez** le client, il échouera en cas de **discordance** dans les données utilisées.
+
+Ainsi, vous **détecterez de nombreuses erreurs** très tôt dans le cycle de développement au lieu d’attendre qu’elles apparaissent pour vos utilisateurs finaux en production puis de tenter de déboguer l’origine du problème. ✨
diff --git a/docs/fr/docs/advanced/middleware.md b/docs/fr/docs/advanced/middleware.md
new file mode 100644
index 000000000..934c91041
--- /dev/null
+++ b/docs/fr/docs/advanced/middleware.md
@@ -0,0 +1,97 @@
+# Utiliser des middlewares avancés { #advanced-middleware }
+
+Dans le tutoriel principal, vous avez vu comment ajouter des [middlewares personnalisés](../tutorial/middleware.md){.internal-link target=_blank} à votre application.
+
+Vous avez également vu comment gérer [CORS avec le `CORSMiddleware`](../tutorial/cors.md){.internal-link target=_blank}.
+
+Dans cette section, nous allons voir comment utiliser d'autres middlewares.
+
+## Ajouter des middlewares ASGI { #adding-asgi-middlewares }
+
+Comme **FastAPI** est basé sur Starlette et implémente la spécification ASGI, vous pouvez utiliser n'importe quel middleware ASGI.
+
+Un middleware n'a pas besoin d'être conçu pour FastAPI ou Starlette pour fonctionner, tant qu'il suit la spécification ASGI.
+
+En général, les middlewares ASGI sont des classes qui s'attendent à recevoir une application ASGI en premier argument.
+
+Ainsi, dans la documentation de middlewares ASGI tiers, on vous indiquera probablement de faire quelque chose comme :
+
+```Python
+from unicorn import UnicornMiddleware
+
+app = SomeASGIApp()
+
+new_app = UnicornMiddleware(app, some_config="rainbow")
+```
+
+Mais FastAPI (en fait Starlette) fournit une manière plus simple de le faire, qui garantit que les middlewares internes gèrent les erreurs serveur et que les gestionnaires d'exceptions personnalisés fonctionnent correctement.
+
+Pour cela, vous utilisez `app.add_middleware()` (comme dans l'exemple pour CORS).
+
+```Python
+from fastapi import FastAPI
+from unicorn import UnicornMiddleware
+
+app = FastAPI()
+
+app.add_middleware(UnicornMiddleware, some_config="rainbow")
+```
+
+`app.add_middleware()` reçoit une classe de middleware en premier argument, ainsi que tout argument supplémentaire à transmettre au middleware.
+
+## Utiliser les middlewares intégrés { #integrated-middlewares }
+
+**FastAPI** inclut plusieurs middlewares pour des cas d'usage courants ; voyons comment les utiliser.
+
+/// note | Détails techniques
+
+Pour les prochains exemples, vous pourriez aussi utiliser `from starlette.middleware.something import SomethingMiddleware`.
+
+**FastAPI** fournit plusieurs middlewares dans `fastapi.middleware` simplement pour vous faciliter la vie, en tant que développeur. Mais la plupart des middlewares disponibles viennent directement de Starlette.
+
+///
+
+## `HTTPSRedirectMiddleware` { #httpsredirectmiddleware }
+
+Impose que toutes les requêtes entrantes soient soit `https`, soit `wss`.
+
+Toute requête entrante en `http` ou `ws` sera redirigée vers le schéma sécurisé correspondant.
+
+{* ../../docs_src/advanced_middleware/tutorial001_py310.py hl[2,6] *}
+
+## `TrustedHostMiddleware` { #trustedhostmiddleware }
+
+Impose que toutes les requêtes entrantes aient un en-tête `Host` correctement défini, afin de se prémunir contre les attaques de type HTTP Host Header.
+
+{* ../../docs_src/advanced_middleware/tutorial002_py310.py hl[2,6:8] *}
+
+Les arguments suivants sont pris en charge :
+
+- `allowed_hosts` - Une liste de noms de domaine autorisés comme noms d'hôte. Les domaines génériques tels que `*.example.com` sont pris en charge pour faire correspondre les sous-domaines. Pour autoriser n'importe quel nom d'hôte, utilisez `allowed_hosts=["*"]` ou omettez le middleware.
+- `www_redirect` - Si défini à `True`, les requêtes vers les versions sans www des hôtes autorisés seront redirigées vers leurs équivalents avec www. Valeur par défaut : `True`.
+
+Si une requête entrante n'est pas valide, une réponse `400` sera envoyée.
+
+## `GZipMiddleware` { #gzipmiddleware }
+
+Gère les réponses GZip pour toute requête qui inclut « gzip » dans l'en-tête `Accept-Encoding`.
+
+Le middleware gérera les réponses standard et en streaming.
+
+{* ../../docs_src/advanced_middleware/tutorial003_py310.py hl[2,6] *}
+
+Les arguments suivants sont pris en charge :
+
+- `minimum_size` - Ne pas compresser en GZip les réponses dont la taille est inférieure à ce minimum en octets. Valeur par défaut : `500`.
+- `compresslevel` - Utilisé pendant la compression GZip. Entier compris entre 1 et 9. Valeur par défaut : `9`. Une valeur plus faible entraîne une compression plus rapide mais des fichiers plus volumineux, tandis qu'une valeur plus élevée entraîne une compression plus lente mais des fichiers plus petits.
+
+## Autres middlewares { #other-middlewares }
+
+Il existe de nombreux autres middlewares ASGI.
+
+Par exemple :
+
+- Le `ProxyHeadersMiddleware` d'Uvicorn
+- MessagePack
+
+Pour voir d'autres middlewares disponibles, consultez la documentation des middlewares de Starlette et la liste ASGI Awesome.
diff --git a/docs/fr/docs/advanced/openapi-callbacks.md b/docs/fr/docs/advanced/openapi-callbacks.md
new file mode 100644
index 000000000..669d9447a
--- /dev/null
+++ b/docs/fr/docs/advanced/openapi-callbacks.md
@@ -0,0 +1,186 @@
+# Callbacks OpenAPI { #openapi-callbacks }
+
+Vous pourriez créer une API avec un *chemin d'accès* qui déclenche une requête vers une *API externe* créée par quelqu'un d'autre (probablement la même personne développeuse qui utiliserait votre API).
+
+Le processus qui se produit lorsque votre application API appelle l’*API externe* s’appelle un « callback ». Parce que le logiciel écrit par la personne développeuse externe envoie une requête à votre API puis votre API « rappelle », en envoyant une requête à une *API externe* (probablement créée par la même personne développeuse).
+
+Dans ce cas, vous pourriez vouloir documenter à quoi cette API externe devrait ressembler. Quel *chemin d'accès* elle devrait avoir, quel corps elle devrait attendre, quelle réponse elle devrait renvoyer, etc.
+
+## Une application avec des callbacks { #an-app-with-callbacks }
+
+Voyons tout cela avec un exemple.
+
+Imaginez que vous développiez une application qui permet de créer des factures.
+
+Ces factures auront un `id`, un `title` (facultatif), un `customer` et un `total`.
+
+L’utilisateur de votre API (une personne développeuse externe) créera une facture dans votre API avec une requête POST.
+
+Ensuite votre API va (imaginons) :
+
+* Envoyer la facture à un client de la personne développeuse externe.
+* Encaisser l’argent.
+* Renvoyer une notification à l’utilisateur de l’API (la personne développeuse externe).
+ * Cela sera fait en envoyant une requête POST (depuis *votre API*) vers une *API externe* fournie par cette personne développeuse externe (c’est le « callback »).
+
+## L’application **FastAPI** normale { #the-normal-fastapi-app }
+
+Voyons d’abord à quoi ressemble l’application API normale avant d’ajouter le callback.
+
+Elle aura un *chemin d'accès* qui recevra un corps `Invoice`, et un paramètre de requête `callback_url` qui contiendra l’URL pour le callback.
+
+Cette partie est assez normale, la plupart du code vous est probablement déjà familier :
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[7:11,34:51] *}
+
+/// tip | Astuce
+
+Le paramètre de requête `callback_url` utilise un type Pydantic Url.
+
+///
+
+La seule nouveauté est `callbacks=invoices_callback_router.routes` comme argument du *décorateur de chemin d'accès*. Nous allons voir ce que c’est ensuite.
+
+## Documenter le callback { #documenting-the-callback }
+
+Le code réel du callback dépendra fortement de votre application API.
+
+Et il variera probablement beaucoup d’une application à l’autre.
+
+Cela pourrait être seulement une ou deux lignes de code, comme :
+
+```Python
+callback_url = "https://example.com/api/v1/invoices/events/"
+httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
+```
+
+Mais la partie la plus importante du callback est sans doute de vous assurer que l’utilisateur de votre API (la personne développeuse externe) implémente correctement l’*API externe*, conformément aux données que *votre API* va envoyer dans le corps de la requête du callback, etc.
+
+Ainsi, ce que nous allons faire ensuite, c’est ajouter le code pour documenter à quoi cette *API externe* devrait ressembler pour recevoir le callback de *votre API*.
+
+Cette documentation apparaîtra dans Swagger UI à `/docs` dans votre API, et permettra aux personnes développeuses externes de savoir comment construire l’*API externe*.
+
+Cet exemple n’implémente pas le callback lui-même (qui pourrait être une simple ligne de code), uniquement la partie documentation.
+
+/// tip | Astuce
+
+Le callback réel n’est qu’une requête HTTP.
+
+En implémentant vous-même le callback, vous pourriez utiliser quelque chose comme HTTPX ou Requests.
+
+///
+
+## Écrire le code de documentation du callback { #write-the-callback-documentation-code }
+
+Ce code ne sera pas exécuté dans votre application, nous en avons seulement besoin pour *documenter* à quoi devrait ressembler cette *API externe*.
+
+Mais vous savez déjà comment créer facilement une documentation automatique pour une API avec **FastAPI**.
+
+Nous allons donc utiliser ce même savoir pour documenter à quoi l’*API externe* devrait ressembler ... en créant le(s) *chemin(s) d'accès* que l’API externe devrait implémenter (ceux que votre API appellera).
+
+/// tip | Astuce
+
+Lorsque vous écrivez le code pour documenter un callback, il peut être utile d’imaginer que vous êtes cette *personne développeuse externe*. Et que vous implémentez actuellement l’*API externe*, pas *votre API*.
+
+Adopter temporairement ce point de vue (celui de la *personne développeuse externe*) peut vous aider à trouver plus évident où placer les paramètres, le modèle Pydantic pour le corps, pour la réponse, etc., pour cette *API externe*.
+
+///
+
+### Créer un `APIRouter` de callback { #create-a-callback-apirouter }
+
+Commencez par créer un nouveau `APIRouter` qui contiendra un ou plusieurs callbacks.
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[1,23] *}
+
+### Créer le *chemin d'accès* du callback { #create-the-callback-path-operation }
+
+Pour créer le *chemin d'accès* du callback, utilisez le même `APIRouter` que vous avez créé ci-dessus.
+
+Il devrait ressembler exactement à un *chemin d'accès* FastAPI normal :
+
+* Il devrait probablement déclarer le corps qu’il doit recevoir, par exemple `body: InvoiceEvent`.
+* Et il pourrait aussi déclarer la réponse qu’il doit renvoyer, par exemple `response_model=InvoiceEventReceived`.
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[14:16,19:20,26:30] *}
+
+Il y a 2 principales différences par rapport à un *chemin d'accès* normal :
+
+* Il n’a pas besoin d’avoir de code réel, car votre application n’appellera jamais ce code. Il sert uniquement à documenter l’*API externe*. La fonction peut donc simplement contenir `pass`.
+* Le *chemin* peut contenir une expression OpenAPI 3 (voir plus bas) où il peut utiliser des variables avec des paramètres et des parties de la requête originale envoyée à *votre API*.
+
+### L’expression du chemin de callback { #the-callback-path-expression }
+
+Le *chemin* du callback peut contenir une expression OpenAPI 3 qui peut inclure des parties de la requête originale envoyée à *votre API*.
+
+Dans ce cas, c’est la `str` :
+
+```Python
+"{$callback_url}/invoices/{$request.body.id}"
+```
+
+Ainsi, si l’utilisateur de votre API (la personne développeuse externe) envoie une requête à *votre API* vers :
+
+```
+https://yourapi.com/invoices/?callback_url=https://www.external.org/events
+```
+
+avec un corps JSON :
+
+```JSON
+{
+ "id": "2expen51ve",
+ "customer": "Mr. Richie Rich",
+ "total": "9999"
+}
+```
+
+alors *votre API* traitera la facture et, à un moment ultérieur, enverra une requête de callback à `callback_url` (l’*API externe*) :
+
+```
+https://www.external.org/events/invoices/2expen51ve
+```
+
+avec un corps JSON contenant quelque chose comme :
+
+```JSON
+{
+ "description": "Payment celebration",
+ "paid": true
+}
+```
+
+et elle s’attendra à une réponse de cette *API externe* avec un corps JSON comme :
+
+```JSON
+{
+ "ok": true
+}
+```
+
+/// tip | Astuce
+
+Remarquez que l’URL de callback utilisée contient l’URL reçue en paramètre de requête dans `callback_url` (`https://www.external.org/events`) et aussi l’`id` de la facture à l’intérieur du corps JSON (`2expen51ve`).
+
+///
+
+### Ajouter le routeur de callback { #add-the-callback-router }
+
+À ce stade, vous avez le(s) *chemin(s) d'accès de callback* nécessaire(s) (celui/ceux que la *personne développeuse externe* doit implémenter dans l’*API externe*) dans le routeur de callback que vous avez créé ci-dessus.
+
+Utilisez maintenant le paramètre `callbacks` dans *le décorateur de chemin d'accès de votre API* pour passer l’attribut `.routes` (qui est en fait juste une `list` de routes/*chemins d'accès*) depuis ce routeur de callback :
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *}
+
+/// tip | Astuce
+
+Remarquez que vous ne passez pas le routeur lui-même (`invoices_callback_router`) à `callback=`, mais l’attribut `.routes`, comme dans `invoices_callback_router.routes`.
+
+///
+
+### Vérifier la documentation { #check-the-docs }
+
+Vous pouvez maintenant démarrer votre application et aller sur http://127.0.0.1:8000/docs.
+
+Vous verrez votre documentation incluant une section « Callbacks » pour votre *chemin d'accès* qui montre à quoi l’*API externe* devrait ressembler :
+
+
diff --git a/docs/fr/docs/advanced/openapi-webhooks.md b/docs/fr/docs/advanced/openapi-webhooks.md
new file mode 100644
index 000000000..21b6f5f00
--- /dev/null
+++ b/docs/fr/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# Webhooks OpenAPI { #openapi-webhooks }
+
+Il existe des cas où vous voulez informer les utilisateurs de votre API que votre application peut appeler leur application (en envoyant une requête) avec des données, généralement pour notifier un type d'événement.
+
+Cela signifie qu'au lieu du processus habituel où vos utilisateurs envoient des requêtes à votre API, c'est votre API (ou votre application) qui peut envoyer des requêtes vers leur système (vers leur API, leur application).
+
+On appelle généralement cela un webhook.
+
+## Étapes des webhooks { #webhooks-steps }
+
+Le processus consiste généralement à définir dans votre code le message que vous enverrez, c'est-à-dire le corps de la requête.
+
+Vous définissez également, d'une manière ou d'une autre, à quels moments votre application enverra ces requêtes ou événements.
+
+Et vos utilisateurs définissent aussi, d'une manière ou d'une autre (par exemple dans un tableau de bord Web), l'URL à laquelle votre application doit envoyer ces requêtes.
+
+Toute la logique de gestion des URL des webhooks et le code qui envoie effectivement ces requêtes vous incombent. Vous l'implémentez comme vous le souhaitez dans votre propre code.
+
+## Documenter des webhooks avec FastAPI et OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }
+
+Avec FastAPI, en utilisant OpenAPI, vous pouvez définir les noms de ces webhooks, les types d'opérations HTTP que votre application peut envoyer (par exemple `POST`, `PUT`, etc.) et les corps des requêtes que votre application enverra.
+
+Cela peut grandement faciliter la tâche de vos utilisateurs pour implémenter leurs API afin de recevoir vos requêtes de webhook ; ils pourront même peut-être générer automatiquement une partie de leur propre code d'API.
+
+/// info
+
+Les webhooks sont disponibles dans OpenAPI 3.1.0 et versions ultérieures, pris en charge par FastAPI `0.99.0` et versions ultérieures.
+
+///
+
+## Créer une application avec des webhooks { #an-app-with-webhooks }
+
+Lorsque vous créez une application FastAPI, il existe un attribut `webhooks` que vous pouvez utiliser pour définir des webhooks, de la même manière que vous définiriez des chemins d'accès, par exemple avec `@app.webhooks.post()`.
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+Les webhooks que vous définissez apparaîtront dans le schéma **OpenAPI** et dans l'interface de **documentation** automatique.
+
+/// info
+
+L'objet `app.webhooks` est en fait simplement un `APIRouter`, le même type que vous utiliseriez pour structurer votre application en plusieurs fichiers.
+
+///
+
+Notez qu'avec les webhooks, vous ne déclarez pas réellement un chemin (comme `/items/`), le texte que vous y passez est simplement un identifiant du webhook (le nom de l'événement). Par exemple, dans `@app.webhooks.post("new-subscription")`, le nom du webhook est `new-subscription`.
+
+C'est parce qu'on s'attend à ce que vos utilisateurs définissent, par un autre moyen (par exemple un tableau de bord Web), le véritable chemin d'URL où ils souhaitent recevoir la requête de webhook.
+
+### Consulter la documentation { #check-the-docs }
+
+Vous pouvez maintenant démarrer votre application et aller sur http://127.0.0.1:8000/docs.
+
+Vous verrez que votre documentation contient les chemins d'accès habituels et désormais aussi des webhooks :
+
+
diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
index fc88f3363..b482f97cc 100644
--- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
@@ -12,7 +12,7 @@ Vous pouvez définir l’OpenAPI `operationId` à utiliser dans votre chemin d
Vous devez vous assurer qu’il est unique pour chaque opération.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
### Utiliser le nom de la fonction de chemin d’accès comme operationId { #using-the-path-operation-function-name-as-the-operationid }
@@ -20,7 +20,7 @@ Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`,
Vous devez le faire après avoir ajouté tous vos chemins d’accès.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py39.py hl[2, 12:21, 24] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
/// tip | Astuce
@@ -40,7 +40,7 @@ Même si elles se trouvent dans des modules différents (fichiers Python).
Pour exclure un chemin d’accès du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et définissez-le à `False` :
-{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
## Description avancée depuis la docstring { #advanced-description-from-docstring }
@@ -92,7 +92,7 @@ Vous pouvez étendre le schéma OpenAPI pour un chemin d’accès en utilisant l
Cet `openapi_extra` peut être utile, par exemple, pour déclarer des [Extensions OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) :
-{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py39.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
Si vous ouvrez la documentation automatique de l’API, votre extension apparaîtra en bas du chemin d’accès spécifique.
@@ -139,9 +139,9 @@ Par exemple, vous pourriez décider de lire et de valider la requête avec votre
Vous pourriez le faire avec `openapi_extra` :
-{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py39.py hl[19:36, 39:40] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
-Dans cet exemple, nous n’avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n’est même pas parsé en JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargée de l’analyser d’une manière ou d’une autre.
+Dans cet exemple, nous n’avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n’est même pas parsé en JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargée de l’analyser d’une manière ou d’une autre.
Néanmoins, nous pouvons déclarer le schéma attendu pour le corps de la requête.
@@ -153,7 +153,7 @@ Et vous pourriez le faire même si le type de données dans la requête n’est
Par exemple, dans cette application nous n’utilisons pas la fonctionnalité intégrée de FastAPI pour extraire le JSON Schema des modèles Pydantic ni la validation automatique pour le JSON. En fait, nous déclarons le type de contenu de la requête comme YAML, pas JSON :
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[15:20, 22] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
Néanmoins, bien que nous n’utilisions pas la fonctionnalité intégrée par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le JSON Schema pour les données que nous souhaitons recevoir en YAML.
@@ -161,7 +161,7 @@ Ensuite, nous utilisons directement la requête et extrayons le corps en tant qu
Ensuite, dans notre code, nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML :
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[24:31] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
/// tip | Astuce
diff --git a/docs/fr/docs/advanced/response-change-status-code.md b/docs/fr/docs/advanced/response-change-status-code.md
new file mode 100644
index 000000000..d08e87099
--- /dev/null
+++ b/docs/fr/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# Réponse - Modifier le code d'état { #response-change-status-code }
+
+Vous avez probablement déjà lu que vous pouvez définir un [Code d'état de la réponse](../tutorial/response-status-code.md){.internal-link target=_blank} par défaut.
+
+Mais dans certains cas, vous devez renvoyer un code d'état différent de celui par défaut.
+
+## Cas d'utilisation { #use-case }
+
+Par exemple, imaginez que vous vouliez renvoyer par défaut un code d'état HTTP « OK » `200`.
+
+Mais si les données n'existent pas, vous voulez les créer et renvoyer un code d'état HTTP « CREATED » `201`.
+
+Mais vous souhaitez toujours pouvoir filtrer et convertir les données que vous renvoyez avec un `response_model`.
+
+Pour ces cas, vous pouvez utiliser un paramètre `Response`.
+
+## Utiliser un paramètre `Response` { #use-a-response-parameter }
+
+Vous pouvez déclarer un paramètre de type `Response` dans votre fonction de chemin d'accès (comme vous pouvez le faire pour les cookies et les en-têtes).
+
+Vous pouvez ensuite définir le `status_code` dans cet objet de réponse *temporaire*.
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+Vous pouvez ensuite renvoyer n'importe quel objet nécessaire, comme d'habitude (un `dict`, un modèle de base de données, etc.).
+
+Et si vous avez déclaré un `response_model`, il sera toujours utilisé pour filtrer et convertir l'objet que vous avez renvoyé.
+
+**FastAPI** utilisera cette réponse *temporaire* pour extraire le code d'état (ainsi que les cookies et les en-têtes), et les placera dans la réponse finale qui contient la valeur que vous avez renvoyée, filtrée par tout `response_model`.
+
+Vous pouvez également déclarer le paramètre `Response` dans des dépendances et y définir le code d'état. Mais gardez à l'esprit que la dernière valeur définie prévaut.
diff --git a/docs/fr/docs/advanced/response-cookies.md b/docs/fr/docs/advanced/response-cookies.md
new file mode 100644
index 000000000..d3e51f331
--- /dev/null
+++ b/docs/fr/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# Cookies de réponse { #response-cookies }
+
+## Utiliser un paramètre `Response` { #use-a-response-parameter }
+
+Vous pouvez déclarer un paramètre de type `Response` dans votre fonction de chemin d'accès.
+
+Vous pouvez ensuite définir des cookies dans cet objet de réponse *temporaire*.
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+Vous pouvez ensuite renvoyer n'importe quel objet dont vous avez besoin, comme d'habitude (un `dict`, un modèle de base de données, etc.).
+
+Et si vous avez déclaré un `response_model`, il sera toujours utilisé pour filtrer et convertir l'objet que vous avez renvoyé.
+
+**FastAPI** utilisera cette réponse *temporaire* pour extraire les cookies (ainsi que les en-têtes et le code d'état), et les placera dans la réponse finale qui contient la valeur que vous avez renvoyée, filtrée par tout `response_model`.
+
+Vous pouvez également déclarer le paramètre `Response` dans des dépendances, et y définir des cookies (et des en-têtes).
+
+## Renvoyer une `Response` directement { #return-a-response-directly }
+
+Vous pouvez également créer des cookies en renvoyant une `Response` directement dans votre code.
+
+Pour ce faire, vous pouvez créer une réponse comme décrit dans [Renvoyer une Response directement](response-directly.md){.internal-link target=_blank}.
+
+Définissez ensuite des cookies dessus, puis renvoyez-la :
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip | Astuce
+
+Gardez à l'esprit que si vous renvoyez une réponse directement au lieu d'utiliser le paramètre `Response`, FastAPI la renverra telle quelle.
+
+Vous devez donc vous assurer que vos données sont du type correct. Par exemple, qu'elles sont compatibles avec JSON si vous renvoyez une `JSONResponse`.
+
+Et également que vous n'envoyez pas de données qui auraient dû être filtrées par un `response_model`.
+
+///
+
+### En savoir plus { #more-info }
+
+/// note | Détails techniques
+
+Vous pouvez également utiliser `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`.
+
+**FastAPI** fournit les mêmes `starlette.responses` que `fastapi.responses` simplement pour votre commodité, en tant que développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+
+Et comme `Response` peut être utilisé fréquemment pour définir des en-têtes et des cookies, **FastAPI** la met également à disposition via `fastapi.Response`.
+
+///
+
+Pour voir tous les paramètres et options disponibles, consultez la documentation de Starlette.
diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md
index f35c39c06..4a4951864 100644
--- a/docs/fr/docs/advanced/response-directly.md
+++ b/docs/fr/docs/advanced/response-directly.md
@@ -22,7 +22,7 @@ En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle s
Et quand vous retournez une `Response`, **FastAPI** la transmet directement.
-Elle ne fera aucune conversion de données avec les modèles Pydantic, elle ne convertira pas le contenu en un type quelconque.
+Elle ne fera aucune conversion de données avec les modèles Pydantic, elle ne convertira pas le contenu en un type quelconque, etc.
Cela vous donne beaucoup de flexibilité. Vous pouvez retourner n'importe quel type de données, surcharger n'importe quelle déclaration ou validation de données, etc.
@@ -54,7 +54,7 @@ Disons que vous voulez retourner une réponse en utilisant le préfixe `X-`.
+
+Mais si vous avez des en-têtes personnalisés que vous voulez qu'un client dans un navigateur puisse voir, vous devez les ajouter à vos configurations CORS (en savoir plus dans [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), en utilisant le paramètre `expose_headers` documenté dans la documentation CORS de Starlette.
diff --git a/docs/fr/docs/advanced/security/http-basic-auth.md b/docs/fr/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 000000000..a8742ce7c
--- /dev/null
+++ b/docs/fr/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# Authentification HTTP Basic { #http-basic-auth }
+
+Pour les cas les plus simples, vous pouvez utiliser l'authentification HTTP Basic.
+
+Avec l'authentification HTTP Basic, l'application attend un en-tête contenant un nom d'utilisateur et un mot de passe.
+
+Si elle ne le reçoit pas, elle renvoie une erreur HTTP 401 « Unauthorized ».
+
+Et elle renvoie un en-tête `WWW-Authenticate` avec la valeur `Basic`, et un paramètre optionnel `realm`.
+
+Cela indique au navigateur d'afficher l'invite intégrée pour saisir un nom d'utilisateur et un mot de passe.
+
+Ensuite, lorsque vous saisissez ce nom d'utilisateur et ce mot de passe, le navigateur les envoie automatiquement dans l'en-tête.
+
+## Authentification HTTP Basic simple { #simple-http-basic-auth }
+
+- Importer `HTTPBasic` et `HTTPBasicCredentials`.
+- Créer un « schéma de sécurité » en utilisant `HTTPBasic`.
+- Utiliser ce `security` avec une dépendance dans votre chemin d'accès.
+- Cela renvoie un objet de type `HTTPBasicCredentials` :
+ - Il contient le `username` et le `password` envoyés.
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+Lorsque vous essayez d'ouvrir l'URL pour la première fois (ou cliquez sur le bouton « Execute » dans les documents) le navigateur vous demandera votre nom d'utilisateur et votre mot de passe :
+
+
+
+## Vérifier le nom d'utilisateur { #check-the-username }
+
+Voici un exemple plus complet.
+
+Utilisez une dépendance pour vérifier si le nom d'utilisateur et le mot de passe sont corrects.
+
+Pour cela, utilisez le module standard Python `secrets` pour vérifier le nom d'utilisateur et le mot de passe.
+
+`secrets.compare_digest()` doit recevoir des `bytes` ou une `str` ne contenant que des caractères ASCII (ceux de l'anglais), ce qui signifie qu'elle ne fonctionnerait pas avec des caractères comme `á`, comme dans `Sebastián`.
+
+Pour gérer cela, nous convertissons d'abord `username` et `password` en `bytes` en les encodant en UTF-8.
+
+Nous pouvons ensuite utiliser `secrets.compare_digest()` pour vérifier que `credentials.username` est « stanleyjobson » et que `credentials.password` est « swordfish ».
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+Cela serait équivalent à :
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Renvoyer une erreur
+ ...
+```
+
+Mais en utilisant `secrets.compare_digest()`, cela sera sécurisé contre un type d'attaques appelé « attaques par chronométrage ».
+
+### Attaques par chronométrage { #timing-attacks }
+
+Mais qu'est-ce qu'une « attaque par chronométrage » ?
+
+Imaginons que des attaquants essaient de deviner le nom d'utilisateur et le mot de passe.
+
+Ils envoient alors une requête avec un nom d'utilisateur `johndoe` et un mot de passe `love123`.
+
+Le code Python de votre application serait alors équivalent à quelque chose comme :
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Mais au moment où Python compare le premier `j` de `johndoe` au premier `s` de `stanleyjobson`, il retournera `False`, car il sait déjà que ces deux chaînes ne sont pas identiques, en se disant qu'« il n'est pas nécessaire de gaspiller plus de calcul pour comparer le reste des lettres ». Et votre application dira « Nom d'utilisateur ou mot de passe incorrect ».
+
+Mais ensuite, les attaquants essaient avec le nom d'utilisateur `stanleyjobsox` et le mot de passe `love123`.
+
+Et le code de votre application fait quelque chose comme :
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Python devra comparer tout `stanleyjobso` dans `stanleyjobsox` et `stanleyjobson` avant de réaliser que les deux chaînes ne sont pas identiques. Cela prendra donc quelques microsecondes supplémentaires pour répondre « Nom d'utilisateur ou mot de passe incorrect ».
+
+#### Le temps de réponse aide les attaquants { #the-time-to-answer-helps-the-attackers }
+
+À ce stade, en remarquant que le serveur a mis quelques microsecondes de plus à envoyer la réponse « Nom d'utilisateur ou mot de passe incorrect », les attaquants sauront qu'ils ont trouvé quelque chose de juste : certaines des premières lettres étaient correctes.
+
+Ils peuvent alors réessayer en sachant que c'est probablement quelque chose de plus proche de `stanleyjobsox` que de `johndoe`.
+
+#### Une attaque « professionnelle » { #a-professional-attack }
+
+Bien sûr, les attaquants n'essaieraient pas tout cela à la main ; ils écriraient un programme pour le faire, avec éventuellement des milliers ou des millions de tests par seconde. Ils obtiendraient une lettre correcte supplémentaire à la fois.
+
+Ce faisant, en quelques minutes ou heures, les attaquants devineraient le nom d'utilisateur et le mot de passe corrects, avec « l'aide » de notre application, simplement en se basant sur le temps de réponse.
+
+#### Corrigez-le avec `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }
+
+Mais dans notre code nous utilisons justement `secrets.compare_digest()`.
+
+En bref, il faudra le même temps pour comparer `stanleyjobsox` à `stanleyjobson` que pour comparer `johndoe` à `stanleyjobson`. Il en va de même pour le mot de passe.
+
+Ainsi, en utilisant `secrets.compare_digest()` dans le code de votre application, votre application sera protégée contre toute cette gamme d'attaques de sécurité.
+
+### Renvoyer l'erreur { #return-the-error }
+
+Après avoir détecté que les identifiants sont incorrects, renvoyez une `HTTPException` avec un code d'état 401 (le même que lorsque aucun identifiant n'est fourni) et ajoutez l'en-tête `WWW-Authenticate` pour que le navigateur affiche à nouveau l'invite de connexion :
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/fr/docs/advanced/security/index.md b/docs/fr/docs/advanced/security/index.md
new file mode 100644
index 000000000..e84fcef62
--- /dev/null
+++ b/docs/fr/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# Sécurité avancée { #advanced-security }
+
+## Fonctionnalités supplémentaires { #additional-features }
+
+Il existe des fonctionnalités supplémentaires pour gérer la sécurité en plus de celles couvertes dans le [Tutoriel - Guide utilisateur : Sécurité](../../tutorial/security/index.md){.internal-link target=_blank}.
+
+/// tip | Astuce
+
+Les sections suivantes ne sont pas nécessairement « advanced ».
+
+Et il est possible que, pour votre cas d’utilisation, la solution se trouve dans l’une d’entre elles.
+
+///
+
+## Lire d’abord le tutoriel { #read-the-tutorial-first }
+
+Les sections suivantes partent du principe que vous avez déjà lu le [Tutoriel - Guide utilisateur : Sécurité](../../tutorial/security/index.md){.internal-link target=_blank} principal.
+
+Elles s’appuient toutes sur les mêmes concepts, mais permettent des fonctionnalités supplémentaires.
diff --git a/docs/fr/docs/advanced/security/oauth2-scopes.md b/docs/fr/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 000000000..c890a5129
--- /dev/null
+++ b/docs/fr/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# Scopes OAuth2 { #oauth2-scopes }
+
+Vous pouvez utiliser des scopes OAuth2 directement avec **FastAPI**, ils sont intégrés pour fonctionner de manière transparente.
+
+Cela vous permettrait d’avoir un système d’autorisations plus fin, conforme au standard OAuth2, intégré à votre application OpenAPI (et à la documentation de l’API).
+
+OAuth2 avec scopes est le mécanisme utilisé par de nombreux grands fournisseurs d’authentification, comme Facebook, Google, GitHub, Microsoft, X (Twitter), etc. Ils l’utilisent pour fournir des permissions spécifiques aux utilisateurs et aux applications.
+
+Chaque fois que vous « log in with » Facebook, Google, GitHub, Microsoft, X (Twitter), cette application utilise OAuth2 avec scopes.
+
+Dans cette section, vous verrez comment gérer l’authentification et l’autorisation avec le même OAuth2 avec scopes dans votre application **FastAPI**.
+
+/// warning | Alertes
+
+C’est une section plus ou moins avancée. Si vous débutez, vous pouvez la passer.
+
+Vous n’avez pas nécessairement besoin des scopes OAuth2, et vous pouvez gérer l’authentification et l’autorisation comme vous le souhaitez.
+
+Mais OAuth2 avec scopes peut s’intégrer élégamment à votre API (avec OpenAPI) et à votre documentation d’API.
+
+Néanmoins, c’est toujours à vous de faire appliquer ces scopes, ou toute autre exigence de sécurité/autorisation, selon vos besoins, dans votre code.
+
+Dans de nombreux cas, OAuth2 avec scopes peut être excessif.
+
+Mais si vous savez que vous en avez besoin, ou si vous êtes curieux, continuez à lire.
+
+///
+
+## Scopes OAuth2 et OpenAPI { #oauth2-scopes-and-openapi }
+
+La spécification OAuth2 définit des « scopes » comme une liste de chaînes séparées par des espaces.
+
+Le contenu de chacune de ces chaînes peut avoir n’importe quel format, mais ne doit pas contenir d’espaces.
+
+Ces scopes représentent des « permissions ».
+
+Dans OpenAPI (par ex. la documentation de l’API), vous pouvez définir des « schémas de sécurité ».
+
+Lorsqu’un de ces schémas de sécurité utilise OAuth2, vous pouvez aussi déclarer et utiliser des scopes.
+
+Chaque « scope » est juste une chaîne (sans espaces).
+
+Ils sont généralement utilisés pour déclarer des permissions de sécurité spécifiques, par exemple :
+
+* `users:read` ou `users:write` sont des exemples courants.
+* `instagram_basic` est utilisé par Facebook / Instagram.
+* `https://www.googleapis.com/auth/drive` est utilisé par Google.
+
+/// info
+
+Dans OAuth2, un « scope » est simplement une chaîne qui déclare une permission spécifique requise.
+
+Peu importe s’il contient d’autres caractères comme `:` ou si c’est une URL.
+
+Ces détails dépendent de l’implémentation.
+
+Pour OAuth2, ce ne sont que des chaînes.
+
+///
+
+## Vue d’ensemble { #global-view }
+
+Voyons d’abord rapidement les parties qui changent par rapport aux exemples du **Tutoriel - Guide utilisateur** pour [OAuth2 avec mot de passe (et hachage), Bearer avec jetons JWT](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Cette fois, en utilisant des scopes OAuth2 :
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+Passons maintenant en revue ces changements étape par étape.
+
+## Déclarer le schéma de sécurité OAuth2 { #oauth2-security-scheme }
+
+Le premier changement est que nous déclarons maintenant le schéma de sécurité OAuth2 avec deux scopes disponibles, `me` et `items`.
+
+Le paramètre `scopes` reçoit un `dict` avec chaque scope en clé et la description en valeur :
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+Comme nous déclarons maintenant ces scopes, ils apparaîtront dans la documentation de l’API lorsque vous vous authentifiez/autorisez.
+
+Et vous pourrez sélectionner à quels scopes vous souhaitez accorder l’accès : `me` et `items`.
+
+C’est le même mécanisme utilisé lorsque vous donnez des permissions en vous connectant avec Facebook, Google, GitHub, etc. :
+
+
+
+## Jeton JWT avec scopes { #jwt-token-with-scopes }
+
+Modifiez maintenant le *chemin d’accès* du jeton pour renvoyer les scopes demandés.
+
+Nous utilisons toujours le même `OAuth2PasswordRequestForm`. Il inclut une propriété `scopes` avec une `list` de `str`, contenant chaque scope reçu dans la requête.
+
+Et nous renvoyons les scopes comme partie du jeton JWT.
+
+/// danger | Danger
+
+Pour simplifier, ici nous ajoutons directement au jeton les scopes reçus.
+
+Mais dans votre application, pour la sécurité, vous devez vous assurer de n’ajouter que les scopes que l’utilisateur est réellement autorisé à avoir, ou ceux que vous avez prédéfinis.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## Déclarer des scopes dans les chemins d’accès et les dépendances { #declare-scopes-in-path-operations-and-dependencies }
+
+Nous déclarons maintenant que le *chemin d’accès* `/users/me/items/` nécessite le scope `items`.
+
+Pour cela, nous importons et utilisons `Security` depuis `fastapi`.
+
+Vous pouvez utiliser `Security` pour déclarer des dépendances (comme `Depends`), mais `Security` reçoit aussi un paramètre `scopes` avec une liste de scopes (chaînes).
+
+Dans ce cas, nous passons une fonction de dépendance `get_current_active_user` à `Security` (de la même manière que nous le ferions avec `Depends`).
+
+Mais nous passons aussi une `list` de scopes, ici avec un seul scope : `items` (il pourrait y en avoir plus).
+
+Et la fonction de dépendance `get_current_active_user` peut également déclarer des sous-dépendances, non seulement avec `Depends` mais aussi avec `Security`. En déclarant sa propre fonction de sous-dépendance (`get_current_user`), et davantage d’exigences de scopes.
+
+Dans ce cas, elle nécessite le scope `me` (elle pourrait en exiger plusieurs).
+
+/// note | Remarque
+
+Vous n’avez pas nécessairement besoin d’ajouter des scopes différents à différents endroits.
+
+Nous le faisons ici pour montrer comment **FastAPI** gère des scopes déclarés à différents niveaux.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | Détails techniques
+
+`Security` est en réalité une sous-classe de `Depends`, et elle n’a qu’un paramètre supplémentaire que nous verrons plus tard.
+
+Mais en utilisant `Security` au lieu de `Depends`, **FastAPI** saura qu’il peut déclarer des scopes de sécurité, les utiliser en interne et documenter l’API avec OpenAPI.
+
+Cependant, lorsque vous importez `Query`, `Path`, `Depends`, `Security` et d’autres depuis `fastapi`, ce sont en fait des fonctions qui renvoient des classes spéciales.
+
+///
+
+## Utiliser `SecurityScopes` { #use-securityscopes }
+
+Mettez maintenant à jour la dépendance `get_current_user`.
+
+C’est celle utilisée par les dépendances ci-dessus.
+
+C’est ici que nous utilisons le même schéma OAuth2 que nous avons créé auparavant, en le déclarant comme dépendance : `oauth2_scheme`.
+
+Comme cette fonction de dépendance n’a pas elle-même d’exigences de scope, nous pouvons utiliser `Depends` avec `oauth2_scheme`, nous n’avons pas à utiliser `Security` quand nous n’avons pas besoin de spécifier des scopes de sécurité.
+
+Nous déclarons également un paramètre spécial de type `SecurityScopes`, importé de `fastapi.security`.
+
+Cette classe `SecurityScopes` est similaire à `Request` (`Request` servait à obtenir directement l’objet requête).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## Utiliser les `scopes` { #use-the-scopes }
+
+Le paramètre `security_scopes` sera de type `SecurityScopes`.
+
+Il aura une propriété `scopes` avec une liste contenant tous les scopes requis par lui-même et par toutes les dépendances qui l’utilisent comme sous-dépendance. Cela signifie, tous les « dépendants » ... cela peut paraître déroutant, c’est expliqué à nouveau plus bas.
+
+L’objet `security_scopes` (de classe `SecurityScopes`) fournit aussi un attribut `scope_str` avec une chaîne unique, contenant ces scopes séparés par des espaces (nous allons l’utiliser).
+
+Nous créons une `HTTPException` que nous pouvons réutiliser (`raise`) plus tard à plusieurs endroits.
+
+Dans cette exception, nous incluons les scopes requis (le cas échéant) sous forme de chaîne séparée par des espaces (en utilisant `scope_str`). Nous plaçons cette chaîne contenant les scopes dans l’en-tête `WWW-Authenticate` (cela fait partie de la spécification).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## Vérifier le `username` et la structure des données { #verify-the-username-and-data-shape }
+
+Nous vérifions que nous obtenons un `username`, et extrayons les scopes.
+
+Nous validons ensuite ces données avec le modèle Pydantic (en capturant l’exception `ValidationError`), et si nous obtenons une erreur lors de la lecture du jeton JWT ou de la validation des données avec Pydantic, nous levons la `HTTPException` que nous avons créée auparavant.
+
+Pour cela, nous mettons à jour le modèle Pydantic `TokenData` avec une nouvelle propriété `scopes`.
+
+En validant les données avec Pydantic, nous pouvons nous assurer que nous avons, par exemple, exactement une `list` de `str` pour les scopes et un `str` pour le `username`.
+
+Au lieu, par exemple, d’un `dict`, ou autre chose, ce qui pourrait casser l’application plus tard et constituer un risque de sécurité.
+
+Nous vérifions également que nous avons un utilisateur avec ce nom d’utilisateur, et sinon, nous levons la même exception que précédemment.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## Vérifier les `scopes` { #verify-the-scopes }
+
+Nous vérifions maintenant que tous les scopes requis, par cette dépendance et tous les dépendants (y compris les *chemins d’accès*), sont inclus dans les scopes fournis dans le jeton reçu, sinon nous levons une `HTTPException`.
+
+Pour cela, nous utilisons `security_scopes.scopes`, qui contient une `list` avec tous ces scopes en `str`.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## Arbre de dépendances et scopes { #dependency-tree-and-scopes }
+
+Revoyons encore cet arbre de dépendances et les scopes.
+
+Comme la dépendance `get_current_active_user` a une sous-dépendance `get_current_user`, le scope « me » déclaré dans `get_current_active_user` sera inclus dans la liste des scopes requis dans `security_scopes.scopes` passé à `get_current_user`.
+
+Le *chemin d’accès* lui-même déclare également un scope, « items », il sera donc aussi présent dans la liste `security_scopes.scopes` passée à `get_current_user`.
+
+Voici à quoi ressemble la hiérarchie des dépendances et des scopes :
+
+* Le *chemin d’accès* `read_own_items` a :
+ * Des scopes requis `["items"]` avec la dépendance :
+ * `get_current_active_user` :
+ * La fonction de dépendance `get_current_active_user` a :
+ * Des scopes requis `["me"]` avec la dépendance :
+ * `get_current_user` :
+ * La fonction de dépendance `get_current_user` a :
+ * Aucun scope requis par elle-même.
+ * Une dépendance utilisant `oauth2_scheme`.
+ * Un paramètre `security_scopes` de type `SecurityScopes` :
+ * Ce paramètre `security_scopes` a une propriété `scopes` avec une `list` contenant tous les scopes déclarés ci-dessus, donc :
+ * `security_scopes.scopes` contiendra `["me", "items"]` pour le *chemin d’accès* `read_own_items`.
+ * `security_scopes.scopes` contiendra `["me"]` pour le *chemin d’accès* `read_users_me`, car il est déclaré dans la dépendance `get_current_active_user`.
+ * `security_scopes.scopes` contiendra `[]` (rien) pour le *chemin d’accès* `read_system_status`, car il n’a déclaré aucun `Security` avec des `scopes`, et sa dépendance, `get_current_user`, ne déclare pas non plus de `scopes`.
+
+/// tip | Astuce
+
+L’élément important et « magique » ici est que `get_current_user` aura une liste différente de `scopes` à vérifier pour chaque *chemin d’accès*.
+
+Tout dépend des `scopes` déclarés dans chaque *chemin d’accès* et chaque dépendance dans l’arbre de dépendances pour ce *chemin d’accès* spécifique.
+
+///
+
+## Détails supplémentaires sur `SecurityScopes` { #more-details-about-securityscopes }
+
+Vous pouvez utiliser `SecurityScopes` à n’importe quel endroit, et à de multiples endroits, il n’a pas besoin d’être dans la dépendance « root ».
+
+Il aura toujours les scopes de sécurité déclarés dans les dépendances `Security` actuelles et tous les dépendants pour **ce** *chemin d’accès* spécifique et **cet** arbre de dépendances spécifique.
+
+Comme `SecurityScopes` contient tous les scopes déclarés par les dépendants, vous pouvez l’utiliser pour vérifier qu’un jeton possède les scopes requis dans une fonction de dépendance centrale, puis déclarer des exigences de scopes différentes dans différents *chemins d’accès*.
+
+Elles seront vérifiées indépendamment pour chaque *chemin d’accès*.
+
+## Tester { #check-it }
+
+Si vous ouvrez la documentation de l’API, vous pouvez vous authentifier et spécifier quels scopes vous voulez autoriser.
+
+
+
+Si vous ne sélectionnez aucun scope, vous serez « authenticated », mais lorsque vous essayerez d’accéder à `/users/me/` ou `/users/me/items/`, vous obtiendrez une erreur indiquant que vous n’avez pas suffisamment de permissions. Vous pourrez toujours accéder à `/status/`.
+
+Et si vous sélectionnez le scope `me` mais pas le scope `items`, vous pourrez accéder à `/users/me/` mais pas à `/users/me/items/`.
+
+C’est ce qui arriverait à une application tierce qui tenterait d’accéder à l’un de ces *chemins d’accès* avec un jeton fourni par un utilisateur, selon le nombre de permissions que l’utilisateur a accordées à l’application.
+
+## À propos des intégrations tierces { #about-third-party-integrations }
+
+Dans cet exemple, nous utilisons le flux OAuth2 « password ».
+
+C’est approprié lorsque nous nous connectons à notre propre application, probablement avec notre propre frontend.
+
+Parce que nous pouvons lui faire confiance pour recevoir le `username` et le `password`, puisque nous le contrôlons.
+
+Mais si vous construisez une application OAuth2 à laquelle d’autres se connecteraient (c.-à-d., si vous construisez un fournisseur d’authentification équivalent à Facebook, Google, GitHub, etc.), vous devez utiliser l’un des autres flux.
+
+Le plus courant est le flux implicite.
+
+Le plus sûr est le flux « code », mais il est plus complexe à implémenter car il nécessite plus d’étapes. Comme il est plus complexe, de nombreux fournisseurs finissent par recommander le flux implicite.
+
+/// note | Remarque
+
+Il est courant que chaque fournisseur d’authentification nomme ses flux différemment, pour en faire une partie de sa marque.
+
+Mais au final, ils implémentent le même standard OAuth2.
+
+///
+
+**FastAPI** inclut des utilitaires pour tous ces flux d’authentification OAuth2 dans `fastapi.security.oauth2`.
+
+## `Security` dans les dépendances du décorateur `dependencies` { #security-in-decorator-dependencies }
+
+De la même manière que vous pouvez définir une `list` de `Depends` dans le paramètre `dependencies` du décorateur (comme expliqué dans [Dépendances dans les décorateurs de chemins d’accès](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), vous pouvez aussi utiliser `Security` avec des `scopes` à cet endroit.
diff --git a/docs/fr/docs/advanced/settings.md b/docs/fr/docs/advanced/settings.md
new file mode 100644
index 000000000..ed724bf4f
--- /dev/null
+++ b/docs/fr/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# Paramètres et variables d'environnement { #settings-and-environment-variables }
+
+Dans de nombreux cas, votre application peut avoir besoin de paramètres ou de configurations externes, par exemple des clés secrètes, des identifiants de base de données, des identifiants pour des services d'e-mail, etc.
+
+La plupart de ces paramètres sont variables (peuvent changer), comme les URL de base de données. Et beaucoup peuvent être sensibles, comme les secrets.
+
+C'est pourquoi il est courant de les fournir via des variables d'environnement lues par l'application.
+
+/// tip | Astuce
+
+Pour comprendre les variables d'environnement, vous pouvez lire [Variables d'environnement](../environment-variables.md){.internal-link target=_blank}.
+
+///
+
+## Types et validation { #types-and-validation }
+
+Ces variables d'environnement ne gèrent que des chaînes de texte, car elles sont externes à Python et doivent être compatibles avec d'autres programmes et le reste du système (et même avec différents systèmes d'exploitation, comme Linux, Windows, macOS).
+
+Cela signifie que toute valeur lue en Python depuis une variable d'environnement sera une `str`, et toute conversion vers un autre type ou toute validation doit être effectuée dans le code.
+
+## Pydantic `Settings` { #pydantic-settings }
+
+Heureusement, Pydantic fournit un excellent utilitaire pour gérer ces paramètres provenant des variables d'environnement avec Pydantic : gestion des paramètres.
+
+### Installer `pydantic-settings` { #install-pydantic-settings }
+
+D'abord, vous devez créer votre [environnement virtuel](../virtual-environments.md){.internal-link target=_blank}, l'activer, puis installer le paquet `pydantic-settings` :
+
+
+
+Ensuite, ouvrez la documentation de la sous‑application à http://127.0.0.1:8000/subapi/docs.
+
+Vous verrez la documentation API automatique pour la sous‑application, n'incluant que ses propres _chemins d'accès_, tous sous le préfixe de sous‑chemin correct `/subapi` :
+
+
+
+Si vous essayez d'interagir avec l'une ou l'autre des deux interfaces, elles fonctionneront correctement, car le navigateur pourra communiquer avec chaque application ou sous‑application spécifique.
+
+### Détails techniques : `root_path` { #technical-details-root-path }
+
+Lorsque vous montez une sous‑application comme ci‑dessus, FastAPI se charge de communiquer le chemin de montage à la sous‑application au moyen d'un mécanisme de la spécification ASGI appelé `root_path`.
+
+De cette manière, la sous‑application saura utiliser ce préfixe de chemin pour l'interface de documentation.
+
+La sous‑application peut également avoir ses propres sous‑applications montées et tout fonctionnera correctement, car FastAPI gère automatiquement tous ces `root_path`.
+
+Vous en apprendrez davantage sur `root_path` et sur la façon de l'utiliser explicitement dans la section [Derrière un proxy](behind-a-proxy.md){.internal-link target=_blank}.
diff --git a/docs/fr/docs/advanced/templates.md b/docs/fr/docs/advanced/templates.md
new file mode 100644
index 000000000..7c886ab69
--- /dev/null
+++ b/docs/fr/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# Templates { #templates }
+
+Vous pouvez utiliser n'importe quel moteur de templates avec **FastAPI**.
+
+Un choix courant est Jinja2, le même que celui utilisé par Flask et d'autres outils.
+
+Il existe des utilitaires pour le configurer facilement que vous pouvez utiliser directement dans votre application **FastAPI** (fournis par Starlette).
+
+## Installer les dépendances { #install-dependencies }
+
+Vous devez créer un [environnement virtuel](../virtual-environments.md){.internal-link target=_blank}, l'activer, puis installer `jinja2` :
+
+
+
+Vous pouvez saisir des messages dans le champ de saisie et les envoyer :
+
+
+
+Et votre application **FastAPI** avec WebSockets vous répondra :
+
+
+
+Vous pouvez envoyer (et recevoir) de nombreux messages :
+
+
+
+Et tous utiliseront la même connexion WebSocket.
+
+## Utiliser `Depends` et autres { #using-depends-and-others }
+
+Dans les endpoints WebSocket, vous pouvez importer depuis `fastapi` et utiliser :
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+Ils fonctionnent de la même manière que pour les autres endpoints/*chemins d'accès* FastAPI :
+
+{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info
+
+Comme il s'agit d'un WebSocket, il n'est pas vraiment logique de lever une `HTTPException`, nous levons plutôt une `WebSocketException`.
+
+Vous pouvez utiliser un code de fermeture parmi les codes valides définis dans la spécification.
+
+///
+
+### Essayez les WebSockets avec des dépendances { #try-the-websockets-with-dependencies }
+
+Si votre fichier s'appelle `main.py`, exécutez votre application avec :
+
+
+
+## Gérer les déconnexions et plusieurs clients { #handling-disconnections-and-multiple-clients }
+
+Lorsqu'une connexion WebSocket est fermée, l'instruction `await websocket.receive_text()` lèvera une exception `WebSocketDisconnect`, que vous pouvez ensuite intercepter et gérer comme dans cet exemple.
+
+{* ../../docs_src/websockets/tutorial003_py310.py hl[79:81] *}
+
+Pour l'essayer :
+
+* Ouvrez l'application dans plusieurs onglets du navigateur.
+* Écrivez des messages depuis ceux-ci.
+* Puis fermez l'un des onglets.
+
+Cela lèvera l'exception `WebSocketDisconnect`, et tous les autres clients recevront un message comme :
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip | Astuce
+
+L'application ci-dessus est un exemple minimal et simple pour montrer comment gérer et diffuser des messages à plusieurs connexions WebSocket.
+
+Mais gardez à l'esprit que, comme tout est géré en mémoire, dans une seule liste, cela ne fonctionnera que tant que le processus s'exécute et uniquement avec un seul processus.
+
+Si vous avez besoin de quelque chose de facile à intégrer avec FastAPI mais plus robuste, pris en charge par Redis, PostgreSQL ou autres, consultez encode/broadcaster.
+
+///
+
+## Plus d'informations { #more-info }
+
+Pour en savoir plus sur les options, consultez la documentation de Starlette concernant :
+
+* La classe `WebSocket`.
+* Gestion des WebSocket basée sur des classes.
diff --git a/docs/fr/docs/advanced/wsgi.md b/docs/fr/docs/advanced/wsgi.md
new file mode 100644
index 000000000..fc89819d2
--- /dev/null
+++ b/docs/fr/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# Inclure WSGI - Flask, Django, autres { #including-wsgi-flask-django-others }
+
+Vous pouvez monter des applications WSGI comme vous l'avez vu avec [Sous-applications - Montages](sub-applications.md){.internal-link target=_blank}, [Derrière un proxy](behind-a-proxy.md){.internal-link target=_blank}.
+
+Pour cela, vous pouvez utiliser `WSGIMiddleware` et l'utiliser pour envelopper votre application WSGI, par exemple Flask, Django, etc.
+
+## Utiliser `WSGIMiddleware` { #using-wsgimiddleware }
+
+/// info
+
+Cela nécessite l'installation de `a2wsgi`, par exemple avec `pip install a2wsgi`.
+
+///
+
+Vous devez importer `WSGIMiddleware` depuis `a2wsgi`.
+
+Ensuite, enveloppez l'application WSGI (par ex. Flask) avec le middleware.
+
+Puis, montez-la sous un chemin.
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note | Remarque
+
+Auparavant, il était recommandé d'utiliser `WSGIMiddleware` depuis `fastapi.middleware.wsgi`, mais il est désormais déprécié.
+
+Il est conseillé d'utiliser le package `a2wsgi` à la place. L'utilisation reste la même.
+
+Assurez-vous simplement que le package `a2wsgi` est installé et importez `WSGIMiddleware` correctement depuis `a2wsgi`.
+
+///
+
+## Vérifiez { #check-it }
+
+Désormais, chaque requête sous le chemin `/v1/` sera gérée par l'application Flask.
+
+Et le reste sera géré par **FastAPI**.
+
+Si vous l'exécutez et allez à http://localhost:8000/v1/, vous verrez la réponse de Flask :
+
+```txt
+Hello, World from Flask!
+```
+
+Et si vous allez à http://localhost:8000/v2, vous verrez la réponse de FastAPI :
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/fr/docs/alternatives.md b/docs/fr/docs/alternatives.md
index 9d8d85705..c344bd1f8 100644
--- a/docs/fr/docs/alternatives.md
+++ b/docs/fr/docs/alternatives.md
@@ -1,8 +1,8 @@
-# Alternatives, inspiration et comparaisons
+# Alternatives, inspiration et comparaisons { #alternatives-inspiration-and-comparisons }
Ce qui a inspiré **FastAPI**, comment il se compare à d'autres solutions et ce qu'il en a appris.
-## Intro
+## Intro { #intro }
**FastAPI** n'existerait pas sans les précédentes contributions d'autres projets.
@@ -13,11 +13,11 @@ fonctionnalités couvertes par **FastAPI** en utilisant de nombreux frameworks,
Mais à un moment donné il n'y avait pas d'autre option que de créer quelque chose qui offrait toutes ces
fonctionnalités, en reprenant et en combinant de la meilleure façon possible les meilleures idées des outils
-précédents, en utilisant des fonctionnalités du langage qui n'étaient même pas disponibles auparavant (type hints depuis Python 3.6+).
+précédents, en utilisant des fonctionnalités du langage qui n'étaient même pas disponibles auparavant (annotations de type depuis Python 3.6+).
-## Outils précédents
+## Outils précédents { #previous-tools }
-### Django
+### Django { #django }
C'est le framework Python le plus populaire et il bénéficie d'une grande confiance. Il est utilisé pour construire
des systèmes tel qu'Instagram.
@@ -26,18 +26,18 @@ Il est relativement fortement couplé aux bases de données relationnelles (comm
n'est pas très facile d'utiliser une base de données NoSQL (comme Couchbase, MongoDB, Cassandra, etc.) comme principal moyen de
stockage.
-Il a été créé pour générer le HTML en backend, pas pour créer des API consommées par un frontend moderne (comme React, Vue.js et Angular) ou par d'autres systèmes (comme les appareils IoT) communiquant avec lui.
+Il a été créé pour générer le HTML en backend, pas pour créer des API consommées par un frontend moderne (comme React, Vue.js et Angular) ou par d'autres systèmes (comme les appareils IoT) communiquant avec lui.
-### Django REST Framework
+### Django REST Framework { #django-rest-framework }
Django REST framework a été conçu comme une boîte à outils flexible permettant de construire des API Web à partir de Django, afin d'améliorer ses capacités en matière d'API.
Il est utilisé par de nombreuses entreprises, dont Mozilla, Red Hat et Eventbrite.
Il s'agissait de l'un des premiers exemples de **documentation automatique pour API**, et c'est précisément l'une des
-premières idées qui a inspiré "la recherche de" **FastAPI**.
+premières idées qui a inspiré « la recherche de » **FastAPI**.
-/// note
+/// note | Remarque
Django REST framework a été créé par Tom Christie. Le créateur de Starlette et Uvicorn, sur lesquels **FastAPI** est basé.
@@ -49,9 +49,9 @@ Avoir une interface de documentation automatique de l'API.
///
-### Flask
+### Flask { #flask }
-Flask est un "micro-framework", il ne comprend pas d'intégrations de bases de données ni beaucoup de choses qui sont fournies par défaut dans Django.
+Flask est un « micro‑framework », il ne comprend pas d'intégrations de bases de données ni beaucoup de choses qui sont fournies par défaut dans Django.
Cette simplicité et cette flexibilité permettent d'utiliser des bases de données NoSQL comme principal système de stockage de données.
@@ -60,20 +60,20 @@ technique par moments.
Il est aussi couramment utilisé pour d'autres applications qui n'ont pas nécessairement besoin d'une base de données, de gestion des utilisateurs ou de l'une des nombreuses fonctionnalités préinstallées dans Django. Bien que beaucoup de ces fonctionnalités puissent être ajoutées avec des plug-ins.
-Ce découplage des parties, et le fait d'être un "micro-framework" qui puisse être étendu pour couvrir exactement ce
+Ce découplage des parties, et le fait d'être un « micro‑framework » qui puisse être étendu pour couvrir exactement ce
qui est nécessaire, était une caractéristique clé que je voulais conserver.
-Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un "Django REST Framework" pour Flask.
+Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un « Django REST Framework » pour Flask.
/// check | A inspiré **FastAPI** à
-Être un micro-framework. Il est donc facile de combiner les outils et les pièces nécessaires.
+Être un micro‑framework. Il est donc facile de combiner les outils et les pièces nécessaires.
Proposer un système de routage simple et facile à utiliser.
///
-### Requests
+### Requests { #requests }
**FastAPI** n'est pas réellement une alternative à **Requests**. Leur cadre est très différent.
@@ -97,7 +97,7 @@ La façon dont vous l'utilisez est très simple. Par exemple, pour faire une req
response = requests.get("http://example.com/some/url")
```
-En contrepartie l'API _des opérations de chemin_ de FastAPI pourrait ressembler à ceci :
+L’opération de chemin d'accès correspondante dans **FastAPI** pourrait ressembler à ceci :
```Python hl_lines="1"
@app.get("/some/url")
@@ -109,13 +109,13 @@ Notez les similitudes entre `requests.get(...)` et `@app.get(...)`.
/// check | A inspiré **FastAPI** à
-Avoir une API simple et intuitive.
-
-Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes.
+* Avoir une API simple et intuitive.
+* Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive.
+* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes.
///
-### Swagger / OpenAPI
+### Swagger / OpenAPI { #swagger-openapi }
La principale fonctionnalité que j'ai emprunté à Django REST Framework était la documentation automatique des API.
@@ -126,7 +126,7 @@ Swagger pour une API permettrait d'utiliser cette interface utilisateur web auto
À un moment donné, Swagger a été cédé à la Fondation Linux, puis a été rebaptisé OpenAPI.
-C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire "Swagger", et pour la version 3+ "OpenAPI".
+C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire « Swagger », et pour la version 3+ « OpenAPI ».
/// check | A inspiré **FastAPI** à
@@ -141,16 +141,15 @@ Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en
///
-### Frameworks REST pour Flask
+### Frameworks REST pour Flask { #flask-rest-frameworks }
Il y a plusieurs frameworks REST pour Flask, mais après avoir investi du temps et du travail pour les étudier, j'ai
découvert que le développement de beaucoup d'entre eux sont suspendus ou abandonnés, avec plusieurs problèmes
permanents qui les rendent inadaptés.
-### Marshmallow
+### Marshmallow { #marshmallow }
-L'une des principales fonctionnalités nécessaires aux systèmes API est la "sérialisation" des données, qui consiste à prendre les données du code (Python) et à
+L'une des principales fonctionnalités nécessaires aux systèmes API est la « sérialisation » des données, qui consiste à prendre les données du code (Python) et à
les convertir en quelque chose qui peut être envoyé sur le réseau. Par exemple, convertir un objet contenant des
données provenant d'une base de données en un objet JSON. Convertir des objets `datetime` en strings, etc.
@@ -163,19 +162,17 @@ Sans un système de validation des données, vous devriez effectuer toutes les v
Ces fonctionnalités sont ce pourquoi Marshmallow a été construit. C'est une excellente bibliothèque, et je l'ai déjà beaucoup utilisée.
-Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow.
+Mais elle a été créée avant que les annotations de type n'existent en Python. Ainsi, pour définir chaque schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow.
/// check | A inspiré **FastAPI** à
-Utilisez du code pour définir des "schémas" qui fournissent automatiquement les types de données et la validation.
+Utilisez du code pour définir des « schémas » qui fournissent automatiquement les types de données et la validation.
///
-### Webargs
+### Webargs { #webargs }
-Une autre grande fonctionnalité requise par les API est le parsing des données provenant des requêtes entrantes.
+Une autre grande fonctionnalité requise par les API est l’analyse des données provenant des requêtes entrantes.
Webargs est un outil qui a été créé pour fournir cela par-dessus plusieurs frameworks, dont Flask.
@@ -195,7 +192,7 @@ Disposer d'une validation automatique des données des requêtes entrantes.
///
-### APISpec
+### APISpec { #apispec }
Marshmallow et Webargs fournissent la validation, l'analyse et la sérialisation en tant que plug-ins.
@@ -225,7 +222,7 @@ Supporter la norme ouverte pour les API, OpenAPI.
///
-### Flask-apispec
+### Flask-apispec { #flask-apispec }
C'est un plug-in pour Flask, qui relie Webargs, Marshmallow et APISpec.
@@ -240,11 +237,11 @@ Cette combinaison de Flask, Flask-apispec avec Marshmallow et Webargs était ma
Son utilisation a conduit à la création de plusieurs générateurs Flask full-stack. Ce sont les principales stacks que
j'ai (ainsi que plusieurs équipes externes) utilisées jusqu'à présent :
-- 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-flask-couchbase
+* https://github.com/tiangolo/full-stack-flask-couchdb
-Ces mêmes générateurs full-stack ont servi de base aux [Générateurs de projets pour **FastAPI**](project-generation.md){.internal-link target=\_blank}.
+Ces mêmes générateurs full-stack ont servi de base aux [Générateurs de projets pour **FastAPI**](project-generation.md){.internal-link target=_blank}.
/// info
@@ -258,15 +255,15 @@ Générer le schéma OpenAPI automatiquement, à partir du même code qui défin
///
-### NestJS (et Angular)
+### NestJS (et Angular) { #nestjs-and-angular }
Ce n'est même pas du Python, NestJS est un framework JavaScript (TypeScript) NodeJS inspiré d'Angular.
Il réalise quelque chose de similaire à ce qui peut être fait avec Flask-apispec.
-Il possède un système d'injection de dépendances intégré, inspiré d'Angular 2. Il nécessite de pré-enregistrer les "injectables" (comme tous les autres systèmes d'injection de dépendances que je connais), donc, cela ajoute à la verbosité et à la répétition du code.
+Il possède un système d'injection de dépendances intégré, inspiré d'Angular 2. Il nécessite de pré-enregistrer les « injectables » (comme tous les autres systèmes d'injection de dépendances que je connais), donc, cela ajoute à la verbosité et à la répétition du code.
-Comme les paramètres sont décrits avec des types TypeScript (similaires aux type hints de Python), la prise en charge
+Comme les paramètres sont décrits avec des types TypeScript (similaires aux annotations de type de Python), la prise en charge
par l'éditeur est assez bonne.
Mais comme les données TypeScript ne sont pas préservées après la compilation en JavaScript, il ne peut pas compter sur les types pour définir la validation, la sérialisation et la documentation en même temps. En raison de cela et de certaines décisions de conception, pour obtenir la validation, la sérialisation et la génération automatique de schémas, il est nécessaire d'ajouter des décorateurs à de nombreux endroits. Cela devient donc assez verbeux.
@@ -281,7 +278,7 @@ Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de
///
-### Sanic
+### Sanic { #sanic }
C'était l'un des premiers frameworks Python extrêmement rapides basés sur `asyncio`. Il a été conçu pour être très similaire à Flask.
@@ -301,14 +298,12 @@ C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework l
///
-### Falcon
+### Falcon { #falcon }
Falcon est un autre framework Python haute performance, il est conçu pour être minimal, et est utilisé comme fondation pour d'autres frameworks comme Hug.
-Il utilise le standard précédent pour les frameworks web Python (WSGI) qui est synchrone, donc il ne peut pas gérer les WebSockets et d'autres cas d'utilisation. Néanmoins, il offre de très bonnes performances.
-
-Il est conçu pour avoir des fonctions qui reçoivent deux paramètres, une "requête" et une "réponse". Ensuite, vous
-"lisez" des parties de la requête et "écrivez" des parties dans la réponse. En raison de cette conception, il n'est
+Il est conçu pour avoir des fonctions qui reçoivent deux paramètres, une « requête » et une « réponse ». Ensuite, vous
+« lisez » des parties de la requête et « écrivez » des parties dans la réponse. En raison de cette conception, il n'est
pas possible de déclarer des paramètres de requête et des corps avec des indications de type Python standard comme paramètres de fonction.
Ainsi, la validation, la sérialisation et la documentation des données doivent être effectuées dans le code, et non pas automatiquement. Ou bien elles doivent être implémentées comme un framework au-dessus de Falcon, comme Hug. Cette même distinction se retrouve dans d'autres frameworks qui s'inspirent de la conception de Falcon, qui consiste à avoir un objet de requête et un objet de réponse comme paramètres.
@@ -323,20 +318,20 @@ Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour d
///
-### Molten
+### Molten { #molten }
J'ai découvert Molten lors des premières étapes de développement de **FastAPI**. Et il a des idées assez similaires :
-- Basé sur les type hints Python.
-- Validation et documentation via ces types.
-- Système d'injection de dépendances.
+* Basé sur les annotations de type Python.
+* Validation et documentation via ces types.
+* Système d'injection de dépendances.
Il n'utilise pas une librairie tiers de validation, sérialisation et de documentation tel que Pydantic, il utilise son propre système. Ainsi, ces définitions de types de données ne sont pas réutilisables aussi facilement.
-Il nécessite une configuration un peu plus verbeuse. Et comme il est basé sur WSGI (au lieu dASGI), il n'est pas
+Il nécessite une configuration un peu plus verbeuse. Et comme il est basé sur WSGI (au lieu d'ASGI), il n'est pas
conçu pour profiter des hautes performances fournies par des outils comme Uvicorn, Starlette et Sanic.
-Le système d'injection de dépendances exige le pré-enregistrement des dépendances et les dépendances sont résolues sur la base des types déclarés. Ainsi, il n'est pas possible de déclarer plus d'un "composant" qui fournit un certain type.
+Le système d'injection de dépendances exige le pré-enregistrement des dépendances et les dépendances sont résolues sur la base des types déclarés. Ainsi, il n'est pas possible de déclarer plus d'un « composant » qui fournit un certain type.
Les routes sont déclarées à un seul endroit, en utilisant des fonctions déclarées à d'autres endroits (au lieu
d'utiliser des décorateurs qui peuvent être placés juste au-dessus de la fonction qui gère l'endpoint). Cette
@@ -345,15 +340,15 @@ qui sont relativement fortement couplées.
/// check | A inspiré **FastAPI** à
-Définir des validations supplémentaires pour les types de données utilisant la valeur "par défaut" des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant.
+Définir des validations supplémentaires pour les types de données utilisant la valeur « par défaut » des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant.
Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic).
///
-### Hug
+### Hug { #hug }
-Hug a été l'un des premiers frameworks à implémenter la déclaration des types de paramètres d'API en utilisant les type hints Python. C'était une excellente idée qui a inspiré d'autres outils à faire de même.
+Hug a été l'un des premiers frameworks à implémenter la déclaration des types de paramètres d'API en utilisant les annotations de type Python. C'était une excellente idée qui a inspiré d'autres outils à faire de même.
Il utilisait des types personnalisés dans ses déclarations au lieu des types Python standard, mais c'était tout de même un énorme pas en avant.
@@ -372,28 +367,28 @@ Hug a été créé par Timothy Crosley, le créateur de APIStar (<= 0.5)
+### APIStar (<= 0.5) { #apistar-0-5 }
Juste avant de décider de développer **FastAPI**, j'ai trouvé le serveur **APIStar**. Il contenait presque tout ce
que je recherchais et avait un beau design.
-C'était l'une des premières implémentations d'un framework utilisant les type hints Python pour déclarer les paramètres
+C'était l'une des premières implémentations d'un framework utilisant les annotations de type Python pour déclarer les paramètres
et les requêtes que j'ai vues (avant NestJS et Molten). Je l'ai trouvé plus ou moins en même temps que Hug. Mais APIStar utilisait le standard OpenAPI.
-Il disposait de la validation automatique, sérialisation des données et d'une génération de schéma OpenAPI basée sur les mêmes type hints à plusieurs endroits.
+Il disposait de la validation automatique, sérialisation des données et d'une génération de schéma OpenAPI basée sur les mêmes annotations de type à plusieurs endroits.
-La définition du schéma de corps de requête n'utilisait pas les mêmes type hints Python que Pydantic, il était un peu plus proche de Marshmallow, donc le support de l'éditeur n'était pas aussi bon, mais APIStar était quand même la meilleure option disponible.
+La définition du schéma de corps de requête n'utilisait pas les mêmes annotations de type Python que Pydantic, il était un peu plus proche de Marshmallow, donc le support de l'éditeur n'était pas aussi bon, mais APIStar était quand même la meilleure option disponible.
Il avait les meilleures performances d'après les benchmarks de l'époque (seulement surpassé par Starlette).
@@ -429,20 +424,20 @@ Et après avoir longtemps cherché un framework similaire et testé de nombreuse
Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**.
-Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents.
+Je considère **FastAPI** comme un « successeur spirituel » d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents.
///
-## Utilisés par **FastAPI**
+## Utilisés par **FastAPI** { #used-by-fastapi }
-### Pydantic
+### Pydantic { #pydantic }
-Pydantic est une bibliothèque permettant de définir la validation, la sérialisation et la documentation des données (à l'aide de JSON Schema) en se basant sur les Python type hints.
+Pydantic est une bibliothèque permettant de définir la validation, la sérialisation et la documentation des données (à l'aide de JSON Schema) en se basant sur les annotations de type Python.
Cela le rend extrêmement intuitif.
Il est comparable à Marshmallow. Bien qu'il soit plus rapide que Marshmallow dans les benchmarks. Et comme il est
-basé sur les mêmes type hints Python, le support de l'éditeur est grand.
+basé sur les mêmes annotations de type Python, le support de l'éditeur est grand.
/// check | **FastAPI** l'utilise pour
@@ -452,9 +447,9 @@ Gérer toute la validation des données, leur sérialisation et la documentation
///
-### Starlette
+### Starlette { #starlette }
-Starlette est un framework/toolkit léger ASGI, qui est idéal pour construire des services asyncio performants.
+Starlette est un framework/toolkit léger ASGI, qui est idéal pour construire des services asyncio performants.
Il est très simple et intuitif. Il est conçu pour être facilement extensible et avoir des composants modulaires.
@@ -462,29 +457,28 @@ Il offre :
- Des performances vraiment impressionnantes.
- Le support des WebSockets.
-- Le support de GraphQL.
- Les tâches d'arrière-plan.
- Les événements de démarrage et d'arrêt.
-- Un client de test basé sur request.
+- Un client de test basé sur HTTPX.
- CORS, GZip, fichiers statiques, streaming des réponses.
- Le support des sessions et des cookies.
- Une couverture de test à 100 %.
- 100 % de la base de code avec des annotations de type.
-- Zéro forte dépendance à d'autres packages.
+- Peu de dépendances strictes.
Starlette est actuellement le framework Python le plus rapide testé. Seulement dépassé par Uvicorn, qui n'est pas un framework, mais un serveur.
-Starlette fournit toutes les fonctionnalités de base d'un micro-framework web.
+Starlette fournit toutes les fonctionnalités de base d'un micro‑framework web.
Mais il ne fournit pas de validation automatique des données, de sérialisation ou de documentation.
-C'est l'une des principales choses que **FastAPI** ajoute par-dessus, le tout basé sur les type hints Python (en utilisant Pydantic). Cela, plus le système d'injection de dépendances, les utilitaires de sécurité, la génération de schémas OpenAPI, etc.
+C'est l'une des principales choses que **FastAPI** ajoute par-dessus, le tout basé sur les annotations de type Python (en utilisant Pydantic). Cela, plus le système d'injection de dépendances, les utilitaires de sécurité, la génération de schémas OpenAPI, etc.
/// note | Détails techniques
-ASGI est une nouvelle "norme" développée par les membres de l'équipe principale de Django. Il ne s'agit pas encore d'une "norme Python" (un PEP), bien qu'ils soient en train de le faire.
+ASGI est une nouvelle « norme » développée par les membres de l'équipe principale de Django. Il ne s'agit pas encore d'une « norme Python » (un PEP), bien qu'ils soient en train de le faire.
-Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`.
+Néanmoins, il est déjà utilisé comme « standard » par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`.
///
@@ -498,7 +492,7 @@ Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire direct
///
-### Uvicorn
+### Uvicorn { #uvicorn }
Uvicorn est un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools.
@@ -511,12 +505,12 @@ C'est le serveur recommandé pour Starlette et **FastAPI**.
Le serveur web principal pour exécuter les applications **FastAPI**.
-Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone.
+Vous pouvez également utiliser l'option de ligne de commande `--workers` pour avoir un serveur multi‑processus asynchrone.
Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}.
///
-## Benchmarks et vitesse
+## Benchmarks et vitesse { #benchmarks-and-speed }
-Pour comprendre, comparer et voir la différence entre Uvicorn, Starlette et FastAPI, consultez la section sur les [Benchmarks](benchmarks.md){.internal-link target=\_blank}.
+Pour comprendre, comparer et voir la différence entre Uvicorn, Starlette et FastAPI, consultez la section sur les [Benchmarks](benchmarks.md){.internal-link target=_blank}.
diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md
index 1437ae517..72923e03b 100644
--- a/docs/fr/docs/async.md
+++ b/docs/fr/docs/async.md
@@ -1,17 +1,18 @@
-# Concurrence et les mots-clés async et await
+# Concurrence et async / await { #concurrency-and-async-await }
-Cette page vise à fournir des détails sur la syntaxe `async def` pour les *fonctions de chemins* et quelques rappels sur le code asynchrone, la concurrence et le parallélisme.
+Détails sur la syntaxe `async def` pour les *fonctions de chemin d'accès* et quelques rappels sur le code asynchrone, la concurrence et le parallélisme.
-## Vous êtes pressés ?
+## Vous êtes pressés ? { #in-a-hurry }
-TL;DR :
+TL;DR :
Si vous utilisez des bibliothèques tierces qui nécessitent d'être appelées avec `await`, telles que :
```Python
results = await some_library()
```
-Alors, déclarez vos *fonctions de chemins* avec `async def` comme ceci :
+
+Alors, déclarez vos *fonctions de chemin d'accès* avec `async def` comme ceci :
```Python hl_lines="2"
@app.get('/')
@@ -20,7 +21,7 @@ async def read_results():
return results
```
-/// note
+/// note | Remarque
Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`.
@@ -28,7 +29,7 @@ Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async
---
-Si vous utilisez une bibliothèque externe qui communique avec quelque chose (une BDD, une API, un système de fichiers, etc.) et qui ne supporte pas l'utilisation d'`await` (ce qui est actuellement le cas pour la majorité des bibliothèques de BDD), alors déclarez vos *fonctions de chemin* normalement, avec le classique `def`, comme ceci :
+Si vous utilisez une bibliothèque externe qui communique avec quelque chose (une base de données, une API, le système de fichiers, etc.) et qui ne supporte pas l'utilisation d'`await` (ce qui est actuellement le cas pour la majorité des bibliothèques de base de données), alors déclarez vos *fonctions de chemin d'accès* normalement, avec le classique `def`, comme ceci :
```Python hl_lines="2"
@app.get('/')
@@ -39,7 +40,7 @@ def results():
---
-Si votre application n'a pas à communiquer avec une bibliothèque externe et pas à attendre de réponse, utilisez `async def`.
+Si votre application n'a pas à communiquer avec une autre chose et à attendre sa réponse, utilisez `async def`, même si vous n'avez pas besoin d'utiliser `await` à l'intérieur.
---
@@ -47,15 +48,15 @@ Si vous ne savez pas, utilisez seulement `def` comme vous le feriez habituelleme
---
-**Note** : vous pouvez mélanger `def` et `async def` dans vos *fonctions de chemin* autant que nécessaire, **FastAPI** saura faire ce qu'il faut avec.
+Note : vous pouvez mélanger `def` et `async def` dans vos *fonctions de chemin d'accès* autant que nécessaire, et définir chacune avec l’option la plus adaptée pour vous. FastAPI fera ce qu'il faut avec elles.
-Au final, peu importe le cas parmi ceux ci-dessus, **FastAPI** fonctionnera de manière asynchrone et sera extrêmement rapide.
+Au final, peu importe le cas parmi ceux ci-dessus, FastAPI fonctionnera de manière asynchrone et sera extrêmement rapide.
-Mais si vous suivez bien les instructions ci-dessus, alors **FastAPI** pourra effectuer quelques optimisations et ainsi améliorer les performances.
+Mais si vous suivez bien les instructions ci-dessus, il pourra effectuer quelques optimisations et ainsi améliorer les performances.
-## Détails techniques
+## Détails techniques { #technical-details }
-Les versions modernes de Python supportent le **code asynchrone** grâce aux **"coroutines"** avec les syntaxes **`async` et `await`**.
+Les versions modernes de Python supportent le **code asynchrone** grâce aux **« coroutines »** avec les syntaxes **`async` et `await`**.
Analysons les différentes parties de cette phrase dans les sections suivantes :
@@ -63,46 +64,46 @@ Analysons les différentes parties de cette phrase dans les sections suivantes :
* **`async` et `await`**
* **Coroutines**
-## Code asynchrone
+## Code asynchrone { #asynchronous-code }
-Faire du code asynchrone signifie que le langage 💬 est capable de dire à l'ordinateur / au programme 🤖 qu'à un moment du code, il 🤖 devra attendre que *quelque chose d'autre* se termine autre part. Disons que ce *quelque chose d'autre* est appelé "fichier-lent" 📝.
+Faire du code asynchrone signifie que le langage 💬 est capable de dire à l'ordinateur / au programme 🤖 qu'à un moment du code, il 🤖 devra attendre que *quelque chose d'autre* se termine autre part. Disons que ce *quelque chose d'autre* est appelé « slow-file » 📝.
-Donc, pendant ce temps, l'ordinateur pourra effectuer d'autres tâches, pendant que "fichier-lent" 📝 se termine.
+Donc, pendant ce temps, l'ordinateur pourra effectuer d'autres tâches, pendant que « slow-file » 📝 se termine.
Ensuite l'ordinateur / le programme 🤖 reviendra à chaque fois qu'il en a la chance que ce soit parce qu'il attend à nouveau, ou car il 🤖 a fini tout le travail qu'il avait à faire. Il 🤖 regardera donc si les tâches qu'il attend ont terminé d'être effectuées.
-Ensuite, il 🤖 prendra la première tâche à finir (disons, notre "fichier-lent" 📝) et continuera à faire avec cette dernière ce qu'il était censé.
+Ensuite, il 🤖 prendra la première tâche à finir (disons, notre « slow-file » 📝) et continuera à faire avec cette dernière ce qu'il était censé.
-Ce "attendre quelque chose d'autre" fait généralement référence à des opérations I/O qui sont relativement "lentes" (comparées à la vitesse du processeur et de la mémoire RAM) telles qu'attendre que :
+Ce « attendre quelque chose d'autre » fait généralement référence à des opérations I/O qui sont relativement « lentes » (comparées à la vitesse du processeur et de la mémoire RAM) telles qu'attendre que :
* de la donnée soit envoyée par le client à travers le réseau
* de la donnée envoyée depuis votre programme soit reçue par le client à travers le réseau
* le contenu d'un fichier sur le disque soit lu par le système et passé à votre programme
* le contenu que votre programme a passé au système soit écrit sur le disque
* une opération effectuée à distance par une API se termine
-* une opération en BDD se termine
-* une requête à une BDD renvoie un résultat
+* une opération en base de données se termine
+* une requête à une base de données renvoie un résultat
* etc.
-Le temps d'exécution étant consommé majoritairement par l'attente d'opérations I/O on appelle ceci des opérations "I/O bound".
+Le temps d'exécution étant consommé majoritairement par l'attente d'opérations I/O, on appelle ceci des opérations « I/O bound ».
-Ce concept se nomme l'"asynchronisme" car l'ordinateur / le programme n'a pas besoin d'être "synchronisé" avec la tâche, attendant le moment exact où cette dernière se terminera en ne faisant rien, pour être capable de récupérer le résultat de la tâche et l'utiliser dans la suite des opérations.
+Ce concept se nomme « asynchrone » car l'ordinateur / le programme n'a pas besoin d'être « synchronisé » avec la tâche, attendant le moment exact où cette dernière se terminera en ne faisant rien, pour être capable de récupérer le résultat de la tâche et l'utiliser dans la suite des opérations.
-À la place, en étant "asynchrone", une fois terminée, une tâche peut légèrement attendre (quelques microsecondes) que l'ordinateur / le programme finisse ce qu'il était en train de faire, et revienne récupérer le résultat.
+À la place, en étant « asynchrone », une fois terminée, une tâche peut légèrement attendre (quelques microsecondes) que l'ordinateur / le programme finisse ce qu'il était en train de faire, et revienne récupérer le résultat.
-Pour parler de tâches "synchrones" (en opposition à "asynchrones"), on utilise souvent le terme "séquentiel", car l'ordinateur / le programme va effectuer toutes les étapes d'une tâche séquentiellement avant de passer à une autre tâche, même si ces étapes impliquent de l'attente.
+Pour parler de tâches « synchrones » (en opposition à « asynchrones »), on utilise souvent le terme « séquentiel », car l'ordinateur / le programme va effectuer toutes les étapes d'une tâche séquentiellement avant de passer à une autre tâche, même si ces étapes impliquent de l'attente.
-### Concurrence et Burgers
+### Concurrence et Burgers { #concurrency-and-burgers }
-L'idée de code **asynchrone** décrite ci-dessus est parfois aussi appelée **"concurrence"**. Ce qui est différent du **"parallélisme"**.
+L'idée de code **asynchrone** décrite ci-dessus est parfois aussi appelée **« concurrence »**. Ce qui est différent du **« parallélisme »**.
-La **concurrence** et le **parallélisme** sont tous deux liés à l'idée de "différentes choses arrivant plus ou moins au même moment".
+La **concurrence** et le **parallélisme** sont tous deux liés à l'idée de « différentes choses arrivant plus ou moins au même moment ».
Mais les détails entre la **concurrence** et le **parallélisme** diffèrent sur de nombreux points.
Pour expliquer la différence, voici une histoire de burgers :
-#### Burgers concurrents
+### Burgers concurrents { #concurrent-burgers }
Vous amenez votre crush 😍 dans votre fast food 🍔 favori, et faites la queue pendant que le serveur 💁 prend les commandes des personnes devant vous.
@@ -122,13 +123,13 @@ Le serveur 💁 vous donne le numéro assigné à votre commande.
-Pendant que vous attendez, vous allez choisir une table avec votre crush 😍, vous discutez avec votre crush 😍 pendant un long moment (les burgers étant "magnifiques" ils sont très longs à préparer ✨🍔✨).
+Pendant que vous attendez, vous allez choisir une table avec votre crush 😍, vous discutez avec votre crush 😍 pendant un long moment (les burgers étant « magnifiques » ils sont très longs à préparer ✨🍔✨).
Pendant que vous êtes assis à table, en attendant que les burgers 🍔 soient prêts, vous pouvez passer ce temps à admirer à quel point votre crush 😍 est géniale, mignonne et intelligente ✨😍✨.
-Pendant que vous discutez avec votre crush 😍, de temps en temps vous jetez un coup d'oeil au nombre affiché au-dessus du comptoir pour savoir si c'est à votre tour d'être servis.
+Pendant que vous discutez avec votre crush 😍, de temps en temps vous jetez un coup d’œil au nombre affiché au-dessus du comptoir pour savoir si c'est à votre tour d'être servis.
Jusqu'au moment où c'est (enfin) votre tour. Vous allez au comptoir, récupérez vos burgers 🍔 et revenez à votre table.
@@ -148,23 +149,23 @@ Illustrations proposées par
@@ -212,7 +213,7 @@ Illustrations proposées par (tout ça grâce à Starlette).
+Et comme on peut avoir du parallélisme et de l'asynchronicité en même temps, on obtient des performances plus hautes que la plupart des frameworks NodeJS testés et égales à celles du Go, qui est un langage compilé plus proche du C (tout ça grâce à Starlette).
-### Est-ce que la concurrence est mieux que le parallélisme ?
+### Est-ce que la concurrence est mieux que le parallélisme ? { #is-concurrency-better-than-parallelism }
Nope ! C'est ça la morale de l'histoire.
@@ -276,11 +277,11 @@ Mais dans ce cas, si pouviez amener 8 ex-serveurs/cuisiniers/devenus-nettoyeurs
Dans ce scénario, chacun des nettoyeurs (vous y compris) serait un processeur, faisant sa partie du travail.
-Et comme la plupart du temps d'exécution est pris par du "vrai" travail (et non de l'attente), et que le travail dans un ordinateur est fait par un CPU, ce sont des problèmes dits "CPU bound".
+Et comme la plupart du temps d'exécution est pris par du « vrai » travail (et non de l'attente), et que le travail dans un ordinateur est fait par un CPU, ce sont des problèmes dits « CPU bound ».
---
-Des exemples communs d'opérations "CPU bounds" sont les procédés qui requièrent des traitements mathématiques complexes.
+Des exemples communs d'opérations « CPU bound » sont les procédés qui requièrent des traitements mathématiques complexes.
Par exemple :
@@ -289,19 +290,19 @@ Par exemple :
* L'apprentissage automatique (ou **Machine Learning**) : cela nécessite de nombreuses multiplications de matrices et vecteurs. Imaginez une énorme feuille de calcul remplie de nombres que vous multiplierez entre eux tous au même moment.
* L'apprentissage profond (ou **Deep Learning**) : est un sous-domaine du **Machine Learning**, donc les mêmes raisons s'appliquent. Avec la différence qu'il n'y a pas une unique feuille de calcul de nombres à multiplier, mais une énorme quantité d'entre elles, et dans de nombreux cas, on utilise un processeur spécial pour construire et / ou utiliser ces modèles.
-### Concurrence + Parallélisme : Web + Machine Learning
+### Concurrence + Parallélisme : Web + Machine Learning { #concurrency-parallelism-web-machine-learning }
Avec **FastAPI** vous pouvez bénéficier de la concurrence qui est très courante en développement web (c'est l'attrait principal de NodeJS).
-Mais vous pouvez aussi profiter du parallélisme et multiprocessing afin de gérer des charges **CPU bound** qui sont récurrentes dans les systèmes de *Machine Learning*.
+Mais vous pouvez aussi profiter du parallélisme et du multiprocessing (plusieurs processus s'exécutant en parallèle) afin de gérer des charges **CPU bound** qui sont récurrentes dans les systèmes de *Machine Learning*.
Ça, ajouté au fait que Python soit le langage le plus populaire pour la **Data Science**, le **Machine Learning** et surtout le **Deep Learning**, font de **FastAPI** un très bon choix pour les APIs et applications de **Data Science** / **Machine Learning**.
Pour comprendre comment mettre en place ce parallélisme en production, allez lire la section [Déploiement](deployment/index.md){.internal-link target=_blank}.
-## `async` et `await`
+## `async` et `await` { #async-and-await }
-Les versions modernes de Python ont une manière très intuitive de définir le code asynchrone, tout en gardant une apparence de code "séquentiel" classique en laissant Python faire l'attente pour vous au bon moment.
+Les versions modernes de Python ont une manière très intuitive de définir le code asynchrone, tout en gardant une apparence de code « séquentiel » classique en laissant Python faire l'attente pour vous au bon moment.
Pour une opération qui nécessite de l'attente avant de donner un résultat et qui supporte ces nouvelles fonctionnalités Python, vous pouvez l'utiliser comme tel :
@@ -319,12 +320,12 @@ async def get_burgers(number: int):
return burgers
```
-...et non `def` :
+... et non `def` :
```Python hl_lines="2"
# Ceci n'est pas asynchrone
def get_sequential_burgers(number: int):
- # Opérations asynchrones pour créer les burgers
+ # Opérations séquentielles pour créer les burgers
return burgers
```
@@ -339,7 +340,7 @@ burgers = get_burgers(2)
---
-Donc, si vous utilisez une bibliothèque qui nécessite que ses fonctions soient appelées avec `await`, vous devez définir la *fonction de chemin* en utilisant `async def` comme dans :
+Donc, si vous utilisez une bibliothèque qui nécessite que ses fonctions soient appelées avec `await`, vous devez définir la *fonction de chemin d'accès* en utilisant `async def` comme dans :
```Python hl_lines="2-3"
@app.get('/burgers')
@@ -348,52 +349,61 @@ async def read_burgers():
return burgers
```
-### Plus de détails techniques
+### Plus de détails techniques { #more-technical-details }
Vous avez donc compris que `await` peut seulement être utilisé dans des fonctions définies avec `async def`.
Mais en même temps, les fonctions définies avec `async def` doivent être appelées avec `await` et donc dans des fonctions définies elles aussi avec `async def`.
-Vous avez donc remarqué ce paradoxe d'oeuf et de la poule, comment appelle-t-on la première fonction `async` ?
+Vous avez donc remarqué ce paradoxe d'œuf et de la poule, comment appelle-t-on la première fonction `async` ?
-Si vous utilisez **FastAPI**, pas besoin de vous en inquiéter, car cette "première" fonction sera votre *fonction de chemin* ; et **FastAPI** saura comment arriver au résultat attendu.
+Si vous utilisez **FastAPI**, pas besoin de vous en inquiéter, car cette « première » fonction sera votre *fonction de chemin d'accès* ; et **FastAPI** saura comment arriver au résultat attendu.
-Mais si vous utilisez `async` / `await` sans **FastAPI**, allez jetez un coup d'oeil à la documentation officielle de Python.
+Mais si vous souhaitez utiliser `async` / `await` sans FastAPI, vous pouvez également le faire.
-### Autres formes de code asynchrone
+### Écrire votre propre code async { #write-your-own-async-code }
+
+Starlette (et **FastAPI**) s’appuie sur AnyIO, ce qui le rend compatible à la fois avec la bibliothèque standard asyncio de Python et avec Trio.
+
+En particulier, vous pouvez utiliser directement AnyIO pour vos cas d’usage de concurrence avancés qui nécessitent des schémas plus élaborés dans votre propre code.
+
+Et même si vous n’utilisiez pas FastAPI, vous pourriez aussi écrire vos propres applications async avec AnyIO pour une grande compatibilité et pour bénéficier de ses avantages (par ex. la « structured concurrency »).
+
+J’ai créé une autre bibliothèque au-dessus d’AnyIO, comme une fine surcouche, pour améliorer un peu les annotations de type et obtenir une meilleure **autocomplétion**, des **erreurs en ligne**, etc. Elle propose également une introduction et un tutoriel accessibles pour vous aider à **comprendre** et écrire **votre propre code async** : Asyncer. Elle sera particulièrement utile si vous devez **combiner du code async avec du code classique** (bloquant/synchrone).
+
+### Autres formes de code asynchrone { #other-forms-of-asynchronous-code }
L'utilisation d'`async` et `await` est relativement nouvelle dans ce langage.
Mais cela rend la programmation asynchrone bien plus simple.
-Cette même syntaxe (ou presque) était aussi incluse dans les versions modernes de Javascript (dans les versions navigateur et NodeJS).
+Cette même syntaxe (ou presque) a aussi été incluse récemment dans les versions modernes de JavaScript (dans les navigateurs et NodeJS).
Mais avant ça, gérer du code asynchrone était bien plus complexe et difficile.
-Dans les versions précédentes de Python, vous auriez utilisé des *threads* ou Gevent. Mais le code aurait été bien plus difficile à comprendre, débugger, et concevoir.
+Dans les versions précédentes de Python, vous auriez utilisé des threads ou Gevent. Mais le code aurait été bien plus difficile à comprendre, débugger, et concevoir.
-Dans les versions précédentes de Javascript NodeJS / Navigateur, vous auriez utilisé des "callbacks". Menant potentiellement à ce que l'on appelle le "callback hell".
+Dans les versions précédentes de JavaScript côté navigateur / NodeJS, vous auriez utilisé des « callbacks ». Menant potentiellement à ce que l'on appelle le « callback hell ».
+## Coroutines { #coroutines }
-## Coroutines
+« Coroutine » est juste un terme élaboré pour désigner ce qui est retourné par une fonction définie avec `async def`. Python sait que c'est comme une fonction classique qui va démarrer à un moment et terminer à un autre, mais qu'elle peut aussi être mise en pause ⏸, du moment qu'il y a un `await` dans son contenu.
-**Coroutine** est juste un terme élaboré pour désigner ce qui est retourné par une fonction définie avec `async def`. Python sait que c'est comme une fonction classique qui va démarrer à un moment et terminer à un autre, mais qu'elle peut aussi être mise en pause ⏸, du moment qu'il y a un `await` dans son contenu.
+Mais toutes ces fonctionnalités d'utilisation de code asynchrone avec `async` et `await` sont souvent résumées comme l'utilisation des « coroutines ». On peut comparer cela à la principale fonctionnalité clé de Go, les « Goroutines ».
-Mais toutes ces fonctionnalités d'utilisation de code asynchrone avec `async` et `await` sont souvent résumées comme l'utilisation des *coroutines*. On peut comparer cela à la principale fonctionnalité clé de Go, les "Goroutines".
-
-## Conclusion
+## Conclusion { #conclusion }
Reprenons la phrase du début de la page :
-> Les versions modernes de Python supportent le **code asynchrone** grâce aux **"coroutines"** avec les syntaxes **`async` et `await`**.
+> Les versions modernes de Python supportent le **code asynchrone** grâce aux **« coroutines »** avec les syntaxes **`async` et `await`**.
Ceci devrait être plus compréhensible désormais. ✨
-Tout ceci est donc ce qui donne sa force à **FastAPI** (à travers Starlette) et lui permet d'avoir des performances aussi impressionnantes.
+Tout ceci est donc ce qui donne sa force à FastAPI (à travers Starlette) et lui permet d'avoir une performance aussi impressionnante.
-## Détails très techniques
+## Détails très techniques { #very-technical-details }
-/// warning | Attention !
+/// warning | Alertes
Vous pouvez probablement ignorer cela.
@@ -403,32 +413,32 @@ Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloqu
///
-### Fonctions de chemin
+### Fonctions de chemin d'accès { #path-operation-functions }
-Quand vous déclarez une *fonction de chemin* avec un `def` normal et non `async def`, elle est exécutée dans un groupe de threads (threadpool) externe qui est ensuite attendu, plutôt que d'être appelée directement (car cela bloquerait le serveur).
+Quand vous déclarez une *fonction de chemin d'accès* avec un `def` normal et non `async def`, elle est exécutée dans un groupe de threads (threadpool) externe qui est ensuite attendu, plutôt que d'être appelée directement (car cela bloquerait le serveur).
-Si vous venez d'un autre framework asynchrone qui ne fonctionne pas comme de la façon décrite ci-dessus et que vous êtes habitués à définir des *fonctions de chemin* basiques avec un simple `def` pour un faible gain de performance (environ 100 nanosecondes), veuillez noter que dans **FastAPI**, l'effet serait plutôt contraire. Dans ces cas-là, il vaut mieux utiliser `async def` à moins que votre *fonction de chemin* utilise du code qui effectue des opérations I/O bloquantes.
+Si vous venez d'un autre framework asynchrone qui ne fonctionne pas comme de la façon décrite ci-dessus et que vous êtes habitué à définir des *fonctions de chemin d'accès* basiques et purement calculatoires avec un simple `def` pour un faible gain de performance (environ 100 nanosecondes), veuillez noter que dans **FastAPI**, l'effet serait plutôt contraire. Dans ces cas-là, il vaut mieux utiliser `async def` à moins que votre *fonction de chemin d'accès* utilise du code qui effectue des opérations I/O bloquantes.
Au final, dans les deux situations, il est fort probable que **FastAPI** soit tout de même [plus rapide](index.md#performance){.internal-link target=_blank} que (ou au moins de vitesse égale à) votre framework précédent.
-### Dépendances
+### Dépendances { #dependencies }
-La même chose s'applique aux dépendances. Si une dépendance est définie avec `def` plutôt que `async def`, elle est exécutée dans la threadpool externe.
+La même chose s'applique aux [dépendances](tutorial/dependencies/index.md){.internal-link target=_blank}. Si une dépendance est définie avec `def` plutôt que `async def`, elle est exécutée dans la threadpool externe.
-### Sous-dépendances
+### Sous-dépendances { #sub-dependencies }
-Vous pouvez avoir de multiples dépendances et sous-dépendances dépendant les unes des autres (en tant que paramètres de la définition de la *fonction de chemin*), certaines créées avec `async def` et d'autres avec `def`. Cela fonctionnerait aussi, et celles définies avec un simple `def` seraient exécutées sur un thread externe (venant de la threadpool) plutôt que d'être "attendues".
+Vous pouvez avoir de multiples dépendances et [sous-dépendances](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} dépendant les unes des autres (en tant que paramètres de la définition de la *fonction de chemin d'accès*), certaines créées avec `async def` et d'autres avec `def`. Cela fonctionnerait aussi, et celles définies avec un simple `def` seraient exécutées sur un thread externe (venant de la threadpool) plutôt que d'être « attendues ».
-### Autres fonctions utilitaires
+### Autres fonctions utilitaires { #other-utility-functions }
-Toute autre fonction utilitaire que vous appelez directement peut être créée avec un classique `def` ou avec `async def` et **FastAPI** n'aura pas d'impact sur la façon dont vous l'appelez.
+Toute autre fonction utilitaire que vous appelez directement peut être créée avec un classique `def` ou avec `async def` et FastAPI n'aura pas d'impact sur la façon dont vous l'appelez.
-Contrairement aux fonctions que **FastAPI** appelle pour vous : les *fonctions de chemin* et dépendances.
+Contrairement aux fonctions que FastAPI appelle pour vous : les *fonctions de chemin d'accès* et dépendances.
-Si votre fonction utilitaire est une fonction classique définie avec `def`, elle sera appelée directement (telle qu'écrite dans votre code), pas dans une threadpool, si la fonction est définie avec `async def` alors vous devrez attendre (avec `await`) que cette fonction se termine avant de passer à la suite du code.
+Si votre fonction utilitaire est une fonction classique définie avec `def`, elle sera appelée directement (telle qu'écrite dans votre code), pas dans une threadpool ; si la fonction est définie avec `async def` alors vous devrez attendre (avec `await`) que cette fonction se termine avant de passer à la suite du code.
---
Encore une fois, ce sont des détails très techniques qui peuvent être utiles si vous venez ici les chercher.
-Sinon, les instructions de la section Vous êtes pressés ? ci-dessus sont largement suffisantes.
+Sinon, les instructions de la section Vous êtes pressés ? ci-dessus sont largement suffisantes.
diff --git a/docs/fr/docs/deployment/cloud.md b/docs/fr/docs/deployment/cloud.md
new file mode 100644
index 000000000..798a72a74
--- /dev/null
+++ b/docs/fr/docs/deployment/cloud.md
@@ -0,0 +1,24 @@
+# Déployer FastAPI sur des fournisseurs cloud { #deploy-fastapi-on-cloud-providers }
+
+Vous pouvez utiliser pratiquement n'importe quel fournisseur cloud pour déployer votre application FastAPI.
+
+Dans la plupart des cas, les principaux fournisseurs cloud proposent des guides pour déployer FastAPI avec leurs services.
+
+## FastAPI Cloud { #fastapi-cloud }
+
+**FastAPI Cloud** est créée par le même auteur et l'équipe à l'origine de **FastAPI**.
+
+Elle simplifie le processus de **création**, de **déploiement** et **d'accès** à une API avec un effort minimal.
+
+Elle apporte la même **expérience développeur** que celle de la création d'applications avec FastAPI au **déploiement** de celles-ci dans le cloud. 🎉
+
+FastAPI Cloud est le sponsor principal et le financeur des projets open source *FastAPI and friends*. ✨
+
+## Fournisseurs cloud - Sponsors { #cloud-providers-sponsors }
+
+D'autres fournisseurs cloud ✨ [**parrainent FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨ également. 🙇
+
+Vous pouvez également envisager ces fournisseurs pour suivre leurs guides et essayer leurs services :
+
+* Render
+* Railway
diff --git a/docs/fr/docs/deployment/concepts.md b/docs/fr/docs/deployment/concepts.md
new file mode 100644
index 000000000..59b8ddd1b
--- /dev/null
+++ b/docs/fr/docs/deployment/concepts.md
@@ -0,0 +1,321 @@
+# Concepts de déploiement { #deployments-concepts }
+
+Lorsque vous déployez une application **FastAPI**, ou en fait n'importe quel type de web API, il existe plusieurs concepts qui vous importent probablement, et en les utilisant vous pouvez trouver la manière la **plus appropriée** de **déployer votre application**.
+
+Parmi les concepts importants, on trouve :
+
+* Sécurité - HTTPS
+* Exécuter au démarrage
+* Redémarrages
+* Réplication (le nombre de processus en cours d'exécution)
+* Mémoire
+* Étapes préalables avant de démarrer
+
+Nous allons voir comment ils affectent les **déploiements**.
+
+Au final, l'objectif ultime est de pouvoir **servir vos clients d'API** de manière **sécurisée**, d'**éviter les interruptions**, et d'utiliser les **ressources de calcul** (par exemple des serveurs/VM distants) aussi efficacement que possible. 🚀
+
+Je vais vous en dire un peu plus ici sur ces **concepts**, ce qui devrait vous donner l'**intuition** nécessaire pour décider comment déployer votre API dans des environnements très différents, voire même dans des environnements **futurs** qui n'existent pas encore.
+
+En tenant compte de ces concepts, vous serez en mesure **d'évaluer et de concevoir** la meilleure façon de déployer **vos propres API**.
+
+Dans les chapitres suivants, je vous donnerai des **recettes concrètes** pour déployer des applications FastAPI.
+
+Mais pour l'instant, voyons ces **idées conceptuelles** importantes. Ces concepts s'appliquent aussi à tout autre type de web API. 💡
+
+## Sécurité - HTTPS { #security-https }
+
+Dans le [chapitre précédent à propos de HTTPS](https.md){.internal-link target=_blank}, nous avons vu comment HTTPS fournit le chiffrement pour votre API.
+
+Nous avons également vu que HTTPS est normalement fourni par un composant **externe** à votre serveur d'application, un **TLS Termination Proxy**.
+
+Et il doit y avoir quelque chose chargé de **renouveler les certificats HTTPS** ; cela peut être le même composant ou quelque chose de différent.
+
+### Exemples d’outils pour HTTPS { #example-tools-for-https }
+
+Parmi les outils que vous pourriez utiliser comme TLS Termination Proxy :
+
+* Traefik
+ * Gère automatiquement le renouvellement des certificats ✨
+* Caddy
+ * Gère automatiquement le renouvellement des certificats ✨
+* Nginx
+ * Avec un composant externe comme Certbot pour le renouvellement des certificats
+* HAProxy
+ * Avec un composant externe comme Certbot pour le renouvellement des certificats
+* Kubernetes avec un Ingress Controller comme Nginx
+ * Avec un composant externe comme cert-manager pour le renouvellement des certificats
+* Pris en charge en interne par un fournisseur cloud dans le cadre de ses services (lisez ci-dessous 👇)
+
+Une autre option consiste à utiliser un **service cloud** qui fait davantage de travail, y compris la mise en place de HTTPS. Il peut avoir certaines restrictions ou vous facturer davantage, etc. Mais dans ce cas, vous n'auriez pas à configurer vous‑même un TLS Termination Proxy.
+
+Je vous montrerai des exemples concrets dans les prochains chapitres.
+
+---
+
+Les concepts suivants à considérer concernent tous le programme qui exécute votre API réelle (par ex. Uvicorn).
+
+## Programme et processus { #program-and-process }
+
+Nous allons beaucoup parler du « **processus** » en cours d'exécution, il est donc utile d'être clair sur ce que cela signifie, et sur la différence avec le mot « **programme** ».
+
+### Qu'est-ce qu'un programme { #what-is-a-program }
+
+Le mot **programme** est couramment utilisé pour décrire plusieurs choses :
+
+* Le **code** que vous écrivez, les **fichiers Python**.
+* Le **fichier** qui peut être **exécuté** par le système d'exploitation, par exemple : `python`, `python.exe` ou `uvicorn`.
+* Un programme particulier lorsqu'il **s'exécute** sur le système d'exploitation, utilisant le CPU et stockant des choses en mémoire. On appelle aussi cela un **processus**.
+
+### Qu'est-ce qu'un processus { #what-is-a-process }
+
+Le mot **processus** est normalement utilisé de manière plus spécifique, en ne se référant qu'à l'élément qui s'exécute dans le système d'exploitation (comme dans le dernier point ci‑dessus) :
+
+* Un programme particulier lorsqu'il **s'exécute** sur le système d'exploitation.
+ * Cela ne se réfère ni au fichier, ni au code ; cela se réfère **spécifiquement** à l'élément qui est **exécuté** et géré par le système d'exploitation.
+* N'importe quel programme, n'importe quel code, **ne peut faire des choses** que lorsqu'il est **exécuté**. Donc, lorsqu'il y a un **processus en cours**.
+* Le processus peut être **arrêté** (ou « tué ») par vous ou par le système d'exploitation. À ce moment‑là, il cesse de s'exécuter/d'être exécuté, et il **ne peut plus rien faire**.
+* Chaque application que vous avez en cours d'exécution sur votre ordinateur a un processus derrière elle, chaque programme lancé, chaque fenêtre, etc. Et il y a normalement de nombreux processus exécutés **en même temps** tant qu'un ordinateur est allumé.
+* Il peut y avoir **plusieurs processus** du **même programme** exécutés simultanément.
+
+Si vous ouvrez le « gestionnaire des tâches » ou le « moniteur système » (ou des outils similaires) de votre système d'exploitation, vous verrez nombre de ces processus en cours d'exécution.
+
+Et, par exemple, vous verrez probablement qu'il y a plusieurs processus exécutant le même navigateur (Firefox, Chrome, Edge, etc.). Ils exécutent normalement un processus par onglet, plus quelques processus supplémentaires.
+
+
+
+---
+
+Maintenant que nous connaissons la différence entre les termes **processus** et **programme**, continuons à parler des déploiements.
+
+## Exécuter au démarrage { #running-on-startup }
+
+Dans la plupart des cas, lorsque vous créez une web API, vous voulez qu'elle **tourne en permanence**, sans interruption, afin que vos clients puissent toujours y accéder. Bien sûr, sauf si vous avez une raison spécifique de ne vouloir l'exécuter que dans certaines situations, mais la plupart du temps vous la voulez constamment en cours et **disponible**.
+
+### Sur un serveur distant { #in-a-remote-server }
+
+Lorsque vous configurez un serveur distant (un serveur cloud, une machine virtuelle, etc.), la chose la plus simple à faire est d'utiliser `fastapi run` (qui utilise Uvicorn) ou quelque chose de similaire, manuellement, de la même manière que lorsque vous développez en local.
+
+Et cela fonctionnera et sera utile **pendant le développement**.
+
+Mais si votre connexion au serveur est coupée, le **processus en cours** va probablement s'arrêter.
+
+Et si le serveur est redémarré (par exemple après des mises à jour, ou des migrations chez le fournisseur cloud) vous **ne le remarquerez probablement pas**. Et à cause de cela, vous ne saurez même pas que vous devez redémarrer le processus manuellement. Ainsi, votre API restera tout simplement à l'arrêt. 😱
+
+### Lancer automatiquement au démarrage { #run-automatically-on-startup }
+
+En général, vous voudrez probablement que le programme serveur (par ex. Uvicorn) soit démarré automatiquement au démarrage du serveur, et sans aucune **intervention humaine**, afin d'avoir en permanence un processus exécutant votre API (par ex. Uvicorn exécutant votre app FastAPI).
+
+### Programme séparé { #separate-program }
+
+Pour y parvenir, vous aurez normalement un **programme séparé** qui s'assure que votre application est lancée au démarrage. Et dans de nombreux cas, il s'assurera également que d'autres composants ou applications sont également lancés, par exemple une base de données.
+
+### Exemples d’outils pour lancer au démarrage { #example-tools-to-run-at-startup }
+
+Voici quelques exemples d'outils capables de faire ce travail :
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker en mode Swarm
+* Systemd
+* Supervisor
+* Pris en charge en interne par un fournisseur cloud dans le cadre de ses services
+* Autres ...
+
+Je vous donnerai des exemples plus concrets dans les prochains chapitres.
+
+## Redémarrages { #restarts }
+
+De la même manière que vous voulez vous assurer que votre application est lancée au démarrage, vous voulez probablement aussi vous assurer qu'elle est **redémarrée** après des échecs.
+
+### Nous faisons des erreurs { #we-make-mistakes }
+
+Nous, humains, faisons des **erreurs**, tout le temps. Les logiciels ont presque *toujours* des **bugs** cachés à différents endroits. 🐛
+
+Et nous, développeurs, continuons à améliorer le code au fur et à mesure que nous trouvons ces bugs et que nous implémentons de nouvelles fonctionnalités (en ajoutant éventuellement de nouveaux bugs aussi 😅).
+
+### Petites erreurs gérées automatiquement { #small-errors-automatically-handled }
+
+Lors de la création de web API avec FastAPI, s'il y a une erreur dans notre code, FastAPI la contiendra normalement à la seule requête qui a déclenché l'erreur. 🛡
+
+Le client recevra un **500 Internal Server Error** pour cette requête, mais l'application continuera de fonctionner pour les requêtes suivantes au lieu de simplement s'effondrer complètement.
+
+### Erreurs plus importantes - plantages { #bigger-errors-crashes }
+
+Néanmoins, il peut y avoir des cas où nous écrivons du code qui **fait planter l'application entière**, faisant planter Uvicorn et Python. 💥
+
+Et malgré cela, vous ne voudrez probablement pas que l'application reste à l'arrêt parce qu'il y a eu une erreur à un endroit ; vous voudrez probablement qu'elle **continue de tourner**, au moins pour les *chemins d'accès* qui ne sont pas cassés.
+
+### Redémarrer après un plantage { #restart-after-crash }
+
+Mais dans ces cas avec de très mauvaises erreurs qui font planter le **processus** en cours, vous voudrez un composant externe chargé de **redémarrer** le processus, au moins quelques fois ...
+
+/// tip | Astuce
+
+... Bien que si l'application entière **plante immédiatement**, il n'est probablement pas logique de continuer à la redémarrer indéfiniment. Mais dans ces cas, vous le remarquerez probablement pendant le développement, ou au moins juste après le déploiement.
+
+Concentrons‑nous donc sur les cas principaux, où elle pourrait planter entièrement dans certaines situations particulières **à l'avenir**, et où il est toujours logique de la redémarrer.
+
+///
+
+Vous voudrez probablement que l'élément chargé de redémarrer votre application soit un **composant externe**, car à ce stade, l'application elle‑même avec Uvicorn et Python a déjà planté, donc il n'y a rien dans le même code de la même app qui pourrait y faire quoi que ce soit.
+
+### Exemples d’outils pour redémarrer automatiquement { #example-tools-to-restart-automatically }
+
+Dans la plupart des cas, le même outil qui est utilisé pour **lancer le programme au démarrage** est également utilisé pour gérer les **redémarrages** automatiques.
+
+Par exemple, cela peut être géré par :
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker en mode Swarm
+* Systemd
+* Supervisor
+* Pris en charge en interne par un fournisseur cloud dans le cadre de ses services
+* Autres ...
+
+## Réplication - Processus et mémoire { #replication-processes-and-memory }
+
+Avec une application FastAPI, en utilisant un programme serveur comme la commande `fastapi` qui exécute Uvicorn, l'exécuter une fois dans **un processus** peut servir plusieurs clients simultanément.
+
+Mais dans de nombreux cas, vous voudrez exécuter plusieurs processus de travail en même temps.
+
+### Multiples processus - Workers { #multiple-processes-workers }
+
+Si vous avez plus de clients que ce qu'un seul processus peut gérer (par exemple si la machine virtuelle n'est pas très grande) et que vous avez **plusieurs cœurs** dans le CPU du serveur, alors vous pouvez avoir **plusieurs processus** exécutant la même application simultanément, et distribuer toutes les requêtes entre eux.
+
+Quand vous exécutez **plusieurs processus** du même programme d'API, on les appelle couramment des **workers**.
+
+### Processus workers et ports { #worker-processes-and-ports }
+
+Rappelez‑vous, d'après les documents [À propos de HTTPS](https.md){.internal-link target=_blank}, qu'un seul processus peut écouter une combinaison de port et d'adresse IP sur un serveur ?
+
+C'est toujours vrai.
+
+Donc, pour pouvoir avoir **plusieurs processus** en même temps, il doit y avoir un **seul processus à l'écoute sur un port** qui transmet ensuite la communication à chaque processus worker d'une manière ou d'une autre.
+
+### Mémoire par processus { #memory-per-process }
+
+Maintenant, lorsque le programme charge des choses en mémoire, par exemple, un modèle de machine learning dans une variable, ou le contenu d'un gros fichier dans une variable, tout cela **consomme une partie de la mémoire (RAM)** du serveur.
+
+Et plusieurs processus **ne partagent normalement pas de mémoire**. Cela signifie que chaque processus en cours a ses propres éléments, variables et mémoire. Et si vous consommez une grande quantité de mémoire dans votre code, **chaque processus** consommera une quantité équivalente de mémoire.
+
+### Mémoire du serveur { #server-memory }
+
+Par exemple, si votre code charge un modèle de Machine Learning de **1 Go**, lorsque vous exécutez un processus avec votre API, il consommera au moins 1 Go de RAM. Et si vous démarrez **4 processus** (4 workers), chacun consommera 1 Go de RAM. Donc au total, votre API consommera **4 Go de RAM**.
+
+Et si votre serveur distant ou votre machine virtuelle n'a que 3 Go de RAM, essayer de charger plus de 4 Go de RAM posera problème. 🚨
+
+### Multiples processus - Un exemple { #multiple-processes-an-example }
+
+Dans cet exemple, il y a un **processus gestionnaire** qui démarre et contrôle deux **processus workers**.
+
+Ce processus gestionnaire serait probablement celui qui écoute sur le **port** de l'IP. Et il transmettrait toute la communication aux processus workers.
+
+Ces processus workers seraient ceux qui exécutent votre application, ils effectueraient les calculs principaux pour recevoir une **requête** et renvoyer une **réponse**, et ils chargeraient tout ce que vous mettez dans des variables en RAM.
+
+
+
+Et bien sûr, la même machine aurait probablement **d'autres processus** en cours d'exécution également, en plus de votre application.
+
+Un détail intéressant est que le pourcentage de **CPU utilisé** par chaque processus peut **varier** fortement dans le temps, mais la **mémoire (RAM)** reste normalement plus ou moins **stable**.
+
+Si vous avez une API qui effectue une quantité comparable de calculs à chaque fois et que vous avez beaucoup de clients, alors l'**utilisation du CPU** sera probablement *également stable* (au lieu de monter et descendre rapidement en permanence).
+
+### Exemples d’outils et de stratégies de réplication { #examples-of-replication-tools-and-strategies }
+
+Il peut y avoir plusieurs approches pour y parvenir, et je vous en dirai plus sur des stratégies spécifiques dans les prochains chapitres, par exemple en parlant de Docker et des conteneurs.
+
+La principale contrainte à considérer est qu'il doit y avoir un **seul** composant gérant le **port** sur l'**IP publique**. Et il doit ensuite avoir un moyen de **transmettre** la communication aux **processus/workers** répliqués.
+
+Voici quelques combinaisons et stratégies possibles :
+
+* **Uvicorn** avec `--workers`
+ * Un **gestionnaire de processus** Uvicorn écouterait sur l'**IP** et le **port**, et il démarrerait **plusieurs processus workers Uvicorn**.
+* **Kubernetes** et autres systèmes **de conteneurs** distribués
+ * Quelque chose dans la couche **Kubernetes** écouterait sur l'**IP** et le **port**. La réplication se ferait en ayant **plusieurs conteneurs**, chacun avec **un processus Uvicorn** en cours.
+* **Services cloud** qui s'en chargent pour vous
+ * Le service cloud **gérera probablement la réplication pour vous**. Il vous permettra éventuellement de définir **un processus à exécuter**, ou une **image de conteneur** à utiliser ; dans tous les cas, ce sera très probablement **un seul processus Uvicorn**, et le service cloud sera chargé de le répliquer.
+
+/// tip | Astuce
+
+Ne vous inquiétez pas si certains de ces éléments concernant les **conteneurs**, Docker ou Kubernetes ne sont pas encore très clairs.
+
+Je vous en dirai plus sur les images de conteneurs, Docker, Kubernetes, etc. dans un chapitre à venir : [FastAPI dans des conteneurs - Docker](docker.md){.internal-link target=_blank}.
+
+///
+
+## Étapes préalables avant de démarrer { #previous-steps-before-starting }
+
+Il existe de nombreux cas où vous souhaitez effectuer certaines étapes **avant de démarrer** votre application.
+
+Par exemple, vous pourriez vouloir exécuter des **migrations de base de données**.
+
+Mais dans la plupart des cas, vous voudrez effectuer ces étapes **une seule fois**.
+
+Vous voudrez donc avoir un **processus unique** pour effectuer ces **étapes préalables**, avant de démarrer l'application.
+
+Et vous devez vous assurer que c'est un processus unique qui exécute ces étapes préalables *même si*, ensuite, vous démarrez **plusieurs processus** (plusieurs workers) pour l'application elle‑même. Si ces étapes étaient exécutées par **plusieurs processus**, ils **dupliqueraient** le travail en l'exécutant **en parallèle**, et si les étapes étaient délicates comme une migration de base de données, elles pourraient entrer en conflit les unes avec les autres.
+
+Bien sûr, il y a des cas où il n'y a aucun problème à exécuter les étapes préalables plusieurs fois ; dans ce cas, c'est beaucoup plus simple à gérer.
+
+/// tip | Astuce
+
+Gardez aussi à l'esprit que selon votre configuration, dans certains cas vous **n'aurez peut‑être même pas besoin d'étapes préalables** avant de démarrer votre application.
+
+Dans ce cas, vous n'auriez pas à vous soucier de tout cela. 🤷
+
+///
+
+### Exemples de stratégies pour les étapes préalables { #examples-of-previous-steps-strategies }
+
+Cela **dépendra fortement** de la manière dont vous **déployez votre système**, et sera probablement lié à votre manière de démarrer les programmes, de gérer les redémarrages, etc.
+
+Voici quelques idées possibles :
+
+* Un « Init Container » dans Kubernetes qui s'exécute avant votre conteneur d'application
+* Un script bash qui exécute les étapes préalables puis démarre votre application
+ * Vous aurez toujours besoin d'un moyen de démarrer/redémarrer *ce* script bash, de détecter les erreurs, etc.
+
+/// tip | Astuce
+
+Je vous donnerai des exemples plus concrets pour faire cela avec des conteneurs dans un chapitre à venir : [FastAPI dans des conteneurs - Docker](docker.md){.internal-link target=_blank}.
+
+///
+
+## Utilisation des ressources { #resource-utilization }
+
+Votre ou vos serveurs constituent une **ressource** que vos programmes peuvent consommer ou **utiliser** : le temps de calcul des CPU et la mémoire RAM disponible.
+
+Quelle quantité des ressources système voulez‑vous consommer/utiliser ? Il peut être facile de penser « pas beaucoup », mais en réalité, vous voudrez probablement consommer **le plus possible sans planter**.
+
+Si vous payez pour 3 serveurs mais que vous n'utilisez qu'un petit peu de leur RAM et CPU, vous **gaspillez probablement de l'argent** 💸, et **gaspillez probablement l'électricité des serveurs** 🌎, etc.
+
+Dans ce cas, il pourrait être préférable de n'avoir que 2 serveurs et d'utiliser un pourcentage plus élevé de leurs ressources (CPU, mémoire, disque, bande passante réseau, etc.).
+
+À l'inverse, si vous avez 2 serveurs et que vous utilisez **100 % de leur CPU et de leur RAM**, à un moment donné un processus demandera plus de mémoire, et le serveur devra utiliser le disque comme « mémoire » (ce qui peut être des milliers de fois plus lent), voire **planter**. Ou un processus pourrait avoir besoin de faire un calcul et devrait attendre que le CPU soit à nouveau libre.
+
+Dans ce cas, il serait préférable d'obtenir **un serveur supplémentaire** et d'y exécuter certains processus afin qu'ils aient tous **suffisamment de RAM et de temps CPU**.
+
+Il est également possible que, pour une raison quelconque, vous ayez un **pic** d'utilisation de votre API. Peut‑être qu'elle devient virale, ou peut‑être que d'autres services ou bots commencent à l'utiliser. Et vous voudrez peut‑être disposer de ressources supplémentaires pour être en sécurité dans ces cas.
+
+Vous pouvez définir un **chiffre arbitraire** comme cible, par exemple **entre 50 % et 90 %** d'utilisation des ressources. L'idée est que ce sont probablement les principaux éléments que vous voudrez mesurer et utiliser pour ajuster vos déploiements.
+
+Vous pouvez utiliser des outils simples comme `htop` pour voir le CPU et la RAM utilisés sur votre serveur ou la quantité utilisée par chaque processus. Ou vous pouvez utiliser des outils de supervision plus complexes, éventuellement distribués sur plusieurs serveurs, etc.
+
+## Récapitulatif { #recap }
+
+Vous venez de lire ici certains des principaux concepts que vous devrez probablement garder à l'esprit lorsque vous décidez comment déployer votre application :
+
+* Sécurité - HTTPS
+* Exécuter au démarrage
+* Redémarrages
+* Réplication (le nombre de processus en cours d'exécution)
+* Mémoire
+* Étapes préalables avant de démarrer
+
+Comprendre ces idées et comment les appliquer devrait vous donner l'intuition nécessaire pour prendre toutes les décisions lors de la configuration et de l'ajustement de vos déploiements. 🤓
+
+Dans les sections suivantes, je vous donnerai des exemples plus concrets de stratégies possibles à suivre. 🚀
diff --git a/docs/fr/docs/deployment/docker.md b/docs/fr/docs/deployment/docker.md
index ec30f9607..2d86d4a40 100644
--- a/docs/fr/docs/deployment/docker.md
+++ b/docs/fr/docs/deployment/docker.md
@@ -14,7 +14,7 @@ Vous êtes pressé et vous connaissez déjà tout ça ? Allez directement au [`D
+
+Mais vous pouvez la désactiver en définissant `syntaxHighlight` à `False` :
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+... et ensuite Swagger UI n'affichera plus la coloration syntaxique :
+
+
+
+## Modifier le thème { #change-the-theme }
+
+De la même manière, vous pouvez définir le thème de la coloration syntaxique avec la clé « syntaxHighlight.theme » (remarquez le point au milieu) :
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+Cette configuration modifierait le thème de couleurs de la coloration syntaxique :
+
+
+
+## Modifier les paramètres Swagger UI par défaut { #change-default-swagger-ui-parameters }
+
+FastAPI inclut des paramètres de configuration par défaut adaptés à la plupart des cas d'utilisation.
+
+Il inclut ces configurations par défaut :
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+Vous pouvez remplacer n'importe lequel d'entre eux en définissant une valeur différente dans l'argument `swagger_ui_parameters`.
+
+Par exemple, pour désactiver `deepLinking`, vous pourriez passer ces paramètres à `swagger_ui_parameters` :
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## Autres paramètres de Swagger UI { #other-swagger-ui-parameters }
+
+Pour voir toutes les autres configurations possibles que vous pouvez utiliser, lisez la documentation officielle des paramètres de Swagger UI.
+
+## Paramètres JavaScript uniquement { #javascript-only-settings }
+
+Swagger UI permet également d'autres configurations qui sont des objets réservés à JavaScript (par exemple, des fonctions JavaScript).
+
+FastAPI inclut aussi ces paramètres `presets` réservés à JavaScript :
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+Ce sont des objets **JavaScript**, pas des chaînes, vous ne pouvez donc pas les passer directement depuis du code Python.
+
+Si vous devez utiliser des configurations réservées à JavaScript comme celles-ci, vous pouvez utiliser l'une des méthodes ci-dessus. Surchargez entièrement le *chemin d'accès* Swagger UI et écrivez manuellement tout JavaScript nécessaire.
diff --git a/docs/fr/docs/how-to/custom-docs-ui-assets.md b/docs/fr/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 000000000..d239a9696
--- /dev/null
+++ b/docs/fr/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# Héberger en propre les ressources statiques de l’UI des docs personnalisées { #custom-docs-ui-static-assets-self-hosting }
+
+Les documents de l’API utilisent **Swagger UI** et **ReDoc**, et chacune nécessite des fichiers JavaScript et CSS.
+
+Par défaut, ces fichiers sont servis depuis un CDN.
+
+Mais il est possible de le personnaliser : vous pouvez définir un CDN spécifique, ou servir vous‑même les fichiers.
+
+## Configurer un CDN personnalisé pour JavaScript et CSS { #custom-cdn-for-javascript-and-css }
+
+Supposons que vous souhaitiez utiliser un autre CDN, par exemple vous voulez utiliser `https://unpkg.com/`.
+
+Cela peut être utile si, par exemple, vous vivez dans un pays qui restreint certaines URL.
+
+### Désactiver les docs automatiques { #disable-the-automatic-docs }
+
+La première étape consiste à désactiver les docs automatiques, car par défaut elles utilisent le CDN par défaut.
+
+Pour les désactiver, définissez leurs URL sur `None` lors de la création de votre application `FastAPI` :
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### Inclure les docs personnalisées { #include-the-custom-docs }
+
+Vous pouvez maintenant créer les chemins d'accès pour les docs personnalisées.
+
+Vous pouvez réutiliser les fonctions internes de FastAPI pour créer les pages HTML de la documentation et leur passer les arguments nécessaires :
+
+- `openapi_url` : l’URL où la page HTML des docs peut récupérer le schéma OpenAPI de votre API. Vous pouvez utiliser ici l’attribut `app.openapi_url`.
+- `title` : le titre de votre API.
+- `oauth2_redirect_url` : vous pouvez utiliser `app.swagger_ui_oauth2_redirect_url` ici pour utiliser la valeur par défaut.
+- `swagger_js_url` : l’URL où la page HTML de Swagger UI peut récupérer le fichier **JavaScript**. C’est l’URL du CDN personnalisé.
+- `swagger_css_url` : l’URL où la page HTML de Swagger UI peut récupérer le fichier **CSS**. C’est l’URL du CDN personnalisé.
+
+Et de même pour ReDoc ...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | Astuce
+
+Le chemin d'accès pour `swagger_ui_redirect` est un assistant lorsque vous utilisez OAuth2.
+
+Si vous intégrez votre API à un fournisseur OAuth2, vous pourrez vous authentifier et revenir aux docs de l’API avec les identifiants acquis. Et interagir avec elle en utilisant la véritable authentification OAuth2.
+
+Swagger UI s’en chargera en arrière‑plan pour vous, mais il a besoin de cet assistant « redirect ».
+
+///
+
+### Créer un chemin d'accès pour tester { #create-a-path-operation-to-test-it }
+
+Maintenant, pour pouvoir vérifier que tout fonctionne, créez un chemin d'accès :
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### Tester { #test-it }
+
+Vous devriez maintenant pouvoir aller à vos docs sur http://127.0.0.1:8000/docs, puis recharger la page : elle chargera ces ressources depuis le nouveau CDN.
+
+## Héberger en propre JavaScript et CSS pour les docs { #self-hosting-javascript-and-css-for-docs }
+
+Héberger vous‑même le JavaScript et le CSS peut être utile si, par exemple, votre application doit continuer de fonctionner même hors ligne, sans accès Internet ouvert, ou sur un réseau local.
+
+Vous verrez ici comment servir ces fichiers vous‑même, dans la même application FastAPI, et configurer les docs pour les utiliser.
+
+### Structure des fichiers du projet { #project-file-structure }
+
+Supposons que la structure de vos fichiers de projet ressemble à ceci :
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+Créez maintenant un répertoire pour stocker ces fichiers statiques.
+
+Votre nouvelle structure de fichiers pourrait ressembler à ceci :
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### Télécharger les fichiers { #download-the-files }
+
+Téléchargez les fichiers statiques nécessaires aux docs et placez‑les dans ce répertoire `static/`.
+
+Vous pouvez probablement cliquer avec le bouton droit sur chaque lien et choisir une option similaire à « Enregistrer le lien sous ... ».
+
+**Swagger UI** utilise les fichiers :
+
+- `swagger-ui-bundle.js`
+- `swagger-ui.css`
+
+Et **ReDoc** utilise le fichier :
+
+- `redoc.standalone.js`
+
+Après cela, votre structure de fichiers pourrait ressembler à :
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### Servir les fichiers statiques { #serve-the-static-files }
+
+- Importer `StaticFiles`.
+- « Monter » une instance `StaticFiles()` sur un chemin spécifique.
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### Tester les fichiers statiques { #test-the-static-files }
+
+Démarrez votre application et rendez‑vous sur http://127.0.0.1:8000/static/redoc.standalone.js.
+
+Vous devriez voir un très long fichier JavaScript pour **ReDoc**.
+
+Il pourrait commencer par quelque chose comme :
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+Cela confirme que vous parvenez à servir des fichiers statiques depuis votre application et que vous avez placé les fichiers statiques des docs au bon endroit.
+
+Nous pouvons maintenant configurer l’application pour utiliser ces fichiers statiques pour les docs.
+
+### Désactiver les docs automatiques pour les fichiers statiques { #disable-the-automatic-docs-for-static-files }
+
+Comme lors de l’utilisation d’un CDN personnalisé, la première étape consiste à désactiver les docs automatiques, car elles utilisent un CDN par défaut.
+
+Pour les désactiver, définissez leurs URL sur `None` lors de la création de votre application `FastAPI` :
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### Inclure les docs personnalisées pour les fichiers statiques { #include-the-custom-docs-for-static-files }
+
+Et comme avec un CDN personnalisé, vous pouvez maintenant créer les chemins d'accès pour les docs personnalisées.
+
+Là encore, vous pouvez réutiliser les fonctions internes de FastAPI pour créer les pages HTML de la documentation et leur passer les arguments nécessaires :
+
+- `openapi_url` : l’URL où la page HTML des docs peut récupérer le schéma OpenAPI de votre API. Vous pouvez utiliser ici l’attribut `app.openapi_url`.
+- `title` : le titre de votre API.
+- `oauth2_redirect_url` : vous pouvez utiliser `app.swagger_ui_oauth2_redirect_url` ici pour utiliser la valeur par défaut.
+- `swagger_js_url` : l’URL où la page HTML de Swagger UI peut récupérer le fichier **JavaScript**. **C’est celui que votre propre application sert désormais**.
+- `swagger_css_url` : l’URL où la page HTML de Swagger UI peut récupérer le fichier **CSS**. **C’est celui que votre propre application sert désormais**.
+
+Et de même pour ReDoc ...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | Astuce
+
+Le chemin d'accès pour `swagger_ui_redirect` est un assistant lorsque vous utilisez OAuth2.
+
+Si vous intégrez votre API à un fournisseur OAuth2, vous pourrez vous authentifier et revenir aux docs de l’API avec les identifiants acquis. Et interagir avec elle en utilisant la véritable authentification OAuth2.
+
+Swagger UI s’en chargera en arrière‑plan pour vous, mais il a besoin de cet assistant « redirect ».
+
+///
+
+### Créer un chemin d'accès pour tester les fichiers statiques { #create-a-path-operation-to-test-static-files }
+
+Maintenant, pour pouvoir vérifier que tout fonctionne, créez un chemin d'accès :
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### Tester l’UI avec des fichiers statiques { #test-static-files-ui }
+
+Vous devriez maintenant pouvoir couper votre Wi‑Fi, aller à vos docs sur http://127.0.0.1:8000/docs et recharger la page.
+
+Et même sans Internet, vous pourrez voir la documentation de votre API et interagir avec elle.
diff --git a/docs/fr/docs/how-to/custom-request-and-route.md b/docs/fr/docs/how-to/custom-request-and-route.md
new file mode 100644
index 000000000..506187d9f
--- /dev/null
+++ b/docs/fr/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# Personnaliser les classes Request et APIRoute { #custom-request-and-apiroute-class }
+
+Dans certains cas, vous pouvez vouloir surcharger la logique utilisée par les classes `Request` et `APIRoute`.
+
+En particulier, cela peut être une bonne alternative à une logique dans un middleware.
+
+Par exemple, si vous voulez lire ou manipuler le corps de la requête avant qu'il ne soit traité par votre application.
+
+/// danger | Danger
+
+Ceci est une fonctionnalité « avancée ».
+
+Si vous débutez avec **FastAPI**, vous pouvez ignorer cette section.
+
+///
+
+## Cas d'utilisation { #use-cases }
+
+Voici quelques cas d'utilisation :
+
+* Convertir des corps de requête non JSON en JSON (par exemple `msgpack`).
+* Décompresser des corps de requête compressés en gzip.
+* Journaliser automatiquement tous les corps de requête.
+
+## Gérer les encodages personnalisés du corps de la requête { #handling-custom-request-body-encodings }
+
+Voyons comment utiliser une sous-classe personnalisée de `Request` pour décompresser des requêtes gzip.
+
+Et une sous-classe d'`APIRoute` pour utiliser cette classe de requête personnalisée.
+
+### Créer une classe `GzipRequest` personnalisée { #create-a-custom-gziprequest-class }
+
+/// tip | Astuce
+
+Il s'agit d'un exemple simplifié pour montrer le fonctionnement ; si vous avez besoin de la prise en charge de Gzip, vous pouvez utiliser le [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} fourni.
+
+///
+
+Commencez par créer une classe `GzipRequest`, qui va surcharger la méthode `Request.body()` pour décompresser le corps en présence d'un en-tête approprié.
+
+S'il n'y a pas `gzip` dans l'en-tête, elle n'essaiera pas de décompresser le corps.
+
+De cette manière, la même classe de route peut gérer des requêtes gzip compressées ou non compressées.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### Créer une classe `GzipRoute` personnalisée { #create-a-custom-gziproute-class }
+
+Ensuite, nous créons une sous-classe personnalisée de `fastapi.routing.APIRoute` qui utilisera `GzipRequest`.
+
+Cette fois, elle va surcharger la méthode `APIRoute.get_route_handler()`.
+
+Cette méthode renvoie une fonction. Et c'est cette fonction qui recevra une requête et retournera une réponse.
+
+Ici, nous l'utilisons pour créer une `GzipRequest` à partir de la requête originale.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | Détails techniques
+
+Un `Request` possède un attribut `request.scope`, qui n'est qu'un `dict` Python contenant les métadonnées liées à la requête.
+
+Un `Request` a également un `request.receive`, qui est une fonction pour « recevoir » le corps de la requête.
+
+Le `dict` `scope` et la fonction `receive` font tous deux partie de la spécification ASGI.
+
+Et ces deux éléments, `scope` et `receive`, sont ce dont on a besoin pour créer une nouvelle instance de `Request`.
+
+Pour en savoir plus sur `Request`, consultez la documentation de Starlette sur les requêtes.
+
+///
+
+La seule chose que fait différemment la fonction renvoyée par `GzipRequest.get_route_handler`, c'est de convertir la `Request` en `GzipRequest`.
+
+Ce faisant, notre `GzipRequest` se chargera de décompresser les données (si nécessaire) avant de les transmettre à nos *chemins d'accès*.
+
+Après cela, toute la logique de traitement est identique.
+
+Mais grâce à nos modifications dans `GzipRequest.body`, le corps de la requête sera automatiquement décompressé lorsque **FastAPI** le chargera, si nécessaire.
+
+## Accéder au corps de la requête dans un gestionnaire d'exceptions { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | Astuce
+
+Pour résoudre ce même problème, il est probablement beaucoup plus simple d'utiliser `body` dans un gestionnaire personnalisé pour `RequestValidationError` ([Gérer les erreurs](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}).
+
+Mais cet exemple reste valable et montre comment interagir avec les composants internes.
+
+///
+
+Nous pouvons également utiliser cette même approche pour accéder au corps de la requête dans un gestionnaire d'exceptions.
+
+Il suffit de traiter la requête dans un bloc `try`/`except` :
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+Si une exception se produit, l'instance de `Request` sera toujours dans la portée, ce qui nous permet de lire et d'utiliser le corps de la requête lors du traitement de l'erreur :
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## Utiliser une classe `APIRoute` personnalisée dans un routeur { #custom-apiroute-class-in-a-router }
+
+Vous pouvez également définir le paramètre `route_class` d'un `APIRouter` :
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+Dans cet exemple, les *chemins d'accès* sous le `router` utiliseront la classe personnalisée `TimedRoute`, et auront un en-tête supplémentaire `X-Response-Time` dans la réponse avec le temps nécessaire pour générer la réponse :
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/fr/docs/how-to/extending-openapi.md b/docs/fr/docs/how-to/extending-openapi.md
new file mode 100644
index 000000000..1c540ea6c
--- /dev/null
+++ b/docs/fr/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# Étendre OpenAPI { #extending-openapi }
+
+Il existe des cas où vous pouvez avoir besoin de modifier le schéma OpenAPI généré.
+
+Dans cette section, vous verrez comment faire.
+
+## Le processus normal { #the-normal-process }
+
+Le processus normal (par défaut) est le suivant.
+
+Une application (instance) `FastAPI` a une méthode `.openapi()` censée retourner le schéma OpenAPI.
+
+Lors de la création de l'objet application, un *chemin d'accès* pour `/openapi.json` (ou pour l'URL que vous avez définie dans votre `openapi_url`) est enregistré.
+
+Il renvoie simplement une réponse JSON avec le résultat de la méthode `.openapi()` de l'application.
+
+Par défaut, la méthode `.openapi()` vérifie la propriété `.openapi_schema` pour voir si elle contient des données et les renvoie.
+
+Sinon, elle les génère à l'aide de la fonction utilitaire `fastapi.openapi.utils.get_openapi`.
+
+Et cette fonction `get_openapi()` reçoit comme paramètres :
+
+* `title` : Le titre OpenAPI, affiché dans les documents.
+* `version` : La version de votre API, p. ex. `2.5.0`.
+* `openapi_version` : La version de la spécification OpenAPI utilisée. Par défaut, la plus récente : `3.1.0`.
+* `summary` : Un court résumé de l'API.
+* `description` : La description de votre API ; elle peut inclure du markdown et sera affichée dans la documentation.
+* `routes` : Une liste de routes ; chacune correspond à un *chemin d'accès* enregistré. Elles sont extraites de `app.routes`.
+
+/// info
+
+Le paramètre `summary` est disponible à partir d'OpenAPI 3.1.0, pris en charge par FastAPI 0.99.0 et versions ultérieures.
+
+///
+
+## Remplacer les valeurs par défaut { #overriding-the-defaults }
+
+En vous appuyant sur les informations ci-dessus, vous pouvez utiliser la même fonction utilitaire pour générer le schéma OpenAPI et remplacer chaque partie dont vous avez besoin.
+
+Par exemple, ajoutons l’extension OpenAPI de ReDoc pour inclure un logo personnalisé.
+
+### **FastAPI** normal { #normal-fastapi }
+
+Tout d’abord, écrivez votre application **FastAPI** comme d’habitude :
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### Générer le schéma OpenAPI { #generate-the-openapi-schema }
+
+Ensuite, utilisez la même fonction utilitaire pour générer le schéma OpenAPI, dans une fonction `custom_openapi()` :
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### Modifier le schéma OpenAPI { #modify-the-openapi-schema }
+
+Vous pouvez maintenant ajouter l’extension ReDoc, en ajoutant un `x-logo` personnalisé à l’« objet » `info` dans le schéma OpenAPI :
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### Mettre en cache le schéma OpenAPI { #cache-the-openapi-schema }
+
+Vous pouvez utiliser la propriété `.openapi_schema` comme « cache » pour stocker votre schéma généré.
+
+Ainsi, votre application n’aura pas à générer le schéma à chaque fois qu’un utilisateur ouvre les documents de votre API.
+
+Il ne sera généré qu’une seule fois, puis le même schéma en cache sera utilisé pour les requêtes suivantes.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### Remplacer la méthode { #override-the-method }
+
+Vous pouvez maintenant remplacer la méthode `.openapi()` par votre nouvelle fonction.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### Vérifier { #check-it }
+
+Une fois que vous allez sur http://127.0.0.1:8000/redoc, vous verrez que vous utilisez votre logo personnalisé (dans cet exemple, le logo de **FastAPI**) :
+
+
diff --git a/docs/fr/docs/how-to/general.md b/docs/fr/docs/how-to/general.md
new file mode 100644
index 000000000..09d4498ac
--- /dev/null
+++ b/docs/fr/docs/how-to/general.md
@@ -0,0 +1,39 @@
+# Général - Guides pratiques - Recettes { #general-how-to-recipes }
+
+Voici plusieurs renvois vers d'autres endroits de la documentation, pour des questions générales ou fréquentes.
+
+## Filtrer des données - Sécurité { #filter-data-security }
+
+Pour vous assurer que vous ne renvoyez pas plus de données que nécessaire, lisez la documentation [Tutoriel - Modèle de réponse - Type de retour](../tutorial/response-model.md){.internal-link target=_blank}.
+
+## Étiquettes de documentation - OpenAPI { #documentation-tags-openapi }
+
+Pour ajouter des étiquettes à vos *chemins d'accès* et les regrouper dans l'interface utilisateur de la documentation, lisez la documentation [Tutoriel - Configurations de chemin d'accès - Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}.
+
+## Résumé et description de la documentation - OpenAPI { #documentation-summary-and-description-openapi }
+
+Pour ajouter un résumé et une description à vos *chemins d'accès* et les afficher dans l'interface utilisateur de la documentation, lisez la documentation [Tutoriel - Configurations de chemin d'accès - Résumé et description](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank}.
+
+## Description de la réponse dans la documentation - OpenAPI { #documentation-response-description-openapi }
+
+Pour définir la description de la réponse, affichée dans l'interface utilisateur de la documentation, lisez la documentation [Tutoriel - Configurations de chemin d'accès - Description de la réponse](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank}.
+
+## Déprécier un *chemin d'accès* dans la documentation - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+Pour déprécier un *chemin d'accès* et l'indiquer dans l'interface utilisateur de la documentation, lisez la documentation [Tutoriel - Configurations de chemin d'accès - Déprécier un chemin d'accès](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank}.
+
+## Convertir n'importe quelles données au format compatible JSON { #convert-any-data-to-json-compatible }
+
+Pour convertir des données vers un format compatible JSON, lisez la documentation [Tutoriel - Encodeur compatible JSON](../tutorial/encoder.md){.internal-link target=_blank}.
+
+## Métadonnées OpenAPI - Documentation { #openapi-metadata-docs }
+
+Pour ajouter des métadonnées à votre schéma OpenAPI, y compris une licence, une version, un contact, etc., lisez la documentation [Tutoriel - Métadonnées et URLs de la documentation](../tutorial/metadata.md){.internal-link target=_blank}.
+
+## URL OpenAPI personnalisée { #openapi-custom-url }
+
+Pour personnaliser l'URL OpenAPI (ou la supprimer), lisez la documentation [Tutoriel - Métadonnées et URLs de la documentation](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}.
+
+## URL de la documentation OpenAPI { #openapi-docs-urls }
+
+Pour mettre à jour les URL utilisées pour les interfaces utilisateur de documentation générées automatiquement, lisez la documentation [Tutoriel - Métadonnées et URLs de la documentation](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}.
diff --git a/docs/fr/docs/how-to/graphql.md b/docs/fr/docs/how-to/graphql.md
new file mode 100644
index 000000000..59cd1590f
--- /dev/null
+++ b/docs/fr/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+Comme **FastAPI** est basé sur la norme **ASGI**, il est très facile d'intégrer toute bibliothèque **GraphQL** également compatible avec ASGI.
+
+Vous pouvez combiner des *chemins d'accès* FastAPI classiques avec GraphQL dans la même application.
+
+/// tip | Astuce
+
+**GraphQL** résout des cas d'utilisation très spécifiques.
+
+Il présente des **avantages** et des **inconvénients** par rapport aux **API web** classiques.
+
+Assurez-vous d'évaluer si les **bénéfices** pour votre cas d'utilisation compensent les **inconvénients**. 🤓
+
+///
+
+## Bibliothèques GraphQL { #graphql-libraries }
+
+Voici quelques bibliothèques **GraphQL** qui prennent en charge **ASGI**. Vous pouvez les utiliser avec **FastAPI** :
+
+* Strawberry 🍓
+ * Avec la documentation pour FastAPI
+* Ariadne
+ * Avec la documentation pour FastAPI
+* Tartiflette
+ * Avec Tartiflette ASGI pour fournir l'intégration ASGI
+* Graphene
+ * Avec starlette-graphene3
+
+## GraphQL avec Strawberry { #graphql-with-strawberry }
+
+Si vous avez besoin ou souhaitez travailler avec **GraphQL**, **Strawberry** est la bibliothèque **recommandée** car sa conception est la plus proche de celle de **FastAPI**, tout est basé sur des **annotations de type**.
+
+Selon votre cas d'utilisation, vous pourriez préférer une autre bibliothèque, mais si vous me le demandiez, je vous suggérerais probablement d'essayer **Strawberry**.
+
+Voici un petit aperçu de la manière dont vous pouvez intégrer Strawberry avec FastAPI :
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+Vous pouvez en apprendre davantage sur Strawberry dans la documentation de Strawberry.
+
+Et également la documentation sur Strawberry avec FastAPI.
+
+## Ancien `GraphQLApp` de Starlette { #older-graphqlapp-from-starlette }
+
+Les versions précédentes de Starlette incluaient une classe `GraphQLApp` pour s'intégrer à Graphene.
+
+Elle a été dépréciée dans Starlette, mais si vous avez du code qui l'utilisait, vous pouvez facilement **migrer** vers starlette-graphene3, qui couvre le même cas d'utilisation et propose une **interface presque identique**.
+
+/// tip | Astuce
+
+Si vous avez besoin de GraphQL, je vous recommande tout de même de regarder Strawberry, car il est basé sur des annotations de type plutôt que sur des classes et types personnalisés.
+
+///
+
+## En savoir plus { #learn-more }
+
+Vous pouvez en apprendre davantage sur **GraphQL** dans la documentation officielle de GraphQL.
+
+Vous pouvez également en lire davantage sur chacune des bibliothèques décrites ci-dessus via leurs liens.
diff --git a/docs/fr/docs/how-to/index.md b/docs/fr/docs/how-to/index.md
new file mode 100644
index 000000000..03736fa43
--- /dev/null
+++ b/docs/fr/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# Comment faire - Recettes { #how-to-recipes }
+
+Vous trouverez ici différentes recettes ou des guides « comment faire » pour **plusieurs sujets**.
+
+La plupart de ces idées sont plus ou moins **indépendantes**, et dans la plupart des cas vous n'avez besoin de les étudier que si elles s'appliquent directement à **votre projet**.
+
+Si quelque chose vous paraît intéressant et utile pour votre projet, allez-y et consultez-le ; sinon, vous pouvez probablement simplement les ignorer.
+
+/// tip | Astuce
+
+Si vous voulez **apprendre FastAPI** de façon structurée (recommandé), allez lire le [Tutoriel - Guide utilisateur](../tutorial/index.md){.internal-link target=_blank} chapitre par chapitre à la place.
+
+///
diff --git a/docs/fr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/fr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 000000000..681cf697b
--- /dev/null
+++ b/docs/fr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Migrer de Pydantic v1 à Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+Si vous avez une ancienne application FastAPI, vous utilisez peut-être Pydantic version 1.
+
+FastAPI version 0.100.0 prenait en charge soit Pydantic v1 soit v2. Il utilisait celle que vous aviez installée.
+
+FastAPI version 0.119.0 a introduit une prise en charge partielle de Pydantic v1 depuis l'intérieur de Pydantic v2 (comme `pydantic.v1`), pour faciliter la migration vers v2.
+
+FastAPI 0.126.0 a supprimé la prise en charge de Pydantic v1, tout en continuant à prendre en charge `pydantic.v1` pendant un certain temps.
+
+/// warning | Alertes
+
+L'équipe Pydantic a arrêté la prise en charge de Pydantic v1 pour les dernières versions de Python, à partir de Python 3.14.
+
+Cela inclut `pydantic.v1`, qui n'est plus pris en charge à partir de Python 3.14.
+
+Si vous souhaitez utiliser les dernières fonctionnalités de Python, vous devez vous assurer que vous utilisez Pydantic v2.
+
+///
+
+Si vous avez une ancienne application FastAPI avec Pydantic v1, je vais vous montrer comment la migrer vers Pydantic v2, et les fonctionnalités de FastAPI 0.119.0 pour vous aider à une migration progressive.
+
+## Guide officiel { #official-guide }
+
+Pydantic propose un Guide de migration officiel de la v1 à la v2.
+
+Il inclut aussi ce qui a changé, comment les validations sont désormais plus correctes et strictes, les pièges possibles, etc.
+
+Vous pouvez le lire pour mieux comprendre ce qui a changé.
+
+## Tests { #tests }
+
+Vous devez vous assurer d'avoir des [tests](../tutorial/testing.md){.internal-link target=_blank} pour votre application et de les exécuter en intégration continue (CI).
+
+De cette façon, vous pouvez effectuer la mise à niveau et vous assurer que tout fonctionne toujours comme prévu.
+
+## `bump-pydantic` { #bump-pydantic }
+
+Dans de nombreux cas, lorsque vous utilisez des modèles Pydantic classiques sans personnalisations, vous pourrez automatiser la majeure partie du processus de migration de Pydantic v1 à Pydantic v2.
+
+Vous pouvez utiliser `bump-pydantic` de la même équipe Pydantic.
+
+Cet outil vous aidera à modifier automatiquement la majeure partie du code à adapter.
+
+Après cela, vous pouvez exécuter les tests et vérifier que tout fonctionne. Si c'est le cas, vous avez terminé. 😎
+
+## Pydantic v1 dans v2 { #pydantic-v1-in-v2 }
+
+Pydantic v2 inclut tout Pydantic v1 sous la forme du sous-module `pydantic.v1`. Mais cela n'est plus pris en charge dans les versions au-delà de Python 3.13.
+
+Cela signifie que vous pouvez installer la dernière version de Pydantic v2 et importer/utiliser les anciens composants de Pydantic v1 depuis ce sous-module, comme si vous aviez l'ancien Pydantic v1 installé.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### Prise en charge de FastAPI pour Pydantic v1 dans v2 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+Depuis FastAPI 0.119.0, il existe également une prise en charge partielle de Pydantic v1 depuis l'intérieur de Pydantic v2, pour faciliter la migration vers v2.
+
+Vous pouvez donc mettre à niveau Pydantic vers la dernière version 2 et modifier les imports pour utiliser le sous-module `pydantic.v1`, et dans de nombreux cas cela fonctionnera tel quel.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | Alertes
+
+Gardez à l'esprit que, puisque l'équipe Pydantic ne prend plus en charge Pydantic v1 dans les versions récentes de Python à partir de Python 3.14, l'utilisation de `pydantic.v1` n'est pas non plus prise en charge à partir de Python 3.14.
+
+///
+
+### Pydantic v1 et v2 dans la même application { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic ne prend pas en charge le fait d'avoir un modèle Pydantic v2 contenant des champs eux-mêmes définis comme des modèles Pydantic v1, et inversement.
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+... mais vous pouvez avoir des modèles séparés utilisant Pydantic v1 et v2 dans la même application.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+Dans certains cas, il est même possible d'avoir des modèles Pydantic v1 et v2 dans le même chemin d'accès de votre application FastAPI :
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+Dans l'exemple ci-dessus, le modèle d'entrée est un modèle Pydantic v1 et le modèle de sortie (défini dans `response_model=ItemV2`) est un modèle Pydantic v2.
+
+### Paramètres Pydantic v1 { #pydantic-v1-parameters }
+
+Si vous devez utiliser certains des outils spécifiques à FastAPI pour les paramètres comme `Body`, `Query`, `Form`, etc., avec des modèles Pydantic v1, vous pouvez les importer depuis `fastapi.temp_pydantic_v1_params` le temps de terminer la migration vers Pydantic v2 :
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### Migrer par étapes { #migrate-in-steps }
+
+/// tip | Astuce
+
+Essayez d'abord avec `bump-pydantic` ; si vos tests passent et que cela fonctionne, vous avez tout terminé en une seule commande. ✨
+
+///
+
+Si `bump-pydantic` ne fonctionne pas pour votre cas d'usage, vous pouvez utiliser la prise en charge des modèles Pydantic v1 et v2 dans la même application pour effectuer la migration vers Pydantic v2 progressivement.
+
+Vous pouvez d'abord mettre à niveau Pydantic pour utiliser la dernière version 2 et modifier les imports pour utiliser `pydantic.v1` pour tous vos modèles.
+
+Ensuite, vous pouvez commencer à migrer vos modèles de Pydantic v1 vers v2 par groupes, par étapes progressives. 🚶
diff --git a/docs/fr/docs/how-to/separate-openapi-schemas.md b/docs/fr/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 000000000..fd767d738
--- /dev/null
+++ b/docs/fr/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# Séparer les schémas OpenAPI pour l'entrée et la sortie ou non { #separate-openapi-schemas-for-input-and-output-or-not }
+
+Depuis la sortie de **Pydantic v2**, l'OpenAPI généré est un peu plus précis et **correct** qu'avant. 😎
+
+En fait, dans certains cas, il y aura même **deux schémas JSON** dans OpenAPI pour le même modèle Pydantic, pour l'entrée et pour la sortie, selon s'ils ont des **valeurs par défaut**.
+
+Voyons comment cela fonctionne et comment le modifier si vous devez le faire.
+
+## Utiliser des modèles Pydantic pour l'entrée et la sortie { #pydantic-models-for-input-and-output }
+
+Supposons que vous ayez un modèle Pydantic avec des valeurs par défaut, comme celui‑ci :
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### Modèle pour l'entrée { #model-for-input }
+
+Si vous utilisez ce modèle en entrée comme ici :
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+... alors, le champ `description` ne sera **pas requis**. Parce qu'il a une valeur par défaut de `None`.
+
+### Modèle d'entrée dans les documents { #input-model-in-docs }
+
+Vous pouvez le confirmer dans les documents, le champ `description` n'a pas d'**astérisque rouge**, il n'est pas indiqué comme requis :
+
+
+
+
+
+
+httpx - Obligatoire si vous souhaitez utiliser le `TestClient`.
* jinja2 - Obligatoire si vous souhaitez utiliser la configuration de template par défaut.
-* python-multipart - Obligatoire si vous souhaitez prendre en charge l’« parsing » de formulaires avec `request.form()`.
+* python-multipart - Obligatoire si vous souhaitez prendre en charge l’« parsing » de formulaires avec `request.form()`.
Utilisées par FastAPI :
diff --git a/docs/fr/docs/learn/index.md b/docs/fr/docs/learn/index.md
index 552687703..e595ecf78 100644
--- a/docs/fr/docs/learn/index.md
+++ b/docs/fr/docs/learn/index.md
@@ -2,4 +2,4 @@
Voici les sections introductives et les tutoriels pour apprendre **FastAPI**.
-Vous pouvez considérer ceci comme un **livre**, un **cours**, la **méthode officielle** et recommandée pour apprendre FastAPI. 😎
+Vous pouvez considérer ceci comme un **livre**, un **cours**, la méthode **officielle** et recommandée pour apprendre FastAPI. 😎
diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md
index f393b0f5c..770f1514a 100644
--- a/docs/fr/docs/python-types.md
+++ b/docs/fr/docs/python-types.md
@@ -1,8 +1,8 @@
# Introduction aux types Python { #python-types-intro }
-Python prend en charge des « type hints » (aussi appelées « annotations de type ») facultatives.
+Python prend en charge des « annotations de type » (aussi appelées « type hints ») facultatives.
-Ces « type hints » ou annotations sont une syntaxe spéciale qui permet de déclarer le type d'une variable.
+Ces **« annotations de type »** sont une syntaxe spéciale qui permet de déclarer le type d'une variable.
En déclarant les types de vos variables, les éditeurs et outils peuvent vous offrir un meilleur support.
@@ -22,7 +22,7 @@ Si vous êtes un expert Python, et que vous savez déjà tout sur les annotation
Commençons par un exemple simple :
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
Exécuter ce programme affiche :
@@ -34,9 +34,9 @@ La fonction fait ce qui suit :
* Prend un `first_name` et un `last_name`.
* Convertit la première lettre de chacun en majuscule avec `title()`.
-* Concatène ces deux valeurs avec un espace au milieu.
+* Concatène ces deux valeurs avec un espace au milieu.
-{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
### Modifier le code { #edit-it }
@@ -78,7 +78,7 @@ C'est tout.
Ce sont les « annotations de type » :
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
Ce n'est pas la même chose que de déclarer des valeurs par défaut, ce qui serait :
@@ -106,7 +106,7 @@ Avec cela, vous pouvez faire défiler en voyant les options, jusqu'à trouver ce
Regardez cette fonction, elle a déjà des annotations de type :
-{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
Comme l'éditeur connaît les types des variables, vous n'obtenez pas seulement l'autocomplétion, vous obtenez aussi des vérifications d'erreurs :
@@ -114,7 +114,7 @@ Comme l'éditeur connaît les types des variables, vous n'obtenez pas seulement
Vous savez maintenant qu'il faut corriger, convertir `age` en chaîne avec `str(age)` :
-{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
## Déclarer des types { #declaring-types }
@@ -133,29 +133,32 @@ Vous pouvez utiliser, par exemple :
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### Types génériques avec paramètres de type { #generic-types-with-type-parameters }
+### Module `typing` { #typing-module }
-Il existe certaines structures de données qui peuvent contenir d'autres valeurs, comme `dict`, `list`, `set` et `tuple`. Et les valeurs internes peuvent aussi avoir leur propre type.
+Pour certains cas d'utilisation supplémentaires, vous pourriez avoir besoin d'importer certains éléments depuis le module standard `typing`, par exemple lorsque vous voulez déclarer que quelque chose a « n'importe quel type », vous pouvez utiliser `Any` depuis `typing` :
-Ces types qui ont des types internes sont appelés types « génériques ». Et il est possible de les déclarer, même avec leurs types internes.
+```python
+from typing import Any
-Pour déclarer ces types et les types internes, vous pouvez utiliser le module standard Python `typing`. Il existe spécifiquement pour prendre en charge ces annotations de type.
-#### Versions plus récentes de Python { #newer-versions-of-python }
+def some_function(data: Any):
+ print(data)
+```
-La syntaxe utilisant `typing` est compatible avec toutes les versions, de Python 3.6 aux plus récentes, y compris Python 3.9, Python 3.10, etc.
+### Types génériques { #generic-types }
-Au fur et à mesure que Python évolue, les versions plus récentes apportent un meilleur support pour ces annotations de type et dans de nombreux cas vous n'aurez même pas besoin d'importer et d'utiliser le module `typing` pour les déclarer.
+Certains types peuvent prendre des « paramètres de type » entre crochets, pour définir leurs types internes, par exemple une « liste de chaînes » se déclarerait `list[str]`.
-Si vous pouvez choisir une version plus récente de Python pour votre projet, vous pourrez profiter de cette simplicité supplémentaire.
+Ces types qui peuvent prendre des paramètres de type sont appelés des **types génériques** ou **Generics**.
-Dans toute la documentation, il y a des exemples compatibles avec chaque version de Python (lorsqu'il y a une différence).
+Vous pouvez utiliser les mêmes types intégrés comme génériques (avec des crochets et des types à l'intérieur) :
-Par exemple « Python 3.6+ » signifie que c'est compatible avec Python 3.6 ou supérieur (y compris 3.7, 3.8, 3.9, 3.10, etc.). Et « Python 3.9+ » signifie que c'est compatible avec Python 3.9 ou supérieur (y compris 3.10, etc).
-
-Si vous pouvez utiliser les dernières versions de Python, utilisez les exemples pour la dernière version, ils auront la meilleure et la plus simple syntaxe, par exemple, « Python 3.10+ ».
+* `list`
+* `tuple`
+* `set`
+* `dict`
#### Liste { #list }
@@ -167,9 +170,9 @@ Comme type, mettez `list`.
Comme la liste est un type qui contient des types internes, mettez-les entre crochets :
-{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
-/// info
+/// info | Info
Ces types internes entre crochets sont appelés « paramètres de type ».
@@ -193,7 +196,7 @@ Et pourtant, l'éditeur sait que c'est un `str` et fournit le support approprié
Vous feriez la même chose pour déclarer des `tuple` et des `set` :
-{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
Cela signifie :
@@ -208,7 +211,7 @@ Le premier paramètre de type est pour les clés du `dict`.
Le second paramètre de type est pour les valeurs du `dict` :
-{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Cela signifie :
@@ -218,46 +221,22 @@ Cela signifie :
#### Union { #union }
-Vous pouvez déclarer qu'une variable peut être de plusieurs types, par exemple, un `int` ou un `str`.
+Vous pouvez déclarer qu'une variable peut être **plusieurs types**, par exemple, un `int` ou un `str`.
-Dans Python 3.6 et supérieur (y compris Python 3.10), vous pouvez utiliser le type `Union` de `typing` et mettre entre crochets les types possibles à accepter.
+Pour le définir, vous utilisez la barre verticale (`|`) pour séparer les deux types.
-Dans Python 3.10, il existe aussi une nouvelle syntaxe où vous pouvez mettre les types possibles séparés par une barre verticale (`|`).
-
-//// tab | Python 3.10+
+C'est ce qu'on appelle une « union », car la variable peut être n'importe quoi dans l'union de ces deux ensembles de types.
```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-////
-
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b_py39.py!}
-```
-
-////
-
-Dans les deux cas, cela signifie que `item` peut être un `int` ou un `str`.
+Cela signifie que `item` peut être un `int` ou un `str`.
#### Possiblement `None` { #possibly-none }
Vous pouvez déclarer qu'une valeur peut avoir un type, comme `str`, mais qu'elle peut aussi être `None`.
-Dans Python 3.6 et supérieur (y compris Python 3.10), vous pouvez le déclarer en important et en utilisant `Optional` depuis le module `typing`.
-
-```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-Utiliser `Optional[str]` au lieu de simplement `str` permettra à l'éditeur de vous aider à détecter des erreurs où vous supposeriez qu'une valeur est toujours un `str`, alors qu'elle pourrait en fait aussi être `None`.
-
-`Optional[Something]` est en réalité un raccourci pour `Union[Something, None]`, ils sont équivalents.
-
-Cela signifie aussi que dans Python 3.10, vous pouvez utiliser `Something | None` :
-
//// tab | Python 3.10+
```Python hl_lines="1"
@@ -266,96 +245,7 @@ Cela signifie aussi que dans Python 3.10, vous pouvez utiliser `Something | None
////
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-////
-
-//// tab | Python 3.9+ alternative
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b_py39.py!}
-```
-
-////
-
-#### Utiliser `Union` ou `Optional` { #using-union-or-optional }
-
-Si vous utilisez une version de Python inférieure à 3.10, voici un conseil de mon point de vue très **subjectif** :
-
-* 🚨 Évitez d'utiliser `Optional[SomeType]`
-* À la place ✨ **utilisez `Union[SomeType, None]`** ✨.
-
-Les deux sont équivalents et sous le capot ce sont les mêmes, mais je recommanderais `Union` plutôt que `Optional` parce que le mot « facultatif » semble impliquer que la valeur est optionnelle, alors que cela signifie en fait « elle peut être `None` », même si elle n'est pas facultative et est toujours requise.
-
-Je pense que `Union[SomeType, None]` est plus explicite sur ce que cela signifie.
-
-Il ne s'agit que des mots et des noms. Mais ces mots peuvent influencer la manière dont vous et vos coéquipiers pensez au code.
-
-Par exemple, prenons cette fonction :
-
-{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
-
-Le paramètre `name` est défini comme `Optional[str]`, mais il n'est pas facultatif, vous ne pouvez pas appeler la fonction sans le paramètre :
-
-```Python
-say_hi() # Oh non, cela lève une erreur ! 😱
-```
-
-Le paramètre `name` est toujours requis (pas « optionnel ») parce qu'il n'a pas de valeur par défaut. Néanmoins, `name` accepte `None` comme valeur :
-
-```Python
-say_hi(name=None) # Cela fonctionne, None est valide 🎉
-```
-
-La bonne nouvelle est que, dès que vous êtes sur Python 3.10, vous n'avez plus à vous en soucier, car vous pourrez simplement utiliser `|` pour définir des unions de types :
-
-{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
-
-Et alors vous n'aurez plus à vous soucier de noms comme `Optional` et `Union`. 😎
-
-#### Types génériques { #generic-types }
-
-Ces types qui prennent des paramètres de type entre crochets sont appelés des **types génériques** ou **Generics**, par exemple :
-
-//// tab | Python 3.10+
-
-Vous pouvez utiliser les mêmes types intégrés comme génériques (avec des crochets et des types à l'intérieur) :
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-Et, comme avec les versions précédentes de Python, depuis le module `typing` :
-
-* `Union`
-* `Optional`
-* ... et d'autres.
-
-Dans Python 3.10, comme alternative à l'utilisation des génériques `Union` et `Optional`, vous pouvez utiliser la barre verticale (`|`) pour déclarer des unions de types, c'est bien mieux et plus simple.
-
-////
-
-//// tab | Python 3.9+
-
-Vous pouvez utiliser les mêmes types intégrés comme génériques (avec des crochets et des types à l'intérieur) :
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-Et des génériques depuis le module `typing` :
-
-* `Union`
-* `Optional`
-* ... et d'autres.
-
-////
+Utiliser `str | None` au lieu de simplement `str` permettra à l'éditeur de vous aider à détecter des erreurs où vous supposeriez qu'une valeur est toujours un `str`, alors qu'elle pourrait en fait aussi être `None`.
### Classes en tant que types { #classes-as-types }
@@ -363,19 +253,19 @@ Vous pouvez aussi déclarer une classe comme type d'une variable.
Disons que vous avez une classe `Person`, avec un nom :
-{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
Vous pouvez ensuite déclarer une variable de type `Person` :
-{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
Et là encore, vous obtenez tout le support de l'éditeur :
-Remarquez que cela signifie « `one_person` est une instance de la classe `Person` ».
+Remarquez que cela signifie « `one_person` est une **instance** de la classe `Person` ».
-Cela ne signifie pas « `one_person` est la classe appelée `Person` ».
+Cela ne signifie pas « `one_person` est la **classe** appelée `Person` ».
## Modèles Pydantic { #pydantic-models }
@@ -393,7 +283,7 @@ Un exemple tiré de la documentation officielle de Pydantic :
{* ../../docs_src/python_types/tutorial011_py310.py *}
-/// info
+/// info | Info
Pour en savoir plus à propos de Pydantic, consultez sa documentation.
@@ -403,33 +293,27 @@ Pour en savoir plus à propos de champs Optionals requis.
-
-///
-
## Annotations de type avec métadonnées { #type-hints-with-metadata-annotations }
-Python dispose également d'une fonctionnalité qui permet de mettre des **métadonnées supplémentaires** dans ces annotations de type en utilisant `Annotated`.
+Python dispose également d'une fonctionnalité qui permet de mettre des **métadonnées supplémentaires** dans ces annotations de type en utilisant `Annotated`.
-Depuis Python 3.9, `Annotated` fait partie de la bibliothèque standard, vous pouvez donc l'importer depuis `typing`.
+Vous pouvez importer `Annotated` depuis `typing`.
-{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
Python lui-même ne fait rien avec ce `Annotated`. Et pour les éditeurs et autres outils, le type est toujours `str`.
Mais vous pouvez utiliser cet espace dans `Annotated` pour fournir à **FastAPI** des métadonnées supplémentaires sur la façon dont vous voulez que votre application se comporte.
-L'important à retenir est que le premier paramètre de type que vous passez à `Annotated` est le type réel. Le reste n'est que des métadonnées pour d'autres outils.
+L'important à retenir est que **le premier « paramètre de type »** que vous passez à `Annotated` est le **type réel**. Le reste n'est que des métadonnées pour d'autres outils.
Pour l'instant, vous avez juste besoin de savoir que `Annotated` existe, et que c'est du Python standard. 😎
-Plus tard, vous verrez à quel point cela peut être puissant.
+Plus tard, vous verrez à quel point cela peut être **puissant**.
/// tip | Astuce
-Le fait que ce soit du Python standard signifie que vous bénéficierez toujours de la meilleure expérience développeur possible dans votre éditeur, avec les outils que vous utilisez pour analyser et refactoriser votre code, etc. ✨
+Le fait que ce soit du **Python standard** signifie que vous bénéficierez toujours de la **meilleure expérience développeur possible** dans votre éditeur, avec les outils que vous utilisez pour analyser et refactoriser votre code, etc. ✨
Et aussi que votre code sera très compatible avec de nombreux autres outils et bibliothèques Python. 🚀
@@ -457,7 +341,7 @@ Tout cela peut sembler abstrait. Ne vous inquiétez pas. Vous verrez tout cela e
L'important est qu'en utilisant les types standards de Python, en un seul endroit (au lieu d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous.
-/// info
+/// info | Info
Si vous avez déjà parcouru tout le tutoriel et êtes revenu pour en voir plus sur les types, une bonne ressource est l'« aide-mémoire » de `mypy`.
diff --git a/docs/fr/docs/resources/index.md b/docs/fr/docs/resources/index.md
new file mode 100644
index 000000000..e62db346d
--- /dev/null
+++ b/docs/fr/docs/resources/index.md
@@ -0,0 +1,3 @@
+# Ressources { #resources }
+
+Ressources supplémentaires, liens externes et plus encore. ✈️
diff --git a/docs/fr/docs/translation-banner.md b/docs/fr/docs/translation-banner.md
new file mode 100644
index 000000000..9eaedf1b1
--- /dev/null
+++ b/docs/fr/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Traduction par IA et humains
+
+Cette traduction a été réalisée par une IA guidée par des humains. 🤝
+
+Elle peut contenir des erreurs d'interprétation du sens original, ou paraître peu naturelle, etc. 🤖
+
+Vous pouvez améliorer cette traduction en [nous aidant à mieux guider le LLM d'IA](https://fastapi.tiangolo.com/fr/contributing/#translations).
+
+[Version anglaise](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/fr/docs/tutorial/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md
index ed7494669..a8444ba27 100644
--- a/docs/fr/docs/tutorial/background-tasks.md
+++ b/docs/fr/docs/tutorial/background-tasks.md
@@ -15,12 +15,14 @@ Cela comprend, par exemple :
Pour commencer, importez `BackgroundTasks` et définissez un paramètre dans votre *fonction de chemin d'accès* avec `BackgroundTasks` comme type déclaré.
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre.
## Créer une fonction de tâche { #create-a-task-function }
+Créez une fonction à exécuter comme tâche d'arrière-plan.
+
Une fonction à exécuter comme tâche d'arrière-plan est juste une fonction standard qui peut recevoir des paramètres.
Elle peut être une fonction asynchrone (`async def`) ou une fonction normale (`def`), **FastAPI** saura la gérer correctement.
@@ -29,13 +31,13 @@ Dans cet exemple, la fonction de tâche écrira dans un fichier (afin de simuler
L'opération d'écriture n'utilisant ni `async` ni `await`, on définit la fonction avec un `def` normal.
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
## Ajouter une tâche d'arrière-plan { #add-the-background-task }
Dans votre *fonction de chemin d'accès*, passez votre fonction de tâche à l'objet de type `BackgroundTasks` (`background_tasks` ici) grâce à la méthode `.add_task()` :
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` reçoit comme arguments :
diff --git a/docs/fr/docs/tutorial/bigger-applications.md b/docs/fr/docs/tutorial/bigger-applications.md
new file mode 100644
index 000000000..065962236
--- /dev/null
+++ b/docs/fr/docs/tutorial/bigger-applications.md
@@ -0,0 +1,504 @@
+# Créer des applications plus grandes - Plusieurs fichiers { #bigger-applications-multiple-files }
+
+Si vous créez une application ou une API web, il est rare que vous puissiez tout mettre dans un seul fichier.
+
+**FastAPI** fournit un outil pratique pour structurer votre application tout en conservant toute la flexibilité.
+
+/// info
+
+Si vous venez de Flask, cela équivaut aux Blueprints de Flask.
+
+///
+
+## Exemple de structure de fichiers { #an-example-file-structure }
+
+Supposons que vous ayez une structure de fichiers comme ceci :
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | Astuce
+
+Il y a plusieurs fichiers `__init__.py` : un dans chaque répertoire ou sous-répertoire.
+
+C'est cela qui permet d'importer du code d'un fichier dans un autre.
+
+Par exemple, dans `app/main.py` vous pourriez avoir une ligne comme :
+
+```
+from app.routers import items
+```
+
+///
+
+* Le répertoire `app` contient tout. Et il a un fichier vide `app/__init__.py`, c'est donc un « package Python » (une collection de « modules Python ») : `app`.
+* Il contient un fichier `app/main.py`. Comme il se trouve dans un package Python (un répertoire avec un fichier `__init__.py`), c'est un « module » de ce package : `app.main`.
+* Il y a aussi un fichier `app/dependencies.py`, tout comme `app/main.py`, c'est un « module » : `app.dependencies`.
+* Il y a un sous-répertoire `app/routers/` avec un autre fichier `__init__.py`, c'est donc un « sous-package Python » : `app.routers`.
+* Le fichier `app/routers/items.py` est dans un package, `app/routers/`, c'est donc un sous-module : `app.routers.items`.
+* De même pour `app/routers/users.py`, c'est un autre sous-module : `app.routers.users`.
+* Il y a aussi un sous-répertoire `app/internal/` avec un autre fichier `__init__.py`, c'est donc un autre « sous-package Python » : `app.internal`.
+* Et le fichier `app/internal/admin.py` est un autre sous-module : `app.internal.admin`.
+
+
+
+La même structure de fichiers avec des commentaires :
+
+```bash
+.
+├── app # "app" est un package Python
+│ ├── __init__.py # ce fichier fait de "app" un "package Python"
+│ ├── main.py # module "main", ex. import app.main
+│ ├── dependencies.py # module "dependencies", ex. import app.dependencies
+│ └── routers # "routers" est un "sous-package Python"
+│ │ ├── __init__.py # fait de "routers" un "sous-package Python"
+│ │ ├── items.py # sous-module "items", ex. import app.routers.items
+│ │ └── users.py # sous-module "users", ex. import app.routers.users
+│ └── internal # "internal" est un "sous-package Python"
+│ ├── __init__.py # fait de "internal" un "sous-package Python"
+│ └── admin.py # sous-module "admin", ex. import app.internal.admin
+```
+
+## `APIRouter` { #apirouter }
+
+Supposons que le fichier dédié à la gestion des utilisateurs soit le sous-module `/app/routers/users.py`.
+
+Vous voulez séparer les *chemins d'accès* liés à vos utilisateurs du reste du code pour le garder organisé.
+
+Mais cela fait toujours partie de la même application/API web **FastAPI** (cela fait partie du même « package Python »).
+
+Vous pouvez créer les *chemins d'accès* pour ce module à l'aide de `APIRouter`.
+
+### Importer `APIRouter` { #import-apirouter }
+
+Vous l'importez et créez une « instance » de la même manière que vous le feriez avec la classe `FastAPI` :
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+
+### Déclarer des *chemins d'accès* avec `APIRouter` { #path-operations-with-apirouter }
+
+Puis vous l'utilisez pour déclarer vos *chemins d'accès*.
+
+Utilisez-le de la même manière que vous utiliseriez la classe `FastAPI` :
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+
+Vous pouvez considérer `APIRouter` comme une « mini `FastAPI` ».
+
+Toutes les mêmes options sont prises en charge.
+
+Tous les mêmes `parameters`, `responses`, `dependencies`, `tags`, etc.
+
+/// tip | Astuce
+
+Dans cet exemple, la variable s'appelle `router`, mais vous pouvez la nommer comme vous le souhaitez.
+
+///
+
+Nous allons inclure ce `APIRouter` dans l'application principale `FastAPI`, mais d'abord, examinons les dépendances et un autre `APIRouter`.
+
+## Gérer les dépendances { #dependencies }
+
+Nous voyons que nous allons avoir besoin de certaines dépendances utilisées à plusieurs endroits de l'application.
+
+Nous les mettons donc dans leur propre module `dependencies` (`app/dependencies.py`).
+
+Nous allons maintenant utiliser une dépendance simple pour lire un en-tête personnalisé `X-Token` :
+
+{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+
+/// tip | Astuce
+
+Nous utilisons un en-tête inventé pour simplifier cet exemple.
+
+Mais dans les cas réels, vous obtiendrez de meilleurs résultats en utilisant les [utilitaires de sécurité](security/index.md){.internal-link target=_blank} intégrés.
+
+///
+
+## Créer un autre module avec `APIRouter` { #another-module-with-apirouter }
+
+Supposons que vous ayez également les endpoints dédiés à la gestion des « items » de votre application dans le module `app/routers/items.py`.
+
+Vous avez des *chemins d'accès* pour :
+
+* `/items/`
+* `/items/{item_id}`
+
+C'est exactement la même structure que pour `app/routers/users.py`.
+
+Mais nous voulons être plus malins et simplifier un peu le code.
+
+Nous savons que tous les *chemins d'accès* de ce module ont les mêmes éléments :
+
+* Préfixe de chemin `prefix` : `/items`.
+* `tags` : (un seul tag : `items`).
+* `responses` supplémentaires.
+* `dependencies` : ils ont tous besoin de la dépendance `X-Token` que nous avons créée.
+
+Donc, au lieu d'ajouter tout cela à chaque *chemin d'accès*, nous pouvons l'ajouter au `APIRouter`.
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+
+Comme le chemin de chaque *chemin d'accès* doit commencer par `/`, comme dans :
+
+```Python hl_lines="1"
+@router.get("/{item_id}")
+async def read_item(item_id: str):
+ ...
+```
+
+... le préfixe ne doit pas inclure un `/` final.
+
+Ainsi, le préfixe dans ce cas est `/items`.
+
+Nous pouvons également ajouter une liste de `tags` et des `responses` supplémentaires qui seront appliqués à tous les *chemins d'accès* inclus dans ce routeur.
+
+Et nous pouvons ajouter une liste de `dependencies` qui seront ajoutées à tous les *chemins d'accès* du routeur et seront exécutées/résolues pour chaque requête qui leur est faite.
+
+/// tip | Astuce
+
+Notez que, tout comme pour les [dépendances dans les décorateurs de *chemin d'accès*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, aucune valeur ne sera transmise à votre *fonction de chemin d'accès*.
+
+///
+
+Le résultat final est que les chemins d'item sont désormais :
+
+* `/items/`
+* `/items/{item_id}`
+
+... comme prévu.
+
+* Ils seront marqués avec une liste de tags qui contient une seule chaîne « items ».
+ * Ces « tags » sont particulièrement utiles pour les systèmes de documentation interactive automatique (utilisant OpenAPI).
+* Ils incluront tous les `responses` prédéfinies.
+* Tous ces *chemins d'accès* auront la liste des `dependencies` évaluées/exécutées avant eux.
+ * Si vous déclarez également des dépendances dans un *chemin d'accès* spécifique, **elles seront aussi exécutées**.
+ * Les dépendances du routeur sont exécutées en premier, puis les [`dependencies` dans le décorateur](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, puis les dépendances des paramètres normaux.
+ * Vous pouvez également ajouter des [`Security` dependencies avec des `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.
+
+/// tip | Astuce
+
+Avoir des `dependencies` dans le `APIRouter` peut servir, par exemple, à exiger une authentification pour tout un groupe de *chemins d'accès*. Même si les dépendances ne sont pas ajoutées individuellement à chacun d'eux.
+
+///
+
+/// check | Vérifications
+
+Les paramètres `prefix`, `tags`, `responses` et `dependencies` sont (comme dans de nombreux autres cas) simplement une fonctionnalité de **FastAPI** pour vous aider à éviter la duplication de code.
+
+///
+
+### Importer les dépendances { #import-the-dependencies }
+
+Ce code se trouve dans le module `app.routers.items`, le fichier `app/routers/items.py`.
+
+Et nous devons récupérer la fonction de dépendance depuis le module `app.dependencies`, le fichier `app/dependencies.py`.
+
+Nous utilisons donc un import relatif avec `..` pour les dépendances :
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}
+
+#### Comprendre le fonctionnement des imports relatifs { #how-relative-imports-work }
+
+/// tip | Astuce
+
+Si vous savez parfaitement comment fonctionnent les imports, passez à la section suivante ci-dessous.
+
+///
+
+Un seul point `.`, comme dans :
+
+```Python
+from .dependencies import get_token_header
+```
+
+signifierait :
+
+* En partant du même package dans lequel vit ce module (le fichier `app/routers/items.py`) (le répertoire `app/routers/`)...
+* trouver le module `dependencies` (un fichier imaginaire `app/routers/dependencies.py`)...
+* et en importer la fonction `get_token_header`.
+
+Mais ce fichier n'existe pas, nos dépendances sont dans un fichier `app/dependencies.py`.
+
+Rappelez-vous à quoi ressemble la structure de notre app/fichiers :
+
+
+
+---
+
+Les deux points `..`, comme dans :
+
+```Python
+from ..dependencies import get_token_header
+```
+
+veulent dire :
+
+* En partant du même package dans lequel vit ce module (le fichier `app/routers/items.py`) (le répertoire `app/routers/`)...
+* aller au package parent (le répertoire `app/`)...
+* et là, trouver le module `dependencies` (le fichier `app/dependencies.py`)...
+* et en importer la fonction `get_token_header`.
+
+Cela fonctionne correctement ! 🎉
+
+---
+
+De la même manière, si nous avions utilisé trois points `...`, comme dans :
+
+```Python
+from ...dependencies import get_token_header
+```
+
+cela voudrait dire :
+
+* En partant du même package dans lequel vit ce module (le fichier `app/routers/items.py`) (le répertoire `app/routers/`)...
+* aller au package parent (le répertoire `app/`)...
+* puis aller au parent de ce package (il n'y a pas de package parent, `app` est le niveau supérieur 😱)...
+* et là, trouver le module `dependencies` (le fichier `app/dependencies.py`)...
+* et en importer la fonction `get_token_header`.
+
+Cela ferait référence à un package au-dessus de `app/`, avec son propre fichier `__init__.py`, etc. Mais nous n'avons pas cela. Donc, cela lèverait une erreur dans notre exemple. 🚨
+
+Mais maintenant vous savez comment cela fonctionne, vous pouvez donc utiliser des imports relatifs dans vos propres applications, aussi complexes soient-elles. 🤓
+
+### Ajouter des `tags`, `responses` et `dependencies` personnalisés { #add-some-custom-tags-responses-and-dependencies }
+
+Nous n'ajoutons pas le préfixe `/items` ni `tags=["items"]` à chaque *chemin d'accès* parce que nous les avons ajoutés au `APIRouter`.
+
+Mais nous pouvons toujours ajouter _davantage_ de `tags` qui seront appliqués à un *chemin d'accès* spécifique, ainsi que des `responses` supplémentaires propres à ce *chemin d'accès* :
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+
+/// tip | Astuce
+
+Ce dernier *chemin d'accès* aura la combinaison de tags : `["items", "custom"]`.
+
+Et il aura également les deux réponses dans la documentation, une pour `404` et une pour `403`.
+
+///
+
+## Créer l'application `FastAPI` principale { #the-main-fastapi }
+
+Voyons maintenant le module `app/main.py`.
+
+C'est ici que vous importez et utilisez la classe `FastAPI`.
+
+Ce sera le fichier principal de votre application qui reliera tout ensemble.
+
+Et comme la plupart de votre logique vivra désormais dans son propre module, le fichier principal sera assez simple.
+
+### Importer `FastAPI` { #import-fastapi }
+
+Vous importez et créez une classe `FastAPI` comme d'habitude.
+
+Et nous pouvons même déclarer des [dépendances globales](dependencies/global-dependencies.md){.internal-link target=_blank} qui seront combinées avec les dépendances de chaque `APIRouter` :
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
+
+### Importer les `APIRouter` { #import-the-apirouter }
+
+Nous importons maintenant les autres sous-modules qui ont des `APIRouter` :
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}
+
+Comme les fichiers `app/routers/users.py` et `app/routers/items.py` sont des sous-modules qui font partie du même package Python `app`, nous pouvons utiliser un seul point `.` pour les importer en utilisant des « imports relatifs ».
+
+### Comprendre le fonctionnement de l'import { #how-the-importing-works }
+
+La section :
+
+```Python
+from .routers import items, users
+```
+
+signifie :
+
+* En partant du même package dans lequel vit ce module (le fichier `app/main.py`) (le répertoire `app/`)...
+* chercher le sous-package `routers` (le répertoire `app/routers/`)...
+* et en importer le sous-module `items` (le fichier `app/routers/items.py`) et `users` (le fichier `app/routers/users.py`)...
+
+Le module `items` aura une variable `router` (`items.router`). C'est celle que nous avons créée dans le fichier `app/routers/items.py`, c'est un objet `APIRouter`.
+
+Nous faisons ensuite la même chose pour le module `users`.
+
+Nous pourrions aussi les importer ainsi :
+
+```Python
+from app.routers import items, users
+```
+
+/// info
+
+La première version est un « import relatif » :
+
+```Python
+from .routers import items, users
+```
+
+La deuxième version est un « import absolu » :
+
+```Python
+from app.routers import items, users
+```
+
+Pour en savoir plus sur les Packages et Modules Python, lisez la documentation officielle de Python sur les modules.
+
+///
+
+### Éviter les collisions de noms { #avoid-name-collisions }
+
+Nous importons le sous-module `items` directement, au lieu d'importer uniquement sa variable `router`.
+
+C'est parce que nous avons également une autre variable nommée `router` dans le sous-module `users`.
+
+Si nous les avions importées l'une après l'autre, comme :
+
+```Python
+from .routers.items import router
+from .routers.users import router
+```
+
+le `router` de `users` écraserait celui de `items` et nous ne pourrions pas les utiliser en même temps.
+
+Donc, pour pouvoir utiliser les deux dans le même fichier, nous importons directement les sous-modules :
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}
+
+### Inclure les `APIRouter` pour `users` et `items` { #include-the-apirouters-for-users-and-items }
+
+Incluons maintenant les `router` des sous-modules `users` et `items` :
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}
+
+/// info
+
+`users.router` contient le `APIRouter` à l'intérieur du fichier `app/routers/users.py`.
+
+Et `items.router` contient le `APIRouter` à l'intérieur du fichier `app/routers/items.py`.
+
+///
+
+Avec `app.include_router()`, nous pouvons ajouter chaque `APIRouter` à l'application principale `FastAPI`.
+
+Cela inclura toutes les routes de ce routeur comme faisant partie de l'application.
+
+/// note | Détails techniques
+
+En interne, cela créera en fait un *chemin d'accès* pour chaque *chemin d'accès* qui a été déclaré dans le `APIRouter`.
+
+Donc, en coulisses, cela fonctionnera comme si tout faisait partie d'une seule et même application.
+
+///
+
+/// check | Vérifications
+
+Vous n'avez pas à vous soucier de la performance lors de l'inclusion de routeurs.
+
+Cela prendra des microsecondes et ne se produira qu'au démarrage.
+
+Donc cela n'affectera pas la performance. ⚡
+
+///
+
+### Inclure un `APIRouter` avec un `prefix`, des `tags`, des `responses` et des `dependencies` personnalisés { #include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies }
+
+Imaginons maintenant que votre organisation vous ait fourni le fichier `app/internal/admin.py`.
+
+Il contient un `APIRouter` avec quelques *chemins d'accès* d'administration que votre organisation partage entre plusieurs projets.
+
+Pour cet exemple, il sera très simple. Mais supposons que, parce qu'il est partagé avec d'autres projets de l'organisation, nous ne puissions pas le modifier et ajouter un `prefix`, des `dependencies`, des `tags`, etc. directement au `APIRouter` :
+
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+
+Mais nous voulons quand même définir un `prefix` personnalisé lors de l'inclusion du `APIRouter` afin que tous ses *chemins d'accès* commencent par `/admin`, nous voulons le sécuriser avec les `dependencies` que nous avons déjà pour ce projet, et nous voulons inclure des `tags` et des `responses`.
+
+Nous pouvons déclarer tout cela sans avoir à modifier le `APIRouter` d'origine en passant ces paramètres à `app.include_router()` :
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}
+
+De cette façon, le `APIRouter` original restera inchangé, afin que nous puissions toujours partager ce même fichier `app/internal/admin.py` avec d'autres projets de l'organisation.
+
+Le résultat est que, dans notre application, chacun des *chemins d'accès* du module `admin` aura :
+
+* Le préfixe `/admin`.
+* Le tag `admin`.
+* La dépendance `get_token_header`.
+* La réponse `418`. 🍵
+
+Mais cela n'affectera que ce `APIRouter` dans notre application, pas dans tout autre code qui l'utilise.
+
+Ainsi, par exemple, d'autres projets pourraient utiliser le même `APIRouter` avec une méthode d'authentification différente.
+
+### Inclure un *chemin d'accès* { #include-a-path-operation }
+
+Nous pouvons également ajouter des *chemins d'accès* directement à l'application `FastAPI`.
+
+Ici, nous le faisons... juste pour montrer que nous le pouvons 🤷 :
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}
+
+et cela fonctionnera correctement, avec tous les autres *chemins d'accès* ajoutés avec `app.include_router()`.
+
+/// info | Détails très techniques
+
+Note : c'est un détail très technique que vous pouvez probablement **simplement ignorer**.
+
+---
+
+Les `APIRouter` ne sont pas « montés », ils ne sont pas isolés du reste de l'application.
+
+C'est parce que nous voulons inclure leurs *chemins d'accès* dans le schéma OpenAPI et les interfaces utilisateur.
+
+Comme nous ne pouvons pas simplement les isoler et les « monter » indépendamment du reste, les *chemins d'accès* sont « clonés » (recréés), pas inclus directement.
+
+///
+
+## Consulter la documentation API automatique { #check-the-automatic-api-docs }
+
+Maintenant, exécutez votre application :
+
+
+
+## Inclure le même routeur plusieurs fois avec des `prefix` différents { #include-the-same-router-multiple-times-with-different-prefix }
+
+Vous pouvez aussi utiliser `.include_router()` plusieurs fois avec le même routeur en utilisant des préfixes différents.
+
+Cela peut être utile, par exemple, pour exposer la même API sous des préfixes différents, p. ex. `/api/v1` et `/api/latest`.
+
+C'est un usage avancé dont vous n'aurez peut-être pas vraiment besoin, mais il est là au cas où.
+
+## Inclure un `APIRouter` dans un autre { #include-an-apirouter-in-another }
+
+De la même manière que vous pouvez inclure un `APIRouter` dans une application `FastAPI`, vous pouvez inclure un `APIRouter` dans un autre `APIRouter` en utilisant :
+
+```Python
+router.include_router(other_router)
+```
+
+Vous devez vous assurer de le faire avant d'inclure `router` dans l'application `FastAPI`, afin que les *chemins d'accès* de `other_router` soient également inclus.
diff --git a/docs/fr/docs/tutorial/body-fields.md b/docs/fr/docs/tutorial/body-fields.md
new file mode 100644
index 000000000..9830292c9
--- /dev/null
+++ b/docs/fr/docs/tutorial/body-fields.md
@@ -0,0 +1,61 @@
+# Corps - Champs { #body-fields }
+
+De la même manière que vous pouvez déclarer des validations supplémentaires et des métadonnées dans les paramètres d'une fonction de chemin d'accès avec `Query`, `Path` et `Body`, vous pouvez déclarer des validations et des métadonnées à l'intérieur des modèles Pydantic en utilisant `Field` de Pydantic.
+
+## Importer `Field` { #import-field }
+
+D'abord, vous devez l'importer :
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
+
+
+/// warning | Alertes
+
+Notez que `Field` est importé directement depuis `pydantic`, et non depuis `fastapi` comme le sont les autres (`Query`, `Path`, `Body`, etc.).
+
+///
+
+## Déclarer les attributs du modèle { #declare-model-attributes }
+
+Vous pouvez ensuite utiliser `Field` avec des attributs de modèle :
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
+
+`Field` fonctionne de la même manière que `Query`, `Path` et `Body`, il dispose des mêmes paramètres, etc.
+
+/// note | Détails techniques
+
+En réalité, `Query`, `Path` et d'autres que vous verrez ensuite créent des objets de sous-classes d'une classe commune `Param`, qui est elle-même une sous-classe de la classe `FieldInfo` de Pydantic.
+
+Et `Field` de Pydantic renvoie également une instance de `FieldInfo`.
+
+`Body` renvoie aussi directement des objets d'une sous-classe de `FieldInfo`. Et il y en a d'autres que vous verrez plus tard qui sont des sous-classes de la classe `Body`.
+
+Rappelez-vous que lorsque vous importez `Query`, `Path` et d'autres depuis `fastapi`, ce sont en réalité des fonctions qui renvoient des classes spéciales.
+
+///
+
+/// tip | Astuce
+
+Remarquez comment chaque attribut de modèle avec un type, une valeur par défaut et `Field` a la même structure qu'un paramètre de fonction de chemin d'accès, avec `Field` au lieu de `Path`, `Query` et `Body`.
+
+///
+
+## Ajouter des informations supplémentaires { #add-extra-information }
+
+Vous pouvez déclarer des informations supplémentaires dans `Field`, `Query`, `Body`, etc. Elles seront incluses dans le JSON Schema généré.
+
+Vous en apprendrez davantage sur l'ajout d'informations supplémentaires plus loin dans les documents, lorsque vous apprendrez à déclarer des exemples.
+
+/// warning | Alertes
+
+Les clés supplémentaires passées à `Field` seront également présentes dans le schéma OpenAPI résultant pour votre application.
+Comme ces clés ne font pas nécessairement partie de la spécification OpenAPI, certains outils OpenAPI, par exemple [le validateur OpenAPI](https://validator.swagger.io/), peuvent ne pas fonctionner avec votre schéma généré.
+
+///
+
+## Récapitulatif { #recap }
+
+Vous pouvez utiliser `Field` de Pydantic pour déclarer des validations supplémentaires et des métadonnées pour les attributs de modèle.
+
+Vous pouvez également utiliser des arguments nommés supplémentaires pour transmettre des métadonnées JSON Schema additionnelles.
diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md
index 92ca2afc3..1c1ab0fca 100644
--- a/docs/fr/docs/tutorial/body-multiple-params.md
+++ b/docs/fr/docs/tutorial/body-multiple-params.md
@@ -104,12 +104,6 @@ Comme, par défaut, les valeurs singulières sont interprétées comme des param
q: str | None = None
```
-Ou en Python 3.9 :
-
-```Python
-q: Union[str, None] = None
-```
-
Par exemple :
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
diff --git a/docs/fr/docs/tutorial/body-nested-models.md b/docs/fr/docs/tutorial/body-nested-models.md
new file mode 100644
index 000000000..dccfdb6c5
--- /dev/null
+++ b/docs/fr/docs/tutorial/body-nested-models.md
@@ -0,0 +1,220 @@
+# Corps - Modèles imbriqués { #body-nested-models }
+
+Avec FastAPI, vous pouvez définir, valider, documenter et utiliser des modèles imbriqués à n'importe quelle profondeur (grâce à Pydantic).
+
+## Déclarer des champs de liste { #list-fields }
+
+Vous pouvez définir un attribut comme étant un sous-type. Par exemple, une `list` Python :
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+Cela fera de `tags` une liste, bien que le type des éléments de la liste ne soit pas déclaré.
+
+## Champs de liste avec paramètre de type { #list-fields-with-type-parameter }
+
+Mais Python a une manière spécifique de déclarer des listes avec des types internes, ou « paramètres de type » :
+
+### Déclarer une `list` avec un paramètre de type { #declare-a-list-with-a-type-parameter }
+
+Pour déclarer des types qui ont des paramètres de type (types internes), comme `list`, `dict`, `tuple`,
+passez le(s) type(s) interne(s) comme « paramètres de type » à l'aide de crochets : `[` et `]`
+
+```Python
+my_list: list[str]
+```
+
+C'est simplement la syntaxe Python standard pour les déclarations de type.
+
+Utilisez cette même syntaxe standard pour les attributs de modèles avec des types internes.
+
+Ainsi, dans notre exemple, nous pouvons faire de `tags` spécifiquement une « liste de chaînes » :
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## Types set { #set-types }
+
+Mais en y réfléchissant, nous réalisons que les tags ne devraient pas se répéter, ce seraient probablement des chaînes uniques.
+
+Et Python dispose d'un type de données spécial pour les ensembles d'éléments uniques, le `set`.
+
+Nous pouvons alors déclarer `tags` comme un set de chaînes :
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+Avec cela, même si vous recevez une requête contenant des doublons, elle sera convertie en un set d'éléments uniques.
+
+Et chaque fois que vous renverrez ces données, même si la source contenait des doublons, elles seront renvoyées sous la forme d'un set d'éléments uniques.
+
+Elles seront également annotées / documentées en conséquence.
+
+## Modèles imbriqués { #nested-models }
+
+Chaque attribut d'un modèle Pydantic a un type.
+
+Mais ce type peut lui-même être un autre modèle Pydantic.
+
+Ainsi, vous pouvez déclarer des « objets » JSON profondément imbriqués avec des noms d'attributs, des types et des validations spécifiques.
+
+Tout cela, de manière arbitrairement imbriquée.
+
+### Définir un sous-modèle { #define-a-submodel }
+
+Par exemple, nous pouvons définir un modèle `Image` :
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### Utiliser le sous-modèle comme type { #use-the-submodel-as-a-type }
+
+Nous pouvons ensuite l'utiliser comme type d'un attribut :
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+Cela signifie que FastAPI attendrait un corps similaire à :
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": ["rock", "metal", "bar"],
+ "image": {
+ "url": "http://example.com/baz.jpg",
+ "name": "The Foo live"
+ }
+}
+```
+
+Là encore, avec cette simple déclaration, avec FastAPI vous obtenez :
+
+- Prise en charge par l'éditeur (autocomplétion, etc.), même pour les modèles imbriqués
+- Conversion des données
+- Validation des données
+- Documentation automatique
+
+## Types spéciaux et validation { #special-types-and-validation }
+
+Outre les types singuliers normaux comme `str`, `int`, `float`, etc. vous pouvez utiliser des types singuliers plus complexes qui héritent de `str`.
+
+Pour voir toutes les options dont vous disposez, consultez l’aperçu des types de Pydantic. Vous verrez quelques exemples au chapitre suivant.
+
+Par exemple, comme dans le modèle `Image` nous avons un champ `url`, nous pouvons le déclarer comme instance de `HttpUrl` de Pydantic au lieu de `str` :
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+La chaîne sera vérifiée comme URL valide et documentée comme telle dans JSON Schema / OpenAPI.
+
+## Attributs avec des listes de sous-modèles { #attributes-with-lists-of-submodels }
+
+Vous pouvez également utiliser des modèles Pydantic comme sous-types de `list`, `set`, etc. :
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+Cela attendra (convertira, validera, documentera, etc.) un corps JSON comme :
+
+```JSON hl_lines="11"
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": [
+ "rock",
+ "metal",
+ "bar"
+ ],
+ "images": [
+ {
+ "url": "http://example.com/baz.jpg",
+ "name": "The Foo live"
+ },
+ {
+ "url": "http://example.com/dave.jpg",
+ "name": "The Baz"
+ }
+ ]
+}
+```
+/// info
+
+Remarquez que la clé `images` contient maintenant une liste d'objets image.
+
+///
+
+## Modèles profondément imbriqués { #deeply-nested-models }
+
+Vous pouvez définir des modèles imbriqués à une profondeur arbitraire :
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info
+
+Remarquez que `Offer` a une liste d’`Item`, qui à leur tour ont une liste optionnelle d’`Image`.
+
+///
+
+## Corps de listes pures { #bodies-of-pure-lists }
+
+Si la valeur de premier niveau du corps JSON attendu est un `array` JSON (une `list` Python), vous pouvez déclarer le type dans le paramètre de la fonction, de la même manière que dans les modèles Pydantic :
+
+```Python
+images: list[Image]
+```
+
+comme :
+
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
+
+## Bénéficier de la prise en charge de l'éditeur partout { #editor-support-everywhere }
+
+Et vous bénéficiez de la prise en charge de l'éditeur partout.
+
+Même pour les éléments à l'intérieur des listes :
+
+
+
+Vous ne pourriez pas obtenir ce type de prise en charge de l'éditeur si vous travailliez directement avec des `dict` au lieu de modèles Pydantic.
+
+Mais vous n'avez pas à vous en soucier non plus, les `dict` entrants sont convertis automatiquement et votre sortie est également convertie automatiquement en JSON.
+
+## Corps de `dict` arbitraires { #bodies-of-arbitrary-dicts }
+
+Vous pouvez également déclarer un corps comme un `dict` avec des clés d’un certain type et des valeurs d’un autre type.
+
+De cette façon, vous n'avez pas besoin de savoir à l'avance quels sont les noms de champs/attributs valides (comme ce serait le cas avec des modèles Pydantic).
+
+Cela serait utile si vous voulez recevoir des clés que vous ne connaissez pas à l'avance.
+
+---
+
+Un autre cas utile est lorsque vous souhaitez avoir des clés d'un autre type (par exemple `int`).
+
+C'est ce que nous allons voir ici.
+
+Dans ce cas, vous accepteriez n'importe quel `dict` tant qu'il a des clés `int` avec des valeurs `float` :
+
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
+
+/// tip | Astuce
+
+Gardez à l'esprit que JSON ne prend en charge que des `str` comme clés.
+
+Mais Pydantic dispose d'une conversion automatique des données.
+
+Cela signifie que, même si vos clients d'API ne peuvent envoyer que des chaînes comme clés, tant que ces chaînes contiennent des entiers purs, Pydantic les convertira et les validera.
+
+Et le `dict` que vous recevez dans `weights` aura en réalité des clés `int` et des valeurs `float`.
+
+///
+
+## Récapitulatif { #recap }
+
+Avec FastAPI, vous bénéficiez de la flexibilité maximale fournie par les modèles Pydantic, tout en gardant votre code simple, concis et élégant.
+
+Mais avec tous les avantages :
+
+- Prise en charge par l'éditeur (autocomplétion partout !)
+- Conversion des données (a.k.a. parsing / sérialisation)
+- Validation des données
+- Documentation des schémas
+- Documentation automatique
diff --git a/docs/fr/docs/tutorial/body-updates.md b/docs/fr/docs/tutorial/body-updates.md
new file mode 100644
index 000000000..36ad12681
--- /dev/null
+++ b/docs/fr/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Corps - Mises à jour { #body-updates }
+
+## Mettre à jour en remplaçant avec `PUT` { #update-replacing-with-put }
+
+Pour mettre à jour un élément, vous pouvez utiliser l’opération HTTP `PUT`.
+
+Vous pouvez utiliser le `jsonable_encoder` pour convertir les données d’entrée en données pouvant être stockées au format JSON (par exemple, avec une base de données NoSQL). Par exemple, convertir `datetime` en `str`.
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+On utilise `PUT` pour recevoir des données qui doivent remplacer les données existantes.
+
+### Avertissement concernant le remplacement { #warning-about-replacing }
+
+Cela signifie que si vous souhaitez mettre à jour l’élément `bar` avec `PUT` et un corps contenant :
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+comme il n’inclut pas l’attribut déjà enregistré « tax »: 20.2, le modèle d’entrée prendrait la valeur par défaut « tax »: 10.5.
+
+Et les données seraient enregistrées avec cette « nouvelle » `tax` de `10.5`.
+
+## Effectuer des mises à jour partielles avec `PATCH` { #partial-updates-with-patch }
+
+Vous pouvez également utiliser l’opération HTTP `PATCH` pour mettre à jour des données de manière partielle.
+
+Cela signifie que vous pouvez n’envoyer que les données que vous souhaitez mettre à jour, en laissant le reste intact.
+
+/// note | Remarque
+
+`PATCH` est moins utilisé et moins connu que `PUT`.
+
+Et de nombreuses équipes n’utilisent que `PUT`, même pour les mises à jour partielles.
+
+Vous êtes libre de les utiliser comme vous le souhaitez, **FastAPI** n’impose aucune restriction.
+
+Mais ce guide vous montre, plus ou moins, la façon dont ils sont censés être utilisés.
+
+///
+
+### Utiliser le paramètre `exclude_unset` de Pydantic { #using-pydantics-exclude-unset-parameter }
+
+Si vous souhaitez recevoir des mises à jour partielles, il est très utile d’utiliser le paramètre `exclude_unset` dans la méthode `.model_dump()` du modèle Pydantic.
+
+Comme `item.model_dump(exclude_unset=True)`.
+
+Cela génère un `dict` ne contenant que les données définies lors de la création du modèle `item`, en excluant les valeurs par défaut.
+
+Vous pouvez ensuite l’utiliser pour produire un `dict` avec uniquement les données définies (envoyées dans la requête), en omettant les valeurs par défaut :
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### Utiliser le paramètre `update` de Pydantic { #using-pydantics-update-parameter }
+
+Vous pouvez maintenant créer une copie du modèle existant avec `.model_copy()`, et passer le paramètre `update` avec un `dict` contenant les données à mettre à jour.
+
+Comme `stored_item_model.model_copy(update=update_data)` :
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### Récapitulatif des mises à jour partielles { #partial-updates-recap }
+
+En résumé, pour appliquer des mises à jour partielles, vous procédez ainsi :
+
+* (Optionnel) utilisez `PATCH` au lieu de `PUT`.
+* Récupérez les données stockées.
+* Placez ces données dans un modèle Pydantic.
+* Générez un `dict` sans valeurs par défaut à partir du modèle d’entrée (en utilisant `exclude_unset`).
+ * De cette façon, vous mettez à jour uniquement les valeurs effectivement définies par l’utilisateur, au lieu d’écraser des valeurs déjà stockées par des valeurs par défaut de votre modèle.
+* Créez une copie du modèle stocké, en mettant à jour ses attributs avec les mises à jour partielles reçues (en utilisant le paramètre `update`).
+* Convertissez le modèle copié en quelque chose qui peut être stocké dans votre base de données (par exemple en utilisant le `jsonable_encoder`).
+ * Cela est comparable à l’utilisation à nouveau de la méthode `.model_dump()` du modèle, mais cela vérifie (et convertit) les valeurs vers des types pouvant être convertis en JSON, par exemple `datetime` en `str`.
+* Enregistrez les données dans votre base de données.
+* Retournez le modèle mis à jour.
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | Astuce
+
+Vous pouvez en réalité utiliser cette même technique avec une opération HTTP `PUT`.
+
+Mais l’exemple ici utilise `PATCH` car il a été créé pour ces cas d’usage.
+
+///
+
+/// note | Remarque
+
+Remarquez que le modèle d’entrée est toujours validé.
+
+Ainsi, si vous souhaitez recevoir des mises à jour partielles pouvant omettre tous les attributs, vous devez disposer d’un modèle avec tous les attributs marqués comme optionnels (avec des valeurs par défaut ou `None`).
+
+Pour distinguer les modèles avec toutes les valeurs optionnelles pour les mises à jour et les modèles avec des valeurs requises pour la création, vous pouvez utiliser les idées décrites dans [Modèles supplémentaires](extra-models.md){.internal-link target=_blank}.
+
+///
diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md
index ca115fabc..a8703e030 100644
--- a/docs/fr/docs/tutorial/body.md
+++ b/docs/fr/docs/tutorial/body.md
@@ -10,7 +10,7 @@ Pour déclarer un corps de **requête**, on utilise les modèles de
-Et seront aussi utilisés dans chaque *opération de chemin* de la documentation utilisant ces modèles :
+Et seront aussi utilisés dans chaque *chemin d'accès* de la documentation utilisant ces modèles :
@@ -115,7 +115,7 @@ Ce qui améliore le support pour les modèles Pydantic avec :
* de l'autocomplétion
* des vérifications de type
-* du « refactoring » (ou remaniement de code)
+* du « refactoring »
* de la recherche
* des inspections
@@ -129,7 +129,7 @@ Dans la fonction, vous pouvez accéder à tous les attributs de l'objet du modè
## Corps de la requête + paramètres de chemin { #request-body-path-parameters }
-Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la même *opération de chemin*.
+Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la même *chemin d'accès*.
**FastAPI** est capable de reconnaître que les paramètres de la fonction qui correspondent aux paramètres de chemin doivent être **récupérés depuis le chemin**, et que les paramètres de fonctions déclarés comme modèles Pydantic devraient être **récupérés depuis le corps de la requête**.
@@ -137,7 +137,7 @@ Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la
## Corps de la requête + paramètres de chemin et de requête { #request-body-path-query-parameters }
-Vous pouvez aussi déclarer un **corps**, et des paramètres de **chemin** et de **requête** dans la même *opération de chemin*.
+Vous pouvez aussi déclarer un **corps**, et des paramètres de **chemin** et de **requête** dans la même *chemin d'accès*.
**FastAPI** saura reconnaître chacun d'entre eux et récupérer la bonne donnée au bon endroit.
@@ -153,7 +153,7 @@ Les paramètres de la fonction seront reconnus comme tel :
**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`.
-L'annotation de type `str | None` (Python 3.10+) ou `Union` dans `Union[str, None]` (Python 3.9+) n'est pas utilisée par **FastAPI** pour déterminer que la valeur n'est pas requise, il le saura parce qu'elle a une valeur par défaut `= None`.
+L'annotation de type `str | None` n'est pas utilisée par **FastAPI** pour déterminer que la valeur n'est pas requise, il le saura parce qu'elle a une valeur par défaut `= None`.
Mais ajouter ces annotations de type permettra à votre éditeur de vous offrir un meilleur support et de détecter des erreurs.
diff --git a/docs/fr/docs/tutorial/cookie-param-models.md b/docs/fr/docs/tutorial/cookie-param-models.md
new file mode 100644
index 000000000..c6fc2f826
--- /dev/null
+++ b/docs/fr/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Modèles de paramètres de cookies { #cookie-parameter-models }
+
+Si vous avez un groupe de **cookies** liés, vous pouvez créer un **modèle Pydantic** pour les déclarer. 🍪
+
+Cela vous permet de **réutiliser le modèle** à **plusieurs endroits** et aussi de déclarer des validations et des métadonnées pour tous les paramètres en une seule fois. 😎
+
+/// note | Remarque
+
+Ceci est pris en charge depuis la version `0.115.0` de FastAPI. 🤓
+
+///
+
+/// tip | Astuce
+
+Cette même technique s'applique à `Query`, `Cookie` et `Header`. 😎
+
+///
+
+## Déclarer des cookies avec un modèle Pydantic { #cookies-with-a-pydantic-model }
+
+Déclarez les paramètres de **cookie** dont vous avez besoin dans un **modèle Pydantic**, puis déclarez le paramètre comme `Cookie` :
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** va **extraire** les données pour **chaque champ** à partir des **cookies** reçus dans la requête et vous fournir le modèle Pydantic que vous avez défini.
+
+## Consulter la documentation { #check-the-docs }
+
+Vous pouvez voir les cookies définis dans l'interface de la documentation à `/docs` :
+
+
+
+
+## Raccourci { #shortcut }
+
+Mais vous voyez qu'il y a ici de la duplication de code : nous écrivons `CommonQueryParams` deux fois :
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ sans Annotated
+
+/// tip | Astuce
+
+Privilégiez la version avec `Annotated` si possible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+**FastAPI** fournit un raccourci pour ces cas, lorsque la dépendance est spécifiquement une classe que **FastAPI** va « appeler » pour créer une instance de la classe elle‑même.
+
+Pour ces cas précis, vous pouvez faire ce qui suit :
+
+Au lieu d'écrire :
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ sans Annotated
+
+/// tip | Astuce
+
+Privilégiez la version avec `Annotated` si possible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+... vous écrivez :
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ sans Annotated
+
+/// tip | Astuce
+
+Privilégiez la version avec `Annotated` si possible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+Vous déclarez la dépendance comme type du paramètre et vous utilisez `Depends()` sans aucun paramètre, au lieu d'avoir à réécrire la classe entière à l'intérieur de `Depends(CommonQueryParams)`.
+
+Le même exemple ressemblerait alors à ceci :
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+... et **FastAPI** saura quoi faire.
+
+/// tip | Astuce
+
+Si cela vous semble plus déroutant qu'utile, ignorez‑le, vous n'en avez pas besoin.
+
+Ce n'est qu'un raccourci. Parce que **FastAPI** tient à vous aider à minimiser la duplication de code.
+
+///
diff --git a/docs/fr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/fr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 000000000..bf697fe8d
--- /dev/null
+++ b/docs/fr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# Gérer les dépendances dans les décorateurs de chemins d'accès { #dependencies-in-path-operation-decorators }
+
+Dans certains cas, vous n'avez pas vraiment besoin de la valeur de retour d'une dépendance dans votre *fonction de chemin d'accès*.
+
+Ou la dépendance ne retourne aucune valeur.
+
+Mais vous avez quand même besoin qu'elle soit exécutée/résolue.
+
+Dans ces cas, au lieu de déclarer un paramètre de *fonction de chemin d'accès* avec `Depends`, vous pouvez ajouter une `list` de `dependencies` au *décorateur de chemin d'accès*.
+
+## Ajouter `dependencies` au *décorateur de chemin d'accès* { #add-dependencies-to-the-path-operation-decorator }
+
+Le *décorateur de chemin d'accès* accepte un argument optionnel `dependencies`.
+
+Il doit s'agir d'une `list` de `Depends()` :
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+Ces dépendances seront exécutées/résolues de la même manière que des dépendances normales. Mais leur valeur (si elles en retournent une) ne sera pas transmise à votre *fonction de chemin d'accès*.
+
+/// tip | Astuce
+
+Certains éditeurs vérifient les paramètres de fonction non utilisés et les signalent comme des erreurs.
+
+En utilisant ces `dependencies` dans le *décorateur de chemin d'accès*, vous pouvez vous assurer qu'elles sont exécutées tout en évitant des erreurs de l'éditeur/des outils.
+
+Cela peut également éviter toute confusion pour les nouveaux développeurs qui voient un paramètre inutilisé dans votre code et pourraient penser qu'il est superflu.
+
+///
+
+/// info | Info
+
+Dans cet exemple, nous utilisons des en-têtes personnalisés fictifs `X-Key` et `X-Token`.
+
+Mais dans des cas réels, lors de l'implémentation de la sécurité, vous tirerez davantage d'avantages en utilisant les [utilitaires de sécurité (chapitre suivant)](../security/index.md){.internal-link target=_blank} intégrés.
+
+///
+
+## Gérer les erreurs et les valeurs de retour des dépendances { #dependencies-errors-and-return-values }
+
+Vous pouvez utiliser les mêmes *fonctions* de dépendance que d'habitude.
+
+### Définir les exigences des dépendances { #dependency-requirements }
+
+Elles peuvent déclarer des exigences pour la requête (comme des en-têtes) ou d'autres sous-dépendances :
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### Lever des exceptions { #raise-exceptions }
+
+Ces dépendances peuvent `raise` des exceptions, comme des dépendances normales :
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### Gérer les valeurs de retour { #return-values }
+
+Elles peuvent retourner des valeurs ou non, ces valeurs ne seront pas utilisées.
+
+Vous pouvez donc réutiliser une dépendance normale (qui retourne une valeur) que vous utilisez déjà ailleurs ; même si la valeur n'est pas utilisée, la dépendance sera exécutée :
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## Définir des dépendances pour un groupe de chemins d'accès { #dependencies-for-a-group-of-path-operations }
+
+Plus tard, en lisant comment structurer des applications plus grandes ([Applications plus grandes - Plusieurs fichiers](../../tutorial/bigger-applications.md){.internal-link target=_blank}), éventuellement avec plusieurs fichiers, vous apprendrez à déclarer un unique paramètre `dependencies` pour un groupe de *chemins d'accès*.
+
+## Définir des dépendances globales { #global-dependencies }
+
+Ensuite, nous verrons comment ajouter des dépendances à l'application `FastAPI` entière, afin qu'elles s'appliquent à chaque *chemin d'accès*.
diff --git a/docs/fr/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/fr/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 000000000..3f06df767
--- /dev/null
+++ b/docs/fr/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,289 @@
+# Utiliser des dépendances avec `yield` { #dependencies-with-yield }
+
+FastAPI prend en charge des dépendances qui effectuent des étapes supplémentaires après l'exécution.
+
+Pour cela, utilisez `yield` au lieu de `return`, et écrivez les étapes supplémentaires (code) après.
+
+/// tip | Astuce
+
+Vous devez vous assurer d'utiliser `yield` une seule fois par dépendance.
+
+///
+
+/// note | Détails techniques
+
+Toute fonction valide à utiliser avec :
+
+* `@contextlib.contextmanager` ou
+* `@contextlib.asynccontextmanager`
+
+sera valide comme dépendance **FastAPI**.
+
+En fait, FastAPI utilise ces deux décorateurs en interne.
+
+///
+
+## Créer une dépendance de base de données avec `yield` { #a-database-dependency-with-yield }
+
+Par exemple, vous pouvez l'utiliser pour créer une session de base de données et la fermer après la fin.
+
+Seul le code précédant et incluant l'instruction `yield` est exécuté avant la création de la réponse :
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+La valeur transmise par `yield` est celle qui est injectée dans les *chemins d'accès* et autres dépendances :
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+Le code suivant l'instruction `yield` est exécuté après la réponse :
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip | Astuce
+
+Vous pouvez utiliser des fonctions `async` ou des fonctions classiques.
+
+**FastAPI** fera ce qu'il faut dans chaque cas, comme avec des dépendances normales.
+
+///
+
+## Créer une dépendance avec `yield` et `try` { #a-dependency-with-yield-and-try }
+
+Si vous utilisez un bloc `try` dans une dépendance avec `yield`, vous recevrez toute exception qui a été levée lors de l'utilisation de la dépendance.
+
+Par exemple, si à un moment donné, dans une autre dépendance ou dans un *chemin d'accès*, un code a effectué un « rollback » de transaction de base de données ou a créé une autre exception, vous recevrez l'exception dans votre dépendance.
+
+Vous pouvez donc rechercher cette exception spécifique dans la dépendance avec `except SomeException`.
+
+De la même manière, vous pouvez utiliser `finally` pour vous assurer que les étapes de sortie sont exécutées, qu'il y ait eu une exception ou non.
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## Utiliser des sous-dépendances avec `yield` { #sub-dependencies-with-yield }
+
+Vous pouvez avoir des sous-dépendances et des « arbres » de sous-dépendances de toute taille et forme, et certaines ou toutes peuvent utiliser `yield`.
+
+**FastAPI** s'assurera que le « code de sortie » dans chaque dépendance avec `yield` est exécuté dans le bon ordre.
+
+Par exemple, `dependency_c` peut dépendre de `dependency_b`, et `dependency_b` de `dependency_a` :
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+Et elles peuvent toutes utiliser `yield`.
+
+Dans ce cas, `dependency_c`, pour exécuter son code de sortie, a besoin que la valeur de `dependency_b` (appelée ici `dep_b`) soit toujours disponible.
+
+Et, à son tour, `dependency_b` a besoin que la valeur de `dependency_a` (appelée ici `dep_a`) soit disponible pour son code de sortie.
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+De la même manière, vous pouvez avoir certaines dépendances avec `yield` et d'autres avec `return`, et faire en sorte que certaines dépendent des autres.
+
+Et vous pouvez avoir une seule dépendance qui exige plusieurs autres dépendances avec `yield`, etc.
+
+Vous pouvez combiner les dépendances comme vous le souhaitez.
+
+**FastAPI** s'assurera que tout est exécuté dans le bon ordre.
+
+/// note | Détails techniques
+
+Cela fonctionne grâce aux gestionnaires de contexte de Python.
+
+**FastAPI** les utilise en interne pour y parvenir.
+
+///
+
+## Utiliser des dépendances avec `yield` et `HTTPException` { #dependencies-with-yield-and-httpexception }
+
+Vous avez vu que vous pouvez utiliser des dépendances avec `yield` et avoir des blocs `try` qui tentent d'exécuter du code puis exécutent du code de sortie après `finally`.
+
+Vous pouvez également utiliser `except` pour intercepter l'exception qui a été levée et faire quelque chose avec.
+
+Par exemple, vous pouvez lever une autre exception, comme `HTTPException`.
+
+/// tip | Astuce
+
+C'est une technique plutôt avancée, et dans la plupart des cas vous n'en aurez pas vraiment besoin, car vous pouvez lever des exceptions (y compris `HTTPException`) depuis le reste de votre code applicatif, par exemple, dans la *fonction de chemin d'accès*.
+
+Mais elle est à votre disposition si vous en avez besoin. 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+Si vous souhaitez intercepter des exceptions et créer une réponse personnalisée en fonction de cela, créez un [Gestionnaire d'exceptions personnalisé](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
+
+## Utiliser des dépendances avec `yield` et `except` { #dependencies-with-yield-and-except }
+
+Si vous interceptez une exception avec `except` dans une dépendance avec `yield` et que vous ne la relancez pas (ou que vous ne levez pas une nouvelle exception), FastAPI ne pourra pas remarquer qu'il y a eu une exception, de la même manière que cela se produirait avec Python classique :
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+Dans ce cas, le client verra une réponse *HTTP 500 Internal Server Error* comme il se doit, étant donné que nous ne levons pas de `HTTPException` ou similaire, mais le serveur **n'aura aucun logs** ni aucune autre indication de l'erreur. 😱
+
+### Toujours `raise` dans les dépendances avec `yield` et `except` { #always-raise-in-dependencies-with-yield-and-except }
+
+Si vous interceptez une exception dans une dépendance avec `yield`, à moins de lever une autre `HTTPException` ou similaire, **vous devez relancer l'exception d'origine**.
+
+Vous pouvez relancer la même exception avec `raise` :
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+À présent, le client recevra la même réponse *HTTP 500 Internal Server Error*, mais le serveur aura notre `InternalError` personnalisé dans les logs. 😎
+
+## Comprendre l'exécution des dépendances avec `yield` { #execution-of-dependencies-with-yield }
+
+La séquence d'exécution ressemble plus ou moins à ce diagramme. Le temps s'écoule de haut en bas. Et chaque colonne représente une des parties qui interagit ou exécute du code.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant handler as Exception handler
+participant dep as Dep with yield
+participant operation as Path Operation
+participant tasks as Background tasks
+
+ Note over client,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ end
+
+ operation ->> client: Return response to client
+ Note over client,operation: Response is already sent, can't change it anymore
+ opt Tasks
+ operation -->> tasks: Send background tasks
+ end
+ opt Raise other exception
+ tasks -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info
+
+Une **seule réponse** sera envoyée au client. Il peut s'agir d'une des réponses d'erreur ou de la réponse provenant du *chemin d'accès*.
+
+Après l'envoi de l'une de ces réponses, aucune autre réponse ne peut être envoyée.
+
+///
+
+/// tip | Astuce
+
+Si vous levez une exception dans le code de la *fonction de chemin d'accès*, elle sera transmise aux dépendances avec `yield`, y compris `HTTPException`. Dans la plupart des cas, vous voudrez relancer cette même exception ou en lever une nouvelle depuis la dépendance avec `yield` pour vous assurer qu'elle est correctement gérée.
+
+///
+
+## Utiliser la sortie anticipée et `scope` { #early-exit-and-scope }
+
+Normalement, le code de sortie des dépendances avec `yield` est exécuté **après la réponse** envoyée au client.
+
+Mais si vous savez que vous n'aurez pas besoin d'utiliser la dépendance après être revenu de la *fonction de chemin d'accès*, vous pouvez utiliser `Depends(scope="function")` pour indiquer à FastAPI qu'il doit fermer la dépendance après le retour de la *fonction de chemin d'accès*, mais **avant** que la **réponse ne soit envoyée**.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` reçoit un paramètre `scope` qui peut être :
+
+* « function » : démarrer la dépendance avant la *fonction de chemin d'accès* qui gère la requête, terminer la dépendance après la fin de la *fonction de chemin d'accès*, mais **avant** que la réponse ne soit renvoyée au client. Ainsi, la fonction de dépendance sera exécutée **autour** de la *fonction de chemin d'accès*.
+* « request » : démarrer la dépendance avant la *fonction de chemin d'accès* qui gère la requête (similaire à l'utilisation de « function »), mais terminer **après** que la réponse a été renvoyée au client. Ainsi, la fonction de dépendance sera exécutée **autour** du cycle **requête** et réponse.
+
+S'il n'est pas spécifié et que la dépendance utilise `yield`, le `scope` sera par défaut « request ».
+
+### Définir `scope` pour les sous-dépendances { #scope-for-sub-dependencies }
+
+Lorsque vous déclarez une dépendance avec un `scope="request"` (par défaut), toute sous-dépendance doit également avoir un `scope` de « request ».
+
+Mais une dépendance avec un `scope` de « function » peut avoir des dépendances avec un `scope` de « function » et un `scope` de « request ».
+
+Cela vient du fait que toute dépendance doit pouvoir exécuter son code de sortie avant ses sous-dépendances, car elle pourrait encore avoir besoin de les utiliser pendant son code de sortie.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## Utiliser des dépendances avec `yield`, `HTTPException`, `except` et Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+Les dépendances avec `yield` ont évolué au fil du temps pour couvrir différents cas d'utilisation et corriger certains problèmes.
+
+Si vous souhaitez voir ce qui a changé dans différentes versions de FastAPI, vous pouvez en savoir plus dans le guide avancé, dans [Dépendances avancées - Dépendances avec `yield`, `HTTPException`, `except` et Background Tasks](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks){.internal-link target=_blank}.
+## Gestionnaires de contexte { #context-managers }
+
+### Que sont les « Context Managers » { #what-are-context-managers }
+
+Les « Context Managers » sont des objets Python que vous pouvez utiliser dans une instruction `with`.
+
+Par exemple, vous pouvez utiliser `with` pour lire un fichier :
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+En coulisse, `open("./somefile.txt")` crée un objet appelé « Context Manager ».
+
+Lorsque le bloc `with` se termine, il s'assure de fermer le fichier, même s'il y a eu des exceptions.
+
+Lorsque vous créez une dépendance avec `yield`, **FastAPI** créera en interne un gestionnaire de contexte pour celle-ci et le combinera avec d'autres outils associés.
+
+### Utiliser des gestionnaires de contexte dans des dépendances avec `yield` { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | Alertes
+
+C'est, plus ou moins, une idée « avancée ».
+
+Si vous débutez avec **FastAPI**, vous voudrez peut-être l'ignorer pour le moment.
+
+///
+
+En Python, vous pouvez créer des gestionnaires de contexte en créant une classe avec deux méthodes : `__enter__()` et `__exit__()`.
+
+Vous pouvez également les utiliser dans des dépendances **FastAPI** avec `yield` en utilisant
+des instructions `with` ou `async with` à l'intérieur de la fonction de dépendance :
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip | Astuce
+
+Une autre façon de créer un gestionnaire de contexte consiste à utiliser :
+
+* `@contextlib.contextmanager` ou
+* `@contextlib.asynccontextmanager`
+
+pour décorer une fonction avec un unique `yield`.
+
+C'est ce que **FastAPI** utilise en interne pour les dépendances avec `yield`.
+
+Mais vous n'avez pas à utiliser ces décorateurs pour les dépendances FastAPI (et vous ne devriez pas).
+
+FastAPI le fera pour vous en interne.
+
+///
diff --git a/docs/fr/docs/tutorial/dependencies/global-dependencies.md b/docs/fr/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 000000000..2c418ee4a
--- /dev/null
+++ b/docs/fr/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,15 @@
+# Dépendances globales { #global-dependencies }
+
+Pour certains types d'applications, vous pourriez vouloir ajouter des dépendances à l'application entière.
+
+Comme vous pouvez [ajouter des `dependencies` aux *décorateurs de chemin d'accès*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, vous pouvez les ajouter à l'application `FastAPI`.
+
+Dans ce cas, elles seront appliquées à tous les *chemins d'accès* de l'application :
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+Et toutes les idées de la section sur [l'ajout de `dependencies` aux *décorateurs de chemin d'accès*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} s'appliquent toujours, mais dans ce cas à tous les *chemins d'accès* de l'application.
+
+## Dépendances pour des groupes de *chemins d'accès* { #dependencies-for-groups-of-path-operations }
+
+Plus tard, en lisant comment structurer des applications plus grandes ([Applications plus grandes - Plusieurs fichiers](../../tutorial/bigger-applications.md){.internal-link target=_blank}), éventuellement avec plusieurs fichiers, vous apprendrez comment déclarer un unique paramètre `dependencies` pour un groupe de *chemins d'accès*.
diff --git a/docs/fr/docs/tutorial/dependencies/index.md b/docs/fr/docs/tutorial/dependencies/index.md
new file mode 100644
index 000000000..8fad77f62
--- /dev/null
+++ b/docs/fr/docs/tutorial/dependencies/index.md
@@ -0,0 +1,250 @@
+# Dépendances { #dependencies }
+
+**FastAPI** dispose d’un système d’**Injection de dépendances** très puissant mais intuitif.
+
+Il est conçu pour être très simple à utiliser, et pour faciliter l’intégration d’autres composants à **FastAPI** pour n’importe quel développeur.
+
+## Qu’est-ce que « l’injection de dépendances » { #what-is-dependency-injection }
+
+L’**« injection de dépendances »** signifie, en programmation, qu’il existe un moyen pour votre code (dans ce cas, vos fonctions de chemins d’accès) de déclarer ce dont il a besoin pour fonctionner et utiliser : « dépendances ».
+
+Ensuite, ce système (dans ce cas **FastAPI**) se charge de faire tout le nécessaire pour fournir à votre code ces dépendances requises (« injecter » les dépendances).
+
+C’est très utile lorsque vous avez besoin de :
+
+* Avoir de la logique partagée (la même logique de code encore et encore).
+* Partager des connexions à la base de données.
+* Imposer la sécurité, l’authentification, des exigences de rôles, etc.
+* Et bien d’autres choses ...
+
+Tout cela, en minimisant la répétition de code.
+
+## Premiers pas { #first-steps }
+
+Voyons un exemple très simple. Il sera tellement simple qu’il n’est pas très utile, pour l’instant.
+
+Mais de cette façon nous pouvons nous concentrer sur le fonctionnement du système d’**injection de dépendances**.
+
+### Créer une dépendance, ou « dependable » { #create-a-dependency-or-dependable }
+
+Concentrons-nous d’abord sur la dépendance.
+
+C’est simplement une fonction qui peut prendre tous les mêmes paramètres qu’une fonction de chemin d’accès peut prendre :
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+C’est tout.
+
+**2 lignes**.
+
+Et elle a la même forme et structure que toutes vos fonctions de chemins d’accès.
+
+Vous pouvez la considérer comme une fonction de chemin d’accès sans le « décorateur » (sans le `@app.get("/some-path")`).
+
+Et elle peut retourner tout ce que vous voulez.
+
+Dans ce cas, cette dépendance attend :
+
+* Un paramètre de requête optionnel `q` qui est une `str`.
+* Un paramètre de requête optionnel `skip` qui est un `int`, et vaut `0` par défaut.
+* Un paramètre de requête optionnel `limit` qui est un `int`, et vaut `100` par défaut.
+
+Puis elle retourne simplement un `dict` contenant ces valeurs.
+
+/// info | Info
+
+FastAPI a ajouté la prise en charge de `Annotated` (et a commencé à le recommander) dans la version 0.95.0.
+
+Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d’utiliser `Annotated`.
+
+Vous devez vous assurer de [mettre à niveau la version de FastAPI](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} vers au moins la 0.95.1 avant d’utiliser `Annotated`.
+
+///
+
+### Importer `Depends` { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### Déclarer la dépendance, dans le « dependant » { #declare-the-dependency-in-the-dependant }
+
+De la même manière que vous utilisez `Body`, `Query`, etc. avec les paramètres de votre fonction de chemin d’accès, utilisez `Depends` avec un nouveau paramètre :
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+Même si vous utilisez `Depends` dans les paramètres de votre fonction de la même façon que `Body`, `Query`, etc., `Depends` fonctionne un peu différemment.
+
+Vous ne donnez à `Depends` qu’un seul paramètre.
+
+Ce paramètre doit être quelque chose comme une fonction.
+
+Vous ne l’appelez pas directement (n’ajoutez pas de parenthèses à la fin), vous le passez simplement en paramètre à `Depends()`.
+
+Et cette fonction prend des paramètres de la même manière que les fonctions de chemins d’accès.
+
+/// tip | Astuce
+
+Vous verrez quelles autres « choses », en plus des fonctions, peuvent être utilisées comme dépendances dans le prochain chapitre.
+
+///
+
+Chaque fois qu’une nouvelle requête arrive, **FastAPI** se charge de :
+
+* Appeler votre fonction de dépendance (« dependable ») avec les bons paramètres.
+* Récupérer le résultat de votre fonction.
+* Affecter ce résultat au paramètre dans votre fonction de chemin d’accès.
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+De cette façon vous écrivez le code partagé une seule fois et **FastAPI** se charge de l’appeler pour vos chemins d’accès.
+
+/// check | Vérifications
+
+Notez que vous n’avez pas à créer une classe spéciale et à la passer quelque part à **FastAPI** pour l’« enregistrer » ou quoi que ce soit de similaire.
+
+Vous la passez simplement à `Depends` et **FastAPI** sait faire le reste.
+
+///
+
+## Partager des dépendances `Annotated` { #share-annotated-dependencies }
+
+Dans les exemples ci-dessus, vous voyez qu’il y a un tout petit peu de **duplication de code**.
+
+Lorsque vous devez utiliser la dépendance `common_parameters()`, vous devez écrire tout le paramètre avec l’annotation de type et `Depends()` :
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+Mais comme nous utilisons `Annotated`, nous pouvons stocker cette valeur `Annotated` dans une variable et l’utiliser à plusieurs endroits :
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | Astuce
+
+C’est simplement du Python standard, cela s’appelle un « alias de type », ce n’est en fait pas spécifique à **FastAPI**.
+
+Mais comme **FastAPI** est basé sur les standards Python, y compris `Annotated`, vous pouvez utiliser cette astuce dans votre code. 😎
+
+///
+
+Les dépendances continueront de fonctionner comme prévu, et la **meilleure partie** est que **l’information de type sera conservée**, ce qui signifie que votre éditeur pourra continuer à vous fournir **l’autocomplétion**, **des erreurs en ligne**, etc. Idem pour d’autres outils comme `mypy`.
+
+Cela sera particulièrement utile lorsque vous l’utiliserez dans une **grande base de code** où vous utilisez **les mêmes dépendances** encore et encore dans **de nombreux chemins d’accès**.
+
+## Utiliser `async` ou non { #to-async-or-not-to-async }
+
+Comme les dépendances seront aussi appelées par **FastAPI** (tout comme vos fonctions de chemins d’accès), les mêmes règles s’appliquent lors de la définition de vos fonctions.
+
+Vous pouvez utiliser `async def` ou un `def` normal.
+
+Et vous pouvez déclarer des dépendances avec `async def` à l’intérieur de fonctions de chemins d’accès `def` normales, ou des dépendances `def` à l’intérieur de fonctions de chemins d’accès `async def`, etc.
+
+Peu importe. **FastAPI** saura quoi faire.
+
+/// note | Remarque
+
+Si vous ne savez pas, consultez la section [Async : *« Pressé ? »*](../../async.md#in-a-hurry){.internal-link target=_blank} à propos de `async` et `await` dans la documentation.
+
+///
+
+## Intégrer à OpenAPI { #integrated-with-openapi }
+
+Toutes les déclarations de requête, validations et exigences de vos dépendances (et sous-dépendances) seront intégrées dans le même schéma OpenAPI.
+
+Ainsi, la documentation interactive contiendra aussi toutes les informations issues de ces dépendances :
+
+
+
+## Utilisation simple { #simple-usage }
+
+Si vous y regardez de près, les fonctions de chemins d’accès sont déclarées pour être utilisées chaque fois qu’un « chemin » et une « opération » correspondent, puis **FastAPI** se charge d’appeler la fonction avec les bons paramètres, en extrayant les données de la requête.
+
+En réalité, tous (ou la plupart) des frameworks web fonctionnent de cette manière.
+
+Vous n’appelez jamais ces fonctions directement. Elles sont appelées par votre framework (dans ce cas, **FastAPI**).
+
+Avec le système d’injection de dépendances, vous pouvez aussi indiquer à **FastAPI** que votre fonction de chemin d’accès « dépend » également d’autre chose qui doit être exécuté avant votre fonction de chemin d’accès, et **FastAPI** se chargera de l’exécuter et d’« injecter » les résultats.
+
+D’autres termes courants pour cette même idée « d’injection de dépendances » sont :
+
+* ressources
+* fournisseurs
+* services
+* injectables
+* composants
+
+## Plug-ins **FastAPI** { #fastapi-plug-ins }
+
+Les intégrations et « plug-ins » peuvent être construits en utilisant le système d’**injection de dépendances**. Mais en réalité, il n’y a **pas besoin de créer des « plug-ins »**, car en utilisant des dépendances il est possible de déclarer un nombre infini d’intégrations et d’interactions qui deviennent disponibles pour vos fonctions de chemins d’accès.
+
+Et les dépendances peuvent être créées de manière très simple et intuitive, ce qui vous permet d’importer juste les packages Python dont vous avez besoin, et de les intégrer à vos fonctions d’API en quelques lignes de code, *littéralement*.
+
+Vous verrez des exemples de cela dans les prochains chapitres, à propos des bases de données relationnelles et NoSQL, de la sécurité, etc.
+
+## Compatibilité **FastAPI** { #fastapi-compatibility }
+
+La simplicité du système d’injection de dépendances rend **FastAPI** compatible avec :
+
+* toutes les bases de données relationnelles
+* les bases de données NoSQL
+* les packages externes
+* les API externes
+* les systèmes d’authentification et d’autorisation
+* les systèmes de supervision d’usage d’API
+* les systèmes d’injection de données de réponse
+* etc.
+
+## Simple et puissant { #simple-and-powerful }
+
+Bien que le système hiérarchique d’injection de dépendances soit très simple à définir et à utiliser, il reste très puissant.
+
+Vous pouvez définir des dépendances qui, à leur tour, peuvent définir leurs propres dépendances.
+
+Au final, un arbre hiérarchique de dépendances est construit, et le système d’**injection de dépendances** se charge de résoudre toutes ces dépendances pour vous (et leurs sous-dépendances) et de fournir (injecter) les résultats à chaque étape.
+
+Par exemple, supposons que vous ayez 4 endpoints d’API (chemins d’accès) :
+
+* `/items/public/`
+* `/items/private/`
+* `/users/{user_id}/activate`
+* `/items/pro/`
+
+alors vous pourriez ajouter différentes exigences d’autorisations pour chacun d’eux uniquement avec des dépendances et des sous-dépendances :
+
+```mermaid
+graph TB
+
+current_user(["current_user"])
+active_user(["active_user"])
+admin_user(["admin_user"])
+paying_user(["paying_user"])
+
+public["/items/public/"]
+private["/items/private/"]
+activate_user["/users/{user_id}/activate"]
+pro_items["/items/pro/"]
+
+current_user --> active_user
+active_user --> admin_user
+active_user --> paying_user
+
+current_user --> public
+active_user --> private
+admin_user --> activate_user
+paying_user --> pro_items
+```
+
+## Intégrer à **OpenAPI** { #integrated-with-openapi_1 }
+
+Toutes ces dépendances, tout en déclarant leurs exigences, ajoutent également des paramètres, des validations, etc. à vos chemins d’accès.
+
+**FastAPI** se chargera d’ajouter le tout au schéma OpenAPI, afin que cela apparaisse dans les systèmes de documentation interactive.
diff --git a/docs/fr/docs/tutorial/dependencies/sub-dependencies.md b/docs/fr/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 000000000..473ff02ba
--- /dev/null
+++ b/docs/fr/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# Sous-dépendances { #sub-dependencies }
+
+Vous pouvez créer des dépendances qui ont des sous-dépendances.
+
+Elles peuvent être aussi profondes que nécessaire.
+
+**FastAPI** se chargera de les résoudre.
+
+## Créer une première dépendance « dependable » { #first-dependency-dependable }
+
+Vous pouvez créer une première dépendance (« dependable ») comme :
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+Elle déclare un paramètre de requête optionnel `q` de type `str`, puis le retourne simplement.
+
+C'est assez simple (pas très utile), mais cela nous aidera à nous concentrer sur le fonctionnement des sous-dépendances.
+
+## Créer une seconde dépendance, « dependable » et « dependant » { #second-dependency-dependable-and-dependant }
+
+Vous pouvez ensuite créer une autre fonction de dépendance (un « dependable ») qui, en même temps, déclare sa propre dépendance (elle est donc aussi un « dependant ») :
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+Concentrons-nous sur les paramètres déclarés :
+
+- Même si cette fonction est elle‑même une dépendance (« dependable »), elle déclare aussi une autre dépendance (elle « dépend » d'autre chose).
+ - Elle dépend de `query_extractor` et affecte la valeur renvoyée au paramètre `q`.
+- Elle déclare également un cookie `last_query` optionnel, de type `str`.
+ - Si l'utilisateur n'a fourni aucune requête `q`, nous utilisons la dernière requête utilisée, que nous avons enregistrée auparavant dans un cookie.
+
+## Utiliser la dépendance { #use-the-dependency }
+
+Nous pouvons ensuite utiliser la dépendance avec :
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info
+
+Notez que nous ne déclarons qu'une seule dépendance dans la *fonction de chemin d'accès*, `query_or_cookie_extractor`.
+
+Mais **FastAPI** saura qu'il doit d'abord résoudre `query_extractor`, pour passer ses résultats à `query_or_cookie_extractor` lors de son appel.
+
+///
+
+```mermaid
+graph TB
+
+query_extractor(["query_extractor"])
+query_or_cookie_extractor(["query_or_cookie_extractor"])
+
+read_query["/items/"]
+
+query_extractor --> query_or_cookie_extractor --> read_query
+```
+
+## Utiliser la même dépendance plusieurs fois { #using-the-same-dependency-multiple-times }
+
+Si l'une de vos dépendances est déclarée plusieurs fois pour le même *chemin d'accès*, par exemple si plusieurs dépendances ont une sous-dépendance commune, **FastAPI** saura n'appeler cette sous-dépendance qu'une seule fois par requête.
+
+Et il enregistrera la valeur renvoyée dans un « cache » et la transmettra à tous les « dependants » qui en ont besoin dans cette requête spécifique, au lieu d'appeler la dépendance plusieurs fois pour la même requête.
+
+Dans un scénario avancé où vous savez que vous avez besoin que la dépendance soit appelée à chaque étape (éventuellement plusieurs fois) dans la même requête au lieu d'utiliser la valeur « mise en cache », vous pouvez définir le paramètre `use_cache=False` lors de l'utilisation de `Depends` :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ non annoté
+
+/// tip | Astuce
+
+Privilégiez la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## Récapituler { #recap }
+
+En dehors de tout le jargon utilisé ici, le système d'**injection de dépendances** est assez simple.
+
+Ce ne sont que des fonctions qui ressemblent aux *fonctions de chemin d'accès*.
+
+Mais il est très puissant et vous permet de déclarer des « graphes » (arbres) de dépendances imbriquées aussi profondément que vous le souhaitez.
+
+/// tip | Astuce
+
+Tout cela peut ne pas sembler très utile avec ces exemples simples.
+
+Mais vous verrez à quel point c'est utile dans les chapitres sur la **sécurité**.
+
+Et vous verrez aussi la quantité de code que cela vous fera économiser.
+
+///
diff --git a/docs/fr/docs/tutorial/encoder.md b/docs/fr/docs/tutorial/encoder.md
new file mode 100644
index 000000000..f94be429c
--- /dev/null
+++ b/docs/fr/docs/tutorial/encoder.md
@@ -0,0 +1,35 @@
+# Encodeur compatible JSON { #json-compatible-encoder }
+
+Il existe des cas où vous pourriez avoir besoin de convertir un type de données (comme un modèle Pydantic) en quelque chose de compatible avec JSON (comme un `dict`, `list`, etc.).
+
+Par exemple, si vous devez le stocker dans une base de données.
+
+Pour cela, **FastAPI** fournit une fonction `jsonable_encoder()`.
+
+## Utiliser `jsonable_encoder` { #using-the-jsonable-encoder }
+
+Imaginons que vous ayez une base de données `fake_db` qui ne reçoit que des données compatibles JSON.
+
+Par exemple, elle ne reçoit pas d'objets `datetime`, car ceux-ci ne sont pas compatibles avec JSON.
+
+Ainsi, un objet `datetime` doit être converti en une `str` contenant les données au format ISO.
+
+De la même manière, cette base de données n'accepterait pas un modèle Pydantic (un objet avec des attributs), seulement un `dict`.
+
+Vous pouvez utiliser `jsonable_encoder` pour cela.
+
+Elle reçoit un objet, comme un modèle Pydantic, et renvoie une version compatible JSON :
+
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
+
+Dans cet exemple, elle convertirait le modèle Pydantic en `dict`, et le `datetime` en `str`.
+
+Le résultat de son appel est quelque chose qui peut être encodé avec la fonction standard de Python `json.dumps()`.
+
+Elle ne renvoie pas une grande `str` contenant les données au format JSON (sous forme de chaîne). Elle renvoie une structure de données standard de Python (par ex. un `dict`) avec des valeurs et sous-valeurs toutes compatibles avec JSON.
+
+/// note | Remarque
+
+`jsonable_encoder` est en fait utilisée par **FastAPI** en interne pour convertir des données. Mais elle est utile dans de nombreux autres scénarios.
+
+///
diff --git a/docs/fr/docs/tutorial/extra-data-types.md b/docs/fr/docs/tutorial/extra-data-types.md
new file mode 100644
index 000000000..edaa7bd4c
--- /dev/null
+++ b/docs/fr/docs/tutorial/extra-data-types.md
@@ -0,0 +1,62 @@
+# Types de données supplémentaires { #extra-data-types }
+
+Jusqu'à présent, vous avez utilisé des types de données courants, comme :
+
+* `int`
+* `float`
+* `str`
+* `bool`
+
+Mais vous pouvez aussi utiliser des types de données plus complexes.
+
+Et vous bénéficierez toujours des mêmes fonctionnalités que jusqu'à présent :
+
+* Excellente prise en charge dans l'éditeur.
+* Conversion des données à partir des requêtes entrantes.
+* Conversion des données pour les données de réponse.
+* Validation des données.
+* Annotations et documentation automatiques.
+
+## Autres types de données { #other-data-types }
+
+Voici quelques types de données supplémentaires que vous pouvez utiliser :
+
+* `UUID` :
+ * Un « identifiant universel unique » standard, couramment utilisé comme ID dans de nombreuses bases de données et systèmes.
+ * Dans les requêtes et les réponses, il sera représenté sous forme de `str`.
+* `datetime.datetime` :
+ * Un `datetime.datetime` Python.
+ * Dans les requêtes et les réponses, il sera représenté sous forme de `str` au format ISO 8601, par exemple : `2008-09-15T15:53:00+05:00`.
+* `datetime.date` :
+ * `datetime.date` Python.
+ * Dans les requêtes et les réponses, il sera représenté sous forme de `str` au format ISO 8601, par exemple : `2008-09-15`.
+* `datetime.time` :
+ * Un `datetime.time` Python.
+ * Dans les requêtes et les réponses, il sera représenté sous forme de `str` au format ISO 8601, par exemple : `14:23:55.003`.
+* `datetime.timedelta` :
+ * Un `datetime.timedelta` Python.
+ * Dans les requêtes et les réponses, il sera représenté sous forme de `float` de secondes totales.
+ * Pydantic permet aussi de le représenter sous la forme d'un « encodage de différence de temps ISO 8601 », voir la documentation pour plus d'informations.
+* `frozenset` :
+ * Dans les requêtes et les réponses, traité de la même manière qu'un `set` :
+ * Dans les requêtes, une liste sera lue, les doublons éliminés, puis convertie en `set`.
+ * Dans les réponses, le `set` sera converti en `list`.
+ * Le schéma généré indiquera que les valeurs du `set` sont uniques (en utilisant `uniqueItems` de JSON Schema).
+* `bytes` :
+ * `bytes` Python standard.
+ * Dans les requêtes et les réponses, traité comme une `str`.
+ * Le schéma généré indiquera qu'il s'agit d'une `str` avec le « format » `binary`.
+* `Decimal` :
+ * `Decimal` Python standard.
+ * Dans les requêtes et les réponses, géré de la même manière qu'un `float`.
+* Vous pouvez consulter tous les types de données Pydantic valides ici : Types de données Pydantic.
+
+## Exemple { #example }
+
+Voici un exemple de *chemin d'accès* avec des paramètres utilisant certains des types ci-dessus.
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
+
+Notez que les paramètres à l'intérieur de la fonction ont leur type de données naturel et que vous pouvez, par exemple, effectuer des manipulations de dates normales, comme :
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/fr/docs/tutorial/extra-models.md b/docs/fr/docs/tutorial/extra-models.md
new file mode 100644
index 000000000..1f9eb1561
--- /dev/null
+++ b/docs/fr/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# Modèles supplémentaires { #extra-models }
+
+En poursuivant l'exemple précédent, il est courant d'avoir plusieurs modèles liés.
+
+C'est particulièrement vrai pour les modèles d'utilisateur, car :
+
+* Le modèle d'entrée doit pouvoir contenir un mot de passe.
+* Le modèle de sortie ne doit pas avoir de mot de passe.
+* Le modèle de base de données devra probablement avoir un mot de passe haché.
+
+/// danger | Danger
+
+Ne stockez jamais les mots de passe des utilisateurs en clair. Stockez toujours un « hachage sécurisé » que vous pourrez ensuite vérifier.
+
+Si vous ne savez pas ce que c'est, vous apprendrez ce qu'est un « hachage de mot de passe » dans les [chapitres sur la sécurité](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+
+///
+
+## Utiliser plusieurs modèles { #multiple-models }
+
+Voici une idée générale de l'apparence des modèles avec leurs champs de mot de passe et les endroits où ils sont utilisés :
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### À propos de `**user_in.model_dump()` { #about-user-in-model-dump }
+
+#### La méthode `.model_dump()` de Pydantic { #pydantics-model-dump }
+
+`user_in` est un modèle Pydantic de classe `UserIn`.
+
+Les modèles Pydantic ont une méthode `.model_dump()` qui renvoie un `dict` avec les données du modèle.
+
+Ainsi, si nous créons un objet Pydantic `user_in` comme :
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+et que nous appelons ensuite :
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+nous avons maintenant un `dict` avec les données dans la variable `user_dict` (c'est un `dict` au lieu d'un objet modèle Pydantic).
+
+Et si nous appelons :
+
+```Python
+print(user_dict)
+```
+
+nous obtiendrions un `dict` Python contenant :
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### Déballer un `dict` { #unpacking-a-dict }
+
+Si nous prenons un `dict` comme `user_dict` et que nous le passons à une fonction (ou une classe) avec `**user_dict`, Python va « déballer » ce `dict`. Il passera les clés et valeurs de `user_dict` directement comme arguments nommés.
+
+Ainsi, en reprenant `user_dict` ci-dessus, écrire :
+
+```Python
+UserInDB(**user_dict)
+```
+
+aurait pour résultat quelque chose d'équivalent à :
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ full_name=None,
+)
+```
+
+Ou plus exactement, en utilisant `user_dict` directement, quels que soient ses contenus futurs :
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+)
+```
+
+#### Créer un modèle Pydantic à partir du contenu d'un autre { #a-pydantic-model-from-the-contents-of-another }
+
+Comme dans l'exemple ci-dessus nous avons obtenu `user_dict` depuis `user_in.model_dump()`, ce code :
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+serait équivalent à :
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+... parce que `user_in.model_dump()` est un `dict`, et nous demandons ensuite à Python de « déballer » ce `dict` en le passant à `UserInDB` précédé de `**`.
+
+Ainsi, nous obtenons un modèle Pydantic à partir des données d'un autre modèle Pydantic.
+
+#### Déballer un `dict` et ajouter des mots-clés supplémentaires { #unpacking-a-dict-and-extra-keywords }
+
+Et en ajoutant ensuite l'argument nommé supplémentaire `hashed_password=hashed_password`, comme ici :
+
+```Python
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
+```
+
+... revient à :
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ hashed_password = hashed_password,
+)
+```
+
+/// warning | Alertes
+
+Les fonctions auxiliaires `fake_password_hasher` et `fake_save_user` ne servent qu'à démontrer un flux de données possible, mais elles n'offrent évidemment aucune sécurité réelle.
+
+///
+
+## Réduire la duplication { #reduce-duplication }
+
+Réduire la duplication de code est l'une des idées centrales de **FastAPI**.
+
+La duplication de code augmente les risques de bogues, de problèmes de sécurité, de désynchronisation du code (lorsque vous mettez à jour un endroit mais pas les autres), etc.
+
+Et ces modèles partagent beaucoup de données et dupliquent des noms et types d'attributs.
+
+Nous pouvons faire mieux.
+
+Nous pouvons déclarer un modèle `UserBase` qui sert de base à nos autres modèles. Ensuite, nous pouvons créer des sous-classes de ce modèle qui héritent de ses attributs (déclarations de type, validation, etc.).
+
+Toutes les conversions de données, validations, documentation, etc., fonctionneront comme d'habitude.
+
+De cette façon, nous pouvons ne déclarer que les différences entre les modèles (avec `password` en clair, avec `hashed_password` et sans mot de passe) :
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` ou `anyOf` { #union-or-anyof }
+
+Vous pouvez déclarer qu'une réponse est l'`Union` de deux types ou plus, ce qui signifie que la réponse peut être n'importe lequel d'entre eux.
+
+Cela sera défini dans OpenAPI avec `anyOf`.
+
+Pour ce faire, utilisez l'annotation de type Python standard `typing.Union` :
+
+/// note | Remarque
+
+Lors de la définition d'une `Union`, incluez d'abord le type le plus spécifique, suivi du type le moins spécifique. Dans l'exemple ci-dessous, le type le plus spécifique `PlaneItem` précède `CarItem` dans `Union[PlaneItem, CarItem]`.
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### `Union` en Python 3.10 { #union-in-python-3-10 }
+
+Dans cet exemple, nous passons `Union[PlaneItem, CarItem]` comme valeur de l'argument `response_model`.
+
+Comme nous le passons comme valeur d'un argument au lieu de l'utiliser dans une annotation de type, nous devons utiliser `Union` même en Python 3.10.
+
+S'il s'agissait d'une annotation de type, nous pourrions utiliser la barre verticale, comme :
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+Mais si nous écrivons cela dans l'affectation `response_model=PlaneItem | CarItem`, nous obtiendrons une erreur, car Python essaierait d'effectuer une « opération invalide » entre `PlaneItem` et `CarItem` au lieu de l'interpréter comme une annotation de type.
+
+## Liste de modèles { #list-of-models }
+
+De la même manière, vous pouvez déclarer des réponses contenant des listes d'objets.
+
+Pour cela, utilisez le `list` Python standard :
+
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
+
+## Réponse avec un `dict` arbitraire { #response-with-arbitrary-dict }
+
+Vous pouvez également déclarer une réponse en utilisant un simple `dict` arbitraire, en déclarant uniquement le type des clés et des valeurs, sans utiliser de modèle Pydantic.
+
+C'est utile si vous ne connaissez pas à l'avance les noms de champs/attributs valides (qui seraient nécessaires pour un modèle Pydantic).
+
+Dans ce cas, vous pouvez utiliser `dict` :
+
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
+
+## Récapitulatif { #recap }
+
+Utilisez plusieurs modèles Pydantic et héritez librement selon chaque cas.
+
+Vous n'avez pas besoin d'avoir un seul modèle de données par entité si cette entité doit pouvoir avoir différents « états ». Comme pour l'« entité » utilisateur, avec un état incluant `password`, `password_hash` et sans mot de passe.
diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md
index b2693b3e5..ae2358468 100644
--- a/docs/fr/docs/tutorial/first-steps.md
+++ b/docs/fr/docs/tutorial/first-steps.md
@@ -1,8 +1,8 @@
-# Démarrage { #first-steps }
+# Démarrer { #first-steps }
Le fichier **FastAPI** le plus simple possible pourrait ressembler à ceci :
-{* ../../docs_src/first_steps/tutorial001_py39.py *}
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
Copiez cela dans un fichier `main.py`.
@@ -56,7 +56,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Cette ligne montre l’URL où votre application est servie, sur votre machine locale.
-### Vérifiez { #check-it }
+### Vérifier { #check-it }
Ouvrez votre navigateur à l’adresse http://127.0.0.1:8000.
@@ -183,7 +183,7 @@ C’est tout ! Vous pouvez maintenant accéder à votre application à cette URL
### Étape 1 : importer `FastAPI` { #step-1-import-fastapi }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[1] *}
`FastAPI` est une classe Python qui fournit toutes les fonctionnalités nécessaires à votre API.
@@ -197,7 +197,7 @@ Vous pouvez donc aussi utiliser toutes les fonctionnalités de get opération
+* en utilisant une get opération
-/// info | `@décorateur` Info
+/// info | `@decorator` Info
Cette syntaxe `@something` en Python est appelée un « décorateur ».
@@ -320,7 +320,7 @@ Voici notre « fonction de chemin d’accès » :
* **opération** : `get`.
* **fonction** : la fonction sous le « décorateur » (sous `@app.get("/")`).
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
C’est une fonction Python.
@@ -332,9 +332,9 @@ Dans ce cas, c’est une fonction `async`.
Vous pouvez aussi la définir comme une fonction normale au lieu de `async def` :
-{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
-/// note
+/// note | Remarque
Si vous ne connaissez pas la différence, consultez [Asynchrone : « Pressé ? »](../async.md#in-a-hurry){.internal-link target=_blank}.
@@ -342,7 +342,7 @@ Si vous ne connaissez pas la différence, consultez [Asynchrone : « Pressé ?
### Étape 5 : retourner le contenu { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
Vous pouvez retourner un `dict`, une `list`, des valeurs uniques comme `str`, `int`, etc.
diff --git a/docs/fr/docs/tutorial/handling-errors.md b/docs/fr/docs/tutorial/handling-errors.md
new file mode 100644
index 000000000..38935c21c
--- /dev/null
+++ b/docs/fr/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# Gérer les erreurs { #handling-errors }
+
+Il existe de nombreuses situations où vous devez signaler une erreur à un client qui utilise votre API.
+
+Ce client peut être un navigateur avec un frontend, un code d'un tiers, un appareil IoT, etc.
+
+Vous pourriez avoir besoin d'indiquer au client que :
+
+* Le client n'a pas les privilèges suffisants pour cette opération.
+* Le client n'a pas accès à cette ressource.
+* L'élément auquel le client tentait d'accéder n'existe pas.
+* etc.
+
+Dans ces cas, vous retournez normalement un **code d'état HTTP** dans la plage de **400** (de 400 à 499).
+
+C'est similaire aux codes d'état HTTP 200 (de 200 à 299). Ces codes « 200 » signifient que, d'une certaine manière, la requête a été un « succès ».
+
+Les codes d'état dans la plage des 400 signifient qu'il y a eu une erreur côté client.
+
+Vous souvenez-vous de toutes ces erreurs **« 404 Not Found »** (et des blagues) ?
+
+## Utiliser `HTTPException` { #use-httpexception }
+
+Pour renvoyer au client des réponses HTTP avec des erreurs, vous utilisez `HTTPException`.
+
+### Importer `HTTPException` { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
+
+### Lever une `HTTPException` dans votre code { #raise-an-httpexception-in-your-code }
+
+`HTTPException` est une exception Python normale avec des données supplémentaires pertinentes pour les API.
+
+Comme il s'agit d'une exception Python, vous ne la `return` pas, vous la `raise`.
+
+Cela signifie aussi que si vous êtes dans une fonction utilitaire appelée depuis votre fonction de chemin d'accès, et que vous levez la `HTTPException` à l'intérieur de cette fonction utilitaire, le reste du code de la fonction de chemin d'accès ne s'exécutera pas : la requête sera immédiatement interrompue et l'erreur HTTP issue de la `HTTPException` sera envoyée au client.
+
+L'avantage de lever une exception plutôt que de retourner une valeur apparaîtra plus clairement dans la section sur les Dépendances et la Sécurité.
+
+Dans cet exemple, lorsque le client demande un élément par un ID qui n'existe pas, levez une exception avec un code d'état `404` :
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+
+### Réponse résultante { #the-resulting-response }
+
+Si le client demande `http://example.com/items/foo` (un `item_id` « foo »), il recevra un code d'état HTTP 200 et une réponse JSON :
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Mais si le client demande `http://example.com/items/bar` (un `item_id` inexistant « bar »), il recevra un code d'état HTTP 404 (l'erreur « not found ») et une réponse JSON :
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | Astuce
+
+Lorsque vous levez une `HTTPException`, vous pouvez passer n'importe quelle valeur convertible en JSON comme paramètre `detail`, pas uniquement un `str`.
+
+Vous pouvez passer un `dict`, une `list`, etc.
+
+Elles sont gérées automatiquement par **FastAPI** et converties en JSON.
+
+///
+
+## Ajouter des en-têtes personnalisés { #add-custom-headers }
+
+Dans certaines situations, il est utile de pouvoir ajouter des en-têtes personnalisés à l'erreur HTTP. Par exemple, pour certains types de sécurité.
+
+Vous n'aurez probablement pas besoin de l'utiliser directement dans votre code.
+
+Mais si vous en aviez besoin pour un scénario avancé, vous pouvez ajouter des en-têtes personnalisés :
+
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
+
+## Installer des gestionnaires d'exception personnalisés { #install-custom-exception-handlers }
+
+Vous pouvez ajouter des gestionnaires d'exception personnalisés avec les mêmes utilitaires d'exception de Starlette.
+
+Supposons que vous ayez une exception personnalisée `UnicornException` que vous (ou une bibliothèque que vous utilisez) pourriez `raise`.
+
+Et vous souhaitez gérer cette exception globalement avec FastAPI.
+
+Vous pouvez ajouter un gestionnaire d'exception personnalisé avec `@app.exception_handler()` :
+
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
+
+Ici, si vous appelez `/unicorns/yolo`, le chemin d'accès va `raise` une `UnicornException`.
+
+Mais elle sera gérée par `unicorn_exception_handler`.
+
+Ainsi, vous recevrez une erreur propre, avec un code d'état HTTP `418` et un contenu JSON :
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette.requests import Request` et `from starlette.responses import JSONResponse`.
+
+**FastAPI** fournit les mêmes `starlette.responses` sous `fastapi.responses` par simple commodité pour vous, développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en va de même pour `Request`.
+
+///
+
+## Remplacer les gestionnaires d'exception par défaut { #override-the-default-exception-handlers }
+
+**FastAPI** fournit des gestionnaires d'exception par défaut.
+
+Ces gestionnaires se chargent de renvoyer les réponses JSON par défaut lorsque vous `raise` une `HTTPException` et lorsque la requête contient des données invalides.
+
+Vous pouvez remplacer ces gestionnaires d'exception par les vôtres.
+
+### Remplacer les exceptions de validation de la requête { #override-request-validation-exceptions }
+
+Lorsqu'une requête contient des données invalides, **FastAPI** lève en interne une `RequestValidationError`.
+
+Et il inclut également un gestionnaire d'exception par défaut pour cela.
+
+Pour la remplacer, importez `RequestValidationError` et utilisez-la avec `@app.exception_handler(RequestValidationError)` pour décorer le gestionnaire d'exception.
+
+Le gestionnaire d'exception recevra une `Request` et l'exception.
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
+
+À présent, si vous allez sur `/items/foo`, au lieu d'obtenir l'erreur JSON par défaut suivante :
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+vous obtiendrez une version texte, avec :
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### Remplacer le gestionnaire d'erreurs `HTTPException` { #override-the-httpexception-error-handler }
+
+De la même manière, vous pouvez remplacer le gestionnaire de `HTTPException`.
+
+Par exemple, vous pourriez vouloir renvoyer une réponse en texte brut au lieu de JSON pour ces erreurs :
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** fournit les mêmes `starlette.responses` sous `fastapi.responses` par simple commodité pour vous, le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+
+///
+
+/// warning | Alertes
+
+Gardez à l'esprit que la `RequestValidationError` contient l'information du nom de fichier et de la ligne où l'erreur de validation se produit, afin que vous puissiez l'afficher dans vos journaux avec les informations pertinentes si vous le souhaitez.
+
+Mais cela signifie que si vous vous contentez de la convertir en chaîne et de renvoyer cette information directement, vous pourriez divulguer un peu d'information sur votre système. C'est pourquoi, ici, le code extrait et affiche chaque erreur indépendamment.
+
+///
+
+### Utiliser le corps de `RequestValidationError` { #use-the-requestvalidationerror-body }
+
+La `RequestValidationError` contient le `body` qu'elle a reçu avec des données invalides.
+
+Vous pouvez l'utiliser pendant le développement de votre application pour journaliser le corps et le déboguer, le renvoyer à l'utilisateur, etc.
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
+
+Essayez maintenant d'envoyer un élément invalide comme :
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Vous recevrez une réponse vous indiquant que les données sont invalides et contenant le corps reçu :
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### `HTTPException` de FastAPI vs `HTTPException` de Starlette { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI** a sa propre `HTTPException`.
+
+Et la classe d'erreur `HTTPException` de **FastAPI** hérite de la classe d'erreur `HTTPException` de Starlette.
+
+La seule différence est que la `HTTPException` de **FastAPI** accepte toute donnée sérialisable en JSON pour le champ `detail`, tandis que la `HTTPException` de Starlette n'accepte que des chaînes.
+
+Ainsi, vous pouvez continuer à lever la `HTTPException` de **FastAPI** normalement dans votre code.
+
+Mais lorsque vous enregistrez un gestionnaire d'exception, vous devez l'enregistrer pour la `HTTPException` de Starlette.
+
+De cette façon, si une partie du code interne de Starlette, ou une extension ou un plug-in Starlette, lève une `HTTPException` de Starlette, votre gestionnaire pourra l'intercepter et la traiter.
+
+Dans cet exemple, afin de pouvoir avoir les deux `HTTPException` dans le même code, les exceptions de Starlette sont renommées en `StarletteHTTPException` :
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Réutiliser les gestionnaires d'exception de **FastAPI** { #reuse-fastapis-exception-handlers }
+
+Si vous souhaitez utiliser l'exception avec les mêmes gestionnaires d'exception par défaut de **FastAPI**, vous pouvez importer et réutiliser les gestionnaires d'exception par défaut depuis `fastapi.exception_handlers` :
+
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
+
+Dans cet exemple, vous vous contentez d'afficher l'erreur avec un message très expressif, mais vous voyez l'idée. Vous pouvez utiliser l'exception puis simplement réutiliser les gestionnaires d'exception par défaut.
diff --git a/docs/fr/docs/tutorial/header-param-models.md b/docs/fr/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..8fc1a3d36
--- /dev/null
+++ b/docs/fr/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Modèles de paramètres d'en-tête { #header-parameter-models }
+
+Si vous avez un groupe de **paramètres d'en-tête** liés, vous pouvez créer un **modèle Pydantic** pour les déclarer.
+
+Cela vous permet de **réutiliser le modèle** à **plusieurs endroits** et aussi de déclarer des validations et des métadonnées pour tous les paramètres en une seule fois. 😎
+
+/// note | Remarque
+
+Cela est pris en charge depuis la version `0.115.0` de FastAPI. 🤓
+
+///
+
+## Paramètres d'en-tête avec un modèle Pydantic { #header-parameters-with-a-pydantic-model }
+
+Déclarez les **paramètres d'en-tête** dont vous avez besoin dans un **modèle Pydantic**, puis déclarez le paramètre comme `Header` :
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** extrait les données de **chaque champ** depuis les **en-têtes** de la requête et vous fournit le modèle Pydantic que vous avez défini.
+
+## Consulter la documentation { #check-the-docs }
+
+Vous pouvez voir les en-têtes requis dans l'interface de la documentation à `/docs` :
+
+
+champs de
contactParamètre Type Description namestrLe nom identifiant de la personne/organisation de contact. urlstrL’URL pointant vers les informations de contact. DOIT être au format d’une URL. emailstrL’adresse e-mail de la personne/organisation de contact. DOIT être au format d’une adresse e-mail. champs de
license_infoParamètre Type Description namestrOBLIGATOIRE (si un license_info est défini). Le nom de la licence utilisée pour l’API.identifierstrUne expression de licence SPDX pour l’API. Le champ identifier est mutuellement exclusif du champ url. Disponible depuis OpenAPI 3.1.0, FastAPI 0.99.0.urlstrUne URL vers la licence utilisée pour l’API. DOIT être au format d’une URL.
+
+## Identifiant de licence { #license-identifier }
+
+Depuis OpenAPI 3.1.0 et FastAPI 0.99.0, vous pouvez également définir `license_info` avec un `identifier` au lieu d’une `url`.
+
+Par exemple :
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## Métadonnées pour les tags { #metadata-for-tags }
+
+Vous pouvez également ajouter des métadonnées supplémentaires pour les différents tags utilisés pour regrouper vos chemins d'accès avec le paramètre `openapi_tags`.
+
+Il prend une liste contenant un dictionnaire pour chaque tag.
+
+Chaque dictionnaire peut contenir :
+
+* `name` (**requis**) : un `str` avec le même nom de tag que vous utilisez dans le paramètre `tags` de vos *chemins d'accès* et `APIRouter`s.
+* `description` : un `str` avec une courte description pour le tag. Il peut contenir du Markdown et sera affiché dans l’interface utilisateur de la documentation.
+* `externalDocs` : un `dict` décrivant une documentation externe avec :
+ * `description` : un `str` avec une courte description pour la documentation externe.
+ * `url` (**requis**) : un `str` avec l’URL de la documentation externe.
+
+### Créer des métadonnées pour les tags { #create-metadata-for-tags }
+
+Essayons cela avec un exemple de tags pour `users` et `items`.
+
+Créez des métadonnées pour vos tags et transmettez-les au paramètre `openapi_tags` :
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+Notez que vous pouvez utiliser Markdown à l’intérieur des descriptions, par exemple « login » sera affiché en gras (**login**) et « fancy » sera affiché en italique (_fancy_).
+
+/// tip | Astuce
+
+Vous n’avez pas à ajouter des métadonnées pour tous les tags que vous utilisez.
+
+///
+
+### Utiliser vos tags { #use-your-tags }
+
+Utilisez le paramètre `tags` avec vos *chemins d'accès* (et `APIRouter`s) pour les affecter à différents tags :
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info
+
+En savoir plus sur les tags dans [Configuration de chemins d'accès](path-operation-configuration.md#tags){.internal-link target=_blank}.
+
+///
+
+### Consultez les documents { #check-the-docs }
+
+Désormais, si vous consultez les documents, ils afficheront toutes les métadonnées supplémentaires :
+
+
+
+### Définir l’ordre des tags { #order-of-tags }
+
+L’ordre de chaque dictionnaire de métadonnées de tag définit également l’ordre affiché dans l’interface utilisateur de la documentation.
+
+Par exemple, même si `users` viendrait après `items` par ordre alphabétique, il est affiché avant, car nous avons ajouté ses métadonnées comme premier dictionnaire de la liste.
+
+## URL OpenAPI { #openapi-url }
+
+Par défaut, le schéma OpenAPI est servi à `/openapi.json`.
+
+Mais vous pouvez le configurer avec le paramètre `openapi_url`.
+
+Par exemple, pour qu’il soit servi à `/api/v1/openapi.json` :
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+Si vous souhaitez désactiver complètement le schéma OpenAPI, vous pouvez définir `openapi_url=None`, cela désactivera également les interfaces utilisateur de la documentation qui l’utilisent.
+
+## URL des documents { #docs-urls }
+
+Vous pouvez configurer les deux interfaces utilisateur de documentation incluses :
+
+* **Swagger UI** : servie à `/docs`.
+ * Vous pouvez définir son URL avec le paramètre `docs_url`.
+ * Vous pouvez la désactiver en définissant `docs_url=None`.
+* **ReDoc** : servie à `/redoc`.
+ * Vous pouvez définir son URL avec le paramètre `redoc_url`.
+ * Vous pouvez la désactiver en définissant `redoc_url=None`.
+
+Par exemple, pour que Swagger UI soit servi à `/documentation` et désactiver ReDoc :
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/fr/docs/tutorial/middleware.md b/docs/fr/docs/tutorial/middleware.md
new file mode 100644
index 000000000..6cbbc3e45
--- /dev/null
+++ b/docs/fr/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# Middleware { #middleware }
+
+Vous pouvez ajouter des middlewares aux applications **FastAPI**.
+
+Un « middleware » est une fonction qui agit sur chaque **requête** avant qu’elle ne soit traitée par un *chemin d'accès* spécifique. Et aussi sur chaque **réponse** avant son renvoi.
+
+* Il intercepte chaque **requête** qui parvient à votre application.
+* Il peut alors faire quelque chose avec cette **requête** ou exécuter tout code nécessaire.
+* Ensuite, il transmet la **requête** pour qu’elle soit traitée par le reste de l’application (par un *chemin d'accès*).
+* Puis il récupère la **réponse** générée par l’application (par un *chemin d'accès*).
+* Il peut faire quelque chose avec cette **réponse** ou exécuter tout code nécessaire.
+* Enfin, il renvoie la **réponse**.
+
+/// note | Détails techniques
+
+Si vous avez des dépendances avec `yield`, le code de sortie s’exécutera après le middleware.
+
+S’il y avait des tâches d’arrière-plan (présentées dans la section [Tâches d’arrière-plan](background-tasks.md){.internal-link target=_blank}, que vous verrez plus tard), elles s’exécuteront après tous les middlewares.
+
+///
+
+## Créer un middleware { #create-a-middleware }
+
+Pour créer un middleware, utilisez le décorateur `@app.middleware("http")` au-dessus d’une fonction.
+
+La fonction de middleware reçoit :
+
+* La `request`.
+* Une fonction `call_next` qui recevra la `request` en paramètre.
+ * Cette fonction transmettra la `request` au *chemin d'accès* correspondant.
+ * Puis elle renverra la `response` générée par le *chemin d'accès* correspondant.
+* Vous pouvez ensuite modifier la `response` avant de la renvoyer.
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip | Astuce
+
+Gardez à l’esprit que des en-têtes propriétaires personnalisés peuvent être ajoutés en utilisant le préfixe `X-`.
+
+Mais si vous avez des en-têtes personnalisés que vous voulez rendre visibles pour un client dans un navigateur, vous devez les ajouter à votre configuration CORS ([CORS (Partage des ressources entre origines)](cors.md){.internal-link target=_blank}) en utilisant le paramètre `expose_headers` documenté dans la documentation CORS de Starlette.
+
+///
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette.requests import Request`.
+
+**FastAPI** le fournit pour votre confort de développeur. Mais cela provient directement de Starlette.
+
+///
+
+### Avant et après la `response` { #before-and-after-the-response }
+
+Vous pouvez ajouter du code à exécuter avec la `request`, avant que tout *chemin d'accès* ne la reçoive.
+
+Et aussi après que la `response` a été générée, avant de la renvoyer.
+
+Par exemple, vous pourriez ajouter un en-tête personnalisé `X-Process-Time` contenant le temps en secondes nécessaire pour traiter la requête et générer une réponse :
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip | Astuce
+
+Ici, nous utilisons `time.perf_counter()` au lieu de `time.time()` car cela peut être plus précis pour ces cas d’usage. 🤓
+
+///
+
+## Ordre d’exécution de plusieurs middlewares { #multiple-middleware-execution-order }
+
+Quand vous ajoutez plusieurs middlewares en utilisant soit le décorateur `@app.middleware()`, soit la méthode `app.add_middleware()`, chaque nouveau middleware enveloppe l’application, formant une pile. Le dernier middleware ajouté est le plus externe, et le premier est le plus interne.
+
+Sur le chemin de la requête, le plus externe s’exécute en premier.
+
+Sur le chemin de la réponse, il s’exécute en dernier.
+
+Par exemple :
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+Cela aboutit à l’ordre d’exécution suivant :
+
+* **Requête** : MiddlewareB → MiddlewareA → route
+
+* **Réponse** : route → MiddlewareA → MiddlewareB
+
+Ce comportement d’empilement garantit que les middlewares s’exécutent dans un ordre prévisible et contrôlable.
+
+## Autres middlewares { #other-middlewares }
+
+Vous pouvez en lire davantage sur d’autres middlewares dans le [Guide de l’utilisateur avancé : Middleware avancé](../advanced/middleware.md){.internal-link target=_blank}.
+
+Vous verrez comment gérer CORS avec un middleware dans la section suivante.
diff --git a/docs/fr/docs/tutorial/path-operation-configuration.md b/docs/fr/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 000000000..f8041fa69
--- /dev/null
+++ b/docs/fr/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# Configurer les chemins d'accès { #path-operation-configuration }
+
+Vous pouvez passer plusieurs paramètres à votre *décorateur de chemin d'accès* pour le configurer.
+
+/// warning | Alertes
+
+Notez que ces paramètres sont passés directement au *décorateur de chemin d'accès*, et non à votre *fonction de chemin d'accès*.
+
+///
+
+## Définir le code d'état de la réponse { #response-status-code }
+
+Vous pouvez définir le `status_code` (HTTP) à utiliser dans la réponse de votre *chemin d'accès*.
+
+Vous pouvez passer directement le code `int`, comme `404`.
+
+Mais si vous ne vous souvenez pas à quoi correspond chaque code numérique, vous pouvez utiliser les constantes abrégées dans `status` :
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+Ce code d'état sera utilisé dans la réponse et ajouté au schéma OpenAPI.
+
+/// note | Détails techniques
+
+Vous pouvez également utiliser `from starlette import status`.
+
+**FastAPI** fournit le même `starlette.status` sous le nom `fastapi.status` pour votre commodité, en tant que développeur. Mais cela provient directement de Starlette.
+
+///
+
+## Ajouter des tags { #tags }
+
+Vous pouvez ajouter des tags à votre *chemin d'accès*, en passant le paramètre `tags` avec une `list` de `str` (généralement un seul `str`) :
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+Ils seront ajoutés au schéma OpenAPI et utilisés par les interfaces de documentation automatiques :
+
+
+
+### Utiliser des tags avec Enum { #tags-with-enums }
+
+Si vous avez une grande application, vous pourriez finir par accumuler **plusieurs tags**, et vous voudrez vous assurer d'utiliser toujours le **même tag** pour les *chemins d'accès* associés.
+
+Dans ces cas, il peut être judicieux de stocker les tags dans un `Enum`.
+
+**FastAPI** le prend en charge de la même manière qu'avec des chaînes simples :
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
+
+## Ajouter un résumé et une description { #summary-and-description }
+
+Vous pouvez ajouter un `summary` et une `description` :
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## Utiliser la description depuis la docstring { #description-from-docstring }
+
+Comme les descriptions ont tendance à être longues et à couvrir plusieurs lignes, vous pouvez déclarer la description du *chemin d'accès* dans la docstring de la fonction et **FastAPI** la lira à partir de là.
+
+Vous pouvez écrire Markdown dans la docstring, il sera interprété et affiché correctement (en tenant compte de l'indentation de la docstring).
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+Elle sera utilisée dans les documents interactifs :
+
+
+
+## Définir la description de la réponse { #response-description }
+
+Vous pouvez spécifier la description de la réponse avec le paramètre `response_description` :
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info
+
+Notez que `response_description` se réfère spécifiquement à la réponse, tandis que `description` se réfère au *chemin d'accès* en général.
+
+///
+
+/// check | Vérifications
+
+OpenAPI spécifie que chaque *chemin d'accès* requiert une description de réponse.
+
+Donc, si vous n'en fournissez pas, **FastAPI** en générera automatiquement une « Réponse réussie ».
+
+///
+
+
+
+## Déprécier un *chemin d'accès* { #deprecate-a-path-operation }
+
+Si vous devez marquer un *chemin d'accès* comme déprécié, sans pour autant le supprimer, passez le paramètre `deprecated` :
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
+
+Il sera clairement marqué comme déprécié dans les documents interactifs :
+
+
+
+Voyez à quoi ressemblent les *chemins d'accès* dépréciés et non dépréciés :
+
+
+
+## Récapitulatif { #recap }
+
+Vous pouvez facilement configurer et ajouter des métadonnées à vos *chemins d'accès* en passant des paramètres aux *décorateurs de chemin d'accès*.
diff --git a/docs/fr/docs/tutorial/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md
index c80710777..2dbaaa8ca 100644
--- a/docs/fr/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md
@@ -54,11 +54,11 @@ Cela n'a pas d'importance pour **FastAPI**. Il détectera les paramètres par le
Ainsi, vous pouvez déclarer votre fonction comme suit :
-{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`.
-{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
## Ordonner les paramètres comme vous le souhaitez, astuces { #order-the-parameters-as-you-need-tricks }
@@ -81,15 +81,15 @@ Si vous voulez :
Passez `*`, comme premier paramètre de la fonction.
-Python ne fera rien avec ce `*`, mais il saura que tous les paramètres suivants doivent être appelés comme arguments "mots-clés" (paires clé-valeur), également connus sous le nom de kwargs. Même s'ils n'ont pas de valeur par défaut.
+Python ne fera rien avec ce `*`, mais il saura que tous les paramètres suivants doivent être appelés comme arguments « mots-clés » (paires clé-valeur), également connus sous le nom de kwargs. Même s'ils n'ont pas de valeur par défaut.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
### Mieux avec `Annotated` { #better-with-annotated }
Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
## Validations numériques : supérieur ou égal { #number-validations-greater-than-or-equal }
@@ -97,7 +97,7 @@ Avec `Query` et `Path` (et d'autres que vous verrez plus tard) vous pouvez décl
Ici, avec `ge=1`, `item_id` devra être un nombre entier « `g`reater than or `e`qual » à `1`.
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
## Validations numériques : supérieur et inférieur ou égal { #number-validations-greater-than-and-less-than-or-equal }
@@ -106,7 +106,7 @@ La même chose s'applique pour :
* `gt` : `g`reater `t`han
* `le` : `l`ess than or `e`qual
-{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
## Validations numériques : flottants, supérieur et inférieur { #number-validations-floats-greater-than-and-less-than }
@@ -118,7 +118,7 @@ Ainsi, `0.5` serait une valeur valide. Mais `0.0` ou `0` ne le serait pas.
Et la même chose pour lt.
-{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
## Pour résumer { #recap }
diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md
index 3b2955a95..985eff635 100644
--- a/docs/fr/docs/tutorial/path-params.md
+++ b/docs/fr/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Vous pouvez déclarer des « paramètres » ou « variables » de chemin avec la même syntaxe utilisée par les chaînes de format Python :
-{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
La valeur du paramètre de chemin `item_id` sera transmise à votre fonction dans l'argument `item_id`.
@@ -16,7 +16,7 @@ Donc, si vous exécutez cet exemple et allez sur Conversion de données { #data-conversion }
+## Conversion de données { #data-conversion }
Si vous exécutez cet exemple et ouvrez votre navigateur sur http://127.0.0.1:8000/items/3, vous verrez comme réponse :
@@ -38,7 +38,7 @@ Si vous exécutez cet exemple et ouvrez votre navigateur sur « parsing » de la requête.
+Ainsi, avec cette déclaration de type, **FastAPI** vous fournit automatiquement le « parsing » de la requête.
///
@@ -118,19 +118,19 @@ Et vous pouvez aussi avoir un chemin `/users/{user_id}` pour récupérer des don
Comme les *chemins d'accès* sont évalués dans l'ordre, vous devez vous assurer que le chemin `/users/me` est déclaré avant celui de `/users/{user_id}` :
-{* ../../docs_src/path_params/tutorial003_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, « pensant » qu'il reçoit un paramètre `user_id` avec la valeur « me ».
De même, vous ne pouvez pas redéfinir un chemin d'accès :
-{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
Le premier sera toujours utilisé puisque le chemin correspond en premier.
## Valeurs prédéfinies { #predefined-values }
-Si vous avez un *chemin d'accès* qui reçoit un *paramètre de chemin*, mais que vous voulez que les valeurs possibles de ce *paramètre de chemin* soient prédéfinies, vous pouvez utiliser une `Enum` Python standard.
+Si vous avez un *chemin d'accès* qui reçoit un *paramètre de chemin*, mais que vous voulez que les valeurs possibles de ce *paramètre de chemin* soient prédéfinies, vous pouvez utiliser une `Enum` Python standard.
### Créer une classe `Enum` { #create-an-enum-class }
@@ -140,11 +140,11 @@ En héritant de `str`, la documentation de l'API saura que les valeurs doivent
Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs valides disponibles :
-{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
/// tip | Astuce
-Si vous vous demandez, « AlexNet », « ResNet » et « LeNet » sont juste des noms de modèles de Machine Learning.
+Si vous vous demandez, « AlexNet », « ResNet » et « LeNet » sont juste des noms de modèles de Machine Learning.
///
@@ -152,7 +152,7 @@ Si vous vous demandez, « AlexNet », « ResNet » et « LeNet » sont juste des
Créez ensuite un *paramètre de chemin* avec une annotation de type utilisant la classe d'énumération que vous avez créée (`ModelName`) :
-{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
### Consulter la documentation { #check-the-docs }
@@ -168,13 +168,13 @@ La valeur du *paramètre de chemin* sera un *membre d'énumération*.
Vous pouvez le comparer avec le *membre d'énumération* dans votre enum `ModelName` :
-{* ../../docs_src/path_params/tutorial005_py39.py hl[17] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
#### Obtenir la *valeur de l'énumération* { #get-the-enumeration-value }
Vous pouvez obtenir la valeur réelle (une `str` dans ce cas) avec `model_name.value`, ou en général, `votre_membre_d_enum.value` :
-{* ../../docs_src/path_params/tutorial005_py39.py hl[20] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
/// tip | Astuce
@@ -188,7 +188,7 @@ Vous pouvez retourner des *membres d'énumération* depuis votre *chemin d'accè
Ils seront convertis vers leurs valeurs correspondantes (des chaînes de caractères ici) avant d'être renvoyés au client :
-{* ../../docs_src/path_params/tutorial005_py39.py hl[18,21,23] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
Dans votre client, vous recevrez une réponse JSON comme :
@@ -227,7 +227,7 @@ Dans ce cas, le nom du paramètre est `file_path`, et la dernière partie, `:pat
Vous pouvez donc l'utiliser ainsi :
-{* ../../docs_src/path_params/tutorial004_py39.py hl[6] *}
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
/// tip | Astuce
@@ -242,7 +242,7 @@ Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double sl
Avec **FastAPI**, en utilisant des déclarations de type Python courtes, intuitives et standard, vous obtenez :
* Support de l'éditeur : vérifications d'erreurs, autocomplétion, etc.
-* Données « parsing »
+* Données « parsing »
* Validation de données
* Annotations d'API et documentation automatique
diff --git a/docs/fr/docs/tutorial/query-param-models.md b/docs/fr/docs/tutorial/query-param-models.md
new file mode 100644
index 000000000..b9bb1d137
--- /dev/null
+++ b/docs/fr/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Modèles de paramètres de requête { #query-parameter-models }
+
+Si vous avez un groupe de paramètres de requête liés, vous pouvez créer un modèle Pydantic pour les déclarer.
+
+Cela vous permet de réutiliser le modèle à plusieurs endroits et aussi de déclarer des validations et des métadonnées pour tous les paramètres en une seule fois. 😎
+
+/// note | Remarque
+
+Pris en charge depuis FastAPI version `0.115.0`. 🤓
+
+///
+
+## Déclarer des paramètres de requête avec un modèle Pydantic { #query-parameters-with-a-pydantic-model }
+
+Déclarez les paramètres de requête dont vous avez besoin dans un modèle Pydantic, puis déclarez le paramètre en tant que `Query` :
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+FastAPI extrait les données pour chaque champ à partir des paramètres de requête de la requête et vous fournit le modèle Pydantic que vous avez défini.
+
+## Consulter les documents { #check-the-docs }
+
+Vous pouvez voir les paramètres de requête dans l'interface des documents à `/docs` :
+
+
+POST.
+
+///
+
+/// warning | Alertes
+
+Vous pouvez déclarer plusieurs paramètres `File` et `Form` dans un *chemin d'accès*, mais vous ne pouvez pas également déclarer des champs `Body` que vous vous attendez à recevoir en JSON, car la requête aura le corps encodé en `multipart/form-data` au lieu de `application/json`.
+
+Ce n'est pas une limitation de **FastAPI**, cela fait partie du protocole HTTP.
+
+///
+
+## Téléversement de fichier facultatif { #optional-file-upload }
+
+Vous pouvez rendre un fichier facultatif en utilisant des annotations de type standard et en définissant une valeur par défaut à `None` :
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` avec des métadonnées supplémentaires { #uploadfile-with-additional-metadata }
+
+Vous pouvez aussi utiliser `File()` avec `UploadFile`, par exemple pour définir des métadonnées supplémentaires :
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## Téléverser plusieurs fichiers { #multiple-file-uploads }
+
+Il est possible de téléverser plusieurs fichiers en même temps.
+
+Ils seraient associés au même « champ de formulaire » envoyé en « données de formulaire ».
+
+Pour cela, déclarez une `list` de `bytes` ou d'`UploadFile` :
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+Vous recevrez, comme déclaré, une `list` de `bytes` ou d'`UploadFile`.
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette.responses import HTMLResponse`.
+
+**FastAPI** fournit les mêmes `starlette.responses` sous `fastapi.responses` simplement pour votre convenance en tant que développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+
+///
+
+### Téléversements multiples avec métadonnées supplémentaires { #multiple-file-uploads-with-additional-metadata }
+
+Et de la même manière que précédemment, vous pouvez utiliser `File()` pour définir des paramètres supplémentaires, même pour `UploadFile` :
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## Récapitulatif { #recap }
+
+Utilisez `File`, `bytes` et `UploadFile` pour déclarer des fichiers à téléverser dans la requête, envoyés en « données de formulaire ».
diff --git a/docs/fr/docs/tutorial/request-form-models.md b/docs/fr/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..3fbac9c74
--- /dev/null
+++ b/docs/fr/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Modèles de formulaire { #form-models }
+
+Vous pouvez utiliser des **modèles Pydantic** pour déclarer des **champs de formulaire** dans FastAPI.
+
+/// info
+
+Pour utiliser les formulaires, installez d'abord `python-multipart`.
+
+Assurez-vous de créer un [environnement virtuel](../virtual-environments.md){.internal-link target=_blank}, de l'activer, puis d'installer le paquet, par exemple :
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Remarque
+
+Ceci est pris en charge depuis la version `0.113.0` de FastAPI. 🤓
+
+///
+
+## Modèles Pydantic pour les formulaires { #pydantic-models-for-forms }
+
+Vous avez simplement besoin de déclarer un **modèle Pydantic** avec les champs que vous souhaitez recevoir comme **champs de formulaire**, puis de déclarer le paramètre comme `Form` :
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** va **extraire** les données pour **chaque champ** à partir des **données de formulaire** de la requête et vous fournir le modèle Pydantic que vous avez défini.
+
+## Consulter les documents { #check-the-docs }
+
+Vous pouvez le vérifier dans l'interface des documents à `/docs` :
+
+
+POST.
+
+///
+
+/// warning | Alertes
+
+Vous pouvez déclarer plusieurs paramètres `Form` dans un chemin d'accès, mais vous ne pouvez pas aussi déclarer des champs `Body` que vous vous attendez à recevoir en JSON, car la requête aura le corps encodé en `application/x-www-form-urlencoded` au lieu de `application/json`.
+
+Ce n'est pas une limitation de **FastAPI**, cela fait partie du protocole HTTP.
+
+///
+
+## Récapitulatif { #recap }
+
+Utilisez `Form` pour déclarer les paramètres d'entrée des données de formulaire.
diff --git a/docs/fr/docs/tutorial/response-model.md b/docs/fr/docs/tutorial/response-model.md
new file mode 100644
index 000000000..337b1aa48
--- /dev/null
+++ b/docs/fr/docs/tutorial/response-model.md
@@ -0,0 +1,343 @@
+# Modèle de réponse - Type de retour { #response-model-return-type }
+
+Vous pouvez déclarer le type utilisé pour la réponse en annotant le **type de retour** de la *fonction de chemin d'accès*.
+
+Vous pouvez utiliser des **annotations de type** de la même manière que pour les données d'entrée dans les **paramètres** de fonction. Vous pouvez utiliser des modèles Pydantic, des listes, des dictionnaires, des valeurs scalaires comme des entiers, des booléens, etc.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+FastAPI utilisera ce type de retour pour :
+
+* **Valider** les données renvoyées.
+ * Si les données sont invalides (par exemple, il manque un champ), cela signifie que le code de *votre* application est défectueux, qu'il ne renvoie pas ce qu'il devrait, et un erreur serveur sera renvoyée au lieu de renvoyer des données incorrectes. De cette façon, vous et vos clients pouvez être certains de recevoir les données attendues et avec la structure attendue.
+* Ajouter un **JSON Schema** pour la réponse, dans l’OpenAPI du *chemin d'accès*.
+ * Ceci sera utilisé par la **documentation automatique**.
+ * Ceci sera également utilisé par les outils de génération automatique de code client.
+
+Mais surtout :
+
+* Il **limitera et filtrera** les données de sortie à ce qui est défini dans le type de retour.
+ * C'est particulièrement important pour la **sécurité**, nous verrons cela plus bas.
+
+## Paramètre `response_model` { #response-model-parameter }
+
+Il existe des cas où vous devez ou souhaitez renvoyer des données qui ne correspondent pas exactement à ce que déclare le type.
+
+Par exemple, vous pourriez vouloir **renvoyer un dictionnaire** ou un objet de base de données, mais **le déclarer comme un modèle Pydantic**. Ainsi, le modèle Pydantic ferait toute la documentation des données, la validation, etc. pour l'objet que vous avez renvoyé (par exemple un dictionnaire ou un objet de base de données).
+
+Si vous ajoutez l'annotation du type de retour, les outils et éditeurs se plaindront avec une (juste) erreur vous indiquant que votre fonction renvoie un type (par exemple un dict) différent de ce que vous avez déclaré (par exemple un modèle Pydantic).
+
+Dans ces cas, vous pouvez utiliser le paramètre `response_model` du *décorateur de chemin d'accès* au lieu du type de retour.
+
+Vous pouvez utiliser le paramètre `response_model` dans n'importe lequel des *chemins d'accès* :
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* etc.
+
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
+
+/// note | Remarque
+
+Notez que `response_model` est un paramètre de la méthode « decorator » (`get`, `post`, etc.). Pas de votre *fonction de chemin d'accès*, comme tous les paramètres et le corps.
+
+///
+
+`response_model` reçoit le même type que vous déclareriez pour un champ de modèle Pydantic, il peut donc s'agir d'un modèle Pydantic, mais il peut aussi être, par exemple, une `list` de modèles Pydantic, comme `List[Item]`.
+
+FastAPI utilisera ce `response_model` pour toute la documentation des données, la validation, etc. et aussi pour **convertir et filtrer les données de sortie** selon sa déclaration de type.
+
+/// tip | Astuce
+
+Si vous avez des vérifications de type strictes dans votre éditeur, mypy, etc., vous pouvez déclarer le type de retour de la fonction en `Any`.
+
+Ainsi, vous indiquez à l'éditeur que vous renvoyez intentionnellement n'importe quoi. Mais FastAPI effectuera quand même la documentation, la validation, le filtrage, etc. des données avec `response_model`.
+
+///
+
+### Priorité de `response_model` { #response-model-priority }
+
+Si vous déclarez à la fois un type de retour et un `response_model`, c'est `response_model` qui aura la priorité et sera utilisé par FastAPI.
+
+De cette manière, vous pouvez ajouter des annotations de type correctes à vos fonctions même si vous renvoyez un type différent du modèle de réponse, pour qu'il soit utilisé par l'éditeur et des outils comme mypy. Et vous pouvez toujours laisser FastAPI faire la validation des données, la documentation, etc. avec `response_model`.
+
+Vous pouvez également utiliser `response_model=None` pour désactiver la création d’un modèle de réponse pour ce *chemin d'accès* ; vous pourriez en avoir besoin si vous ajoutez des annotations de type pour des choses qui ne sont pas des champs valides Pydantic, vous verrez un exemple de cela dans une des sections ci-dessous.
+
+## Renvoyer les mêmes données d'entrée { #return-the-same-input-data }
+
+Ici, nous déclarons un modèle `UserIn`, il contiendra un mot de passe en clair :
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
+
+/// info | Info
+
+Pour utiliser `EmailStr`, installez d'abord `email-validator`.
+
+Assurez-vous de créer un [environnement virtuel](../virtual-environments.md){.internal-link target=_blank}, de l'activer, puis de l'installer, par exemple :
+
+```console
+$ pip install email-validator
+```
+
+ou avec :
+
+```console
+$ pip install "pydantic[email]"
+```
+
+///
+
+Et nous utilisons ce modèle pour déclarer notre entrée et le même modèle pour déclarer notre sortie :
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
+
+Désormais, chaque fois qu'un navigateur crée un utilisateur avec un mot de passe, l'API renverra le même mot de passe dans la réponse.
+
+Dans ce cas, cela peut ne pas poser de problème, car c'est le même utilisateur qui envoie le mot de passe.
+
+Mais si nous utilisons le même modèle pour un autre *chemin d'accès*, nous pourrions envoyer les mots de passe de nos utilisateurs à tous les clients.
+
+/// danger | Danger
+
+Ne stockez jamais le mot de passe en clair d'un utilisateur et ne l'envoyez pas dans une réponse de cette manière, à moins de connaître tous les écueils et de savoir exactement ce que vous faites.
+
+///
+
+## Ajouter un modèle de sortie { #add-an-output-model }
+
+Nous pouvons à la place créer un modèle d'entrée avec le mot de passe en clair et un modèle de sortie sans celui-ci :
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
+
+Ici, même si notre *fonction de chemin d'accès* renvoie le même utilisateur d'entrée qui contient le mot de passe :
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
+
+... nous avons déclaré `response_model` comme étant notre modèle `UserOut`, qui n'inclut pas le mot de passe :
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
+
+Ainsi, **FastAPI** se chargera de filtrer toutes les données qui ne sont pas déclarées dans le modèle de sortie (en utilisant Pydantic).
+
+### `response_model` ou type de retour { #response-model-or-return-type }
+
+Dans ce cas, comme les deux modèles sont différents, si nous annotions le type de retour de la fonction en `UserOut`, l’éditeur et les outils se plaindraient que nous renvoyons un type invalide, car ce sont des classes différentes.
+
+C'est pourquoi, dans cet exemple, nous devons le déclarer dans le paramètre `response_model`.
+
+... mais continuez à lire ci-dessous pour voir comment contourner cela.
+
+## Type de retour et filtrage des données { #return-type-and-data-filtering }
+
+Continuons l'exemple précédent. Nous voulions **annoter la fonction avec un type**, mais nous voulions pouvoir renvoyer depuis la fonction quelque chose qui inclut **plus de données**.
+
+Nous voulons que FastAPI continue de **filtrer** les données à l’aide du modèle de réponse. Ainsi, même si la fonction renvoie plus de données, la réponse n’inclura que les champs déclarés dans le modèle de réponse.
+
+Dans l'exemple précédent, comme les classes étaient différentes, nous avons dû utiliser le paramètre `response_model`. Mais cela signifie aussi que nous ne bénéficions pas de la prise en charge de l'éditeur et des outils pour la vérification du type de retour de la fonction.
+
+Mais dans la plupart des cas où nous avons besoin de quelque chose comme cela, nous voulons que le modèle **filtre/supprime** simplement une partie des données comme dans cet exemple.
+
+Et dans ces cas, nous pouvons utiliser des classes et l'héritage pour tirer parti des **annotations de type** de fonction afin d'obtenir une meilleure prise en charge dans l'éditeur et les outils, tout en bénéficiant du **filtrage de données** de FastAPI.
+
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
+
+Avec cela, nous obtenons la prise en charge des outils, des éditeurs et de mypy car ce code est correct en termes de types, et nous bénéficions également du filtrage des données par FastAPI.
+
+Comment cela fonctionne-t-il ? Voyons cela. 🤓
+
+### Annotations de type et outils { #type-annotations-and-tooling }
+
+Voyons d'abord comment les éditeurs, mypy et autres outils considèreraient cela.
+
+`BaseUser` a les champs de base. Puis `UserIn` hérite de `BaseUser` et ajoute le champ `password`, il inclura donc tous les champs des deux modèles.
+
+Nous annotons le type de retour de la fonction en `BaseUser`, mais nous renvoyons en réalité une instance de `UserIn`.
+
+L’éditeur, mypy et d'autres outils ne s’en plaindront pas car, en termes de typage, `UserIn` est une sous-classe de `BaseUser`, ce qui signifie que c’est un type *valide* lorsque ce qui est attendu est n'importe quoi de type `BaseUser`.
+
+### Filtrage des données par FastAPI { #fastapi-data-filtering }
+
+Maintenant, pour FastAPI, il verra le type de retour et s'assurera que ce que vous renvoyez inclut **uniquement** les champs qui sont déclarés dans le type.
+
+FastAPI fait plusieurs choses en interne avec Pydantic pour s'assurer que ces mêmes règles d'héritage de classes ne sont pas utilisées pour le filtrage des données renvoyées, sinon vous pourriez finir par renvoyer beaucoup plus de données que prévu.
+
+De cette façon, vous obtenez le meilleur des deux mondes : annotations de type avec **prise en charge par les outils** et **filtrage des données**.
+
+## Le voir dans la documentation { #see-it-in-the-docs }
+
+Dans la documentation automatique, vous pouvez vérifier que le modèle d'entrée et le modèle de sortie auront chacun leur propre JSON Schema :
+
+
+
+Et les deux modèles seront utilisés pour la documentation API interactive :
+
+
+
+## Autres annotations de type de retour { #other-return-type-annotations }
+
+Il peut y avoir des cas où vous renvoyez quelque chose qui n'est pas un champ Pydantic valide et vous l'annotez dans la fonction, uniquement pour obtenir la prise en charge fournie par les outils (l’éditeur, mypy, etc.).
+
+### Renvoyer directement une Response { #return-a-response-directly }
+
+Le cas le plus courant serait [de renvoyer directement une Response comme expliqué plus loin dans la documentation avancée](../advanced/response-directly.md){.internal-link target=_blank}.
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+Ce cas simple est géré automatiquement par FastAPI car l'annotation du type de retour est la classe (ou une sous-classe de) `Response`.
+
+Et les outils seront également satisfaits car `RedirectResponse` et `JSONResponse` sont des sous-classes de `Response`, donc l'annotation de type est correcte.
+
+### Annoter une sous-classe de Response { #annotate-a-response-subclass }
+
+Vous pouvez aussi utiliser une sous-classe de `Response` dans l'annotation de type :
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+Cela fonctionnera également car `RedirectResponse` est une sous-classe de `Response`, et FastAPI gérera automatiquement ce cas simple.
+
+### Annotations de type de retour invalides { #invalid-return-type-annotations }
+
+Mais lorsque vous renvoyez un autre objet arbitraire qui n'est pas un type Pydantic valide (par exemple un objet de base de données) et que vous l'annotez ainsi dans la fonction, FastAPI essaiera de créer un modèle de réponse Pydantic à partir de cette annotation de type, et échouera.
+
+Il en serait de même si vous aviez quelque chose comme une union entre différents types dont un ou plusieurs ne sont pas des types Pydantic valides, par exemple ceci échouerait 💥 :
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+... cela échoue parce que l'annotation de type n'est pas un type Pydantic et n'est pas juste une unique classe `Response` ou une sous-classe, c'est une union (l'un des deux) entre une `Response` et un `dict`.
+
+### Désactiver le modèle de réponse { #disable-response-model }
+
+En reprenant l'exemple ci-dessus, vous pourriez ne pas vouloir avoir la validation par défaut des données, la documentation, le filtrage, etc. effectués par FastAPI.
+
+Mais vous pourriez vouloir tout de même conserver l’annotation du type de retour dans la fonction pour bénéficier de la prise en charge des outils comme les éditeurs et les vérificateurs de type (par exemple mypy).
+
+Dans ce cas, vous pouvez désactiver la génération du modèle de réponse en définissant `response_model=None` :
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+Cela fera en sorte que FastAPI ignore la génération du modèle de réponse et vous permettra ainsi d’avoir toutes les annotations de type de retour dont vous avez besoin sans que cela n’affecte votre application FastAPI. 🤓
+
+## Paramètres d'encodage du modèle de réponse { #response-model-encoding-parameters }
+
+Votre modèle de réponse peut avoir des valeurs par défaut, par exemple :
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None` (ou `str | None = None` en Python 3.10) a une valeur par défaut `None`.
+* `tax: float = 10.5` a une valeur par défaut `10.5`.
+* `tags: List[str] = []` a une valeur par défaut de liste vide : `[]`.
+
+mais vous pourriez vouloir les omettre du résultat si elles n'ont pas été réellement stockées.
+
+Par exemple, si vous avez des modèles avec de nombreux attributs optionnels dans une base NoSQL, mais que vous ne voulez pas envoyer de très longues réponses JSON remplies de valeurs par défaut.
+
+### Utiliser le paramètre `response_model_exclude_unset` { #use-the-response-model-exclude-unset-parameter }
+
+Vous pouvez définir le paramètre du *décorateur de chemin d'accès* `response_model_exclude_unset=True` :
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+et ces valeurs par défaut ne seront pas incluses dans la réponse, uniquement les valeurs effectivement définies.
+
+Ainsi, si vous envoyez une requête à ce *chemin d'accès* pour l'article avec l'ID `foo`, la réponse (sans les valeurs par défaut) sera :
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | Info
+
+Vous pouvez également utiliser :
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+comme décrit dans la documentation Pydantic pour `exclude_defaults` et `exclude_none`.
+
+///
+
+#### Données avec des valeurs pour des champs avec des valeurs par défaut { #data-with-values-for-fields-with-defaults }
+
+Mais si vos données ont des valeurs pour les champs du modèle avec des valeurs par défaut, comme l'article avec l'ID `bar` :
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+elles seront incluses dans la réponse.
+
+#### Données avec les mêmes valeurs que les valeurs par défaut { #data-with-the-same-values-as-the-defaults }
+
+Si les données ont les mêmes valeurs que les valeurs par défaut, comme l'article avec l'ID `baz` :
+
+```Python hl_lines="3 5-6"
+{
+ "name": "Baz",
+ "description": None,
+ "price": 50.2,
+ "tax": 10.5,
+ "tags": []
+}
+```
+
+FastAPI est suffisamment intelligent (en fait, Pydantic l’est) pour comprendre que, même si `description`, `tax` et `tags` ont les mêmes valeurs que les valeurs par défaut, elles ont été définies explicitement (au lieu d'être prises depuis les valeurs par défaut).
+
+Elles seront donc incluses dans la réponse JSON.
+
+/// tip | Astuce
+
+Notez que les valeurs par défaut peuvent être n'importe quoi, pas seulement `None`.
+
+Elles peuvent être une liste (`[]`), un `float` de `10.5`, etc.
+
+///
+
+### `response_model_include` et `response_model_exclude` { #response-model-include-and-response-model-exclude }
+
+Vous pouvez également utiliser les paramètres du *décorateur de chemin d'accès* `response_model_include` et `response_model_exclude`.
+
+Ils prennent un `set` de `str` avec les noms des attributs à inclure (en omettant le reste) ou à exclure (en incluant le reste).
+
+Cela peut être utilisé comme un raccourci rapide si vous n'avez qu'un seul modèle Pydantic et que vous souhaitez supprimer certaines données de la sortie.
+
+/// tip | Astuce
+
+Mais il est toujours recommandé d'utiliser les idées ci-dessus, en utilisant plusieurs classes, plutôt que ces paramètres.
+
+En effet, le JSON Schema généré dans l’OpenAPI de votre application (et la documentation) restera celui du modèle complet, même si vous utilisez `response_model_include` ou `response_model_exclude` pour omettre certains attributs.
+
+Cela s'applique également à `response_model_by_alias` qui fonctionne de manière similaire.
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | Astuce
+
+La syntaxe `{"name", "description"}` crée un `set` avec ces deux valeurs.
+
+Elle est équivalente à `set(["name", "description"])`.
+
+///
+
+#### Utiliser des `list` au lieu de `set` { #using-lists-instead-of-sets }
+
+Si vous oubliez d'utiliser un `set` et utilisez une `list` ou un `tuple` à la place, FastAPI le convertira quand même en `set` et cela fonctionnera correctement :
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## Récapitulatif { #recap }
+
+Utilisez le paramètre du *décorateur de chemin d'accès* `response_model` pour définir les modèles de réponse et surtout pour garantir que les données privées sont filtrées.
+
+Utilisez `response_model_exclude_unset` pour ne renvoyer que les valeurs définies explicitement.
diff --git a/docs/fr/docs/tutorial/response-status-code.md b/docs/fr/docs/tutorial/response-status-code.md
new file mode 100644
index 000000000..388a53b3d
--- /dev/null
+++ b/docs/fr/docs/tutorial/response-status-code.md
@@ -0,0 +1,101 @@
+# Code d'état de la réponse { #response-status-code }
+
+De la même manière que vous pouvez spécifier un modèle de réponse, vous pouvez également déclarer le code d'état HTTP utilisé pour la réponse avec le paramètre `status_code` dans n'importe lequel des chemins d'accès :
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* etc.
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+/// note | Remarque
+
+Remarquez que `status_code` est un paramètre de la méthode « decorator » (`get`, `post`, etc.). Pas de votre fonction de chemin d'accès, comme tous les paramètres et le corps.
+
+///
+
+Le paramètre `status_code` reçoit un nombre correspondant au code d'état HTTP.
+
+/// info
+
+`status_code` peut aussi recevoir un `IntEnum`, comme le `http.HTTPStatus` de Python.
+
+///
+
+Il va :
+
+* Renvoyer ce code d'état dans la réponse.
+* Le documenter comme tel dans le schéma OpenAPI (et donc dans les interfaces utilisateur) :
+
+
+
+/// note | Remarque
+
+Certains codes de réponse (voir la section suivante) indiquent que la réponse n'a pas de corps.
+
+FastAPI le sait et produira une documentation OpenAPI indiquant qu'il n'y a pas de corps de réponse.
+
+///
+
+## À propos des codes d'état HTTP { #about-http-status-codes }
+
+/// note | Remarque
+
+Si vous savez déjà ce que sont les codes d'état HTTP, passez à la section suivante.
+
+///
+
+En HTTP, vous envoyez un code d'état numérique de 3 chiffres dans la réponse.
+
+Ces codes d'état ont un nom associé pour les reconnaître, mais la partie importante est le nombre.
+
+En bref :
+
+* `100 - 199` sont pour « Information ». Vous les utilisez rarement directement. Les réponses avec ces codes d'état ne peuvent pas avoir de corps.
+* **`200 - 299`** sont pour les réponses de « Succès ». Ce sont celles que vous utiliserez le plus.
+ * `200` est le code d'état par défaut, ce qui signifie que tout était « OK ».
+ * Un autre exemple est `201`, « Créé ». Il est couramment utilisé après la création d'un nouvel enregistrement dans la base de données.
+ * Un cas particulier est `204`, « Aucun contenu ». Cette réponse est utilisée lorsqu'il n'y a aucun contenu à renvoyer au client ; la réponse ne doit donc pas avoir de corps.
+* **`300 - 399`** sont pour la « Redirection ». Les réponses avec ces codes d'état peuvent avoir ou non un corps, sauf `304`, « Non modifié », qui ne doit pas en avoir.
+* **`400 - 499`** sont pour les réponses d'« Erreur côté client ». C'est probablement le deuxième type que vous utiliserez le plus.
+ * Un exemple est `404`, pour une réponse « Non trouvé ».
+ * Pour des erreurs génériques du client, vous pouvez simplement utiliser `400`.
+* `500 - 599` sont pour les erreurs côté serveur. Vous ne les utilisez presque jamais directement. Lorsqu'un problème survient quelque part dans le code de votre application ou sur le serveur, il renverra automatiquement l'un de ces codes d'état.
+
+/// tip | Astuce
+
+Pour en savoir plus sur chaque code d'état et à quoi il correspond, consultez la MDN documentation about HTTP status codes.
+
+///
+
+## Raccourci pour se souvenir des noms { #shortcut-to-remember-the-names }
+
+Reprenons l'exemple précédent :
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+`201` est le code d'état pour « Créé ».
+
+Mais vous n'avez pas à mémoriser la signification de chacun de ces codes.
+
+Vous pouvez utiliser les variables pratiques de `fastapi.status`.
+
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
+
+Elles ne sont qu'une commodité, elles contiennent le même nombre, mais de cette façon vous pouvez utiliser l'autocomplétion de l'éditeur pour les trouver :
+
+
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette import status`.
+
+FastAPI fournit le même `starlette.status` que `fastapi.status`, uniquement pour votre commodité de développeur. Mais cela vient directement de Starlette.
+
+///
+
+## Modifier la valeur par défaut { #changing-the-default }
+
+Plus tard, dans le [Guide utilisateur avancé](../advanced/response-change-status-code.md){.internal-link target=_blank}, vous verrez comment renvoyer un code d'état différent de celui par défaut que vous déclarez ici.
diff --git a/docs/fr/docs/tutorial/schema-extra-example.md b/docs/fr/docs/tutorial/schema-extra-example.md
new file mode 100644
index 000000000..d4403c779
--- /dev/null
+++ b/docs/fr/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# Déclarer des exemples de données de requête { #declare-request-example-data }
+
+Vous pouvez déclarer des exemples des données que votre application peut recevoir.
+
+Voici plusieurs façons de le faire.
+
+## Ajouter des données JSON Schema supplémentaires dans les modèles Pydantic { #extra-json-schema-data-in-pydantic-models }
+
+Vous pouvez déclarer `examples` pour un modèle Pydantic qui seront ajoutés au JSON Schema généré.
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+Ces informations supplémentaires seront ajoutées telles quelles au **JSON Schema** de sortie pour ce modèle, et elles seront utilisées dans la documentation de l'API.
+
+Vous pouvez utiliser l'attribut `model_config` qui accepte un `dict` comme décrit dans Documentation de Pydantic : Configuration.
+
+Vous pouvez définir `"json_schema_extra"` avec un `dict` contenant toutes les données supplémentaires que vous souhaitez voir apparaître dans le JSON Schema généré, y compris `examples`.
+
+/// tip | Astuce
+
+Vous pouvez utiliser la même technique pour étendre le JSON Schema et ajouter vos propres informations supplémentaires personnalisées.
+
+Par exemple, vous pourriez l'utiliser pour ajouter des métadonnées pour une interface utilisateur frontend, etc.
+
+///
+
+/// info
+
+OpenAPI 3.1.0 (utilisé depuis FastAPI 0.99.0) a ajouté la prise en charge de `examples`, qui fait partie du standard **JSON Schema**.
+
+Avant cela, seule la clé `example` avec un exemple unique était prise en charge. Elle l'est toujours par OpenAPI 3.1.0, mais elle est dépréciée et ne fait pas partie du standard JSON Schema. Vous êtes donc encouragé à migrer de `example` vers `examples`. 🤓
+
+Vous pouvez en lire davantage à la fin de cette page.
+
+///
+
+## Arguments supplémentaires de `Field` { #field-additional-arguments }
+
+Lorsque vous utilisez `Field()` avec des modèles Pydantic, vous pouvez également déclarer des `examples` supplémentaires :
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## `examples` dans JSON Schema - OpenAPI { #examples-in-json-schema-openapi }
+
+En utilisant l'un des éléments suivants :
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+vous pouvez également déclarer un groupe de `examples` avec des informations supplémentaires qui seront ajoutées à leurs **JSON Schemas** à l'intérieur d'**OpenAPI**.
+
+### `Body` avec `examples` { #body-with-examples }
+
+Ici, nous passons `examples` contenant un exemple des données attendues dans `Body()` :
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### Exemple dans l'interface des documents { #example-in-the-docs-ui }
+
+Avec l'une des méthodes ci-dessus, cela ressemblerait à ceci dans le `/docs` :
+
+
+
+### `Body` avec plusieurs `examples` { #body-with-multiple-examples }
+
+Vous pouvez bien sûr aussi passer plusieurs `examples` :
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+Lorsque vous faites cela, les exemples feront partie du **JSON Schema** interne pour ces données de corps.
+
+Néanmoins, au moment de la rédaction, Swagger UI, l'outil chargé d'afficher l'interface des documents, ne prend pas en charge l'affichage de plusieurs exemples pour les données dans **JSON Schema**. Mais lisez ci-dessous pour un contournement.
+
+### `examples` spécifiques à OpenAPI { #openapi-specific-examples }
+
+Avant que **JSON Schema** ne prenne en charge `examples`, OpenAPI prenait déjà en charge un autre champ également appelé `examples`.
+
+Ce `examples` **spécifique à OpenAPI** se trouve dans une autre section de la spécification OpenAPI. Il se trouve dans les **détails de chaque *chemin d'accès***, et non à l'intérieur de chaque JSON Schema.
+
+Et Swagger UI prend en charge ce champ particulier `examples` depuis un certain temps. Vous pouvez donc l'utiliser pour **afficher** différents **exemples dans l'interface des documents**.
+
+La forme de ce champ `examples` spécifique à OpenAPI est un `dict` avec **plusieurs exemples** (au lieu d'une `list`), chacun avec des informations supplémentaires qui seront également ajoutées à **OpenAPI**.
+
+Cela ne va pas à l'intérieur de chaque JSON Schema contenu dans OpenAPI, cela se place à l'extérieur, directement dans le *chemin d'accès*.
+
+### Utiliser le paramètre `openapi_examples` { #using-the-openapi-examples-parameter }
+
+Vous pouvez déclarer le `examples` spécifique à OpenAPI dans FastAPI avec le paramètre `openapi_examples` pour :
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+Les clés du `dict` identifient chaque exemple, et chaque valeur est un autre `dict`.
+
+Chaque `dict` d'exemple spécifique dans `examples` peut contenir :
+
+* `summary` : une courte description de l'exemple.
+* `description` : une description longue qui peut contenir du texte Markdown.
+* `value` : c'est l'exemple réel affiché, par ex. un `dict`.
+* `externalValue` : alternative à `value`, une URL pointant vers l'exemple. Cependant, cela pourrait ne pas être pris en charge par autant d'outils que `value`.
+
+Vous pouvez l'utiliser ainsi :
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### Exemples OpenAPI dans l'interface des documents { #openapi-examples-in-the-docs-ui }
+
+Avec `openapi_examples` ajouté à `Body()`, le `/docs` ressemblerait à :
+
+
+
+## Détails techniques { #technical-details }
+
+/// tip | Astuce
+
+Si vous utilisez déjà **FastAPI** en version **0.99.0 ou supérieure**, vous pouvez probablement **passer** ces détails.
+
+Ils sont plus pertinents pour les versions plus anciennes, avant que OpenAPI 3.1.0 ne soit disponible.
+
+Vous pouvez considérer ceci comme une courte leçon d'histoire d'OpenAPI et de JSON Schema. 🤓
+
+///
+
+/// warning | Alertes
+
+Ce sont des détails très techniques au sujet des standards **JSON Schema** et **OpenAPI**.
+
+Si les idées ci-dessus fonctionnent déjà pour vous, cela pourrait suffire, et vous n'avez probablement pas besoin de ces détails, n'hésitez pas à les ignorer.
+
+///
+
+Avant OpenAPI 3.1.0, OpenAPI utilisait une version plus ancienne et modifiée de **JSON Schema**.
+
+JSON Schema n'avait pas `examples`, donc OpenAPI a ajouté son propre champ `example` à sa version modifiée.
+
+OpenAPI a également ajouté les champs `example` et `examples` à d'autres parties de la spécification :
+
+* `Parameter Object` (dans la spécification) qui était utilisé par les éléments FastAPI :
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* `Request Body Object`, dans le champ `content`, sur le `Media Type Object` (dans la spécification) qui était utilisé par les éléments FastAPI :
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info
+
+Ce paramètre `examples` ancien et spécifique à OpenAPI est désormais `openapi_examples` depuis FastAPI `0.103.0`.
+
+///
+
+### Le champ `examples` de JSON Schema { #json-schemas-examples-field }
+
+Ensuite, JSON Schema a ajouté un champ `examples` dans une nouvelle version de la spécification.
+
+Puis le nouveau OpenAPI 3.1.0 s'est basé sur la dernière version (JSON Schema 2020-12) qui incluait ce nouveau champ `examples`.
+
+Et désormais, ce nouveau champ `examples` a priorité sur l'ancien champ unique (et personnalisé) `example`, qui est maintenant déprécié.
+
+Ce nouveau champ `examples` dans JSON Schema est **juste une `list`** d'exemples, et non pas un dict avec des métadonnées supplémentaires comme dans les autres endroits d'OpenAPI (décrits ci-dessus).
+
+/// info
+
+Même après la sortie d'OpenAPI 3.1.0 avec cette nouvelle intégration plus simple avec JSON Schema, pendant un temps, Swagger UI, l'outil qui fournit la documentation automatique, ne prenait pas en charge OpenAPI 3.1.0 (il le fait depuis la version 5.0.0 🎉).
+
+À cause de cela, les versions de FastAPI antérieures à 0.99.0 utilisaient encore des versions d'OpenAPI inférieures à 3.1.0.
+
+///
+
+### `examples` avec Pydantic et FastAPI { #pydantic-and-fastapi-examples }
+
+Lorsque vous ajoutez `examples` dans un modèle Pydantic, en utilisant `schema_extra` ou `Field(examples=["something"])`, cet exemple est ajouté au **JSON Schema** de ce modèle Pydantic.
+
+Et ce **JSON Schema** du modèle Pydantic est inclus dans l'**OpenAPI** de votre API, puis il est utilisé dans l'interface de la documentation.
+
+Dans les versions de FastAPI antérieures à 0.99.0 (0.99.0 et supérieures utilisent le nouveau OpenAPI 3.1.0), lorsque vous utilisiez `example` ou `examples` avec l'une des autres utilitaires (`Query()`, `Body()`, etc.), ces exemples n'étaient pas ajoutés au JSON Schema qui décrit ces données (pas même à la version de JSON Schema propre à OpenAPI), ils étaient ajoutés directement à la déclaration du *chemin d'accès* dans OpenAPI (en dehors des parties d'OpenAPI qui utilisent JSON Schema).
+
+Mais maintenant que FastAPI 0.99.0 et supérieures utilisent OpenAPI 3.1.0, qui utilise JSON Schema 2020-12, et Swagger UI 5.0.0 et supérieures, tout est plus cohérent et les exemples sont inclus dans JSON Schema.
+
+### Swagger UI et `examples` spécifiques à OpenAPI { #swagger-ui-and-openapi-specific-examples }
+
+Comme Swagger UI ne prenait pas en charge plusieurs exemples JSON Schema (au 2023-08-26), les utilisateurs n'avaient pas de moyen d'afficher plusieurs exemples dans les documents.
+
+Pour résoudre cela, FastAPI `0.103.0` a **ajouté la prise en charge** de la déclaration du même ancien champ `examples` **spécifique à OpenAPI** avec le nouveau paramètre `openapi_examples`. 🤓
+
+### Résumé { #summary }
+
+Je disais que je n'aimais pas trop l'histoire ... et me voilà maintenant à donner des leçons d'« tech history ». 😅
+
+En bref, **mettez à niveau vers FastAPI 0.99.0 ou supérieur**, et les choses sont bien plus **simples, cohérentes et intuitives**, et vous n'avez pas besoin de connaître tous ces détails historiques. 😎
diff --git a/docs/fr/docs/tutorial/security/first-steps.md b/docs/fr/docs/tutorial/security/first-steps.md
new file mode 100644
index 000000000..8c4eb50d7
--- /dev/null
+++ b/docs/fr/docs/tutorial/security/first-steps.md
@@ -0,0 +1,203 @@
+# Sécurité - Premiers pas { #security-first-steps }
+
+Imaginons que vous ayez votre API de **backend** sur un certain domaine.
+
+Et vous avez un **frontend** sur un autre domaine ou dans un chemin différent du même domaine (ou dans une application mobile).
+
+Et vous voulez que le **frontend** puisse s'authentifier auprès du **backend**, en utilisant un **username** et un **password**.
+
+Nous pouvons utiliser **OAuth2** pour construire cela avec **FastAPI**.
+
+Mais épargnons-vous le temps de lire toute la spécification complète juste pour trouver les petites informations dont vous avez besoin.
+
+Utilisons les outils fournis par **FastAPI** pour gérer la sécurité.
+
+## Voir à quoi cela ressemble { #how-it-looks }
+
+Commençons par utiliser le code et voir comment cela fonctionne, puis nous reviendrons pour comprendre ce qui se passe.
+
+## Créer `main.py` { #create-main-py }
+
+Copiez l'exemple dans un fichier `main.py` :
+
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## Exécuter { #run-it }
+
+/// info
+
+Le package `python-multipart` est installé automatiquement avec **FastAPI** lorsque vous exécutez la commande `pip install "fastapi[standard]"`.
+
+Cependant, si vous utilisez la commande `pip install fastapi`, le package `python-multipart` n'est pas inclus par défaut.
+
+Pour l'installer manuellement, vous devez vous assurer de créer un [environnement virtuel](../../virtual-environments.md){.internal-link target=_blank}, de l'activer, puis de l'installer avec :
+
+```console
+$ pip install python-multipart
+```
+
+Cela est dû au fait que **OAuth2** utilise des « form data » pour envoyer le `username` et le `password`.
+
+///
+
+Exécutez l'exemple avec :
+
+
+
+/// check | Bouton « Authorize » !
+
+Vous avez déjà un tout nouveau bouton « Authorize ».
+
+Et votre *chemin d'accès* a un petit cadenas dans le coin supérieur droit sur lequel vous pouvez cliquer.
+
+///
+
+Et si vous cliquez dessus, vous obtenez un petit formulaire d'autorisation pour saisir un `username` et un `password` (et d'autres champs optionnels) :
+
+
+
+/// note | Remarque
+
+Peu importe ce que vous saisissez dans le formulaire, cela ne fonctionnera pas encore. Mais nous y viendrons.
+
+///
+
+Ce n'est bien sûr pas le frontend pour les utilisateurs finaux, mais c'est un excellent outil automatique pour documenter de manière interactive toute votre API.
+
+Il peut être utilisé par l'équipe frontend (qui peut aussi être vous-même).
+
+Il peut être utilisé par des applications et des systèmes tiers.
+
+Et il peut aussi être utilisé par vous-même, pour déboguer, vérifier et tester la même application.
+
+## Le flux `password` { #the-password-flow }
+
+Revenons un peu en arrière et comprenons de quoi il s'agit.
+
+Le « flux » `password` est l'une des manières (« flows ») définies dans OAuth2 pour gérer la sécurité et l'authentification.
+
+OAuth2 a été conçu pour que le backend ou l'API puisse être indépendant du serveur qui authentifie l'utilisateur.
+
+Mais dans ce cas, la même application **FastAPI** gérera l'API et l'authentification.
+
+Voyons cela selon ce point de vue simplifié :
+
+- L'utilisateur saisit le `username` et le `password` dans le frontend, puis appuie sur Entrée.
+- Le frontend (exécuté dans le navigateur de l'utilisateur) envoie ce `username` et ce `password` vers une URL spécifique de notre API (déclarée avec `tokenUrl="token"`).
+- L'API vérifie ce `username` et ce `password`, et répond avec un « token » (nous n'avons encore rien implémenté de tout cela).
+ - Un « token » n'est qu'une chaîne contenant des informations que nous pouvons utiliser plus tard pour vérifier cet utilisateur.
+ - Normalement, un token est configuré pour expirer après un certain temps.
+ - Ainsi, l'utilisateur devra se reconnecter à un moment donné.
+ - Et si le token est volé, le risque est moindre. Ce n'est pas une clé permanente qui fonctionnerait indéfiniment (dans la plupart des cas).
+- Le frontend stocke ce token temporairement quelque part.
+- L'utilisateur clique dans le frontend pour aller vers une autre section de l'application web frontend.
+- Le frontend doit récupérer d'autres données depuis l'API.
+ - Mais cela nécessite une authentification pour cet endpoint spécifique.
+ - Donc, pour s'authentifier auprès de notre API, il envoie un en-tête `Authorization` avec une valeur `Bearer ` suivie du token.
+ - Si le token contient `foobar`, le contenu de l'en-tête `Authorization` serait : `Bearer foobar`.
+
+## Le `OAuth2PasswordBearer` de **FastAPI** { #fastapis-oauth2passwordbearer }
+
+**FastAPI** fournit plusieurs outils, à différents niveaux d'abstraction, pour implémenter ces fonctionnalités de sécurité.
+
+Dans cet exemple, nous allons utiliser **OAuth2**, avec le flux **Password**, en utilisant un token **Bearer**. Nous le faisons avec la classe `OAuth2PasswordBearer`.
+
+/// info
+
+Un token « bearer » n'est pas la seule option.
+
+Mais c'est la meilleure pour notre cas d'utilisation.
+
+Et cela pourrait être la meilleure pour la plupart des cas, sauf si vous êtes expert en OAuth2 et savez exactement pourquoi une autre option convient mieux à vos besoins.
+
+Dans ce cas, **FastAPI** vous fournit aussi les outils pour la construire.
+
+///
+
+Lorsque nous créons une instance de la classe `OAuth2PasswordBearer`, nous passons le paramètre `tokenUrl`. Ce paramètre contient l'URL que le client (le frontend s'exécutant dans le navigateur de l'utilisateur) utilisera pour envoyer le `username` et le `password` afin d'obtenir un token.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip | Astuce
+
+Ici `tokenUrl="token"` fait référence à une URL relative `token` que nous n'avons pas encore créée. Comme c'est une URL relative, elle est équivalente à `./token`.
+
+Parce que nous utilisons une URL relative, si votre API se trouvait à `https://example.com/`, alors elle ferait référence à `https://example.com/token`. Mais si votre API se trouvait à `https://example.com/api/v1/`, alors elle ferait référence à `https://example.com/api/v1/token`.
+
+Utiliser une URL relative est important pour vous assurer que votre application continue de fonctionner même dans un cas d'usage avancé comme [Derrière un proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+
+///
+
+Ce paramètre ne crée pas cet endpoint / *chemin d'accès*, mais déclare que l'URL `/token` sera celle que le client doit utiliser pour obtenir le token. Cette information est utilisée dans OpenAPI, puis dans les systèmes de documentation API interactifs.
+
+Nous créerons bientôt aussi le véritable chemin d'accès.
+
+/// info
+
+Si vous êtes un « Pythonista » très strict, vous pourriez ne pas apprécier le style du nom de paramètre `tokenUrl` au lieu de `token_url`.
+
+C'est parce qu'il utilise le même nom que dans la spécification OpenAPI. Ainsi, si vous devez approfondir l'un de ces schémas de sécurité, vous pouvez simplement copier-coller pour trouver plus d'informations à ce sujet.
+
+///
+
+La variable `oauth2_scheme` est une instance de `OAuth2PasswordBearer`, mais c'est aussi un « callable ».
+
+Elle pourrait être appelée ainsi :
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+Ainsi, elle peut être utilisée avec `Depends`.
+
+### Utiliser { #use-it }
+
+Vous pouvez maintenant passer ce `oauth2_scheme` en dépendance avec `Depends`.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Cette dépendance fournira une `str` qui est affectée au paramètre `token` de la fonction de *chemin d'accès*.
+
+**FastAPI** saura qu'il peut utiliser cette dépendance pour définir un « schéma de sécurité » dans le schéma OpenAPI (et la documentation API automatique).
+
+/// info | Détails techniques
+
+**FastAPI** saura qu'il peut utiliser la classe `OAuth2PasswordBearer` (déclarée dans une dépendance) pour définir le schéma de sécurité dans OpenAPI parce qu'elle hérite de `fastapi.security.oauth2.OAuth2`, qui hérite à son tour de `fastapi.security.base.SecurityBase`.
+
+Tous les utilitaires de sécurité qui s'intègrent à OpenAPI (et à la documentation API automatique) héritent de `SecurityBase`, c'est ainsi que **FastAPI** sait comment les intégrer dans OpenAPI.
+
+///
+
+## Ce que cela fait { #what-it-does }
+
+Il va chercher dans la requête cet en-tête `Authorization`, vérifier si la valeur est `Bearer ` plus un token, et renverra le token en tant que `str`.
+
+S'il ne voit pas d'en-tête `Authorization`, ou si la valeur n'a pas de token `Bearer `, il répondra directement avec une erreur de code d'état 401 (`UNAUTHORIZED`).
+
+Vous n'avez même pas à vérifier si le token existe pour renvoyer une erreur. Vous pouvez être sûr que si votre fonction est exécutée, elle aura une `str` dans ce token.
+
+Vous pouvez déjà l'essayer dans la documentation interactive :
+
+
+
+Nous ne vérifions pas encore la validité du token, mais c'est déjà un début.
+
+## Récapitulatif { #recap }
+
+Ainsi, en seulement 3 ou 4 lignes supplémentaires, vous disposez déjà d'une forme primitive de sécurité.
diff --git a/docs/fr/docs/tutorial/security/get-current-user.md b/docs/fr/docs/tutorial/security/get-current-user.md
new file mode 100644
index 000000000..5f73efea9
--- /dev/null
+++ b/docs/fr/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# Obtenir l'utilisateur actuel { #get-current-user }
+
+Dans le chapitre précédent, le système de sécurité (basé sur le système d'injection de dépendances) fournissait à la *fonction de chemin d'accès* un `token` en tant que `str` :
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Mais ce n'est pas encore très utile.
+
+Faisons en sorte qu'il nous fournisse l'utilisateur actuel.
+
+## Créer un modèle d'utilisateur { #create-a-user-model }
+
+Commençons par créer un modèle d'utilisateur Pydantic.
+
+De la même manière que nous utilisons Pydantic pour déclarer des corps de requête, nous pouvons l'utiliser ailleurs :
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## Créer une dépendance `get_current_user` { #create-a-get-current-user-dependency }
+
+Créons une dépendance `get_current_user`.
+
+Rappelez-vous que les dépendances peuvent avoir des sous-dépendances ?
+
+`get_current_user` aura une dépendance avec le même `oauth2_scheme` que nous avons créé précédemment.
+
+Comme nous le faisions auparavant directement dans le *chemin d'accès*, notre nouvelle dépendance `get_current_user` recevra un `token` en tant que `str` de la sous-dépendance `oauth2_scheme` :
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## Récupérer l'utilisateur { #get-the-user }
+
+`get_current_user` utilisera une fonction utilitaire (factice) que nous avons créée, qui prend un token en `str` et retourne notre modèle Pydantic `User` :
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## Injecter l'utilisateur actuel { #inject-the-current-user }
+
+Nous pouvons donc utiliser le même `Depends` avec notre `get_current_user` dans le *chemin d'accès* :
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+Remarquez que nous déclarons le type de `current_user` comme le modèle Pydantic `User`.
+
+Cela nous aidera dans la fonction avec toute l'autocomplétion et les vérifications de type.
+
+/// tip | Astuce
+
+Vous vous souvenez peut-être que les corps de requête sont également déclarés avec des modèles Pydantic.
+
+Ici, **FastAPI** ne s'y trompera pas car vous utilisez `Depends`.
+
+///
+
+/// check | Vérifications
+
+La manière dont ce système de dépendances est conçu nous permet d'avoir différentes dépendances (différents « dependables ») qui retournent toutes un modèle `User`.
+
+Nous ne sommes pas limités à une seule dépendance pouvant retourner ce type de données.
+
+///
+
+## Autres modèles { #other-models }
+
+Vous pouvez maintenant obtenir l'utilisateur actuel directement dans les *fonctions de chemin d'accès* et gérer les mécanismes de sécurité au niveau de l'**Injection de dépendances**, en utilisant `Depends`.
+
+Et vous pouvez utiliser n'importe quel modèle ou données pour les exigences de sécurité (dans ce cas, un modèle Pydantic `User`).
+
+Mais vous n'êtes pas limité à un modèle, une classe ou un type de données spécifique.
+
+Voulez-vous avoir un `id` et `email` et ne pas avoir de `username` dans votre modèle ? Bien sûr. Vous pouvez utiliser ces mêmes outils.
+
+Voulez-vous simplement avoir un `str` ? Ou juste un `dict` ? Ou directement une instance d'un modèle de classe de base de données ? Tout fonctionne de la même manière.
+
+Vous n'avez en fait pas d'utilisateurs qui se connectent à votre application, mais des robots, bots ou d'autres systèmes, qui n'ont qu'un jeton d'accès ? Là encore, tout fonctionne de la même façon.
+
+Utilisez simplement tout type de modèle, toute sorte de classe, tout type de base de données dont vous avez besoin pour votre application. **FastAPI** vous couvre avec le système d'injection de dépendances.
+
+## Taille du code { #code-size }
+
+Cet exemple peut sembler verbeux. Gardez à l'esprit que nous mélangeons sécurité, modèles de données, fonctions utilitaires et *chemins d'accès* dans le même fichier.
+
+Mais voici le point clé.
+
+La partie sécurité et injection de dépendances est écrite une seule fois.
+
+Et vous pouvez la rendre aussi complexe que vous le souhaitez. Et malgré tout, ne l'écrire qu'une seule fois, en un seul endroit. Avec toute la flexibilité.
+
+Mais vous pouvez avoir des milliers d'endpoints (*chemins d'accès*) utilisant le même système de sécurité.
+
+Et tous (ou seulement une partie d'entre eux, si vous le souhaitez) peuvent profiter de la réutilisation de ces dépendances ou de toute autre dépendance que vous créez.
+
+Et tous ces milliers de *chemins d'accès* peuvent tenir en seulement 3 lignes :
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## Récapitulatif { #recap }
+
+Vous pouvez désormais obtenir l'utilisateur actuel directement dans votre *fonction de chemin d'accès*.
+
+Nous avons déjà fait la moitié du chemin.
+
+Il nous suffit d'ajouter un *chemin d'accès* pour que l'utilisateur/client envoie effectivement le `username` et le `password`.
+
+C'est pour la suite.
diff --git a/docs/fr/docs/tutorial/security/index.md b/docs/fr/docs/tutorial/security/index.md
new file mode 100644
index 000000000..6de75aed6
--- /dev/null
+++ b/docs/fr/docs/tutorial/security/index.md
@@ -0,0 +1,106 @@
+# Sécurité { #security }
+
+Il existe de nombreuses façons de gérer la sécurité, l'authentification et l'autorisation.
+
+Et c'est normalement un sujet complexe et « difficile ».
+
+Dans de nombreux frameworks et systèmes, le simple fait de gérer la sécurité et l'authentification demande beaucoup d'efforts et de code (dans de nombreux cas, cela peut représenter 50 % ou plus de tout le code écrit).
+
+**FastAPI** fournit plusieurs outils pour vous aider à gérer la **Sécurité** facilement, rapidement, de manière standard, sans avoir à étudier et apprendre toutes les spécifications de sécurité.
+
+Mais d'abord, voyons quelques notions.
+
+## Pressé ? { #in-a-hurry }
+
+Si ces termes ne vous intéressent pas et que vous avez simplement besoin d'ajouter une sécurité avec une authentification basée sur un nom d'utilisateur et un mot de passe immédiatement, passez aux chapitres suivants.
+
+## OAuth2 { #oauth2 }
+
+OAuth2 est une spécification qui définit plusieurs façons de gérer l'authentification et l'autorisation.
+
+C'est une spécification assez vaste qui couvre plusieurs cas d'utilisation complexes.
+
+Elle inclut des moyens de s'authentifier en utilisant un « tiers ».
+
+C'est ce que tous les systèmes avec « connexion avec Facebook, Google, X (Twitter), GitHub » utilisent en arrière-plan.
+
+### OAuth 1 { #oauth-1 }
+
+Il y a eu un OAuth 1, très différent d'OAuth2, et plus complexe, car il incluait des spécifications directes sur la manière de chiffrer la communication.
+
+Il n'est plus très populaire ni utilisé de nos jours.
+
+OAuth2 ne spécifie pas comment chiffrer la communication ; il suppose que votre application est servie en HTTPS.
+
+/// tip | Astuce
+
+Dans la section sur le déploiement, vous verrez comment configurer HTTPS gratuitement, en utilisant Traefik et Let's Encrypt.
+
+///
+
+## OpenID Connect { #openid-connect }
+
+OpenID Connect est une autre spécification, basée sur **OAuth2**.
+
+Elle étend simplement OAuth2 en précisant certains points relativement ambigus dans OAuth2, afin d'essayer de la rendre plus interopérable.
+
+Par exemple, la connexion Google utilise OpenID Connect (qui, en arrière-plan, utilise OAuth2).
+
+Mais la connexion Facebook ne prend pas en charge OpenID Connect. Elle a sa propre variante d'OAuth2.
+
+### OpenID (pas « OpenID Connect ») { #openid-not-openid-connect }
+
+Il y avait aussi une spécification « OpenID ». Elle essayait de résoudre la même chose qu'**OpenID Connect**, mais n'était pas basée sur OAuth2.
+
+C'était donc un système totalement distinct.
+
+Il n'est plus très populaire ni utilisé de nos jours.
+
+## OpenAPI { #openapi }
+
+OpenAPI (précédemment connu sous le nom de Swagger) est la spécification ouverte pour construire des API (désormais partie de la Linux Foundation).
+
+**FastAPI** est basé sur **OpenAPI**.
+
+C'est ce qui rend possibles plusieurs interfaces de documentation interactive automatiques, la génération de code, etc.
+
+OpenAPI propose une manière de définir plusieurs « schémas » de sécurité.
+
+En les utilisant, vous pouvez tirer parti de tous ces outils basés sur des standards, y compris ces systèmes de documentation interactive.
+
+OpenAPI définit les schémas de sécurité suivants :
+
+* `apiKey` : une clé spécifique à l'application qui peut provenir :
+ * D'un paramètre de requête.
+ * D'un en-tête.
+ * D'un cookie.
+* `http` : des systèmes d'authentification HTTP standards, notamment :
+ * `bearer` : un en-tête `Authorization` avec une valeur `Bearer ` plus un jeton. Hérité d'OAuth2.
+ * Authentification HTTP Basic.
+ * HTTP Digest, etc.
+* `oauth2` : toutes les méthodes OAuth2 pour gérer la sécurité (appelées « flows »).
+ * Plusieurs de ces flows conviennent pour construire un fournisseur d'authentification OAuth 2.0 (comme Google, Facebook, X (Twitter), GitHub, etc.) :
+ * `implicit`
+ * `clientCredentials`
+ * `authorizationCode`
+ * Mais il existe un « flow » spécifique qui peut parfaitement être utilisé pour gérer l'authentification directement dans la même application :
+ * `password` : certains des prochains chapitres couvriront des exemples à ce sujet.
+* `openIdConnect` : propose un moyen de définir comment découvrir automatiquement les données d'authentification OAuth2.
+ * Cette découverte automatique est ce qui est défini dans la spécification OpenID Connect.
+
+
+/// tip | Astuce
+
+Intégrer d'autres fournisseurs d'authentification/autorisation comme Google, Facebook, X (Twitter), GitHub, etc. est également possible et relativement facile.
+
+Le problème le plus complexe est de construire un fournisseur d'authentification/autorisation comme ceux-là, mais **FastAPI** vous donne les outils pour le faire facilement, tout en effectuant le gros du travail pour vous.
+
+///
+
+## Outils **FastAPI** { #fastapi-utilities }
+
+FastAPI propose plusieurs outils pour chacun de ces schémas de sécurité dans le module fastapi.security qui simplifient l'utilisation de ces mécanismes de sécurité.
+
+Dans les prochains chapitres, vous verrez comment ajouter de la sécurité à votre API en utilisant ces outils fournis par **FastAPI**.
+
+Et vous verrez aussi comment cela s'intègre automatiquement au système de documentation interactive.
diff --git a/docs/fr/docs/tutorial/security/oauth2-jwt.md b/docs/fr/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 000000000..d35530fc9
--- /dev/null
+++ b/docs/fr/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# OAuth2 avec mot de passe (et hachage), Bearer avec des jetons JWT { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+Maintenant que nous avons tout le flux de sécurité, rendons réellement l'application sécurisée, en utilisant des jetons JWT et un hachage de mot de passe sécurisé.
+
+Ce code est utilisable dans votre application, enregistrez les hachages de mots de passe dans votre base de données, etc.
+
+Nous allons repartir d'où nous nous sommes arrêtés dans le chapitre précédent et l'enrichir.
+
+## À propos de JWT { #about-jwt }
+
+JWT signifie « JSON Web Tokens ».
+
+C'est une norme pour coder un objet JSON dans une longue chaîne compacte sans espaces. Cela ressemble à ceci :
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+Il n'est pas chiffré ; ainsi, n'importe qui peut récupérer les informations à partir de son contenu.
+
+Mais il est signé. Ainsi, quand vous recevez un jeton que vous avez émis, vous pouvez vérifier que vous l'avez bien émis.
+
+De cette façon, vous pouvez créer un jeton avec une expiration d'une semaine, par exemple. Et quand l'utilisateur revient le lendemain avec ce jeton, vous savez qu'il est toujours connecté à votre système.
+
+Après une semaine, le jeton aura expiré et l'utilisateur ne sera pas autorisé et devra se reconnecter pour obtenir un nouveau jeton. Et si l'utilisateur (ou un tiers) essayait de modifier le jeton pour changer l'expiration, vous pourriez le détecter, car les signatures ne correspondraient pas.
+
+Si vous voulez expérimenter avec des jetons JWT et voir comment ils fonctionnent, consultez https://jwt.io.
+
+## Installer `PyJWT` { #install-pyjwt }
+
+Nous devons installer `PyJWT` pour générer et vérifier les jetons JWT en Python.
+
+Assurez-vous de créer un [environnement virtuel](../../virtual-environments.md){.internal-link target=_blank}, de l'activer, puis d'installer `pyjwt` :
+
+
+
+Autorisez l'application de la même manière qu'auparavant.
+
+En utilisant les identifiants :
+
+Nom d'utilisateur : `johndoe`
+Mot de passe : `secret`
+
+/// check | Vérifications
+
+Remarquez qu'à aucun endroit du code le mot de passe en clair « secret » n'apparaît, nous n'avons que la version hachée.
+
+///
+
+
+
+Appelez le point de terminaison `/users/me/`, vous obtiendrez la réponse suivante :
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+Si vous ouvrez les outils de développement, vous pouvez voir que les données envoyées n'incluent que le jeton ; le mot de passe n'est envoyé que dans la première requête pour authentifier l'utilisateur et obtenir ce jeton d'accès, mais plus ensuite :
+
+
+
+/// note | Remarque
+
+Remarquez l'en-tête `Authorization`, avec une valeur qui commence par `Bearer `.
+
+///
+
+## Utilisation avancée avec `scopes` { #advanced-usage-with-scopes }
+
+OAuth2 comporte la notion de « scopes ».
+
+Vous pouvez les utiliser pour ajouter un ensemble spécifique d'autorisations à un jeton JWT.
+
+Vous pouvez ensuite donner ce jeton directement à un utilisateur ou à un tiers, pour interagir avec votre API avec un ensemble de restrictions.
+
+Vous pouvez apprendre à les utiliser et comment ils sont intégrés à **FastAPI** plus tard dans le **Guide de l'utilisateur avancé**.
+
+## Récapitulatif { #recap }
+
+Avec ce que vous avez vu jusqu'à présent, vous pouvez configurer une application **FastAPI** sécurisée en utilisant des standards comme OAuth2 et JWT.
+
+Dans presque n'importe quel framework, la gestion de la sécurité devient assez rapidement un sujet plutôt complexe.
+
+De nombreux packages qui la simplifient beaucoup doivent faire de nombreux compromis avec le modèle de données, la base de données et les fonctionnalités disponibles. Et certains de ces packages qui simplifient trop les choses comportent en fait des failles de sécurité sous-jacentes.
+
+---
+
+**FastAPI** ne fait aucun compromis avec une base de données, un modèle de données ni un outil.
+
+Il vous donne toute la flexibilité pour choisir ceux qui conviennent le mieux à votre projet.
+
+Et vous pouvez utiliser directement de nombreux packages bien maintenus et largement utilisés comme `pwdlib` et `PyJWT`, car **FastAPI** n'exige aucun mécanisme complexe pour intégrer des packages externes.
+
+Mais il vous fournit les outils pour simplifier le processus autant que possible sans compromettre la flexibilité, la robustesse ou la sécurité.
+
+Et vous pouvez utiliser et implémenter des protocoles sécurisés et standard, comme OAuth2, de manière relativement simple.
+
+Vous pouvez en apprendre davantage dans le **Guide de l'utilisateur avancé** sur la façon d'utiliser les « scopes » OAuth2, pour un système d'autorisations plus fin, en suivant ces mêmes standards. OAuth2 avec scopes est le mécanisme utilisé par de nombreux grands fournisseurs d'authentification, comme Facebook, Google, GitHub, Microsoft, X (Twitter), etc., pour autoriser des applications tierces à interagir avec leurs API au nom de leurs utilisateurs.
diff --git a/docs/fr/docs/tutorial/security/simple-oauth2.md b/docs/fr/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 000000000..662444753
--- /dev/null
+++ b/docs/fr/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# OAuth2 simple avec Password et Bearer { #simple-oauth2-with-password-and-bearer }
+
+Construisons maintenant à partir du chapitre précédent et ajoutons les éléments manquants pour avoir un flux de sécurité complet.
+
+## Obtenir `username` et `password` { #get-the-username-and-password }
+
+Nous allons utiliser les utilitaires de sécurité de **FastAPI** pour obtenir `username` et `password`.
+
+OAuth2 spécifie que lorsqu'on utilise le « password flow » (ce que nous utilisons), le client/utilisateur doit envoyer des champs `username` et `password` en tant que données de formulaire.
+
+Et la spécification indique que les champs doivent porter exactement ces noms. Ainsi, `user-name` ou `email` ne fonctionneraient pas.
+
+Mais ne vous inquiétez pas, vous pouvez l'afficher comme vous le souhaitez à vos utilisateurs finaux dans le frontend.
+
+Et vos modèles de base de données peuvent utiliser les noms que vous voulez.
+
+Mais pour le chemin d'accès de connexion, nous devons utiliser ces noms pour être compatibles avec la spécification (et pouvoir, par exemple, utiliser le système de documentation API intégré).
+
+La spécification précise également que `username` et `password` doivent être envoyés en données de formulaire (donc pas de JSON ici).
+
+### `scope` { #scope }
+
+La spécification indique aussi que le client peut envoyer un autre champ de formulaire « scope ».
+
+Le nom du champ de formulaire est `scope` (au singulier), mais il s'agit en fait d'une longue chaîne contenant des « scopes » séparés par des espaces.
+
+Chaque « scope » n'est qu'une chaîne (sans espaces).
+
+Ils sont normalement utilisés pour déclarer des permissions de sécurité spécifiques, par exemple :
+
+* `users:read` ou `users:write` sont des exemples courants.
+* `instagram_basic` est utilisé par Facebook / Instagram.
+* `https://www.googleapis.com/auth/drive` est utilisé par Google.
+
+/// info
+
+En OAuth2, un « scope » est simplement une chaîne qui déclare une permission spécifique requise.
+
+Peu importe s'il contient d'autres caractères comme `:` ou si c'est une URL.
+
+Ces détails dépendent de l'implémentation.
+
+Pour OAuth2, ce ne sont que des chaînes.
+
+///
+
+## Écrire le code pour obtenir `username` et `password` { #code-to-get-the-username-and-password }
+
+Utilisons maintenant les utilitaires fournis par **FastAPI** pour gérer cela.
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+Tout d'abord, importez `OAuth2PasswordRequestForm`, et utilisez-la en tant que dépendance avec `Depends` dans le chemin d'accès pour `/token` :
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` est une dépendance de classe qui déclare un corps de formulaire avec :
+
+* Le `username`.
+* Le `password`.
+* Un champ optionnel `scope` sous forme d'une grande chaîne, composée de chaînes séparées par des espaces.
+* Un `grant_type` optionnel.
+
+/// tip | Astuce
+
+La spécification OAuth2 exige en réalité un champ `grant_type` avec la valeur fixe `password`, mais `OAuth2PasswordRequestForm` ne l'impose pas.
+
+Si vous avez besoin de l'imposer, utilisez `OAuth2PasswordRequestFormStrict` au lieu de `OAuth2PasswordRequestForm`.
+
+///
+
+* Un `client_id` optionnel (nous n'en avons pas besoin pour notre exemple).
+* Un `client_secret` optionnel (nous n'en avons pas besoin pour notre exemple).
+
+/// info
+
+La classe `OAuth2PasswordRequestForm` n'est pas une classe spéciale pour **FastAPI** comme l'est `OAuth2PasswordBearer`.
+
+`OAuth2PasswordBearer` indique à **FastAPI** qu'il s'agit d'un schéma de sécurité. Il est donc ajouté de cette façon à OpenAPI.
+
+Mais `OAuth2PasswordRequestForm` est simplement une dépendance de classe que vous auriez pu écrire vous‑même, ou vous auriez pu déclarer des paramètres `Form` directement.
+
+Mais comme c'est un cas d'usage courant, elle est fournie directement par **FastAPI**, simplement pour vous faciliter la vie.
+
+///
+
+### Utiliser les données du formulaire { #use-the-form-data }
+
+/// tip | Astuce
+
+L'instance de la classe de dépendance `OAuth2PasswordRequestForm` n'aura pas d'attribut `scope` contenant la longue chaîne séparée par des espaces ; elle aura plutôt un attribut `scopes` avec la liste réelle des chaînes pour chaque scope envoyé.
+
+Nous n'utilisons pas `scopes` dans cet exemple, mais la fonctionnalité est disponible si vous en avez besoin.
+
+///
+
+Récupérez maintenant les données utilisateur depuis la (fausse) base de données, en utilisant le `username` du champ de formulaire.
+
+S'il n'existe pas d'utilisateur, nous renvoyons une erreur indiquant « Incorrect username or password ».
+
+Pour l'erreur, nous utilisons l'exception `HTTPException` :
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### Vérifier le mot de passe { #check-the-password }
+
+À ce stade, nous avons les données utilisateur depuis notre base, mais nous n'avons pas encore vérifié le mot de passe.
+
+Mettons d'abord ces données dans le modèle Pydantic `UserInDB`.
+
+Vous ne devez jamais enregistrer des mots de passe en clair ; nous allons donc utiliser le système (factice) de hachage de mot de passe.
+
+Si les mots de passe ne correspondent pas, nous renvoyons la même erreur.
+
+#### Hachage de mot de passe { #password-hashing }
+
+Le « hachage » signifie : convertir un contenu (un mot de passe, dans ce cas) en une séquence d'octets (juste une chaîne) qui ressemble à du charabia.
+
+Chaque fois que vous fournissez exactement le même contenu (exactement le même mot de passe), vous obtenez exactement le même charabia.
+
+Mais vous ne pouvez pas convertir ce charabia pour retrouver le mot de passe.
+
+##### Pourquoi utiliser le hachage de mot de passe { #why-use-password-hashing }
+
+Si votre base de données est volée, le voleur n'aura pas les mots de passe en clair de vos utilisateurs, seulement les hachages.
+
+Ainsi, il ne pourra pas essayer d'utiliser ces mêmes mots de passe dans un autre système (comme beaucoup d'utilisateurs utilisent le même mot de passe partout, ce serait dangereux).
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### À propos de `**user_dict` { #about-user-dict }
+
+`UserInDB(**user_dict)` signifie :
+
+Passez les clés et valeurs de `user_dict` directement comme arguments clé‑valeur, équivalent à :
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info
+
+Pour une explication plus complète de `**user_dict`, consultez [la documentation pour **Modèles supplémentaires**](../extra-models.md#about-user-in-dict){.internal-link target=_blank}.
+
+///
+
+## Renvoyer le jeton { #return-the-token }
+
+La réponse de l'endpoint `token` doit être un objet JSON.
+
+Il doit contenir un `token_type`. Dans notre cas, comme nous utilisons des jetons « Bearer », le type de jeton doit être « bearer ».
+
+Et il doit contenir un `access_token`, avec une chaîne contenant notre jeton d'accès.
+
+Pour cet exemple simple, nous allons faire quelque chose de complètement non sécurisé et renvoyer le même `username` comme jeton.
+
+/// tip | Astuce
+
+Dans le prochain chapitre, vous verrez une véritable implémentation sécurisée, avec du hachage de mot de passe et des jetons JWT.
+
+Mais pour l'instant, concentrons‑nous sur les détails spécifiques dont nous avons besoin.
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | Astuce
+
+D'après la spécification, vous devez renvoyer un JSON avec un `access_token` et un `token_type`, comme dans cet exemple.
+
+C'est quelque chose que vous devez faire vous‑même dans votre code, et vous devez vous assurer d'utiliser ces clés JSON.
+
+C'est presque la seule chose que vous devez vous rappeler de faire correctement vous‑même pour être conforme aux spécifications.
+
+Pour le reste, **FastAPI** s'en charge pour vous.
+
+///
+
+## Mettre à jour les dépendances { #update-the-dependencies }
+
+Nous allons maintenant mettre à jour nos dépendances.
+
+Nous voulons obtenir `current_user` uniquement si cet utilisateur est actif.
+
+Nous créons donc une dépendance supplémentaire `get_current_active_user` qui utilise à son tour `get_current_user` comme dépendance.
+
+Ces deux dépendances renverront simplement une erreur HTTP si l'utilisateur n'existe pas, ou s'il est inactif.
+
+Ainsi, dans notre endpoint, nous n'obtiendrons un utilisateur que si l'utilisateur existe, a été correctement authentifié et est actif :
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info
+
+L'en‑tête supplémentaire `WWW-Authenticate` avec la valeur `Bearer` que nous renvoyons ici fait également partie de la spécification.
+
+Il est prévu qu'un code d'état HTTP (d'erreur) 401 « UNAUTHORIZED » renvoie également un en‑tête `WWW-Authenticate`.
+
+Dans le cas des jetons bearer (notre cas), la valeur de cet en‑tête doit être `Bearer`.
+
+Vous pouvez en réalité omettre cet en‑tête supplémentaire et cela fonctionnerait quand même.
+
+Mais il est fourni ici pour être conforme aux spécifications.
+
+De plus, il peut exister des outils qui l'attendent et l'utilisent (maintenant ou à l'avenir) et cela pourrait vous être utile, à vous ou à vos utilisateurs, maintenant ou à l'avenir.
+
+C'est l'avantage des standards ...
+
+///
+
+## Voir en action { #see-it-in-action }
+
+Ouvrez la documentation interactive : http://127.0.0.1:8000/docs.
+
+### S'authentifier { #authenticate }
+
+Cliquez sur le bouton « Authorize ».
+
+Utilisez les identifiants :
+
+Utilisateur : `johndoe`
+
+Mot de passe : `secret`
+
+
+
+Après vous être authentifié dans le système, vous verrez ceci :
+
+
+
+### Obtenir vos propres données utilisateur { #get-your-own-user-data }
+
+Utilisez maintenant l'opération `GET` avec le chemin `/users/me`.
+
+Vous obtiendrez les données de votre utilisateur, par exemple :
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+Si vous cliquez sur l'icône de cadenas et vous vous déconnectez, puis réessayez la même opération, vous obtiendrez une erreur HTTP 401 :
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### Utilisateur inactif { #inactive-user }
+
+Essayez maintenant avec un utilisateur inactif, authentifiez‑vous avec :
+
+Utilisateur : `alice`
+
+Mot de passe : `secret2`
+
+Et essayez d'utiliser l'opération `GET` avec le chemin `/users/me`.
+
+Vous obtiendrez une erreur « Inactive user », par exemple :
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## Récapitulatif { #recap }
+
+Vous avez maintenant les outils pour implémenter un système de sécurité complet basé sur `username` et `password` pour votre API.
+
+En utilisant ces outils, vous pouvez rendre le système de sécurité compatible avec n'importe quelle base de données et avec n'importe quel modèle d'utilisateur ou de données.
+
+Le seul détail manquant est qu'il n'est pas encore réellement « sécurisé ».
+
+Dans le prochain chapitre, vous verrez comment utiliser une bibliothèque de hachage de mot de passe sécurisée et des jetons JWT.
diff --git a/docs/fr/docs/tutorial/sql-databases.md b/docs/fr/docs/tutorial/sql-databases.md
new file mode 100644
index 000000000..75f9ae14f
--- /dev/null
+++ b/docs/fr/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# Bases de données SQL (relationnelles) { #sql-relational-databases }
+
+**FastAPI** ne vous oblige pas à utiliser une base de données SQL (relationnelle). Mais vous pouvez utiliser **n'importe quelle base de données** que vous voulez.
+
+Ici, nous allons voir un exemple utilisant SQLModel.
+
+**SQLModel** est construit au-dessus de SQLAlchemy et de Pydantic. Il a été créé par le même auteur que **FastAPI** pour être l'accord parfait pour les applications FastAPI qui ont besoin d'utiliser des **bases de données SQL**.
+
+/// tip | Astuce
+
+Vous pouvez utiliser toute autre bibliothèque SQL ou NoSQL que vous voulez (dans certains cas appelées « ORMs »), FastAPI ne vous impose rien. 😎
+
+///
+
+Comme SQLModel est basé sur SQLAlchemy, vous pouvez facilement utiliser **toute base prise en charge** par SQLAlchemy (ce qui les rend également prises en charge par SQLModel), comme :
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server, etc.
+
+Dans cet exemple, nous utiliserons **SQLite**, car il utilise un seul fichier et Python a un support intégré. Ainsi, vous pouvez copier cet exemple et l'exécuter tel quel.
+
+Plus tard, pour votre application de production, vous voudrez peut-être utiliser un serveur de base de données comme **PostgreSQL**.
+
+/// tip | Astuce
+
+Il existe un générateur de projet officiel avec **FastAPI** et **PostgreSQL**, incluant un frontend et plus d'outils : https://github.com/fastapi/full-stack-fastapi-template
+
+///
+
+Il s'agit d'un tutoriel très simple et court ; si vous souhaitez apprendre sur les bases de données en général, sur SQL, ou des fonctionnalités plus avancées, allez voir la documentation SQLModel.
+
+## Installer `SQLModel` { #install-sqlmodel }
+
+D'abord, assurez-vous de créer votre [environnement virtuel](../virtual-environments.md){.internal-link target=_blank}, de l'activer, puis d'installer `sqlmodel` :
+
+
+
+harry v1]
+ style harry-1 fill:#ccc,stroke-dasharray: 5 5
+ harry-3[harry v3]
+ end
+ subgraph stone-project[philosophers-stone project]
+ stone(philosophers-stone) -.-x|⛔️| harry-1
+ end
+ subgraph azkaban-project[prisoner-of-azkaban project]
+ azkaban(prisoner-of-azkaban) --> |requires| harry-3
+ end
+```
+
+/// tip | Astuce
+
+Il est très courant que les packages Python fassent de leur mieux pour éviter les changements cassants dans les nouvelles versions, mais il vaut mieux jouer la sécurité et installer de nouvelles versions intentionnellement et lorsque vous pouvez exécuter les tests pour vérifier que tout fonctionne correctement.
+
+///
+
+Maintenant, imaginez cela avec beaucoup d’autres packages dont tous vos projets dépendent. C’est très difficile à gérer. Et vous finiriez probablement par exécuter certains projets avec des versions incompatibles des packages, sans savoir pourquoi quelque chose ne fonctionne pas.
+
+De plus, selon votre système d’exploitation (par exemple Linux, Windows, macOS), il se peut qu’il soit livré avec Python déjà installé. Et dans ce cas, il avait probablement des packages préinstallés avec des versions spécifiques nécessaires à votre système. Si vous installez des packages dans l’environnement Python global, vous pourriez finir par casser certains des programmes fournis avec votre système d’exploitation.
+
+## Où les packages sont-ils installés { #where-are-packages-installed }
+
+Lorsque vous installez Python, il crée des répertoires avec des fichiers sur votre ordinateur.
+
+Certains de ces répertoires sont chargés de contenir tous les packages que vous installez.
+
+Lorsque vous exécutez :
+
+lt
+* XWT
+* PSGI
+
+### abbr 提供完整詞組與說明 { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | 資訊
+
+「abbr」元素的「title」屬性需依特定規則翻譯。
+
+翻譯可以自行新增「abbr」元素(例如為解釋英文單字),LLM 不應移除它們。
+
+請見 `scripts/translate.py` 中通用提示的 `### HTML abbr elements` 小節。
+
+////
+
+## HTML「dfn」元素 { #html-dfn-elements }
+
+* 叢集
+* 深度學習
+
+## 標題 { #headings }
+
+//// tab | 測試
+
+### 開發網頁應用程式 - 教學 { #develop-a-webapp-a-tutorial }
+
+Hello.
+
+### 型別提示與註解 { #type-hints-and-annotations }
+
+Hello again.
+
+### 超類與子類別 { #super-and-subclasses }
+
+Hello again.
+
+////
+
+//// tab | 資訊
+
+標題唯一的硬性規則是保留花括號中的雜湊片段不變,以確保連結不會失效。
+
+請見 `scripts/translate.py` 中通用提示的 `### Headings` 小節。
+
+關於語言特定的說明,參見例如 `docs/de/llm-prompt.md` 中的 `### Headings` 小節。
+
+////
+
+## 文件中使用的術語 { #terms-used-in-the-docs }
+
+//// tab | 測試
+
+* you
+* your
+
+* e.g.
+* etc.
+
+* `foo` as an `int`
+* `bar` as a `str`
+* `baz` as a `list`
+
+* 教學 - 使用者指南
+* 進階使用者指南
+* SQLModel 文件
+* API 文件
+* 自動文件
+
+* 資料科學
+* 深度學習
+* 機器學習
+* 相依性注入
+* HTTP 基本驗證
+* HTTP 摘要驗證
+* ISO 格式
+* JSON Schema 標準
+* JSON 結構描述
+* 結構描述定義
+* 密碼流程
+* 行動裝置
+
+* 已棄用
+* 設計的
+* 無效
+* 即時
+* 標準
+* 預設
+* 區分大小寫
+* 不區分大小寫
+
+* 提供應用程式服務
+* 提供頁面服務
+
+* 應用程式
+* 應用程式
+
+* 請求
+* 回應
+* 錯誤回應
+
+* 路徑操作
+* 路徑操作裝飾器
+* 路徑操作函式
+
+* 主體
+* 請求主體
+* 回應主體
+* JSON 主體
+* 表單主體
+* 檔案主體
+* 函式主體
+
+* 參數
+* 主體參數
+* 路徑參數
+* 查詢參數
+* Cookie 參數
+* 標頭參數
+* 表單參數
+* 函式參數
+
+* 事件
+* 啟動事件
+* 伺服器的啟動
+* 關閉事件
+* 生命週期事件
+
+* 處理器
+* 事件處理器
+* 例外處理器
+* 處理
+
+* 模型
+* Pydantic 模型
+* 資料模型
+* 資料庫模型
+* 表單模型
+* 模型物件
+
+* 類別
+* 基底類別
+* 父類別
+* 子類別
+* 子類別
+* 同級類別
+* 類別方法
+
+* 標頭
+* 標頭
+* 授權標頭
+* `Authorization` 標頭
+* 轉送標頭
+
+* 相依性注入系統
+* 相依項
+* 可相依對象
+* 相依者
+
+* I/O 受限
+* CPU 受限
+* 並發
+* 平行處理
+* 多處理程序
+
+* 環境變數
+* 環境變數
+* `PATH`
+* `PATH` 變數
+
+* 驗證
+* 驗證提供者
+* 授權
+* 授權表單
+* 授權提供者
+* 使用者進行驗證
+* 系統驗證使用者
+
+* CLI
+* 命令列介面
+
+* 伺服器
+* 用戶端
+
+* 雲端提供者
+* 雲端服務
+
+* 開發
+* 開發階段
+
+* dict
+* 字典
+* 列舉
+* enum
+* 列舉成員
+
+* 編碼器
+* 解碼器
+* 編碼
+* 解碼
+
+* 例外
+* 拋出
+
+* 運算式
+* 陳述式
+
+* 前端
+* 後端
+
+* GitHub 討論
+* GitHub 議題
+
+* 效能
+* 效能優化
+
+* 回傳型別
+* 回傳值
+
+* 安全性
+* 安全性機制
+
+* 任務
+* 背景任務
+* 任務函式
+
+* 樣板
+* 樣板引擎
+
+* 型別註解
+* 型別提示
+
+* 伺服器工作進程
+* Uvicorn 工作進程
+* Gunicorn 工作進程
+* 工作進程
+* worker 類別
+* 工作負載
+
+* 部署
+* 部署
+
+* SDK
+* 軟體開發工具組
+
+* `APIRouter`
+* `requirements.txt`
+* Bearer Token
+* 相容性破壞變更
+* 錯誤
+* 按鈕
+* 可呼叫對象
+* 程式碼
+* 提交
+* 情境管理器
+* 協程
+* 資料庫工作階段
+* 磁碟
+* 網域
+* 引擎
+* 假的 X
+* HTTP GET 方法
+* 項目
+* 函式庫
+* 生命週期
+* 鎖
+* 中介軟體
+* 行動應用程式
+* 模組
+* 掛載
+* 網路
+* 來源
+* 覆寫
+* 有效負載
+* 處理器
+* 屬性
+* 代理
+* pull request
+* 查詢
+* RAM
+* 遠端機器
+* 狀態碼
+* 字串
+* 標籤
+* Web 框架
+* 萬用字元
+* 回傳
+* 驗證
+
+////
+
+//// tab | 資訊
+
+這是一份不完整且非規範性的(多為)技術術語清單,來源為文件內容。它可能有助於提示設計者判斷哪些術語需要 LLM 的特別協助。例如當 LLM 反覆把好的翻譯改回成較差的版本,或在你的語言中對某詞的詞形變化處理有困難時。
+
+請見例如 `docs/de/llm-prompt.md` 中的 `### List of English terms and their preferred German translations` 小節。
+
+////
diff --git a/docs/zh-hant/docs/advanced/additional-responses.md b/docs/zh-hant/docs/advanced/additional-responses.md
new file mode 100644
index 000000000..bb2bf259b
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# OpenAPI 中的額外回應 { #additional-responses-in-openapi }
+
+/// warning | 警告
+
+這是一個偏進階的主題。
+
+如果你剛開始使用 **FastAPI**,大多情況下不需要用到它。
+
+///
+
+你可以宣告額外的回應,包含額外的狀態碼、媒體型別、描述等。
+
+這些額外回應會被包含在 OpenAPI 中,因此也會顯示在 API 文件裡。
+
+但對於這些額外回應,你必須直接回傳像 `JSONResponse` 這樣的 `Response`,並包含你的狀態碼與內容。
+
+## 使用 `model` 的額外回應 { #additional-response-with-model }
+
+你可以在你的「路徑操作裝飾器」中傳入參數 `responses`。
+
+它接收一個 `dict`:鍵是各回應的狀態碼(例如 `200`),值是另一個 `dict`,其中包含每個回應的資訊。
+
+每個回應的 `dict` 都可以有一個鍵 `model`,包含一個 Pydantic 模型,與 `response_model` 類似。
+
+**FastAPI** 會取用該模型、產生其 JSON Schema,並把它放到 OpenAPI 中正確的位置。
+
+例如,要宣告一個狀態碼為 `404` 的額外回應,並使用 Pydantic 模型 `Message`,你可以這樣寫:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | 注意
+
+請記住你必須直接回傳 `JSONResponse`。
+
+///
+
+/// info | 說明
+
+`model` 這個鍵不屬於 OpenAPI。
+
+**FastAPI** 會從這裡取出 Pydantic 模型,產生 JSON Schema,並放到正確位置。
+
+正確的位置是:
+
+* 在 `content` 這個鍵中,其值是一個 JSON 物件(`dict`),包含:
+ * 一個媒體型別作為鍵,例如 `application/json`,其值是另一個 JSON 物件,當中包含:
+ * 鍵 `schema`,其值是該模型的 JSON Schema,這裡就是正確的位置。
+ * **FastAPI** 會在這裡加入一個指向你 OpenAPI 中全域 JSON Schemas 的參照,而不是直接把它嵌入。如此一來,其他應用與用戶端可以直接使用那些 JSON Schemas,提供更好的程式碼產生工具等。
+
+///
+
+這個路徑操作在 OpenAPI 中產生的回應將會是:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+這些 Schemas 會在 OpenAPI 中以參照的方式指向其他位置:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## 主回應的其他媒體型別 { #additional-media-types-for-the-main-response }
+
+你可以用同一個 `responses` 參數,替相同的主回應新增不同的媒體型別。
+
+例如,你可以新增 `image/png` 這種媒體型別,宣告你的「路徑操作」可以回傳 JSON 物件(媒體型別為 `application/json`)或一張 PNG 圖片:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | 注意
+
+請注意你必須直接用 `FileResponse` 回傳圖片。
+
+///
+
+/// info | 說明
+
+除非你在 `responses` 參數中明確指定不同的媒體型別,否則 FastAPI 會假設回應的媒體型別與主回應類別相同(預設為 `application/json`)。
+
+但如果你指定了一個自訂的回應類別,且其媒體型別為 `None`,那麼對於任何具關聯模型的額外回應,FastAPI 會使用 `application/json`。
+
+///
+
+## 結合資訊 { #combining-information }
+
+你也可以從多個地方結合回應資訊,包括 `response_model`、`status_code` 與 `responses` 參數。
+
+你可以宣告一個 `response_model`,使用預設狀態碼 `200`(或你需要的自訂狀態碼),然後在 `responses` 中直接於 OpenAPI Schema 為相同的回應宣告額外資訊。
+
+**FastAPI** 會保留 `responses` 提供的額外資訊,並把它和你模型的 JSON Schema 結合。
+
+例如,你可以宣告一個狀態碼為 `404` 的回應,使用一個 Pydantic 模型,並帶有自訂的 `description`。
+
+以及一個狀態碼為 `200` 的回應,使用你的 `response_model`,但包含自訂的 `example`:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+以上都會被結合並包含在你的 OpenAPI 中,並顯示在 API 文件:
+
+
+
+## 結合預先定義與自訂的回應 { #combine-predefined-responses-and-custom-ones }
+
+你可能想要有一些適用於多個「路徑操作」的預先定義回應,但也想與每個「路徑操作」所需的自訂回應結合。
+
+在這些情況下,你可以使用 Python 的「解包」`dict` 技巧,透過 `**dict_to_unpack`:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+此處,`new_dict` 會包含 `old_dict` 的所有鍵值配對,再加上新的鍵值配對:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+你可以用這個技巧在「路徑操作」中重用一些預先定義的回應,並與其他自訂回應結合。
+
+例如:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## 關於 OpenAPI 回應的更多資訊 { #more-information-about-openapi-responses }
+
+若要查看回應中究竟可以包含哪些內容,你可以參考 OpenAPI 規範中的這些章節:
+
+* OpenAPI Responses 物件,其中包含 `Response Object`。
+* OpenAPI Response 物件,你可以把這裡的任何內容直接放到 `responses` 參數內各個回應中。包含 `description`、`headers`、`content`(在其中宣告不同的媒體型別與 JSON Schemas)、以及 `links`。
diff --git a/docs/zh-hant/docs/advanced/additional-status-codes.md b/docs/zh-hant/docs/advanced/additional-status-codes.md
new file mode 100644
index 000000000..450a4705a
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/additional-status-codes.md
@@ -0,0 +1,41 @@
+# 額外的狀態碼 { #additional-status-codes }
+
+在預設情況下,**FastAPI** 會使用 `JSONResponse` 傳回回應,並把你從你的「路徑操作(path operation)」回傳的內容放進該 `JSONResponse` 中。
+
+它會使用預設的狀態碼,或你在路徑操作中設定的狀態碼。
+
+## 額外的狀態碼 { #additional-status-codes_1 }
+
+如果你想在主要狀態碼之外再回傳其他狀態碼,可以直接回傳一個 `Response`(例如 `JSONResponse`),並直接設定你想要的額外狀態碼。
+
+例如,你想要有一個允許更新項目的路徑操作,成功時回傳 HTTP 狀態碼 200 "OK"。
+
+但你也希望它能接受新項目;當項目先前不存在時就建立它們,並回傳 HTTP 狀態碼 201 "Created"。
+
+要達成這點,匯入 `JSONResponse`,直接在那裡回傳內容,並設定你想要的 `status_code`:
+
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
+
+/// warning
+
+當你直接回傳一個 `Response`(就像上面的範例),它會原封不動地被送出。
+
+不會再經過模型序列化等處理。
+
+請確認其中包含你要的資料,且各值是合法的 JSON(如果你使用的是 `JSONResponse`)。
+
+///
+
+/// note | 注意
+
+你也可以使用 `from starlette.responses import JSONResponse`。
+
+**FastAPI** 也將同樣的 `starlette.responses` 以 `fastapi.responses` 的形式提供,純粹是為了讓你(開發者)更方便。但大多數可用的回應類別其實都直接來自 Starlette。`status` 也一樣。
+
+///
+
+## OpenAPI 與 API 文件 { #openapi-and-api-docs }
+
+如果你直接回傳額外的狀態碼與回應,它們不會被包含進 OpenAPI 綱要(API 文件)中,因為 FastAPI 無法事先知道你會回傳什麼。
+
+但你可以在程式碼中補充文件,使用:[額外的回應](additional-responses.md){.internal-link target=_blank}。
diff --git a/docs/zh-hant/docs/advanced/advanced-dependencies.md b/docs/zh-hant/docs/advanced/advanced-dependencies.md
new file mode 100644
index 000000000..472cf470b
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# 進階相依 { #advanced-dependencies }
+
+## 參數化的相依 { #parameterized-dependencies }
+
+到目前為止看到的相依都是固定的函式或類別。
+
+但有些情況下,你可能想要能為相依設定參數,而不必宣告許多不同的函式或類別。
+
+想像我們想要一個相依,用來檢查查詢參數 `q` 是否包含某些固定內容。
+
+同時我們希望能將那個固定內容參數化。
+
+## 「callable」的實例 { #a-callable-instance }
+
+在 Python 中有一種方式可以讓一個類別的實例變成「callable」。
+
+不是類別本身(類別本來就可呼叫),而是該類別的實例。
+
+要做到這點,我們宣告一個 `__call__` 方法:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+在這個情境中,**FastAPI** 會用這個 `__call__` 來檢查額外的參數與子相依,並在之後呼叫它,把回傳值傳遞給你的「路徑操作函式」中的參數。
+
+## 讓實例可參數化 { #parameterize-the-instance }
+
+接著,我們可以用 `__init__` 來宣告這個實例的參數,用以「參數化」這個相依:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+在這裡,**FastAPI** 完全不會接觸或在意 `__init__`,我們會直接在自己的程式碼中使用它。
+
+## 建立一個實例 { #create-an-instance }
+
+我們可以這樣建立該類別的實例:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+如此一來我們就能「參數化」相依,現在它內部含有 `"bar"`,作為屬性 `checker.fixed_content`。
+
+## 將實例作為相依使用 { #use-the-instance-as-a-dependency }
+
+然後,我們可以在 `Depends(checker)` 中使用這個 `checker`,而不是 `Depends(FixedContentQueryChecker)`,因為相依是那個實例 `checker`,不是類別本身。
+
+當解析相依時,**FastAPI** 會像這樣呼叫這個 `checker`:
+
+```Python
+checker(q="somequery")
+```
+
+...並將其回傳值,作為相依的值,以參數 `fixed_content_included` 傳給我們的「路徑操作函式」:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | 提示
+
+這一切現在看起來也許有點牽強,而且目前可能還不太清楚有何用途。
+
+這些範例刻意保持簡單,但展示了整個機制如何運作。
+
+在關於安全性的章節裡,有一些工具函式也是用同樣的方式實作。
+
+如果你理解了以上內容,你其實已經知道那些安全性工具在底層是如何運作的。
+
+///
+
+## 同時含有 `yield`、`HTTPException`、`except` 與背景任務的相依 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | 警告
+
+你很可能不需要這些技術細節。
+
+這些細節主要在於:如果你有一個 0.121.0 之前的 FastAPI 應用,並且在使用含有 `yield` 的相依時遇到問題,會對你有幫助。
+
+///
+
+含有 `yield` 的相依隨著時間演進,以涵蓋不同的使用情境並修正一些問題。以下是變更摘要。
+
+### 含有 `yield` 與 `scope` 的相依 { #dependencies-with-yield-and-scope }
+
+在 0.121.0 版中,FastAPI 為含有 `yield` 的相依加入了 `Depends(scope="function")` 的支援。
+
+使用 `Depends(scope="function")` 時,`yield` 之後的結束程式碼會在「路徑操作函式」執行完畢後立刻執行,在回應發送回客戶端之前。
+
+而當使用 `Depends(scope="request")`(預設值)時,`yield` 之後的結束程式碼會在回應送出之後才執行。
+
+你可以在文件中閱讀更多:[含有 `yield` 的相依 - 提前結束與 `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope)。
+
+### 含有 `yield` 與 `StreamingResponse` 的相依,技術細節 { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+在 FastAPI 0.118.0 之前,如果你使用含有 `yield` 的相依,它會在「路徑操作函式」回傳之後、發送回應之前,執行結束程式碼。
+
+這樣做的用意是避免在等待回應穿越網路時,比必要的時間更久地占用資源。
+
+但這也意味著,如果你回傳的是 `StreamingResponse`,該含有 `yield` 的相依的結束程式碼早已執行完畢。
+
+例如,如果你在含有 `yield` 的相依中使用了一個資料庫 session,`StreamingResponse` 在串流資料時將無法使用該 session,因為它已在 `yield` 之後的結束程式碼中被關閉了。
+
+這個行為在 0.118.0 被還原,使得 `yield` 之後的結束程式碼會在回應送出之後才被執行。
+
+/// info | 資訊
+
+如下所見,這與 0.106.0 之前的行為非常類似,但對一些邊界情況做了多項改進與錯誤修正。
+
+///
+
+#### 需要提早執行結束程式碼的情境 { #use-cases-with-early-exit-code }
+
+有些特定條件的使用情境,可能會受益於舊行為(在送出回應之前執行含有 `yield` 的相依的結束程式碼)。
+
+例如,假設你在含有 `yield` 的相依中只用資料庫 session 來驗證使用者,而這個 session 之後並未在「路徑操作函式」中使用,僅在相依中使用,且回應需要很長時間才會送出,例如一個慢速傳送資料的 `StreamingResponse`,但它並沒有使用資料庫。
+
+在這種情況下,資料庫 session 會一直被保留到回應傳送完畢為止,但如果你根本不會用到它,就沒有必要一直持有它。
+
+可能會像這樣:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+結束程式碼(自動關閉 `Session`)在:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...會在回應完成傳送這些慢速資料後才執行:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+但因為 `generate_stream()` 並未使用資料庫 session,實際上不需要在傳送回應時保持 session 開啟。
+
+如果你用的是 SQLModel(或 SQLAlchemy)且有這種特定情境,你可以在不再需要時明確關閉該 session:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+如此一來,該 session 就會釋放資料庫連線,讓其他請求可以使用。
+
+如果你有不同的情境,需要從含有 `yield` 的相依中提早結束,請建立一個 GitHub 討論問題,描述你的具體情境,以及為何提早關閉含有 `yield` 的相依對你有幫助。
+
+如果有令人信服的案例需要在含有 `yield` 的相依中提前關閉,我會考慮加入一種新的選項,讓你可以選擇性啟用提前關閉。
+
+### 含有 `yield` 與 `except` 的相依,技術細節 { #dependencies-with-yield-and-except-technical-details }
+
+在 FastAPI 0.110.0 之前,如果你使用含有 `yield` 的相依,並且在該相依中用 `except` 捕捉到例外,且沒有再次拋出,那個例外會自動被拋出/轉交給任何例外處理器或內部伺服器錯誤處理器。
+
+在 0.110.0 版本中,這被修改以修復沒有處理器(內部伺服器錯誤)而被轉交的例外所造成的未處理記憶體消耗,並使其行為與一般 Python 程式碼一致。
+
+### 背景任務與含有 `yield` 的相依,技術細節 { #background-tasks-and-dependencies-with-yield-technical-details }
+
+在 FastAPI 0.106.0 之前,不可能在 `yield` 之後拋出例外;含有 `yield` 的相依的結束程式碼會在回應送出之後才執行,因此[例外處理器](../tutorial/handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} 早就已經跑完了。
+
+當初這樣設計主要是為了允許在背景任務中使用由相依「yield」出來的同一組物件,因為結束程式碼會在背景任務結束後才執行。
+
+在 FastAPI 0.106.0 中,這個行為被修改,目的是在等待回應穿越網路的期間,不要持有資源。
+
+/// tip | 提示
+
+此外,背景任務通常是一組獨立的邏輯,應該用自己的資源(例如自己的資料庫連線)來處理。
+
+這樣你的程式碼通常會更乾淨。
+
+///
+
+如果你先前依賴這種行為,現在應該在背景任務本身裡建立所需資源,並且只使用不依賴含有 `yield` 的相依之資源的資料。
+
+例如,不要共用同一個資料庫 session,而是在背景任務中建立一個新的資料庫 session,並用這個新的 session 從資料庫取得物件。接著,在呼叫背景任務函式時,不是傳遞資料庫物件本身,而是傳遞該物件的 ID,然後在背景任務函式內再透過這個 ID 取得物件。
diff --git a/docs/zh-hant/docs/advanced/advanced-python-types.md b/docs/zh-hant/docs/advanced/advanced-python-types.md
new file mode 100644
index 000000000..ffa139427
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# 進階 Python 型別 { #advanced-python-types }
+
+以下是一些在使用 Python 型別時可能有用的額外想法。
+
+## 使用 `Union` 或 `Optional` { #using-union-or-optional }
+
+如果你的程式碼因某些原因無法使用 `|`,例如不是在型別註記中,而是在像 `response_model=` 之類的參數位置,那麼你可以用 `typing` 中的 `Union` 來取代豎線(`|`)。
+
+例如,你可以宣告某個值可以是 `str` 或 `None`:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+在 `typing` 中也有用 `Optional` 宣告某個值可以是 `None` 的速記法。
+
+以下是我個人(非常主觀)的建議:
+
+* 🚨 避免使用 `Optional[SomeType]`
+* 改為 ✨ 使用 `Union[SomeType, None]` ✨。
+
+兩者等價且底層相同,但我會推薦用 `Union` 而不要用 `Optional`,因為「optional」這個詞看起來會讓人以為這個值是可選的,但實際上它的意思是「可以是 `None`」,即使它不是可選的、仍然是必填。
+
+我認為 `Union[SomeType, None]` 更能清楚表達其含義。
+
+這只是措辭與命名問題,但這些詞會影響你與團隊成員對程式碼的理解。
+
+例如,看看下面這個函式:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+參數 `name` 被標註為 `Optional[str]`,但它並不是可選的;你不能在沒有該參數的情況下呼叫這個函式:
+
+```Python
+say_hi() # 糟了,這會拋出錯誤!😱
+```
+
+參數 `name` 仍是必填(不是可選),因為它沒有預設值。不過,`name` 可以接受 `None` 作為值:
+
+```Python
+say_hi(name=None) # 這可行,None 是有效的 🎉
+```
+
+好消息是,多數情況下你可以直接用 `|` 來定義型別聯集:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+因此,通常你不必為 `Optional` 與 `Union` 這些名稱操心。😎
diff --git a/docs/zh-hant/docs/advanced/async-tests.md b/docs/zh-hant/docs/advanced/async-tests.md
new file mode 100644
index 000000000..cb7430bf6
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# 非同步測試 { #async-tests }
+
+你已經看過如何使用提供的 `TestClient` 來測試你的 FastAPI 應用。到目前為止,你只看到如何撰寫同步測試,沒有使用 `async` 函式。
+
+在測試中能使用非同步函式會很有用,例如當你以非同步方式查詢資料庫時。想像你想測試發送請求到 FastAPI 應用,然後在使用非同步資料庫函式庫時,驗證後端是否成功把正確資料寫入資料庫。
+
+來看看怎麼做。
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+若要在測試中呼叫非同步函式,測試函式本身也必須是非同步的。AnyIO 為此提供了一個好用的外掛,讓我們可以標示某些測試函式以非同步方式執行。
+
+## HTTPX { #httpx }
+
+即使你的 FastAPI 應用使用一般的 `def` 函式而非 `async def`,它在底層仍然是個 `async` 應用。
+
+`TestClient` 在內部做了一些魔法,讓我們能在一般的 `def` 測試函式中,使用標準 pytest 來呼叫非同步的 FastAPI 應用。但當我們在非同步函式中使用它時,這個魔法就不再奏效了。也就是說,當以非同步方式執行測試時,就不能在測試函式內使用 `TestClient`。
+
+`TestClient` 是建立在 HTTPX 之上,所幸我們可以直接使用它來測試 API。
+
+## 範例 { #example }
+
+作為簡單範例,讓我們考慮與[更大型的應用](../tutorial/bigger-applications.md){.internal-link target=_blank}與[測試](../tutorial/testing.md){.internal-link target=_blank}中描述的類似檔案結構:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+檔案 `main.py` 會是:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+檔案 `test_main.py` 會包含針對 `main.py` 的測試,現在可能像這樣:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## 執行 { #run-it }
+
+如常執行測試:
+
+
Host: mysuperapp.com
Path: /items
+
+ Note over Proxy: Proxy adds forwarded headers
+
+ Proxy->>Server: HTTP Request
X-Forwarded-For: [client IP]
X-Forwarded-Proto: https
X-Forwarded-Host: mysuperapp.com
Path: /items
+
+ Note over Server: Server interprets headers
(if --forwarded-allow-ips is set)
+
+ Server->>Proxy: HTTP Response
with correct HTTPS URLs
+
+ Proxy->>Client: HTTPS Response
+```
+
+「代理」會攔截原始用戶端請求,並在將其轉交給「應用伺服器」之前加入特殊的「轉發」標頭(`X-Forwarded-*`)。
+
+這些標頭會保留原始請求中原本會遺失的資訊:
+
+* X-Forwarded-For:原始用戶端的 IP 位址
+* X-Forwarded-Proto:原始協定(`https`)
+* X-Forwarded-Host:原始主機(`mysuperapp.com`)
+
+當以 `--forwarded-allow-ips` 設定好 FastAPI CLI 後,它會信任並使用這些標頭,例如在重新導向時產生正確的 URL。
+
+## 具有移除路徑前綴的代理 { #proxy-with-a-stripped-path-prefix }
+
+你可能會有一個會為你的應用加入路徑前綴的代理。
+
+在這些情況下,你可以使用 `root_path` 來設定你的應用。
+
+`root_path` 是 ASGI 規格(FastAPI 透過 Starlette 所遵循的規格)所提供的機制。
+
+`root_path` 用來處理這些特定情境。
+
+在掛載子應用時,內部也會使用它。
+
+這種「具有移除路徑前綴的代理」情況,代表你在程式碼中宣告了 `/app` 的路徑,但你在上面又加了一層(代理),把你的 FastAPI 應用放在像是 `/api/v1` 這樣的路徑底下。
+
+在這種情況下,原本的 `/app` 路徑實際上會以 `/api/v1/app` 對外提供服務。
+
+即使你的程式碼都是以只有 `/app` 為前提撰寫的。
+
+{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[6] *}
+
+而代理會在把請求轉交給應用伺服器(多半是透過 FastAPI CLI 啟動的 Uvicorn)之前,動態地「移除」這個「路徑前綴」,讓你的應用仍然以為自己是在 `/app` 底下被提供,這樣你就不需要把整個程式碼都改成包含 `/api/v1` 這個前綴。
+
+到目前為止,一切都會如常運作。
+
+但是,當你打開整合的文件 UI(前端)時,它會預期在 `/openapi.json` 取得 OpenAPI 模式,而不是在 `/api/v1/openapi.json`。
+
+因此,前端(在瀏覽器中執行)會嘗試存取 `/openapi.json`,但無法取得 OpenAPI 模式。
+
+因為我們的應用前面有一個將路徑前綴設定為 `/api/v1` 的代理,所以前端需要從 `/api/v1/openapi.json` 取得 OpenAPI 模式。
+
+```mermaid
+graph LR
+
+browser("Browser")
+proxy["Proxy on http://0.0.0.0:9999/api/v1/app"]
+server["Server on http://127.0.0.1:8000/app"]
+
+browser --> proxy
+proxy --> server
+```
+
+/// tip
+
+IP `0.0.0.0` 通常用來表示程式在該機器/伺服器上的所有可用 IP 上監聽。
+
+///
+
+文件 UI 也需要 OpenAPI 模式宣告此 API 的 `server` 位在 `/api/v1`(代理之後)。例如:
+
+```JSON hl_lines="4-8"
+{
+ "openapi": "3.1.0",
+ // 其他內容
+ "servers": [
+ {
+ "url": "/api/v1"
+ }
+ ],
+ "paths": {
+ // 其他內容
+ }
+}
+```
+
+在這個例子中,「Proxy」可以是 **Traefik**。而伺服器可以是以 **Uvicorn** 啟動的 FastAPI CLI,運行你的 FastAPI 應用。
+
+### 提供 `root_path` { #providing-the-root-path }
+
+要達成這一點,你可以像這樣使用命令列選項 `--root-path`:
+
+
+
+但如果我們改用「正式」的 URL,也就是使用埠號 `9999` 的代理、並在 `/api/v1/docs`,它就能正確運作了!🎉
+
+你可以在 http://127.0.0.1:9999/api/v1/docs 檢查:
+
+
+
+正如我們所希望的那樣。✔️
+
+這是因為 FastAPI 使用這個 `root_path` 來在 OpenAPI 中建立預設的 `server`,其 URL 就是 `root_path` 所提供的值。
+
+## 其他 servers { #additional-servers }
+
+/// warning
+
+這是更進階的用法。你可以選擇略過。
+
+///
+
+預設情況下,FastAPI 會在 OpenAPI 模式中建立一個 `server`,其 URL 為 `root_path`。
+
+但你也可以另外提供其他 `servers`,例如你想要用「同一份」文件 UI 來與測試(staging)與正式(production)環境互動。
+
+如果你傳入自訂的 `servers` 清單,且同時存在 `root_path`(因為你的 API 位於代理之後),FastAPI 會在清單開頭插入一個 `server`,其 URL 為該 `root_path`。
+
+例如:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+將會產生如下的 OpenAPI 模式:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // 其他內容
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // 其他內容
+ }
+}
+```
+
+/// tip
+
+注意自動產生的 server,其 `url` 值為 `/api/v1`,取自 `root_path`。
+
+///
+
+在位於 http://127.0.0.1:9999/api/v1/docs 的文件 UI 中看起來會像這樣:
+
+
+
+/// tip
+
+文件 UI 會與你所選擇的 server 互動。
+
+///
+
+/// note | 技術細節
+
+OpenAPI 規格中的 `servers` 屬性是可選的。
+
+如果你沒有指定 `servers` 參數,且 `root_path` 等於 `/`,則在產生的 OpenAPI 模式中會完全省略 `servers` 屬性(預設行為),這等同於只有一個 `url` 值為 `/` 的 server。
+
+///
+
+### 停用從 `root_path` 自動加入的 server { #disable-automatic-server-from-root-path }
+
+如果你不希望 FastAPI 使用 `root_path` 自動加入一個 server,你可以使用參數 `root_path_in_servers=False`:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+這樣它就不會被包含在 OpenAPI 模式中。
+
+## 掛載子應用 { #mounting-a-sub-application }
+
+如果你需要在同時使用具有 `root_path` 的代理時,掛載一個子應用(如[[子應用 - 掛載](sub-applications.md){.internal-link target=_blank}]中所述),可以像平常一樣操作,正如你所預期的那樣。
+
+FastAPI 會在內部智慧地使用 `root_path`,所以一切都能順利運作。✨
diff --git a/docs/zh-hant/docs/advanced/custom-response.md b/docs/zh-hant/docs/advanced/custom-response.md
new file mode 100644
index 000000000..b723aa82f
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/custom-response.md
@@ -0,0 +1,312 @@
+# 自訂回應——HTML、串流、檔案與其他 { #custom-response-html-stream-file-others }
+
+預設情況下,**FastAPI** 會使用 `JSONResponse` 傳回回應。
+
+你可以像在[直接回傳 Response](response-directly.md){.internal-link target=_blank} 中所示,直接回傳一個 `Response` 來覆寫它。
+
+但如果你直接回傳一個 `Response`(或其子類別,如 `JSONResponse`),資料將不會被自動轉換(即使你宣告了 `response_model`),而且文件也不會自動產生(例如,在產生的 OpenAPI 中包含 HTTP 標頭 `Content-Type` 的特定「media type」)。
+
+你也可以在「路徑操作裝飾器」中使用 `response_class` 參數,宣告要使用的 `Response`(例如任意 `Response` 子類別)。
+
+你從「路徑操作函式」回傳的內容,會被放進該 `Response` 中。
+
+若該 `Response` 的 media type 是 JSON(`application/json`),像 `JSONResponse` 與 `UJSONResponse`,則你回傳的資料會自動以你在「路徑操作裝飾器」中宣告的 Pydantic `response_model` 進行轉換(與過濾)。
+
+/// note
+
+若你使用的回應類別沒有 media type,FastAPI 會假設你的回應沒有內容,因此不會在產生的 OpenAPI 文件中記錄回應格式。
+
+///
+
+## 使用 `ORJSONResponse` { #use-orjsonresponse }
+
+例如,若你在追求效能,你可以安裝並使用 `orjson`,並將回應設為 `ORJSONResponse`。
+
+匯入你想使用的 `Response` 類別(子類),並在「路徑操作裝飾器」中宣告它。
+
+對於大型回應,直接回傳 `Response` 會比回傳 `dict` 快得多。
+
+這是因為預設情況下,FastAPI 會檢查每個項目並確認它能被序列化為 JSON,使用與教學中說明的相同[JSON 相容編碼器](../tutorial/encoder.md){.internal-link target=_blank}。這使你可以回傳「任意物件」,例如資料庫模型。
+
+但如果你確定你回傳的內容「可以用 JSON 序列化」,你可以直接將它傳給回應類別,避免 FastAPI 在把你的回傳內容交給回應類別之前,先經過 `jsonable_encoder` 所帶來的額外開銷。
+
+{* ../../docs_src/custom_response/tutorial001b_py310.py hl[2,7] *}
+
+/// info
+
+參數 `response_class` 也會用來定義回應的「media type」。
+
+在此情況下,HTTP 標頭 `Content-Type` 會被設為 `application/json`。
+
+而且它會以此形式被記錄到 OpenAPI 中。
+
+///
+
+/// tip
+
+`ORJSONResponse` 只在 FastAPI 中可用,在 Starlette 中不可用。
+
+///
+
+## HTML 回應 { #html-response }
+
+要直接從 **FastAPI** 回傳 HTML,使用 `HTMLResponse`。
+
+- 匯入 `HTMLResponse`。
+- 在「路徑操作裝飾器」中,將 `HTMLResponse` 傳給 `response_class` 參數。
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info
+
+參數 `response_class` 也會用來定義回應的「media type」。
+
+在此情況下,HTTP 標頭 `Content-Type` 會被設為 `text/html`。
+
+而且它會以此形式被記錄到 OpenAPI 中。
+
+///
+
+### 回傳 `Response` { #return-a-response }
+
+如[直接回傳 Response](response-directly.md){.internal-link target=_blank} 所示,你也可以在「路徑操作」中直接回傳以覆寫回應。
+
+上面的相同範例,回傳 `HTMLResponse`,可以像這樣:
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning
+
+由你的「路徑操作函式」直接回傳的 `Response` 不會被記錄進 OpenAPI(例如不會記錄 `Content-Type`),也不會出現在自動產生的互動式文件中。
+
+///
+
+/// info
+
+當然,實際的 `Content-Type` 標頭、狀態碼等,會來自你回傳的 `Response` 物件。
+
+///
+
+### 在 OpenAPI 中文件化並覆寫 `Response` { #document-in-openapi-and-override-response }
+
+如果你想在函式內覆寫回應,同時又要在 OpenAPI 中記錄「media type」,你可以同時使用 `response_class` 參數並回傳一個 `Response` 物件。
+
+此時,`response_class` 只會用於記錄該 OpenAPI「路徑操作」,而你回傳的 `Response` 將會如實使用。
+
+#### 直接回傳 `HTMLResponse` { #return-an-htmlresponse-directly }
+
+例如,可能會像這樣:
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+在這個例子中,函式 `generate_html_response()` 已經產生並回傳了一個 `Response`,而不是把 HTML 當作 `str` 回傳。
+
+透過回傳 `generate_html_response()` 的結果,你其實已經回傳了一個 `Response`,這會覆寫 **FastAPI** 的預設行為。
+
+但因為你同時也在 `response_class` 中傳入了 `HTMLResponse`,**FastAPI** 便能在 OpenAPI 與互動式文件中,將其以 `text/html` 的 HTML 形式記錄:
+
+
+
+## 可用的回應 { #available-responses }
+
+以下是一些可用的回應類別。
+
+記得你可以用 `Response` 回傳其他任何東西,甚至建立自訂的子類別。
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import HTMLResponse`。
+
+**FastAPI** 將 `starlette.responses` 以 `fastapi.responses` 提供給你(開發者)做為方便之用。但大多數可用的回應其實直接來自 Starlette。
+
+///
+
+### `Response` { #response }
+
+主要的 `Response` 類別,其他回應皆繼承自它。
+
+你也可以直接回傳它。
+
+它接受以下參數:
+
+- `content` - `str` 或 `bytes`。
+- `status_code` - `int` 類型的 HTTP 狀態碼。
+- `headers` - 由字串組成的 `dict`。
+- `media_type` - 描述 media type 的 `str`。例如 `"text/html"`。
+
+FastAPI(實際上是 Starlette)會自動包含 Content-Length 標頭。也會根據 `media_type`(並為文字型別附加 charset)包含 Content-Type 標頭。
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+接收文字或位元組並回傳 HTML 回應,如上所述。
+
+### `PlainTextResponse` { #plaintextresponse }
+
+接收文字或位元組並回傳純文字回應。
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+接收資料並回傳 `application/json` 編碼的回應。
+
+這是 **FastAPI** 的預設回應,如上所述。
+
+### `ORJSONResponse` { #orjsonresponse }
+
+使用 `orjson` 的快速替代 JSON 回應,如上所述。
+
+/// info
+
+這需要安裝 `orjson`,例如使用 `pip install orjson`。
+
+///
+
+### `UJSONResponse` { #ujsonresponse }
+
+使用 `ujson` 的替代 JSON 回應。
+
+/// info
+
+這需要安裝 `ujson`,例如使用 `pip install ujson`。
+
+///
+
+/// warning
+
+`ujson` 在處理某些邊界情況時,沒那麼嚴謹,較 Python 內建實作更「隨意」。
+
+///
+
+{* ../../docs_src/custom_response/tutorial001_py310.py hl[2,7] *}
+
+/// tip
+
+`ORJSONResponse` 可能是更快的替代方案。
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+回傳一個 HTTP 重新導向。預設使用 307 狀態碼(Temporary Redirect)。
+
+你可以直接回傳 `RedirectResponse`:
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+或者你可以在 `response_class` 參數中使用它:
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+若這麼做,你就可以在「路徑操作函式」中直接回傳 URL。
+
+在此情況下,所使用的 `status_code` 會是 `RedirectResponse` 的預設值 `307`。
+
+---
+
+你也可以同時搭配 `status_code` 與 `response_class` 參數:
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+接收一個 async 產生器或一般的產生器/疊代器,並以串流方式傳送回應本文。
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[2,14] *}
+
+#### 對「類檔案物件」使用 `StreamingResponse` { #using-streamingresponse-with-file-like-objects }
+
+如果你有一個類檔案(file-like)物件(例如 `open()` 回傳的物件),你可以建立一個產生器函式來疊代該類檔案物件。
+
+如此一來,你不必先把它全部讀進記憶體,就能將那個產生器函式傳給 `StreamingResponse` 並回傳。
+
+這也包含許多用於雲端儲存、影像/影音處理等的函式庫。
+
+{* ../../docs_src/custom_response/tutorial008_py310.py hl[2,10:12,14] *}
+
+1. 這是產生器函式。因為它內含 `yield` 陳述式,所以是「產生器函式」。
+2. 透過 `with` 區塊,我們確保在產生器函式結束後關閉類檔案物件。因此,在完成傳送回應後就會關閉。
+3. 這個 `yield from` 告訴函式去疊代名為 `file_like` 的東西。對於每個被疊代到的部分,就把該部分當作此產生器函式(`iterfile`)的輸出進行 `yield`。
+
+ 因此,這是一個把「生成」工作在內部轉交給其他東西的產生器函式。
+
+ 透過這樣做,我們可以把它放進 `with` 區塊,藉此確保在完成後關閉類檔案物件。
+
+/// tip
+
+注意,這裡我們使用的是標準的 `open()`,它不支援 `async` 與 `await`,因此我們用一般的 `def` 來宣告路徑操作。
+
+///
+
+### `FileResponse` { #fileresponse }
+
+以非同步串流方式將檔案作為回應。
+
+它在初始化時所需的參數與其他回應型別不同:
+
+- `path` - 要串流的檔案路徑。
+- `headers` - 要包含的自訂標頭,字典形式。
+- `media_type` - 描述 media type 的字串。若未設定,將根據檔名或路徑推斷 media type。
+- `filename` - 若設定,會包含在回應的 `Content-Disposition` 中。
+
+檔案回應會包含適當的 `Content-Length`、`Last-Modified` 與 `ETag` 標頭。
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+你也可以使用 `response_class` 參數:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+在此情況下,你可以在「路徑操作函式」中直接回傳檔案路徑。
+
+## 自訂回應類別 { #custom-response-class }
+
+你可以建立自己的自訂回應類別,繼承自 `Response` 並加以使用。
+
+例如,假設你要使用 `orjson`,但想套用一些未包含在 `ORJSONResponse` 類別中的自訂設定。
+
+假設你想回傳縮排且格式化的 JSON,因此要使用 orjson 選項 `orjson.OPT_INDENT_2`。
+
+你可以建立 `CustomORJSONResponse`。你主要需要做的是建立一個 `Response.render(content)` 方法,將內容以 `bytes` 回傳:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+現在,不再是回傳:
+
+```json
+{"message": "Hello World"}
+```
+
+……這個回應會回傳:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+當然,你大概能找到比格式化 JSON 更好的方式來利用這個能力。😉
+
+## 預設回應類別 { #default-response-class }
+
+在建立 **FastAPI** 類別實例或 `APIRouter` 時,你可以指定預設要使用哪個回應類別。
+
+用來設定的是 `default_response_class` 參數。
+
+在下面的例子中,**FastAPI** 會在所有「路徑操作」中預設使用 `ORJSONResponse`,而不是 `JSONResponse`。
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip
+
+你仍然可以在「路徑操作」中像以前一樣覆寫 `response_class`。
+
+///
+
+## 其他文件化選項 { #additional-documentation }
+
+你也可以在 OpenAPI 中使用 `responses` 宣告 media type 與其他許多細節:[在 OpenAPI 中的額外回應](additional-responses.md){.internal-link target=_blank}。
diff --git a/docs/zh-hant/docs/advanced/dataclasses.md b/docs/zh-hant/docs/advanced/dataclasses.md
new file mode 100644
index 000000000..d586bd684
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/dataclasses.md
@@ -0,0 +1,87 @@
+# 使用 Dataclasses { #using-dataclasses }
+
+FastAPI 建立在 **Pydantic** 之上,我之前示範過如何使用 Pydantic 模型來宣告請求與回應。
+
+但 FastAPI 也同樣支援以相同方式使用 `dataclasses`:
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+這之所以可行,要感謝 **Pydantic**,因為它 內建支援 `dataclasses`。
+
+所以,即使上面的程式碼沒有明確使用 Pydantic,FastAPI 仍會使用 Pydantic 將那些標準的 dataclass 轉換為 Pydantic 版本的 dataclass。
+
+而且當然一樣支援:
+
+- 資料驗證
+- 資料序列化
+- 資料文件化等
+
+它的運作方式與 Pydantic 模型相同;實際上,底層就是透過 Pydantic 達成的。
+
+/// info
+
+請記得,dataclass 無法做到 Pydantic 模型能做的一切。
+
+所以你可能仍然需要使用 Pydantic 模型。
+
+但如果你手邊剛好有一堆 dataclass,這是個不錯的小技巧,可以用來用 FastAPI 驅動一個 Web API。🤓
+
+///
+
+## 在 `response_model` 中使用 Dataclasses { #dataclasses-in-response-model }
+
+你也可以在 `response_model` 參數中使用 `dataclasses`:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+該 dataclass 會自動轉換為 Pydantic 的 dataclass。
+
+如此一來,其結構描述(schema)會顯示在 API 文件介面中:
+
+
+
+## 巢狀資料結構中的 Dataclasses { #dataclasses-in-nested-data-structures }
+
+你也可以將 `dataclasses` 與其他型別註記結合,建立巢狀的資料結構。
+
+在某些情況下,你可能仍需要使用 Pydantic 版本的 `dataclasses`。例如,當自動產生的 API 文件出現錯誤時。
+
+這種情況下,你可以把標準的 `dataclasses` 直接換成 `pydantic.dataclasses`,它是可直接替換(drop-in replacement)的:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. 我們仍然從標準的 `dataclasses` 匯入 `field`。
+2. `pydantic.dataclasses` 是 `dataclasses` 的可直接替換版本。
+3. `Author` dataclass 內含一個 `Item` dataclass 的清單。
+4. `Author` dataclass 被用作 `response_model` 參數。
+5. 你可以將其他標準型別註記與 dataclass 一起用作請求本文。
+
+ 在此例中,它是 `Item` dataclass 的清單。
+6. 這裡我們回傳一個字典,其中的 `items` 是一個 dataclass 清單。
+
+ FastAPI 仍能將資料序列化為 JSON。
+7. 這裡 `response_model` 使用的是「`Author` dataclass 的清單」這種型別註記。
+
+ 同樣地,你可以把 `dataclasses` 與標準型別註記組合使用。
+8. 注意這個「路徑操作函式」使用的是一般的 `def` 而非 `async def`。
+
+ 一如往常,在 FastAPI 中你可以視需要混用 `def` 與 `async def`。
+
+ 如果需要複習何時用哪個,請參考文件中關於 [`async` 與 `await`](../async.md#in-a-hurry){.internal-link target=_blank} 的章節「In a hurry?」。
+9. 這個「路徑操作函式」回傳的不是 dataclass(雖然也可以),而是一個包含內部資料的字典清單。
+
+ FastAPI 會使用 `response_model` 參數(其中包含 dataclass)來轉換回應。
+
+你可以把 `dataclasses` 與其他型別註記以多種方式組合,形成複雜的資料結構。
+
+查看上面程式碼中的註解提示以了解更具體的細節。
+
+## 延伸閱讀 { #learn-more }
+
+你也可以將 `dataclasses` 與其他 Pydantic 模型結合、從它們繼承、把它們包含進你的自訂模型等。
+
+想了解更多,請參考 Pydantic 關於 dataclasses 的文件。
+
+## 版本 { #version }
+
+自 FastAPI 版本 `0.67.0` 起可用。🔖
diff --git a/docs/zh-hant/docs/advanced/events.md b/docs/zh-hant/docs/advanced/events.md
new file mode 100644
index 000000000..e5c0afe48
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# 生命週期事件 { #lifespan-events }
+
+你可以定義在應用程式**啟動**之前要執行的邏輯(程式碼)。也就是說,這段程式碼會在應用開始接收請求**之前**、**只執行一次**。
+
+同樣地,你也可以定義在應用程式**關閉**時要執行的邏輯(程式碼)。在這種情況下,這段程式碼會在處理了**許多請求**之後、**只執行一次**。
+
+因為這些程式碼分別在應用開始接收請求**之前**與**完成**處理請求之後執行,所以涵蓋了整個應用的**生命週期**(「lifespan」這個詞稍後會很重要 😉)。
+
+這對於為整個應用設定需要**共用**於多個請求的**資源**,以及在之後進行**清理**,非常有用。比如資料庫連線池、或載入一個共用的機器學習模型。
+
+## 使用情境 { #use-case }
+
+先從一個**使用情境**開始,然後看看如何用這個機制解決。
+
+想像你有一些要用來處理請求的**機器學習模型**。🤖
+
+同一組模型會在多個請求間共用,所以不是每個請求或每個使用者各有一個模型。
+
+再想像一下,載入模型**需要一段時間**,因為它必須從**磁碟**讀取大量資料。所以你不想在每個請求都做一次。
+
+你可以在模組/檔案的最上層載入,但這也表示即使只是要跑一個簡單的自動化測試,也會去**載入模型**,導致測試**變慢**,因為它得等模型載入完才能執行與模型無關的程式碼部分。
+
+我們要解決的正是這件事:在開始處理請求之前再載入模型,但只在應用程式即將開始接收請求時載入,而不是在匯入程式碼時就載入。
+
+## 生命週期(Lifespan) { #lifespan }
+
+你可以使用 `FastAPI` 應用的 `lifespan` 參數,搭配「context manager」(稍後會示範),來定義這些 *startup* 與 *shutdown* 邏輯。
+
+先看一個例子,接著再深入說明。
+
+我們建立一個帶有 `yield` 的非同步函式 `lifespan()`,如下:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+這裡我們透過在 `yield` 之前把(假的)模型函式放進機器學習模型的字典中,來模擬昂貴的 *startup* 載入模型操作。這段程式會在應用**開始接收請求之前**執行,也就是 *startup* 階段。
+
+接著,在 `yield` 之後,我們卸載模型。這段程式會在應用**完成處理請求之後**、也就是 *shutdown* 前執行。這可以用來釋放資源,例如記憶體或 GPU。
+
+/// tip
+
+`shutdown` 會在你**停止**應用程式時發生。
+
+也許你要啟動新版本,或只是不想再跑它了。🤷
+
+///
+
+### Lifespan 函式 { #lifespan-function }
+
+首先要注意的是,我們定義了一個帶有 `yield` 的 async 函式。這和帶有 `yield` 的依賴(Dependencies)非常相似。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+函式在 `yield` 之前的部分,會在應用啟動前先執行。
+
+`yield` 之後的部分,會在應用結束後再執行。
+
+### 非同步內容管理器(Async Context Manager) { #async-context-manager }
+
+你會看到這個函式被 `@asynccontextmanager` 裝飾。
+
+它會把函式轉換成所謂的「**非同步內容管理器(async context manager)**」。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Python 中的**內容管理器(context manager)**可以用在 `with` 陳述式中,例如 `open()` 可以作為內容管理器使用:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+在較新的 Python 版本中,也有**非同步內容管理器**。你可以用 `async with` 來使用它:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+當你像上面那樣建立一個內容管理器或非同步內容管理器時,在進入 `with` 區塊之前,會先執行 `yield` 之前的程式碼;離開 `with` 區塊之後,會執行 `yield` 之後的程式碼。
+
+在我們的範例中,並不是直接用它,而是把它傳給 FastAPI 來使用。
+
+`FastAPI` 應用的 `lifespan` 參數需要一個**非同步內容管理器**,所以我們可以把剛寫好的 `lifespan` 非同步內容管理器傳給它。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## 替代事件(已棄用) { #alternative-events-deprecated }
+
+/// warning
+
+目前建議使用上面所述,透過 `FastAPI` 應用的 `lifespan` 參數來處理 *startup* 與 *shutdown*。如果你提供了 `lifespan` 參數,`startup` 與 `shutdown` 事件處理器將不會被呼叫。要嘛全用 `lifespan`,要嘛全用事件,不能同時混用。
+
+你大概可以直接跳過這一節。
+
+///
+
+也有另一種方式可以定義在 *startup* 與 *shutdown* 期間要執行的邏輯。
+
+你可以定義事件處理器(函式)來在應用啟動前或關閉時執行。
+
+這些函式可以用 `async def` 或一般的 `def` 宣告。
+
+### `startup` 事件 { #startup-event }
+
+要加入一個在應用啟動前執行的函式,使用事件 `"startup"` 來宣告:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+在這個例子中,`startup` 事件處理器函式會用一些值來初始化 items 的「資料庫」(其實就是個 `dict`)。
+
+你可以註冊多個事件處理函式。
+
+而且在所有 `startup` 事件處理器都完成之前,你的應用不會開始接收請求。
+
+### `shutdown` 事件 { #shutdown-event }
+
+要加入一個在應用關閉時執行的函式,使用事件 `"shutdown"` 來宣告:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+在這裡,`shutdown` 事件處理器函式會把一行文字 `"Application shutdown"` 寫入檔案 `log.txt`。
+
+/// info
+
+在 `open()` 函式中,`mode="a"` 表示「append(附加)」;也就是說,這行文字會加在檔案現有內容之後,而不會覆寫先前的內容。
+
+///
+
+/// tip
+
+注意這裡我們使用的是標準 Python 的 `open()` 函式來操作檔案。
+
+這涉及 I/O(輸入/輸出),也就是需要「等待」資料寫入磁碟。
+
+但 `open()` 並不使用 `async` 與 `await`。
+
+所以我們用一般的 `def` 來宣告事件處理器,而不是 `async def`。
+
+///
+
+### 同時使用 `startup` 與 `shutdown` { #startup-and-shutdown-together }
+
+你的 *startup* 與 *shutdown* 邏輯很可能是相關聯的:你可能會先啟動某個東西再把它結束、先取得資源再釋放它,等等。
+
+如果把它們拆成兩個彼此不共享邏輯或變數的獨立函式,會比較麻煩,你得把值存在全域變數或用其他技巧。
+
+因此,現在建議改用上面介紹的 `lifespan`。
+
+## 技術細節 { #technical-details }
+
+給有興趣鑽研的同好一點技術細節。🤓
+
+在底層的 ASGI 技術規範中,這屬於 Lifespan Protocol 的一部分,並定義了 `startup` 與 `shutdown` 兩種事件。
+
+/// info
+
+你可以在 Starlette 的 Lifespan 文件 讀到更多關於 Starlette `lifespan` 處理器的資訊。
+
+也包含如何處理可在程式其他區域使用的 lifespan 狀態。
+
+///
+
+## 子應用程式 { #sub-applications }
+
+🚨 請記住,這些生命週期事件(startup 與 shutdown)只會在主應用程式上執行,不會在[子應用程式 - 掛載](sub-applications.md){.internal-link target=_blank}上執行。
diff --git a/docs/zh-hant/docs/advanced/generate-clients.md b/docs/zh-hant/docs/advanced/generate-clients.md
new file mode 100644
index 000000000..8d374566c
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# 產生 SDK { #generating-sdks }
+
+由於 **FastAPI** 建立在 **OpenAPI** 規格之上,其 API 能以許多工具都能理解的標準格式來描述。
+
+這讓你能輕鬆產生最新的**文件**、多語言的用戶端程式庫(**SDKs**),以及與程式碼保持同步的**測試**或**自動化工作流程**。
+
+在本指南中,你將學會如何為你的 FastAPI 後端產生 **TypeScript SDK**。
+
+## 開源 SDK 產生器 { #open-source-sdk-generators }
+
+其中一個相當萬用的選擇是 OpenAPI Generator,它支援**多種程式語言**,並能從你的 OpenAPI 規格產生 SDK。
+
+針對 **TypeScript 用戶端**,Hey API 是專門打造的解決方案,為 TypeScript 生態系提供最佳化的體驗。
+
+你可以在 OpenAPI.Tools 找到更多 SDK 產生器。
+
+/// tip
+
+FastAPI 會自動產生 **OpenAPI 3.1** 規格,因此你使用的任何工具都必須支援這個版本。
+
+///
+
+## 來自 FastAPI 贊助商的 SDK 產生器 { #sdk-generators-from-fastapi-sponsors }
+
+本節重點介紹由贊助 FastAPI 的公司提供的**創投支持**與**公司維運**的解決方案。這些產品在高品質的自動產生 SDK 之外,還提供**額外功能**與**整合**。
+
+透過 ✨ [**贊助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,這些公司幫助確保框架與其**生態系**維持健康且**永續**。
+
+他們的贊助也展現對 FastAPI **社群**(你)的高度承諾,不僅關心提供**優良服務**,也支持 **FastAPI** 作為一個**穩健且蓬勃的框架**。🙇
+
+例如,你可以嘗試:
+
+* Speakeasy
+* Stainless
+* liblab
+
+其中有些方案也可能是開源或提供免費方案,讓你不需財務承諾就能試用。其他商業的 SDK 產生器也不少,你可以在網路上找到。🤓
+
+## 建立 TypeScript SDK { #create-a-typescript-sdk }
+
+先從一個簡單的 FastAPI 應用開始:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+注意這些 *路徑操作* 為請求與回應的有效載荷定義了所用的模型,使用了 `Item` 與 `ResponseMessage` 這兩個模型。
+
+### API 文件 { #api-docs }
+
+如果你前往 `/docs`,你會看到其中包含了請求要送出的資料與回應接收的資料之**結構(schemas)**:
+
+
+
+你之所以能看到這些結構,是因為它們在應用內以模型宣告了。
+
+這些資訊都在應用的 **OpenAPI 結構**中,並顯示在 API 文件裡。
+
+同樣包含在 OpenAPI 中的模型資訊,也可以用來**產生用戶端程式碼**。
+
+### Hey API { #hey-api }
+
+當我們有含模型的 FastAPI 應用後,就能用 Hey API 來產生 TypeScript 用戶端。最快的方法是透過 npx:
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+這會在 `./src/client` 產生一個 TypeScript SDK。
+
+你可以在他們的網站了解如何安裝 `@hey-api/openapi-ts`,以及閱讀產生的輸出內容。
+
+### 使用 SDK { #using-the-sdk }
+
+現在你可以匯入並使用用戶端程式碼。大致看起來會像這樣,你會發現方法有自動完成:
+
+
+
+你也會對要送出的有效載荷獲得自動完成:
+
+
+
+/// tip
+
+注意 `name` 與 `price` 的自動完成,這是由 FastAPI 應用中的 `Item` 模型所定義。
+
+///
+
+你在送出的資料上也會看到行內錯誤:
+
+
+
+回應物件同樣有自動完成:
+
+
+
+## 含標籤的 FastAPI 應用 { #fastapi-app-with-tags }
+
+在許多情況下,你的 FastAPI 應用會更大,你可能會用標籤將不同群組的 *路徑操作* 分開。
+
+例如,你可以有一個 **items** 區塊與另一個 **users** 區塊,並透過標籤區分:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### 使用標籤產生 TypeScript 用戶端 { #generate-a-typescript-client-with-tags }
+
+若你為使用標籤的 FastAPI 應用產生用戶端,產生器通常也會依標籤將用戶端程式碼分開。
+
+如此一來,用戶端程式碼就能有條理地正確分組與排列:
+
+
+
+在此例中,你會有:
+
+* `ItemsService`
+* `UsersService`
+
+### 用戶端方法名稱 { #client-method-names }
+
+目前像 `createItemItemsPost` 這樣的產生方法名稱看起來不太俐落:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+……那是因為用戶端產生器對每個 *路徑操作* 都使用 OpenAPI 內部的**操作 ID(operation ID)**。
+
+OpenAPI 要求每個操作 ID 在所有 *路徑操作* 之間必須唯一,因此 FastAPI 會用**函式名稱**、**路徑**與 **HTTP 方法/操作**來產生該操作 ID,如此便能確保操作 ID 的唯一性。
+
+接下來我會示範如何把它變得更好看。🤓
+
+## 自訂 Operation ID 與更好的方法名稱 { #custom-operation-ids-and-better-method-names }
+
+你可以**修改**這些操作 ID 的**產生方式**,讓它們更簡潔,並在用戶端中得到**更簡潔的方法名稱**。
+
+在這種情況下,你需要用其他方式確保每個操作 ID 都是**唯一**的。
+
+例如,你可以確保每個 *路徑操作* 都有標籤,接著根據**標籤**與 *路徑操作* 的**名稱**(函式名稱)來產生操作 ID。
+
+### 自訂唯一 ID 產生函式 { #custom-generate-unique-id-function }
+
+FastAPI 會為每個 *路徑操作* 使用一個**唯一 ID**,它會被用於**操作 ID**,以及任何請求或回應所需的自訂模型名稱。
+
+你可以自訂該函式。它接收一個 APIRoute 並回傳字串。
+
+例如,下面使用第一個標籤(你通常只會有一個標籤)以及 *路徑操作* 的名稱(函式名稱)。
+
+接著你可以將這個自訂函式以 `generate_unique_id_function` 參數傳給 **FastAPI**:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### 使用自訂 Operation ID 產生 TypeScript 用戶端 { #generate-a-typescript-client-with-custom-operation-ids }
+
+現在,如果你再次產生用戶端,會看到方法名稱已改善:
+
+
+
+如你所見,方法名稱現在包含標籤與函式名稱,不再包含 URL 路徑與 HTTP 操作的資訊。
+
+### 為用戶端產生器預處理 OpenAPI 規格 { #preprocess-the-openapi-specification-for-the-client-generator }
+
+產生的程式碼仍有一些**重複資訊**。
+
+我們已經知道這個方法與 **items** 相關,因為該字已出現在 `ItemsService`(取自標籤)中,但方法名稱仍然加上了標籤名稱做前綴。😕
+
+對於 OpenAPI 本身,我們可能仍想保留,因為那能確保操作 ID 是**唯一**的。
+
+但就產生用戶端而言,我們可以在產生前**修改** OpenAPI 的操作 ID,來讓方法名稱更**簡潔**、更**乾淨**。
+
+我們可以把 OpenAPI JSON 下載到 `openapi.json` 檔案,然後用像這樣的腳本**移除該標籤前綴**:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+如此一來,操作 ID 會從 `items-get_items` 之類的字串,變成單純的 `get_items`,讓用戶端產生器能產生更簡潔的方法名稱。
+
+### 使用預處理後的 OpenAPI 產生 TypeScript 用戶端 { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+由於最終結果現在是在 `openapi.json` 檔案中,你需要更新輸入位置:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+產生新的用戶端後,你現在會得到**乾淨的方法名稱**,同時保有所有的**自動完成**、**行內錯誤**等功能:
+
+
+
+## 好處 { #benefits }
+
+使用自動產生的用戶端時,你會得到以下項目的**自動完成**:
+
+* 方法
+* 本文中的請求有效載荷、查詢參數等
+* 回應的有效載荷
+
+你也會對所有內容獲得**行內錯誤**提示。
+
+而且每當你更新後端程式碼並**重新產生**前端(用戶端),新的 *路徑操作* 會以方法形式可用、舊的會被移除,其他任何變更也都會反映到產生的程式碼中。🤓
+
+這也代表只要有任何變更,便會自動**反映**到用戶端程式碼;而當你**建置**用戶端時,如果使用的資料有任何**不匹配**,就會直接報錯。
+
+因此,你能在開發週期的很早期就**偵測到許多錯誤**,而不必等到錯誤在正式環境的最終使用者那裡才出現,然後才開始追查問題所在。✨
diff --git a/docs/zh-hant/docs/advanced/index.md b/docs/zh-hant/docs/advanced/index.md
new file mode 100644
index 000000000..cfbc17afe
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/index.md
@@ -0,0 +1,21 @@
+# 進階使用者指南 { #advanced-user-guide }
+
+## 更多功能 { #additional-features }
+
+主要的[教學 - 使用者指南](../tutorial/index.md){.internal-link target=_blank} 應足以帶你快速瀏覽 **FastAPI** 的所有核心功能。
+
+在接下來的章節中,你會看到其他選項、設定,以及更多功能。
+
+/// tip
+
+接下來的章節不一定「進階」。
+
+而且對於你的使用情境,解法很可能就在其中某一節。
+
+///
+
+## 先閱讀教學 { #read-the-tutorial-first }
+
+只要掌握主要[教學 - 使用者指南](../tutorial/index.md){.internal-link target=_blank} 的內容,你就能使用 **FastAPI** 的大多數功能。
+
+接下來的章節也假設你已經讀過,並已了解那些主要觀念。
diff --git a/docs/zh-hant/docs/advanced/middleware.md b/docs/zh-hant/docs/advanced/middleware.md
new file mode 100644
index 000000000..80cda345c
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/middleware.md
@@ -0,0 +1,97 @@
+# 進階中介軟體 { #advanced-middleware }
+
+在主要教學中你已學過如何將[自訂中介軟體](../tutorial/middleware.md){.internal-link target=_blank}加入到你的應用程式。
+
+你也讀過如何使用 `CORSMiddleware` 處理 [CORS](../tutorial/cors.md){.internal-link target=_blank}。
+
+本節將示範如何使用其他中介軟體。
+
+## 新增 ASGI 中介軟體 { #adding-asgi-middlewares }
+
+由於 **FastAPI** 建立在 Starlette 上並實作了 ASGI 規範,你可以使用任何 ASGI 中介軟體。
+
+中介軟體不一定要為 FastAPI 或 Starlette 專門撰寫,只要遵循 ASGI 規範即可運作。
+
+一般來說,ASGI 中介軟體是類別,預期第一個參數接收一個 ASGI 應用程式。
+
+因此,在第三方 ASGI 中介軟體的文件中,通常會指示你這樣做:
+
+```Python
+from unicorn import UnicornMiddleware
+
+app = SomeASGIApp()
+
+new_app = UnicornMiddleware(app, some_config="rainbow")
+```
+
+但 FastAPI(實際上是 Starlette)提供了一種更簡單的方式,確保內部中介軟體能處理伺服器錯誤,且自訂例外處理器可正常運作。
+
+為此,你可以使用 `app.add_middleware()`(如同 CORS 範例)。
+
+```Python
+from fastapi import FastAPI
+from unicorn import UnicornMiddleware
+
+app = FastAPI()
+
+app.add_middleware(UnicornMiddleware, some_config="rainbow")
+```
+
+`app.add_middleware()` 將中介軟體類別作為第一個引數,並接收要傳遞給該中介軟體的其他引數。
+
+## 內建中介軟體 { #integrated-middlewares }
+
+**FastAPI** 內建數個常見用途的中介軟體,以下將示範如何使用。
+
+/// note | 技術細節
+
+在接下來的範例中,你也可以使用 `from starlette.middleware.something import SomethingMiddleware`。
+
+**FastAPI** 在 `fastapi.middleware` 中提供了一些中介軟體,純粹是為了方便你這位開發者。但大多數可用的中介軟體直接來自 Starlette。
+
+///
+
+## `HTTPSRedirectMiddleware` { #httpsredirectmiddleware }
+
+強制所有傳入請求必須使用 `https` 或 `wss`。
+
+任何指向 `http` 或 `ws` 的請求都會被重新導向至對應的安全協定。
+
+{* ../../docs_src/advanced_middleware/tutorial001_py310.py hl[2,6] *}
+
+## `TrustedHostMiddleware` { #trustedhostmiddleware }
+
+強制所有傳入請求正確設定 `Host` 標頭,以防範 HTTP Host Header 攻擊。
+
+{* ../../docs_src/advanced_middleware/tutorial002_py310.py hl[2,6:8] *}
+
+支援以下參數:
+
+- `allowed_hosts` - 允許作為主機名稱的網域名稱清單。支援萬用字元網域(例如 `*.example.com`)以比對子網域。若要允許任意主機名稱,可使用 `allowed_hosts=["*"]`,或乾脆不要加上此中介軟體。
+- `www_redirect` - 若設為 True,對允許主機的不含 www 版本的請求會被重新導向至其 www 對應版本。預設為 `True`。
+
+若傳入請求驗證失敗,將回傳 `400` 回應。
+
+## `GZipMiddleware` { #gzipmiddleware }
+
+處理在 `Accept-Encoding` 標頭中包含 `"gzip"` 的請求之 GZip 壓縮回應。
+
+此中介軟體會處理一般與串流回應。
+
+{* ../../docs_src/advanced_middleware/tutorial003_py310.py hl[2,6] *}
+
+支援以下參數:
+
+- `minimum_size` - 小於此位元組大小的回應不會進行 GZip。預設為 `500`。
+- `compresslevel` - GZip 壓縮時使用的等級。為 1 到 9 的整數。預設為 `9`。值越小壓縮越快但檔案較大,值越大壓縮較慢但檔案較小。
+
+## 其他中介軟體 { #other-middlewares }
+
+還有許多其他 ASGI 中介軟體。
+
+例如:
+
+- Uvicorn 的 `ProxyHeadersMiddleware`
+- MessagePack
+
+想瞭解更多可用的中介軟體,請參考 Starlette 的中介軟體文件 與 ASGI 精選清單。
diff --git a/docs/zh-hant/docs/advanced/openapi-callbacks.md b/docs/zh-hant/docs/advanced/openapi-callbacks.md
new file mode 100644
index 000000000..b1a16be24
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/openapi-callbacks.md
@@ -0,0 +1,186 @@
+# OpenAPI 回呼 { #openapi-callbacks }
+
+你可以建立一個含有「路徑操作(path operation)」的 API,該操作會觸發對某個「外部 API(external API)」的請求(通常由使用你 API 的同一位開發者提供)。
+
+當你的 API 應用呼叫「外部 API」時發生的過程稱為「回呼(callback)」。因為外部開發者撰寫的軟體會先向你的 API 發出請求,接著你的 API 再「回呼」,也就是向(可能同一位開發者建立的)外部 API 發送請求。
+
+在這種情況下,你可能想要文件化說明該外部 API 應該長什麼樣子。它應該有哪些「路徑操作」、應該接受什麼 body、應該回傳什麼 response,等等。
+
+## 帶有回呼的應用 { #an-app-with-callbacks }
+
+我們用一個例子來看。
+
+想像你開發了一個允許建立發票的應用。
+
+這些發票會有 `id`、`title`(可選)、`customer` 和 `total`。
+
+你的 API 的使用者(外部開發者)會透過一個 POST 請求在你的 API 中建立一張發票。
+
+然後你的 API 會(讓我們想像):
+
+* 將發票寄給該外部開發者的某位客戶。
+* 代收款項。
+* 再把通知回傳給 API 使用者(外部開發者)。
+ * 這會透過從「你的 API」向該外部開發者提供的「外部 API」送出 POST 請求完成(這就是「回呼」)。
+
+## 一般的 **FastAPI** 應用 { #the-normal-fastapi-app }
+
+先看看在加入回呼之前,一個一般的 API 應用會長什麼樣子。
+
+它會有一個接收 `Invoice` body 的「路徑操作」,以及一個查詢參數 `callback_url`,其中包含用於回呼的 URL。
+
+這部分很正常,多數程式碼你應該已經很熟悉了:
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[7:11,34:51] *}
+
+/// tip
+
+`callback_url` 查詢參數使用的是 Pydantic 的 Url 型別。
+
+///
+
+唯一新的地方是在「路徑操作裝飾器」中加入參數 `callbacks=invoices_callback_router.routes`。我們接下來會看到那是什麼。
+
+## 文件化回呼 { #documenting-the-callback }
+
+實際的回呼程式碼會高度依賴你的 API 應用本身。
+
+而且很可能每個應用都差很多。
+
+它可能就只有一兩行,例如:
+
+```Python
+callback_url = "https://example.com/api/v1/invoices/events/"
+httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
+```
+
+但回呼中最重要的部分,可能是在確保你的 API 使用者(外部開發者)能正確實作「外部 API」,符合「你的 API」在回呼請求 body 中要送出的資料格式,等等。
+
+因此,接下來我們要加上用來「文件化」說明,該「外部 API」應該長什麼樣子,才能接收來自「你的 API」的回呼。
+
+這份文件會出現在你的 API 的 Swagger UI `/docs`,讓外部開發者知道該如何建置「外部 API」。
+
+這個範例不會實作回呼本身(那可能就只是一行程式碼),只會實作文件的部分。
+
+/// tip
+
+實際的回呼就是一個 HTTP 請求。
+
+當你自己實作回呼時,可以使用像是 HTTPX 或 Requests。
+
+///
+
+## 撰寫回呼的文件化程式碼 { #write-the-callback-documentation-code }
+
+這段程式碼在你的應用中不會被執行,我們只需要它來「文件化」說明那個「外部 API」應該長什麼樣子。
+
+不過,你已經知道如何用 **FastAPI** 輕鬆為 API 建立自動文件。
+
+所以我們會用同樣的方式,來文件化「外部 API」應該長什麼樣子... 也就是建立外部 API 應該實作的「路徑操作(們)」(那些「你的 API」會去呼叫的操作)。
+
+/// tip
+
+在撰寫回呼的文件化程式碼時,把自己想像成那位「外部開發者」會很有幫助。而且你現在是在實作「外部 API」,不是「你的 API」。
+
+暫時採用這個(外部開發者)的視角,有助於讓你更直覺地決定該把參數、body 的 Pydantic 模型、response 的模型等放在哪裡,對於那個「外部 API」會更清楚。
+
+///
+
+### 建立一個回呼用的 `APIRouter` { #create-a-callback-apirouter }
+
+先建立一個新的 `APIRouter`,用來放一個或多個回呼。
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[1,23] *}
+
+### 建立回呼的「路徑操作」 { #create-the-callback-path-operation }
+
+要建立回呼的「路徑操作」,就使用你上面建立的同一個 `APIRouter`。
+
+它看起來就像一般的 FastAPI「路徑操作」:
+
+* 可能需要宣告它應該接收的 body,例如 `body: InvoiceEvent`。
+* 也可以宣告它應該回傳的 response,例如 `response_model=InvoiceEventReceived`。
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[14:16,19:20,26:30] *}
+
+和一般「路徑操作」相比有兩個主要差異:
+
+* 不需要任何實際程式碼,因為你的應用永遠不會呼叫這段程式。它只用來文件化「外部 API」。因此函式可以只有 `pass`。
+* 「路徑」可以包含一個 OpenAPI 3 表達式(見下文),可使用參數與原始送到「你的 API」的請求中的部分欄位。
+
+### 回呼路徑表達式 { #the-callback-path-expression }
+
+回呼的「路徑」可以包含一個 OpenAPI 3 表達式,能引用原本送到「你的 API」的請求中的部分內容。
+
+在這個例子中,它是一個 `str`:
+
+```Python
+"{$callback_url}/invoices/{$request.body.id}"
+```
+
+所以,如果你的 API 使用者(外部開發者)向「你的 API」送出這樣的請求:
+
+```
+https://yourapi.com/invoices/?callback_url=https://www.external.org/events
+```
+
+並附上這個 JSON body:
+
+```JSON
+{
+ "id": "2expen51ve",
+ "customer": "Mr. Richie Rich",
+ "total": "9999"
+}
+```
+
+那麼「你的 API」會處理這張發票,並在稍後某個時點,向 `callback_url`(也就是「外部 API」)送出回呼請求:
+
+```
+https://www.external.org/events/invoices/2expen51ve
+```
+
+其 JSON body 大致包含:
+
+```JSON
+{
+ "description": "Payment celebration",
+ "paid": true
+}
+```
+
+而它會預期該「外部 API」回傳的 JSON body 例如:
+
+```JSON
+{
+ "ok": true
+}
+```
+
+/// tip
+
+注意回呼所用的 URL,包含了在查詢參數 `callback_url` 中收到的 URL(`https://www.external.org/events`),以及來自 JSON body 內的發票 `id`(`2expen51ve`)。
+
+///
+
+### 加入回呼 router { #add-the-callback-router }
+
+此時你已經在先前建立的回呼 router 中,擁有所需的回呼「路徑操作(們)」(也就是「外部開發者」應該在「外部 API」中實作的那些)。
+
+現在在「你的 API 的路徑操作裝飾器」中使用參數 `callbacks`,將該回呼 router 的屬性 `.routes`(實際上就是一個由路由/「路徑操作」所組成的 `list`)傳入:
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *}
+
+/// tip
+
+注意你傳給 `callback=` 的不是整個 router 本身(`invoices_callback_router`),而是它的屬性 `.routes`,也就是 `invoices_callback_router.routes`。
+
+///
+
+### 檢查文件 { #check-the-docs }
+
+現在你可以啟動應用,並前往 http://127.0.0.1:8000/docs。
+
+你會在文件中看到你的「路徑操作」包含一個「Callbacks」區塊,顯示「外部 API」應該長什麼樣子:
+
+
diff --git a/docs/zh-hant/docs/advanced/openapi-webhooks.md b/docs/zh-hant/docs/advanced/openapi-webhooks.md
new file mode 100644
index 000000000..ef52c3884
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# OpenAPI Webhook { #openapi-webhooks }
+
+有些情況下,你會想告訴你的 API 使用者,你的應用程式可能會攜帶一些資料去呼叫他們的應用程式(發送請求),通常是為了通知某種類型的事件。
+
+這表示,與其由使用者向你的 API 發送請求,改為你的 API(或你的應用)可能會向他們的系統(他們的 API、他們的應用)發送請求。
+
+這通常稱為 webhook。
+
+## Webhook 步驟 { #webhooks-steps }
+
+流程通常是:你在程式碼中定義要發送的訊息,也就是請求的主體(request body)。
+
+你也會以某種方式定義應用在哪些時刻會發送那些請求或事件。
+
+而你的使用者則會以某種方式(例如在某個 Web 控制台)設定你的應用應該將這些請求送往的 URL。
+
+關於如何註冊 webhook 的 URL,以及實際發送那些請求的程式碼等所有邏輯,都由你決定。你可以在自己的程式碼中用你想要的方式撰寫。
+
+## 使用 FastAPI 與 OpenAPI 記錄 webhook { #documenting-webhooks-with-fastapi-and-openapi }
+
+在 FastAPI 中,透過 OpenAPI,你可以定義這些 webhook 的名稱、你的應用將發送的 HTTP 操作類型(例如 `POST`、`PUT` 等),以及你的應用要發送的請求主體。
+
+這能讓你的使用者更容易實作他們的 API 以接收你的 webhook 請求,甚至可能自動產生部分他們自己的 API 程式碼。
+
+/// info
+
+Webhook 功能自 OpenAPI 3.1.0 起提供,FastAPI `0.99.0` 以上版本支援。
+
+///
+
+## 含有 webhook 的應用 { #an-app-with-webhooks }
+
+建立 FastAPI 應用時,會有一個 `webhooks` 屬性可用來定義 webhook,方式與定義路徑操作相同,例如使用 `@app.webhooks.post()`。
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+你定義的 webhook 會出現在 OpenAPI 結構描述與自動產生的文件 UI 中。
+
+/// info
+
+`app.webhooks` 其實就是一個 `APIRouter`,與你在將應用拆分為多個檔案時所使用的型別相同。
+
+///
+
+注意,使用 webhook 時你其實不是在宣告路徑(例如 `/items/`),你傳入的文字只是該 webhook 的識別名稱(事件名稱)。例如在 `@app.webhooks.post("new-subscription")` 中,webhook 名稱是 `new-subscription`。
+
+這是因為預期由你的使用者以其他方式(例如 Web 控制台)來設定實際要接收 webhook 請求的 URL 路徑。
+
+### 查看文件 { #check-the-docs }
+
+現在你可以啟動應用,然後前往 http://127.0.0.1:8000/docs。
+
+你會在文件中看到一般的路徑操作,另外還有一些 webhook:
+
+
diff --git a/docs/zh-hant/docs/advanced/path-operation-advanced-configuration.md b/docs/zh-hant/docs/advanced/path-operation-advanced-configuration.md
new file mode 100644
index 000000000..4f25eb987
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,172 @@
+# 路徑操作進階設定 { #path-operation-advanced-configuration }
+
+## OpenAPI operationId { #openapi-operationid }
+
+/// warning
+
+如果你不是 OpenAPI 的「專家」,大概不需要這個。
+
+///
+
+你可以用參數 `operation_id` 為你的*路徑操作(path operation)*設定要使用的 OpenAPI `operationId`。
+
+你必須確保每個操作的 `operationId` 都是唯一的。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
+
+### 使用路徑操作函式(path operation function)的名稱作為 operationId { #using-the-path-operation-function-name-as-the-operationid }
+
+如果你想用 API 的函式名稱作為 `operationId`,你可以遍歷所有路徑,並使用各自的 `APIRoute.name` 覆寫每個*路徑操作*的 `operation_id`。
+
+應在加入所有*路徑操作*之後再這麼做。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
+
+/// tip
+
+如果你會手動呼叫 `app.openapi()`,請務必先更新所有 `operationId` 再呼叫。
+
+///
+
+/// warning
+
+如果你這樣做,必須確保每個*路徑操作函式*都有唯一的名稱,
+
+即使它們位於不同的模組(Python 檔案)中。
+
+///
+
+## 從 OpenAPI 排除 { #exclude-from-openapi }
+
+若要從產生的 OpenAPI 結構(也就是自動文件系統)中排除某個*路徑操作*,使用參數 `include_in_schema` 並將其設為 `False`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## 從 docstring 提供進階描述 { #advanced-description-from-docstring }
+
+你可以限制 OpenAPI 從*路徑操作函式*的 docstring 中使用的內容行數。
+
+加上一個 `\f`(跳頁字元,form feed)會讓 FastAPI 在此處截斷用於 OpenAPI 的輸出。
+
+這個字元不會出現在文件中,但其他工具(例如 Sphinx)仍可使用其後的內容。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## 額外回應 { #additional-responses }
+
+你大概已看過如何為*路徑操作*宣告 `response_model` 與 `status_code`。
+
+這會定義該*路徑操作*主要回應的中繼資料。
+
+你也可以宣告額外的回應及其模型、狀態碼等。
+
+文件中有完整章節說明,請見 [OpenAPI 中的額外回應](additional-responses.md){.internal-link target=_blank}。
+
+## OpenAPI 額外資訊 { #openapi-extra }
+
+當你在應用程式中宣告一個*路徑操作*時,FastAPI 會自動產生該*路徑操作*的相關中繼資料,並納入 OpenAPI 結構中。
+
+/// note | 技術細節
+
+在 OpenAPI 規格中,這稱為 Operation 物件。
+
+///
+
+它包含關於*路徑操作*的所有資訊,並用於產生自動文件。
+
+其中包含 `tags`、`parameters`、`requestBody`、`responses` 等。
+
+這個針對單一路徑操作的 OpenAPI 結構通常由 FastAPI 自動產生,但你也可以擴充它。
+
+/// tip
+
+這是一個較低階的擴充介面。
+
+如果你只需要宣告額外回應,更方便的方式是使用 [OpenAPI 中的額外回應](additional-responses.md){.internal-link target=_blank}。
+
+///
+
+你可以使用參數 `openapi_extra` 來擴充某個*路徑操作*的 OpenAPI 結構。
+
+### OpenAPI 擴充 { #openapi-extensions }
+
+`openapi_extra` 可用來宣告例如 [OpenAPI 擴充](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) 的資料:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+打開自動產生的 API 文件時,你的擴充會顯示在該*路徑操作*頁面的底部。
+
+
+
+而在檢視產生出的 OpenAPI(位於你的 API 的 `/openapi.json`)時,也可以在相應*路徑操作*中看到你的擴充:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### 自訂 OpenAPI 路徑操作結構 { #custom-openapi-path-operation-schema }
+
+`openapi_extra` 中的字典會與自動產生的該*路徑操作*之 OpenAPI 結構進行深度合併。
+
+因此你可以在自動產生的結構上加入額外資料。
+
+例如,你可以選擇用自己的程式碼讀取並驗證請求,而不使用 FastAPI 與 Pydantic 的自動功能,但仍然希望在 OpenAPI 結構中定義該請求。
+
+你可以透過 `openapi_extra` 辦到:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+在這個範例中,我們沒有宣告任何 Pydantic 模型。事實上,請求本文甚至不會被 解析 為 JSON,而是直接以 `bytes` 讀取,並由函式 `magic_data_reader()` 以某種方式負責解析。
+
+儘管如此,我們仍可宣告請求本文的預期結構。
+
+### 自訂 OpenAPI Content-Type { #custom-openapi-content-type }
+
+用同樣的方法,你可以使用 Pydantic 模型來定義 JSON Schema,並把它包含到該*路徑操作*的自訂 OpenAPI 區段中。
+
+即使請求中的資料型別不是 JSON 也可以這麼做。
+
+例如,在這個應用中,我們不使用 FastAPI 內建的從 Pydantic 模型擷取 JSON Schema 的功能,也不使用 JSON 的自動驗證。實際上,我們將請求的 content type 宣告為 YAML,而非 JSON:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+儘管沒有使用預設的內建功能,我們仍透過 Pydantic 模型手動產生想以 YAML 接收之資料的 JSON Schema。
+
+接著我們直接使用請求,並將本文擷取為 `bytes`。這表示 FastAPI 甚至不會嘗試把請求負載解析為 JSON。
+
+然後在程式中直接解析該 YAML 內容,並再次使用相同的 Pydantic 模型來驗證該 YAML 內容:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip
+
+這裡我們重複使用同一個 Pydantic 模型。
+
+不過也可以用其他方式進行驗證。
+
+///
diff --git a/docs/zh-hant/docs/advanced/response-change-status-code.md b/docs/zh-hant/docs/advanced/response-change-status-code.md
new file mode 100644
index 000000000..4b8d459ca
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# 回應 - 變更狀態碼 { #response-change-status-code }
+
+你可能已經讀過,可以設定預設的[回應狀態碼](../tutorial/response-status-code.md){.internal-link target=_blank}。
+
+但有些情況你需要回傳與預設不同的狀態碼。
+
+## 使用情境 { #use-case }
+
+例如,假設你預設想回傳 HTTP 狀態碼 "OK" `200`。
+
+但如果資料不存在,你想要建立它,並回傳 HTTP 狀態碼 "CREATED" `201`。
+
+同時你仍希望能用 `response_model` 過濾並轉換所回傳的資料。
+
+在這些情況下,你可以使用 `Response` 參數。
+
+## 使用 `Response` 參數 { #use-a-response-parameter }
+
+你可以在你的路徑操作函式(path operation function)中宣告一個 `Response` 型別的參數(就像你可以對 Cookies 和標頭那樣)。
+
+接著你可以在那個「*暫時的*」回應物件上設定 `status_code`。
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+然後你可以照常回傳任何需要的物件(例如 `dict`、資料庫模型等)。
+
+若你宣告了 `response_model`,它仍會被用來過濾並轉換你回傳的物件。
+
+FastAPI 會使用那個「*暫時的*」回應來取得狀態碼(以及 Cookies 和標頭),並將它們放入最終回應中;最終回應包含你回傳的值,且會被任何 `response_model` 過濾。
+
+你也可以在相依性(dependencies)中宣告 `Response` 參數,並在其中設定狀態碼。但請注意,最後被設定的值會生效。
diff --git a/docs/zh-hant/docs/advanced/response-cookies.md b/docs/zh-hant/docs/advanced/response-cookies.md
new file mode 100644
index 000000000..b7225d571
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# 回應 Cookie { #response-cookies }
+
+## 使用 `Response` 參數 { #use-a-response-parameter }
+
+你可以在路徑操作函式(path operation function)中宣告一個型別為 `Response` 的參數。
+
+接著你可以在那個「暫時」的 `Response` 物件上設定 Cookie。
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+之後如常回傳你需要的任何物件(例如 `dict`、資料庫模型等)。
+
+如果你宣告了 `response_model`,它仍會用來過濾並轉換你回傳的物件。
+
+FastAPI 會使用那個暫時的 `Response` 取出 Cookie(以及標頭與狀態碼),並將它們放入最終回應;最終回應包含你回傳的值,且會套用任何 `response_model` 的過濾。
+
+你也可以在相依項(dependencies)中宣告 `Response` 參數,並在其中設定 Cookie(與標頭)。
+
+## 直接回傳 `Response` { #return-a-response-directly }
+
+當你在程式碼中直接回傳 `Response` 時,也可以建立 Cookie。
+
+要這麼做,你可以依照 [直接回傳 Response](response-directly.md){.internal-link target=_blank} 中的說明建立一個回應。
+
+接著在其中設定 Cookie,然後回傳它:
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip | 提示
+
+請注意,如果你不是使用 `Response` 參數,而是直接回傳一個 `Response`,FastAPI 會原樣回傳它。
+
+因此你必須確保資料型別正確;例如,如果你回傳的是 `JSONResponse`,就要確保資料可與 JSON 相容。
+
+同時也要確認沒有送出原本應該由 `response_model` 過濾的資料。
+
+///
+
+### 更多資訊 { #more-info }
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import Response` 或 `from starlette.responses import JSONResponse`。
+
+為了方便開發者,FastAPI 也將相同的 `starlette.responses` 透過 `fastapi.responses` 提供。不過,大多數可用的回應類別都直接來自 Starlette。
+
+另外由於 `Response` 常用於設定標頭與 Cookie,FastAPI 也在 `fastapi.Response` 提供了它。
+
+///
+
+想查看所有可用的參數與選項,請參閱 Starlette 文件。
diff --git a/docs/zh-hant/docs/advanced/response-directly.md b/docs/zh-hant/docs/advanced/response-directly.md
new file mode 100644
index 000000000..560354893
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/response-directly.md
@@ -0,0 +1,65 @@
+# 直接回傳 Response { #return-a-response-directly }
+
+當你建立一個 **FastAPI** 的路徑操作 (path operation) 時,通常可以從中回傳任何資料:`dict`、`list`、Pydantic 模型、資料庫模型等。
+
+預設情況下,**FastAPI** 會使用在[JSON 相容編碼器](../tutorial/encoder.md){.internal-link target=_blank}中說明的 `jsonable_encoder`,自動將回傳值轉為 JSON。
+
+然後在幕後,它會把這些與 JSON 相容的資料(例如 `dict`)放進 `JSONResponse`,用來把回應傳回給用戶端。
+
+但你也可以直接從路徑操作回傳 `JSONResponse`。
+
+例如,當你需要回傳自訂的 headers 或 cookies 時就很有用。
+
+## 回傳 `Response` { #return-a-response }
+
+其實,你可以回傳任何 `Response`,或其任何子類別。
+
+/// tip
+
+`JSONResponse` 本身就是 `Response` 的子類別。
+
+///
+
+當你回傳一個 `Response` 時,**FastAPI** 會直接傳遞它。
+
+它不會對 Pydantic 模型做任何資料轉換,也不會把內容轉成其他型別等。
+
+這給了你很大的彈性。你可以回傳任何資料型別、覆寫任何資料宣告或驗證等。
+
+## 在 `Response` 中使用 `jsonable_encoder` { #using-the-jsonable-encoder-in-a-response }
+
+因為 **FastAPI** 不會對你回傳的 `Response` 做任何更動,你需要自行確保它的內容已經準備好。
+
+例如,你不能直接把一個 Pydantic 模型放進 `JSONResponse`,需要先把它轉成 `dict`,並將所有資料型別(像是 `datetime`、`UUID` 等)轉成與 JSON 相容的型別。
+
+在這些情況下,你可以先用 `jsonable_encoder` 把資料轉好,再傳給回應物件:
+
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import JSONResponse`。
+
+**FastAPI** 為了方便開發者,將 `starlette.responses` 也提供為 `fastapi.responses`。但大多數可用的回應類型其實直接來自 Starlette。
+
+///
+
+## 回傳自訂 `Response` { #returning-a-custom-response }
+
+上面的範例展示了所需的各個部分,但目前還不太實用,因為你其實可以直接回傳 `item`,**FastAPI** 就會幫你把它放進 `JSONResponse`,轉成 `dict` 等,這些都是預設行為。
+
+現在來看看如何用它來回傳自訂回應。
+
+假設你想要回傳一個 XML 回應。
+
+你可以把 XML 內容放進一個字串,把它放進 `Response`,然後回傳它:
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## 注意事項 { #notes }
+
+當你直接回傳 `Response` 時,其資料不會自動被驗證、轉換(序列化)或文件化。
+
+但你仍然可以依照[在 OpenAPI 中的額外回應](additional-responses.md){.internal-link target=_blank}中的說明進行文件化。
+
+在後續章節中,你會看到如何在仍保有自動資料轉換、文件化等的同時,使用/宣告這些自訂的 `Response`。
diff --git a/docs/zh-hant/docs/advanced/response-headers.md b/docs/zh-hant/docs/advanced/response-headers.md
new file mode 100644
index 000000000..6e32ca1b3
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# 回應標頭 { #response-headers }
+
+## 使用 `Response` 參數 { #use-a-response-parameter }
+
+你可以在你的*路徑操作函式(path operation function)*中宣告一個 `Response` 型別的參數(就像處理 Cookie 一樣)。
+
+然後你可以在那個*暫時性的* `Response` 物件上設定標頭。
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+接著你可以像平常一樣回傳任何你需要的物件(`dict`、資料庫模型等)。
+
+如果你宣告了 `response_model`,它仍會用來過濾並轉換你回傳的物件。
+
+FastAPI 會使用那個暫時性的回應來擷取標頭(還有 Cookie 與狀態碼),並把它們放到最終回應中;最終回應包含你回傳的值,且會依任何 `response_model` 進行過濾。
+
+你也可以在依賴中宣告 `Response` 參數,並在其中設定標頭(與 Cookie)。
+
+## 直接回傳 `Response` { #return-a-response-directly }
+
+當你直接回傳 `Response` 時,也能加入標頭。
+
+依照[直接回傳 Response](response-directly.md){.internal-link target=_blank}中的說明建立回應,並把標頭作為額外參數傳入:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import Response` 或 `from starlette.responses import JSONResponse`。
+
+為了方便開發者,FastAPI 提供與 `starlette.responses` 相同的內容於 `fastapi.responses`。但大多數可用的回應類型其實直接來自 Starlette。
+
+由於 `Response` 常用來設定標頭與 Cookie,FastAPI 也在 `fastapi.Response` 提供了它。
+
+///
+
+## 自訂標頭 { #custom-headers }
+
+請記住,專有的自訂標頭可以使用 `X-` 前綴來新增。
+
+但如果你有自訂標頭並希望瀏覽器端的客戶端能看見它們,你需要把這些標頭加入到 CORS 設定中(詳見 [CORS(跨來源資源共用)](../tutorial/cors.md){.internal-link target=_blank}),使用在Starlette 的 CORS 文件中記載的 `expose_headers` 參數。
diff --git a/docs/zh-hant/docs/advanced/security/http-basic-auth.md b/docs/zh-hant/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 000000000..ea3d52829
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP 基本認證 { #http-basic-auth }
+
+在最簡單的情況下,你可以使用 HTTP Basic 認證。
+
+在 HTTP Basic 認證中,應用程式會期待一個包含使用者名稱與密碼的標頭。
+
+如果沒有接收到,會回傳 HTTP 401「Unauthorized」錯誤。
+
+並回傳一個 `WWW-Authenticate` 標頭,其值為 `Basic`,以及可選的 `realm` 參數。
+
+這會告訴瀏覽器顯示內建的使用者名稱與密碼提示視窗。
+
+接著,當你輸入該使用者名稱與密碼時,瀏覽器會自動在標頭中送出它們。
+
+## 簡單的 HTTP 基本認證 { #simple-http-basic-auth }
+
+- 匯入 `HTTPBasic` 與 `HTTPBasicCredentials`。
+- 使用 `HTTPBasic` 建立一個「`security` scheme」。
+- 在你的*路徑操作*中以依賴的方式使用該 `security`。
+- 它會回傳一個 `HTTPBasicCredentials` 型別的物件:
+ - 其中包含傳來的 `username` 與 `password`。
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+當你第一次嘗試開啟該 URL(或在文件中點擊 "Execute" 按鈕)時,瀏覽器會要求輸入你的使用者名稱與密碼:
+
+
+
+## 檢查使用者名稱 { #check-the-username }
+
+以下是一個更完整的範例。
+
+使用一個依賴來檢查使用者名稱與密碼是否正確。
+
+為此,使用 Python 標準模組 `secrets` 來比對使用者名稱與密碼。
+
+`secrets.compare_digest()` 需要接收 `bytes`,或是只包含 ASCII 字元(英文字符)的 `str`。這表示它無法處理像 `á` 這樣的字元,例如 `Sebastián`。
+
+為了處理這點,我們會先將 `username` 與 `password` 以 UTF-8 編碼成 `bytes`。
+
+接著我們可以使用 `secrets.compare_digest()` 來確認 `credentials.username` 等於 `"stanleyjobson"`,而 `credentials.password` 等於 `"swordfish"`。
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+這大致等同於:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # 回傳錯誤
+ ...
+```
+
+但藉由使用 `secrets.compare_digest()`,可以防禦一種稱為「計時攻擊」的攻擊。
+
+### 計時攻擊 { #timing-attacks }
+
+什麼是「計時攻擊」呢?
+
+想像有攻擊者在嘗試猜測使用者名稱與密碼。
+
+他們送出一個帶有使用者名稱 `johndoe` 與密碼 `love123` 的請求。
+
+接著,你的應用程式中的 Python 程式碼等同於:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+當 Python 比較 `johndoe` 的第一個 `j` 與 `stanleyjobson` 的第一個 `s` 時,會立刻回傳 `False`,因為已經知道兩個字串不同,覺得「沒必要浪費計算資源繼續比較剩下的字元」。你的應用程式便會回應「Incorrect username or password」。
+
+但接著攻擊者改用使用者名稱 `stanleyjobsox` 與密碼 `love123` 嘗試。
+
+你的應用程式程式碼會做類似:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Python 會必須先比較完整的 `stanleyjobso`(在 `stanleyjobsox` 與 `stanleyjobson` 之中都一樣),才會發現兩個字串不同。因此回覆「Incorrect username or password」會多花一些微秒。
+
+#### 回應時間幫了攻擊者 { #the-time-to-answer-helps-the-attackers }
+
+此時,透過觀察伺服器回覆「Incorrect username or password」多花了幾個微秒,攻擊者就知道他們有某些地方猜對了,前幾個字母是正確的。
+
+接著他們會再嘗試,知道它更可能接近 `stanleyjobsox` 而不是 `johndoe`。
+
+#### 「專業」的攻擊 { #a-professional-attack }
+
+當然,攻擊者不會手動嘗試這一切,他們會寫程式來做,可能每秒進行上千或上百萬次測試,一次只多猜中一個正確字母。
+
+但這樣做,幾分鐘或幾小時內,他們就能在我們應用程式「協助」下,僅靠回應時間就猜出正確的使用者名稱與密碼。
+
+#### 用 `secrets.compare_digest()` 修正 { #fix-it-with-secrets-compare-digest }
+
+但在我們的程式碼中實際使用的是 `secrets.compare_digest()`。
+
+簡而言之,將 `stanleyjobsox` 與 `stanleyjobson` 比較所花的時間,會與將 `johndoe` 與 `stanleyjobson` 比較所花的時間相同;密碼也一樣。
+
+如此一來,在應用程式程式碼中使用 `secrets.compare_digest()`,就能安全地防禦這整類的安全攻擊。
+
+### 回傳錯誤 { #return-the-error }
+
+在偵測到憑證不正確之後,回傳一個狀態碼為 401 的 `HTTPException`(與未提供憑證時相同),並加上 `WWW-Authenticate` 標頭,讓瀏覽器再次顯示登入提示:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/zh-hant/docs/advanced/security/index.md b/docs/zh-hant/docs/advanced/security/index.md
new file mode 100644
index 000000000..9a4cfbbfd
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# 進階安全性 { #advanced-security }
+
+## 額外功能 { #additional-features }
+
+除了[教學 - 使用者指南:安全性](../../tutorial/security/index.md){.internal-link target=_blank}中涵蓋的內容外,還有一些用來處理安全性的額外功能。
+
+/// tip
+
+以下各節不一定是「進階」內容。
+
+而且你的情境很可能可以在其中找到解決方案。
+
+///
+
+## 請先閱讀教學 { #read-the-tutorial-first }
+
+以下各節假設你已閱讀主要的[教學 - 使用者指南:安全性](../../tutorial/security/index.md){.internal-link target=_blank}。
+
+它們都建立在相同的概念之上,但提供一些額外的功能。
diff --git a/docs/zh-hant/docs/advanced/security/oauth2-scopes.md b/docs/zh-hant/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 000000000..029572d43
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2 範圍(scopes) { #oauth2-scopes }
+
+你可以直接在 FastAPI 中使用 OAuth2 的 scopes,已整合可無縫運作。
+
+這能讓你在 OpenAPI 應用(以及 API 文件)中,依照 OAuth2 標準,實作更細粒度的權限系統。
+
+帶有 scopes 的 OAuth2 是許多大型身分驗證提供者(如 Facebook、Google、GitHub、Microsoft、X(Twitter)等)所使用的機制。他們用它來為使用者與應用程式提供特定權限。
+
+每次你「使用」Facebook、Google、GitHub、Microsoft、X(Twitter)「登入」時,那個應用就是在使用帶有 scopes 的 OAuth2。
+
+在本節中,你將看到如何在你的 FastAPI 應用中,用同樣的帶有 scopes 的 OAuth2 管理驗證與授權。
+
+/// warning
+
+這一節算是進階內容。如果你剛開始,可以先跳過。
+
+你不一定需要 OAuth2 scopes,你可以用任何你想要的方式處理驗證與授權。
+
+但帶有 scopes 的 OAuth2 可以很漂亮地整合進你的 API(透過 OpenAPI)與 API 文件。
+
+無論如何,你仍然會在程式碼中,依你的需求,強制檢查那些 scopes,或其他任何安全性/授權需求。
+
+在許多情況下,帶有 scopes 的 OAuth2 可能有點大材小用。
+
+但如果你確定需要,或是好奇,請繼續閱讀。
+
+///
+
+## OAuth2 scopes 與 OpenAPI { #oauth2-scopes-and-openapi }
+
+OAuth2 規格將「scopes」定義為以空白分隔的一串字串列表。
+
+每個字串的內容可以有任意格式,但不應包含空白。
+
+這些 scopes 代表「權限」。
+
+在 OpenAPI(例如 API 文件)中,你可以定義「security schemes」。
+
+當某個 security scheme 使用 OAuth2 時,你也可以宣告並使用 scopes。
+
+每個「scope」就是一個(不含空白的)字串。
+
+它們通常用來宣告特定的安全性權限,例如:
+
+- `users:read` 或 `users:write` 是常見的例子。
+- `instagram_basic` 是 Facebook / Instagram 使用的。
+- `https://www.googleapis.com/auth/drive` 是 Google 使用的。
+
+/// info
+
+在 OAuth2 中,「scope」只是宣告所需特定權限的一個字串。
+
+是否包含像 `:` 這樣的字元,或是否是一個 URL,都沒差。
+
+那些細節取決於實作。
+
+對 OAuth2 而言,它們就是字串。
+
+///
+
+## 全局概觀 { #global-view }
+
+先快速看看相對於主教學「使用密碼(與雜湊)、Bearer 與 JWT token 的 OAuth2」的差異([OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank})。現在加入了 OAuth2 scopes:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+接著我們一步一步檢視這些變更。
+
+## OAuth2 安全性方案 { #oauth2-security-scheme }
+
+第一個變更是:我們現在宣告了帶有兩個可用 scope 的 OAuth2 安全性方案,`me` 與 `items`。
+
+參數 `scopes` 接收一個 `dict`,以各 scope 為鍵、其描述為值:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+由於現在宣告了這些 scopes,當你登入/授權時,它們會出現在 API 文件中。
+
+你可以選擇要授予哪些 scopes 存取權:`me` 與 `items`。
+
+這與你使用 Facebook、Google、GitHub 等登入時所授與權限的機制相同:
+
+
+
+## 內含 scopes 的 JWT token { #jwt-token-with-scopes }
+
+現在,修改 token 的路徑操作以回傳所請求的 scopes。
+
+我們仍然使用相同的 `OAuth2PasswordRequestForm`。它包含屬性 `scopes`,其為 `list` 的 `str`,列出請求中收到的每個 scope。
+
+並且我們將這些 scopes 作為 JWT token 的一部分回傳。
+
+/// danger
+
+為了簡化,這裡我們只是直接把接收到的 scopes 加進 token。
+
+但在你的應用中,為了安全性,你應確保只加入該使用者實際可擁有或你預先定義的 scopes。
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## 在路徑操作與相依性中宣告 scopes { #declare-scopes-in-path-operations-and-dependencies }
+
+現在我們宣告 `/users/me/items/` 這個路徑操作需要 `items` 這個 scope。
+
+為此,我們從 `fastapi` 匯入並使用 `Security`。
+
+你可以使用 `Security` 來宣告相依性(就像 `Depends`),但 `Security` 也能接收參數 `scopes`,其為 scopes(字串)的列表。
+
+在這裡,我們將相依函式 `get_current_active_user` 傳給 `Security`(就像使用 `Depends` 一樣)。
+
+但同時也傳入一個 `list` 的 scopes,這裡只有一個 scope:`items`(當然也可以有更多)。
+
+而相依函式 `get_current_active_user` 也能宣告子相依性,不只用 `Depends`,也能用 `Security`。它宣告了自己的子相依函式(`get_current_user`),並加入更多 scope 要求。
+
+在這個例子中,它要求 `me` 這個 scope(也可以要求多個)。
+
+/// note
+
+你不一定需要在不同地方加上不同的 scopes。
+
+我們在這裡這樣做,是為了示範 FastAPI 如何處理在不同層級宣告的 scopes。
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | 技術細節
+
+`Security` 其實是 `Depends` 的子類別,僅多了一個我們稍後會看到的參數。
+
+改用 `Security` 而不是 `Depends`,能讓 FastAPI 知道可以宣告安全性 scopes、在內部使用它們,並用 OpenAPI 文件化 API。
+
+另外,當你從 `fastapi` 匯入 `Query`、`Path`、`Depends`、`Security` 等時,實際上它們是回傳特殊類別的函式。
+
+///
+
+## 使用 `SecurityScopes` { #use-securityscopes }
+
+現在更新相依性 `get_current_user`。
+
+上面的相依性就是使用它。
+
+這裡我們使用先前建立的相同 OAuth2 scheme,並將其宣告為相依性:`oauth2_scheme`。
+
+因為此相依函式本身沒有任何 scope 要求,所以我們可以用 `Depends` 搭配 `oauth2_scheme`,當不需要指定安全性 scopes 時就不必用 `Security`。
+
+我們也宣告了一個型別為 `SecurityScopes` 的特殊參數,從 `fastapi.security` 匯入。
+
+這個 `SecurityScopes` 類似於 `Request`(`Request` 用來直接取得請求物件)。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## 使用這些 `scopes` { #use-the-scopes }
+
+參數 `security_scopes` 的型別是 `SecurityScopes`。
+
+它會有屬性 `scopes`,包含一個列表,內含此函式本身與所有使用它為子相依性的相依性所要求的所有 scopes。也就是所有「相依者(dependants)」... 這聽起來可能有點混亂,下面會再解釋。
+
+`security_scopes` 物件(類別 `SecurityScopes`)也提供 `scope_str` 屬性,為一個字串,包含那些以空白分隔的 scopes(我們會用到)。
+
+我們建立一個可在多處重複丟出(`raise`)的 `HTTPException`。
+
+在這個例外中,我們把所需的 scopes(若有)以空白分隔的字串形式(透過 `scope_str`)加入,並將該包含 scopes 的字串放在 `WWW-Authenticate` 標頭中(這是規格的一部分)。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## 驗證 `username` 與資料結構 { #verify-the-username-and-data-shape }
+
+我們先確認取得了 `username`,並取出 scopes。
+
+接著用 Pydantic 模型驗證這些資料(捕捉 `ValidationError` 例外),若在讀取 JWT token 或用 Pydantic 驗證資料時出錯,就丟出先前建立的 `HTTPException`。
+
+為此,我們更新了 Pydantic 模型 `TokenData`,加入新屬性 `scopes`。
+
+透過 Pydantic 驗證資料,我們可以確保,例如,scopes 正好是 `list` 的 `str`,而 `username` 是 `str`。
+
+否則若是 `dict` 或其他型別,可能在後續某處使應用壞掉,造成安全風險。
+
+我們也會確認該 `username` 對應的使用者是否存在,否則同樣丟出之前建立的例外。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## 驗證 `scopes` { #verify-the-scopes }
+
+我們現在要驗證,此相依性與所有相依者(包含路徑操作)所要求的所有 scopes,是否都包含在收到的 token 內所提供的 scopes 中;否則就丟出 `HTTPException`。
+
+為此,我們使用 `security_scopes.scopes`,其中包含一個 `list`,列出所有這些 `str` 形式的 scopes。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## 相依性樹與 scopes { #dependency-tree-and-scopes }
+
+我們再回顧一次這個相依性樹與 scopes。
+
+由於 `get_current_active_user` 相依於 `get_current_user`,因此在 `get_current_active_user` 宣告的 `"me"` 這個 scope 會包含在傳給 `get_current_user` 的 `security_scopes.scopes` 的必須 scopes 清單中。
+
+路徑操作本身也宣告了 `"items"` 這個 scope,因此它也會包含在傳給 `get_current_user` 的 `security_scopes.scopes` 中。
+
+以下是相依性與 scopes 的階層關係:
+
+- 路徑操作 `read_own_items` 具有:
+ - 需要的 scopes `["items"]`,並有相依性:
+ - `get_current_active_user`:
+ - 相依函式 `get_current_active_user` 具有:
+ - 需要的 scopes `["me"]`,並有相依性:
+ - `get_current_user`:
+ - 相依函式 `get_current_user` 具有:
+ - 自身沒有需要的 scopes。
+ - 一個使用 `oauth2_scheme` 的相依性。
+ - 一個型別為 `SecurityScopes` 的 `security_scopes` 參數:
+ - 這個 `security_scopes` 參數有屬性 `scopes`,其為一個 `list`,包含了上面宣告的所有 scopes,因此:
+ - 對於路徑操作 `read_own_items`,`security_scopes.scopes` 會包含 `["me", "items"]`。
+ - 對於路徑操作 `read_users_me`,因為它在相依性 `get_current_active_user` 中被宣告,`security_scopes.scopes` 會包含 `["me"]`。
+ - 對於路徑操作 `read_system_status`,因為它沒有宣告任何帶 `scopes` 的 `Security`,且其相依性 `get_current_user` 也未宣告任何 `scopes`,所以 `security_scopes.scopes` 會包含 `[]`(空)。
+
+/// tip
+
+這裡重要且「神奇」的是:`get_current_user` 在每個路徑操作中,會有不同的 `scopes` 清單需要檢查。
+
+這完全取決於該路徑操作與其相依性樹中每個相依性所宣告的 `scopes`。
+
+///
+
+## 更多關於 `SecurityScopes` 的細節 { #more-details-about-securityscopes }
+
+你可以在任意位置、多個地方使用 `SecurityScopes`,它不需要位於「根」相依性。
+
+它會永遠帶有對於「該特定」路徑操作與「該特定」相依性樹中,目前 `Security` 相依性所宣告的安全性 scopes(以及所有相依者):
+
+因為 `SecurityScopes` 會擁有由相依者宣告的所有 scopes,你可以在一個集中式相依函式中用它來驗證 token 是否具有所需 scopes,然後在不同路徑操作中宣告不同的 scope 要求。
+
+它們會在每個路徑操作被各自獨立檢查。
+
+## 試用看看 { #check-it }
+
+如果你打開 API 文件,你可以先驗證並指定你要授權的 scopes。
+
+
+
+如果你沒有選任何 scope,你仍會「通過驗證」,但當你嘗試存取 `/users/me/` 或 `/users/me/items/` 時,會收到沒有足夠權限的錯誤。你仍能存取 `/status/`。
+
+若你只選了 `me` 而未選 `items`,你能存取 `/users/me/`,但無法存取 `/users/me/items/`。
+
+這就是第三方應用在取得使用者提供的 token 後,嘗試存取上述路徑操作時,會依使用者授與該應用的權限多寡而有不同結果。
+
+## 關於第三方整合 { #about-third-party-integrations }
+
+在這個範例中,我們使用 OAuth2 的「password」流程。
+
+當我們登入自己的應用(可能也有自己的前端)時,這是合適的。
+
+因為我們可以信任它接收 `username` 與 `password`,因為我們掌控它。
+
+但如果你要打造一個讓他人連接的 OAuth2 應用(也就是你要建立一個相當於 Facebook、Google、GitHub 等的身分驗證提供者),你應該使用其他流程之一。
+
+最常見的是 Implicit Flow(隱式流程)。
+
+最安全的是 Authorization Code Flow(授權碼流程),但它需要更多步驟、實作也更複雜。因為較複雜,許多提供者最後會建議使用隱式流程。
+
+/// note
+
+很常見的是,每個身分驗證提供者會用不同的方式命名他們的流程,讓它成為品牌的一部分。
+
+但最終,他們實作的都是相同的 OAuth2 標準。
+
+///
+
+FastAPI 在 `fastapi.security.oauth2` 中提供了所有這些 OAuth2 驗證流程的工具。
+
+## 在裝飾器 `dependencies` 中使用 `Security` { #security-in-decorator-dependencies }
+
+就像你可以在裝飾器的 `dependencies` 參數中定義一個 `Depends` 的 `list` 一樣(詳見[路徑操作裝飾器中的相依性](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}),你也可以在那裡使用帶有 `scopes` 的 `Security`。
diff --git a/docs/zh-hant/docs/advanced/settings.md b/docs/zh-hant/docs/advanced/settings.md
new file mode 100644
index 000000000..1ee5ad7cc
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# 設定與環境變數 { #settings-and-environment-variables }
+
+在許多情況下,你的應用程式可能需要一些外部設定或組態,例如密鑰、資料庫憑證、電子郵件服務的憑證等。
+
+這些設定大多是可變的(可能會改變),像是資料庫 URL。也有許多可能是敏感資訊,例如密鑰。
+
+因此,通常會透過環境變數提供這些設定,讓應用程式去讀取。
+
+/// tip
+
+若想了解環境變數,你可以閱讀[環境變數](../environment-variables.md){.internal-link target=_blank}。
+
+///
+
+## 型別與驗證 { #types-and-validation }
+
+這些環境變數只能處理文字字串,因為它們在 Python 之外,必須與其他程式與系統的其餘部分相容(甚至跨作業系統,如 Linux、Windows、macOS)。
+
+這表示在 Python 中自環境變數讀取到的任何值都會是 `str`,而任何轉型成其他型別或驗證都必須在程式碼中完成。
+
+## Pydantic `Settings` { #pydantic-settings }
+
+幸好,Pydantic 提供了很好的工具,可用來處理由環境變數而來的設定:Pydantic:設定管理。
+
+### 安裝 `pydantic-settings` { #install-pydantic-settings }
+
+首先,請先建立你的[虛擬環境](../virtual-environments.md){.internal-link target=_blank},啟用它,然後安裝 `pydantic-settings` 套件:
+
+
+
+接著,開啟子應用程式的文件:http://127.0.0.1:8000/subapi/docs。
+
+你會看到子應用程式的自動 API 文件,只包含它自己的*路徑操作*,而且都在正確的子路徑前綴 `/subapi` 之下:
+
+
+
+如果你嘗試在任一介面中互動,它們都會正常運作,因為瀏覽器能與各自的應用程式或子應用程式通訊。
+
+### 技術細節:`root_path` { #technical-details-root-path }
+
+當你像上面那樣掛載子應用程式時,FastAPI 會使用 ASGI 規範中的一個機制 `root_path`,將子應用程式的掛載路徑告知它。
+
+如此一來,子應用程式就會知道在文件 UI 使用該路徑前綴。
+
+而且子應用程式也能再掛載自己的子應用程式,一切都能正確運作,因為 FastAPI 會自動處理所有這些 `root_path`。
+
+你可以在[在代理伺服器之後](behind-a-proxy.md){.internal-link target=_blank}一節中進一步了解 `root_path` 與如何顯式使用它。
diff --git a/docs/zh-hant/docs/advanced/templates.md b/docs/zh-hant/docs/advanced/templates.md
new file mode 100644
index 000000000..ffc7599ae
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# 模板 { #templates }
+
+你可以在 **FastAPI** 中使用任意你想要的模板引擎。
+
+常見的選擇是 Jinja2,與 Flask 與其他工具所使用的一樣。
+
+有一些工具可讓你輕鬆設定,並可直接在你的 **FastAPI** 應用程式中使用(由 Starlette 提供)。
+
+## 安裝相依套件 { #install-dependencies }
+
+請先建立一個[虛擬環境](../virtual-environments.md){.internal-link target=_blank}、啟用它,然後安裝 `jinja2`:
+
+
+
+你可以在輸入框輸入訊息並送出:
+
+
+
+你的 **FastAPI** 應用會透過 WebSockets 回應:
+
+
+
+你可以傳送(與接收)多則訊息:
+
+
+
+而且它們都會使用同一個 WebSocket 連線。
+
+## 使用 `Depends` 與其他功能 { #using-depends-and-others }
+
+在 WebSocket 端點中,你可以從 `fastapi` 匯入並使用:
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+它們的運作方式與其他 FastAPI 端點/*路徑操作* 相同:
+
+{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info
+
+因為這是 WebSocket,拋出 `HTTPException` 並沒有意義,因此我們改為拋出 `WebSocketException`。
+
+你可以使用規範中定義的有效關閉代碼之一。
+
+///
+
+### 用依賴試用 WebSocket { #try-the-websockets-with-dependencies }
+
+如果你的檔案名為 `main.py`,用以下指令執行應用:
+
+
+
+## 處理斷線與多個用戶端 { #handling-disconnections-and-multiple-clients }
+
+當 WebSocket 連線關閉時,`await websocket.receive_text()` 會拋出 `WebSocketDisconnect` 例外,你可以像範例中那樣捕捉並處理。
+
+{* ../../docs_src/websockets/tutorial003_py310.py hl[79:81] *}
+
+試用方式:
+
+* 用多個瀏覽器分頁開啟該應用。
+* 從每個分頁傳送訊息。
+* 然後關閉其中一個分頁。
+
+這會引發 `WebSocketDisconnect` 例外,其他所有用戶端都會收到類似以下的訊息:
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip
+
+上面的應用是一個極簡範例,用來示範如何處理並向多個 WebSocket 連線廣播訊息。
+
+但請注意,因為所有狀態都在記憶體中的單一 list 裡管理,它只會在該程序執行期間生效,且僅適用於單一程序。
+
+如果你需要一個容易與 FastAPI 整合、但更健壯,且可由 Redis、PostgreSQL 等後端支援的方案,請參考 encode/broadcaster。
+
+///
+
+## 更多資訊 { #more-info }
+
+想了解更多選項,請參考 Starlette 的文件:
+
+* `WebSocket` 類別。
+* 以類別為基礎的 WebSocket 處理。
diff --git a/docs/zh-hant/docs/advanced/wsgi.md b/docs/zh-hant/docs/advanced/wsgi.md
new file mode 100644
index 000000000..9d03b5692
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# 包含 WSGI:Flask、Django 等 { #including-wsgi-flask-django-others }
+
+你可以像在 [子應用程式 - 掛載](sub-applications.md){.internal-link target=_blank}、[在 Proxy 後方](behind-a-proxy.md){.internal-link target=_blank} 中所見那樣掛載 WSGI 應用。
+
+為此,你可以使用 `WSGIMiddleware` 來包住你的 WSGI 應用,例如 Flask、Django 等。
+
+## 使用 `WSGIMiddleware` { #using-wsgimiddleware }
+
+/// info
+
+這需要先安裝 `a2wsgi`,例如使用 `pip install a2wsgi`。
+
+///
+
+你需要從 `a2wsgi` 匯入 `WSGIMiddleware`。
+
+然後用該 middleware 包住 WSGI(例如 Flask)應用。
+
+接著把它掛載到某個路徑下。
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note
+
+先前建議使用來自 `fastapi.middleware.wsgi` 的 `WSGIMiddleware`,但現在已棄用。
+
+建議改用 `a2wsgi` 套件。用法保持相同。
+
+只要確保已安裝 `a2wsgi`,並從 `a2wsgi` 正確匯入 `WSGIMiddleware` 即可。
+
+///
+
+## 試試看 { #check-it }
+
+現在,位於路徑 `/v1/` 底下的所有請求都會由 Flask 應用處理。
+
+其餘則由 **FastAPI** 處理。
+
+如果你啟動它並前往 http://localhost:8000/v1/,你會看到來自 Flask 的回應:
+
+```txt
+Hello, World from Flask!
+```
+
+如果你前往 http://localhost:8000/v2,你會看到來自 FastAPI 的回應:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/zh-hant/docs/alternatives.md b/docs/zh-hant/docs/alternatives.md
new file mode 100644
index 000000000..340c47d8b
--- /dev/null
+++ b/docs/zh-hant/docs/alternatives.md
@@ -0,0 +1,485 @@
+# 替代方案、靈感與比較 { #alternatives-inspiration-and-comparisons }
+
+啟發 FastAPI 的來源、與其他方案的比較,以及從中學到的內容。
+
+## 介紹 { #intro }
+
+沒有前人的工作,就不會有 **FastAPI**。
+
+在它誕生之前,已經有許多工具啟發了它的設計。
+
+我多年來一直避免打造新框架。起初我嘗試用許多不同的框架、外掛與工具,來實作 **FastAPI** 涵蓋的所有功能。
+
+但在某個時間點,除了創建一個能提供所有這些功能、汲取前人工具的優點,並以最佳方式組合起來、同時運用過去甚至不存在的語言特性(Python 3.6+ 的型別提示)之外,已別無他法。
+
+## 先前的工具 { #previous-tools }
+
+### Django { #django }
+
+它是最受歡迎且廣受信任的 Python 框架。像 Instagram 等系統就是用它打造的。
+
+它與關聯式資料庫(如 MySQL 或 PostgreSQL)相對緊密耦合,因此要以 NoSQL 資料庫(如 Couchbase、MongoDB、Cassandra 等)作為主要儲存引擎並不容易。
+
+它一開始是為在後端產生 HTML 而設計,而非為了建立提供現代前端(如 React、Vue.js、Angular)或其他系統(如 IoT 裝置)使用的 API。
+
+### Django REST Framework { #django-rest-framework }
+
+Django REST framework 的目標是成為一套在 Django 之上構建 Web API 的彈性工具組,以強化其 API 能力。
+
+它被 Mozilla、Red Hat、Eventbrite 等眾多公司使用。
+
+它是「自動 API 文件」的早期典範之一,而這正是啟發我「尋找」**FastAPI** 的第一個想法。
+
+/// note | 注意
+
+Django REST Framework 由 Tom Christie 創建。他同時也是 Starlette 與 Uvicorn 的作者,而 **FastAPI** 就是建立在它們之上。
+
+///
+
+/// check | 啟發 **FastAPI**
+
+提供自動化的 API 文件網頁使用者介面。
+
+///
+
+### Flask { #flask }
+
+Flask 是一個「微框架」,它不包含資料庫整合,也沒有像 Django 那樣內建許多功能。
+
+這種簡單與彈性,讓你可以把 NoSQL 資料庫作為主要的資料儲存系統。
+
+由於它非常簡單,學起來相對直觀,儘管文件在某些地方會變得較技術性。
+
+它也常用於其他不一定需要資料庫、使用者管理或 Django 內建眾多功能的應用程式。雖然這些功能中的許多都可以用外掛新增。
+
+這種元件的解耦,以及作為可擴充以精準滿足需求的「微框架」,是我想要保留的關鍵特性。
+
+基於 Flask 的簡潔,它看起來很適合用來構建 API。接下來要找的,就是 Flask 世界裡的「Django REST Framework」。
+
+/// check | 啟發 **FastAPI**
+
+成為一個微框架,讓所需的工具與元件能輕鬆搭配組合。
+
+具備簡單、易用的路由系統。
+
+///
+
+### Requests { #requests }
+
+**FastAPI** 其實不是 **Requests** 的替代品。兩者的範疇截然不同。
+
+在 FastAPI 應用程式「內部」使用 Requests 其實很常見。
+
+儘管如此,FastAPI 仍從 Requests 得到了不少啟發。
+
+**Requests** 是一個「與 API 互動」(作為用戶端)的程式庫,而 **FastAPI** 是一個「建立 API」(作為伺服端)的程式庫。
+
+它們大致位於相反兩端,彼此互補。
+
+Requests 設計非常簡單直觀、容易使用,且有合理的預設值。同時它也非常強大且可自訂。
+
+因此,如其官網所言:
+
+> Requests is one of the most downloaded Python packages of all time
+
+用法非常簡單。例如,發出一個 `GET` 請求,你會寫:
+
+```Python
+response = requests.get("http://example.com/some/url")
+```
+
+相對地,FastAPI 的 API 路徑操作(path operation)可能像這樣:
+
+```Python hl_lines="1"
+@app.get("/some/url")
+def read_url():
+ return {"message": "Hello World"}
+```
+
+看看 `requests.get(...)` 與 `@app.get(...)` 的相似之處。
+
+/// check | 啟發 **FastAPI**
+
+* 擁有簡單直觀的 API。
+* 直接使用 HTTP 方法名稱(操作),以直接、直觀的方式表達。
+* 具備合理的預設值,同時提供強大的自訂能力。
+
+///
+
+### Swagger / OpenAPI { #swagger-openapi }
+
+我想從 Django REST Framework 得到的主要功能是自動 API 文件。
+
+後來我發現有一個使用 JSON(或 YAML,JSON 的延伸)來描述 API 的標準,叫做 Swagger。
+
+而且已有對 Swagger API 的網頁使用者介面。因此,只要能為 API 產生 Swagger 文件,就可以自動使用這個網頁介面。
+
+之後 Swagger 交由 Linux 基金會管理,並更名為 OpenAPI。
+
+因此,談到 2.0 版時常說「Swagger」,而 3+ 版則是「OpenAPI」。
+
+/// check | 啟發 **FastAPI**
+
+採用並使用開放的 API 規格標準,而非自訂格式。
+
+並整合基於標準的使用者介面工具:
+
+* Swagger UI
+* ReDoc
+
+選擇這兩個是因為它們相當受歡迎且穩定,但稍加搜尋,你會發現有數十種 OpenAPI 的替代使用者介面(都能與 **FastAPI** 一起使用)。
+
+///
+
+### Flask 的 REST 框架 { #flask-rest-frameworks }
+
+有幾個 Flask 的 REST 框架,但在投入時間調查後,我發現許多已停止維護或被棄置,且存在一些關鍵問題使之不適用。
+
+### Marshmallow { #marshmallow }
+
+API 系統需要的主要功能之一是資料「序列化」,也就是把程式中的資料(Python)轉成能透過網路傳輸的形式。例如,將含有資料庫資料的物件轉成 JSON 物件、把 `datetime` 物件轉成字串等等。
+
+API 需要的另一個重要功能是資料驗證,確保資料在特定條件下有效。例如,某個欄位必須是 `int`,而不是隨便的字串。這對於輸入資料特別有用。
+
+沒有資料驗證系統的話,你就得在程式碼中手動逐一檢查。
+
+這些功能正是 Marshmallow 所要提供的。它是很棒的函式庫,我之前也大量使用。
+
+但它誕生於 Python 型別提示出現之前。因此,為了定義每個 結構(schema),你需要使用 Marshmallow 提供的特定工具與類別。
+
+/// check | 啟發 **FastAPI**
+
+用程式碼定義能自動提供資料型別與驗證的「schemas」。
+
+///
+
+### Webargs { #webargs }
+
+API 所需的另一項大功能,是從傳入請求中解析資料。
+
+Webargs 是在多個框架(包含 Flask)之上提供該功能的工具。
+
+它底層使用 Marshmallow 來做資料驗證,且由同一群開發者建立。
+
+它是一個很棒的工具,在有 **FastAPI** 之前我也經常使用。
+
+/// info
+
+Webargs 由與 Marshmallow 相同的開發者創建。
+
+///
+
+/// check | 啟發 **FastAPI**
+
+自動驗證傳入請求資料。
+
+///
+
+### APISpec { #apispec }
+
+Marshmallow 與 Webargs 以外掛提供驗證、解析與序列化。
+
+但文件仍然缺失,於是 APISpec 出現了。
+
+它是多個框架的外掛(Starlette 也有對應外掛)。
+
+它的作法是:你在處理路由的每個函式的 docstring 中,用 YAML 格式撰寫結構定義。
+
+然後它會產生 OpenAPI schemas。
+
+在 Flask、Starlette、Responder 等框架中都是這樣運作。
+
+但這又帶來一個問題:在 Python 字串中(大型 YAML)加入一段微語法。
+
+編輯器幫不上太多忙。而且如果我們修改了參數或 Marshmallow 的 schemas 卻忘了同步修改 YAML docstring,產生的結構就會過時。
+
+/// info
+
+APISpec 由與 Marshmallow 相同的開發者創建。
+
+///
+
+/// check | 啟發 **FastAPI**
+
+支援 API 的開放標準 OpenAPI。
+
+///
+
+### Flask-apispec { #flask-apispec }
+
+這是一個 Flask 外掛,把 Webargs、Marshmallow 與 APISpec 串在一起。
+
+它使用 Webargs 與 Marshmallow 的資訊,透過 APISpec 自動產生 OpenAPI 結構。
+
+它是個很棒但被低估的工具。它理應比許多 Flask 外掛更受歡迎,可能因為它的文件過於簡潔與抽象。
+
+這解決了在 Python 文件字串中撰寫 YAML(另一種語法)的问题。
+
+在打造 **FastAPI** 前,我最喜歡的後端技術組合就是 Flask、Flask-apispec、Marshmallow 與 Webargs。
+
+使用它促成了數個 Flask 全端(full-stack)產生器。這些是我(以及若干外部團隊)至今主要使用的技術組合:
+
+* https://github.com/tiangolo/full-stack
+* https://github.com/tiangolo/full-stack-flask-couchbase
+* https://github.com/tiangolo/full-stack-flask-couchdb
+
+而這些全端產生器,也成為了 [**FastAPI** 專案產生器](project-generation.md){.internal-link target=_blank} 的基礎。
+
+/// info
+
+Flask-apispec 由與 Marshmallow 相同的開發者創建。
+
+///
+
+/// check | 啟發 **FastAPI**
+
+從定義序列化與驗證的相同程式碼,自動產生 OpenAPI 結構(schema)。
+
+///
+
+### NestJS(與 Angular) { #nestjs-and-angular }
+
+這甚至不是 Python。NestJS 是受 Angular 啟發的 JavaScript(TypeScript)NodeJS 框架。
+
+它達成的效果與 Flask-apispec 能做的有點相似。
+
+它有一套受 Angular 2 啟發的整合式相依性注入(Dependency Injection)系統。需要預先註冊「可注入」元件(就像我所知的其他相依性注入系統一樣),因此會增加冗長與重複程式碼。
+
+由於參數以 TypeScript 型別描述(與 Python 型別提示相似),編輯器支援相當不錯。
+
+但因為 TypeScript 的型別在編譯成 JavaScript 後不會被保留,它無法僅靠型別同時定義驗證、序列化與文件。由於這點以及部分設計決定,若要取得驗證、序列化與自動結構產生,就需要在許多地方加上裝飾器,因此會相當冗長。
+
+它無法很好地處理巢狀模型。若請求的 JSON 主體中有內層欄位,且這些內層欄位又是巢狀 JSON 物件,就無法被妥善地文件化與驗證。
+
+/// check | 啟發 **FastAPI**
+
+使用 Python 型別以獲得優秀的編輯器支援。
+
+提供強大的相依性注入系統,並想辦法將重複程式碼降到最低。
+
+///
+
+### Sanic { #sanic }
+
+它是最早基於 `asyncio` 的極高速 Python 框架之一,並做得很像 Flask。
+
+/// note | 技術細節
+
+它使用 `uvloop` 取代預設的 Python `asyncio` 事件圈。這也是它如此之快的原因。
+
+它明顯啟發了 Uvicorn 與 Starlette,而在公開的基準測試中,它們目前比 Sanic 更快。
+
+///
+
+/// check | 啟發 **FastAPI**
+
+想辦法達到瘋狂的效能。
+
+這就是為什麼 **FastAPI** 建立於 Starlette 之上,因為它是可用的最快框架(由第三方評測)。
+
+///
+
+### Falcon { #falcon }
+
+Falcon 是另一個高效能 Python 框架,設計上極簡,並作為其他框架(如 Hug)的基礎。
+
+它設計為函式接收兩個參數,一個是「request」,一個是「response」。然後你從 request「讀取」資料、往 response「寫入」資料。由於這種設計,無法使用標準的 Python 型別提示,直接以函式參數宣告請求參數與主體。
+
+因此,資料驗證、序列化與文件必須以程式碼手動完成,無法自動化。或者需在 Falcon 之上實作另一層框架(如 Hug)。其他受 Falcon 設計啟發的框架也有同樣的區別:將 request 與 response 物件作為參數。
+
+/// check | 啟發 **FastAPI**
+
+設法取得優秀的效能。
+
+連同 Hug(Hug 建立於 Falcon 之上)一起,也啟發 **FastAPI** 在函式中宣告一個 `response` 參數。
+
+不過在 FastAPI 中它是可選的,主要用來設定標頭、Cookie 與替代狀態碼。
+
+///
+
+### Molten { #molten }
+
+我在 **FastAPI** 打造的早期發現了 Molten。它有一些相當類似的想法:
+
+* 基於 Python 型別提示。
+* 從這些型別取得驗證與文件。
+* 相依性注入系統。
+
+它沒有使用像 Pydantic 這樣的第三方資料驗證、序列化與文件庫,而是有自己的。因此,這些資料型別定義較不容易重複使用。
+
+它需要更為冗長的設定。而且因為它基於 WSGI(而非 ASGI),並未設計來享受如 Uvicorn、Starlette、Sanic 等工具所提供的高效能。
+
+其相依性注入系統需要預先註冊依賴,並且依據宣告的型別來解析依賴。因此,無法宣告多個能提供相同型別的「元件」。
+
+路由需要在單一地方宣告,使用在其他地方宣告的函式(而不是用可以直接放在端點處理函式上方的裝飾器)。這更接近 Django 的作法,而不是 Flask(與 Starlette)的作法。它在程式碼中分離了其實相當緊密耦合的事物。
+
+/// check | 啟發 **FastAPI**
+
+用模型屬性的「預設值」來定義資料型別的額外驗證。這提升了編輯器支援,而這在當時的 Pydantic 還不支援。
+
+這實際上也啟發了 Pydantic 的部分更新,以支援相同的驗證宣告風格(這些功能現在已在 Pydantic 中可用)。
+
+///
+
+### Hug { #hug }
+
+Hug 是最早使用 Python 型別提示來宣告 API 參數型別的框架之一。這是個很棒的點子,也啟發了其他工具。
+
+它在宣告中使用自訂型別而非標準 Python 型別,但仍然是巨大的一步。
+
+它也是最早能以 JSON 產出自訂結構、描述整個 API 的框架之一。
+
+它不是基於 OpenAPI 與 JSON Schema 等標準。因此,與其他工具(如 Swagger UI)的整合並不直覺。但它仍是一個非常創新的想法。
+
+它有個有趣、少見的功能:同一個框架可同時建立 API 與 CLI。
+
+由於它基於同步 Python 網頁框架的舊標準(WSGI),無法處理 WebSocket 與其他功能,儘管效能仍然很高。
+
+/// info
+
+Hug 由 Timothy Crosley 創建,他同時也是 `isort` 的作者,一個自動排序 Python 匯入的好工具。
+
+///
+
+/// check | 啟發 **FastAPI** 的想法
+
+Hug 啟發了 APIStar 的部分設計,也是我覺得最有前景的工具之一,與 APIStar 並列。
+
+Hug 啟發 **FastAPI** 使用 Python 型別提示宣告參數,並自動產生定義 API 的結構。
+
+Hug 啟發 **FastAPI** 在函式中宣告 `response` 參數以設定標頭與 Cookie。
+
+///
+
+### APIStar (<= 0.5) { #apistar-0-5 }
+
+在決定打造 **FastAPI** 之前,我找到了 **APIStar** 伺服器。它幾乎具備我所尋找的一切,而且設計很出色。
+
+它是我見過最早使用 Python 型別提示來宣告參數與請求的框架實作之一(早於 NestJS 與 Molten)。我與 Hug 幾乎在同時間發現它。不過 APIStar 使用的是 OpenAPI 標準。
+
+它基於相同的型別提示,在多處自動進行資料驗證、資料序列化與 OpenAPI 結構產生。
+
+主體結構(body schema)的定義並未使用像 Pydantic 那樣的 Python 型別提示,更像 Marshmallow,因此編輯器支援沒有那麼好,但整體而言,APIStar 是當時最好的選擇。
+
+它在當時的效能評測中名列前茅(僅被 Starlette 超越)。
+
+一開始它沒有自動 API 文件的網頁 UI,但我知道我可以替它加上 Swagger UI。
+
+它有相依性注入系統。需要預先註冊元件,與上面提到的其他工具相同。不過這仍是很棒的功能。
+
+我從未能在完整專案中使用它,因為它沒有安全性整合,所以無法取代我用 Flask-apispec 全端產生器所擁有的全部功能。我曾把新增該功能的 pull request 放在待辦清單中。
+
+但之後,專案的重心改變了。
+
+它不再是 API 網頁框架,因為作者需要專注於 Starlette。
+
+現在的 APIStar 是一套用於驗證 OpenAPI 規格的工具,不是網頁框架。
+
+/// info
+
+APIStar 由 Tom Christie 創建。他也創建了:
+
+* Django REST Framework
+* Starlette(**FastAPI** 建立於其上)
+* Uvicorn(Starlette 與 **FastAPI** 使用)
+
+///
+
+/// check | 啟發 **FastAPI**
+
+存在。
+
+用相同的 Python 型別同時宣告多件事(資料驗證、序列化與文件),並同時提供出色的編輯器支援,這是一個極好的點子。
+
+在長時間尋找並測試多種不同替代方案後,APIStar 是最好的可用選擇。
+
+當 APIStar 不再作為伺服器存在,而 Starlette 誕生並成為更好的基礎時,這成為打造 **FastAPI** 的最後一個靈感。
+
+我將 **FastAPI** 視為 APIStar 的「精神繼承者」,同時基於所有這些先前工具的經驗,改進並擴增了功能、型別系統與其他部分。
+
+///
+
+## **FastAPI** 所採用的工具 { #used-by-fastapi }
+
+### Pydantic { #pydantic }
+
+Pydantic 是基於 Python 型別提示,定義資料驗證、序列化與文件(使用 JSON Schema)的函式庫。
+
+這讓它非常直覺。
+
+它可與 Marshmallow 相提並論。儘管在效能測試中它比 Marshmallow 更快。而且因為它基於相同的 Python 型別提示,編輯器支援也很出色。
+
+/// check | **FastAPI** 用於
+
+處理所有資料驗證、資料序列化與自動模型文件(基於 JSON Schema)。
+
+**FastAPI** 接著會把這些 JSON Schema 資料放入 OpenAPI 中,此外還有其他許多功能。
+
+///
+
+### Starlette { #starlette }
+
+Starlette 是一個輕量的 ASGI 框架/工具集,非常適合用來建構高效能的 asyncio 服務。
+
+它非常簡單直觀。設計上易於擴充,且元件化。
+
+它具備:
+
+* 令人印象深刻的效能。
+* WebSocket 支援。
+* 行程內(in-process)背景任務。
+* 啟動與關閉事件。
+* 建立在 HTTPX 上的測試用戶端。
+* CORS、GZip、靜態檔案、串流回應。
+* Session 與 Cookie 支援。
+* 100% 測試涵蓋率。
+* 100% 型別註解的程式碼庫。
+* 幾乎沒有硬性相依。
+
+Starlette 目前是測試中最快的 Python 框架。僅次於 Uvicorn(它不是框架,而是伺服器)。
+
+Starlette 提供所有網頁微框架的基礎功能。
+
+但它不提供自動的資料驗證、序列化或文件。
+
+這正是 **FastAPI** 在其上方加入的主要功能之一,且全部基於 Python 型別提示(使用 Pydantic)。此外還有相依性注入系統、安全性工具、OpenAPI 結構產生等。
+
+/// note | 技術細節
+
+ASGI 是由 Django 核心團隊成員正在開發的新「標準」。它尚未成為「Python 標準」(PEP),但他們正著手進行中。
+
+儘管如此,它已被多個工具作為「標準」採用。這大幅提升了互通性,例如你可以把 Uvicorn 換成其他 ASGI 伺服器(如 Daphne 或 Hypercorn),或加入相容 ASGI 的工具,如 `python-socketio`。
+
+///
+
+/// check | **FastAPI** 用於
+
+處理所有核心網頁部分,並在其上加上功能。
+
+`FastAPI` 這個類別本身直接繼承自 `Starlette` 類別。
+
+因此,凡是你能用 Starlette 做的事,你幾乎都能直接用 **FastAPI** 完成,因為它基本上就是加強版的 Starlette。
+
+///
+
+### Uvicorn { #uvicorn }
+
+Uvicorn 是基於 uvloop 與 httptools 的極速 ASGI 伺服器。
+
+它不是網頁框架,而是伺服器。例如,它不提供依據路徑路由的工具。這是像 Starlette(或 **FastAPI**)這樣的框架在其上方提供的功能。
+
+它是 Starlette 與 **FastAPI** 推薦使用的伺服器。
+
+/// check | **FastAPI** 建議用作
+
+執行 **FastAPI** 應用的主要網頁伺服器。
+
+你也可以使用 `--workers` 命令列選項,取得非同步的多製程伺服器。
+
+更多細節請見[部署](deployment/index.md){.internal-link target=_blank}章節。
+
+///
+
+## 效能與速度 { #benchmarks-and-speed }
+
+想了解、比較並看出 Uvicorn、Starlette 與 FastAPI 之間的差異,請參考[效能評測](benchmarks.md){.internal-link target=_blank}。
diff --git a/docs/zh-hant/docs/async.md b/docs/zh-hant/docs/async.md
index 09e2bf994..a03d71815 100644
--- a/docs/zh-hant/docs/async.md
+++ b/docs/zh-hant/docs/async.md
@@ -1,10 +1,10 @@
-# 並行與 async / await
+# 並行與 async / await { #concurrency-and-async-await }
有關*路徑操作函式*的 `async def` 語法的細節與非同步 (asynchronous) 程式碼、並行 (concurrency) 與平行 (parallelism) 的一些背景知識。
-## 趕時間嗎?
+## 趕時間嗎? { #in-a-hurry }
-TL;DR:
+TL;DR:
如果你正在使用要求你以 `await` 語法呼叫的第三方函式庫,例如:
@@ -41,7 +41,7 @@ def results():
---
-如果你的應用程式不需要與外部資源進行任何通訊並等待其回應,請使用 `async def`。
+如果你的應用程式不需要與外部資源進行任何通訊並等待其回應,請使用 `async def`,即使內部不需要使用 `await` 也可以。
---
@@ -55,7 +55,7 @@ def results():
但透過遵循上述步驟,它將能進行一些效能最佳化。
-## 技術細節
+## 技術細節 { #technical-details }
現代版本的 Python 支援使用 **「協程」** 的 **`async` 和 `await`** 語法來寫 **「非同步程式碼」**。
@@ -65,7 +65,7 @@ def results():
* **`async` 和 `await`**
* **協程**
-## 非同步程式碼
+## 非同步程式碼 { #asynchronous-code }
非同步程式碼僅意味著程式語言 💬 有辦法告訴電腦/程式 🤖 在程式碼中的某個點,它 🤖 需要等待某些事情完成。讓我們假設這些事情被稱為「慢速檔案」📝。
@@ -74,7 +74,7 @@ def results():
接著程式 🤖 會在有空檔時回來查看是否有等待的工作已經完成,並執行必要的後續操作。
接下來,它 🤖 完成第一個工作(例如我們的「慢速檔案」📝)並繼續執行相關的所有操作。
-這個「等待其他事情」通常指的是一些相對較慢的(與處理器和 RAM 記憶體的速度相比)的 I/O 操作,比如說:
+這個「等待其他事情」通常指的是一些相對較慢的(與處理器和 RAM 記憶體的速度相比)的 I/O 操作,比如說:
* 透過網路傳送來自用戶端的資料
* 從網路接收來自用戶端的資料
@@ -85,7 +85,7 @@ def results():
* 資料庫查詢
* 等等
-由於大部分的執行時間都消耗在等待 I/O 操作上,因此這些操作被稱為 "I/O 密集型" 操作。
+由於大部分的執行時間都消耗在等待 I/O 操作上,因此這些操作被稱為 "I/O 密集型" 操作。
之所以稱為「非同步」,是因為電腦/程式不需要與那些耗時的任務「同步」,等待任務完成的精確時間,然後才能取得結果並繼續工作。
@@ -93,7 +93,7 @@ def results():
相對於「非同步」(asynchronous),「同步」(synchronous)也常被稱作「順序性」(sequential),因為電腦/程式會依序執行所有步驟,即便這些步驟涉及等待,才會切換到其他任務。
-### 並行與漢堡
+### 並行與漢堡 { #concurrency-and-burgers }
上述非同步程式碼的概念有時也被稱為「並行」,它不同於「平行」。
@@ -103,7 +103,7 @@ def results():
為了理解差異,請想像以下有關漢堡的故事:
-### 並行漢堡
+### 並行漢堡 { #concurrent-burgers }
你和你的戀人去速食店,排隊等候時,收銀員正在幫排在你前面的人點餐。😍
@@ -163,7 +163,7 @@ def results():
然後你走向櫃檯 🔀,回到已經完成的最初任務 ⏯,拿起漢堡,說聲謝謝,並帶回桌上。這就結束了與櫃檯的互動步驟/任務 ⏹,接下來會產生一個新的任務,「吃漢堡」 🔀 ⏯,而先前的「拿漢堡」任務已經完成了 ⏹。
-### 平行漢堡
+### 平行漢堡 { #parallel-burgers }
現在,讓我們來想像這裡不是「並行漢堡」,而是「平行漢堡」。
@@ -233,7 +233,7 @@ def results():
所以,你不會想帶你的戀人 😍 一起去銀行辦事 🏦。
-### 漢堡結論
+### 漢堡結論 { #burger-conclusion }
在「和戀人一起吃速食漢堡」的這個場景中,由於有大量的等待 🕙,使用並行系統 ⏸🔀⏯ 更有意義。
@@ -253,7 +253,7 @@ def results():
你可以同時利用並行性和平行性,進一步提升效能,這比大多數已測試的 NodeJS 框架都更快,並且與 Go 語言相當,而 Go 是一種更接近 C 的編譯語言(感謝 Starlette)。
-### 並行比平行更好嗎?
+### 並行比平行更好嗎? { #is-concurrency-better-than-parallelism }
不是的!這不是故事的本意。
@@ -277,7 +277,7 @@ def results():
在這個場景中,每個清潔工(包括你)都是一個處理器,完成工作的一部分。
-由於大多數的執行時間都花在實際的工作上(而不是等待),而電腦中的工作由 CPU 完成,因此這些問題被稱為「CPU 密集型」。
+由於大多數的執行時間都花在實際的工作上(而不是等待),而電腦中的工作由 CPU 完成,因此這些問題被稱為「CPU 密集型」。
---
@@ -290,7 +290,7 @@ def results():
* **機器學習**: 通常需要大量的「矩陣」和「向量」運算。想像一個包含數字的巨大電子表格,並所有的數字同時相乘;
* **深度學習**: 這是機器學習的子領域,同樣適用。只不過這不僅僅是一張數字表格,而是大量的數據集合,並且在很多情況下,你會使用特殊的處理器來構建或使用這些模型。
-### 並行 + 平行: Web + 機器學習
+### 並行 + 平行: Web + 機器學習 { #concurrency-parallelism-web-machine-learning }
使用 **FastAPI**,你可以利用並行的優勢,這在 Web 開發中非常常見(這也是 NodeJS 的最大吸引力)。
@@ -300,9 +300,9 @@ def results():
想了解如何在生產環境中實現這種平行性,請參見 [部屬](deployment/index.md){.internal-link target=_blank}。
-## `async` 和 `await`
+## `async` 和 `await` { #async-and-await }
-現代 Python 版本提供一種非常直觀的方式定義非同步程式碼。這使得它看起來就像正常的「順序」程式碼,並在適當的時機「等待」。
+現代 Python 版本提供一種非常直觀的方式定義非同步程式碼。這使得它看起來就像正常的「順序」程式碼,並在適當的時機替你「等待」。
當某個操作需要等待才能回傳結果,並且支援這些新的 Python 特性時,你可以像這樣編寫程式碼:
@@ -329,7 +329,7 @@ def get_sequential_burgers(number: int):
return burgers
```
-使用 `async def`,Python Python 知道在該函式內需要注意 `await`,並且它可以「暫停」 ⏸ 執行該函式,然後執行其他任務 🔀 後回來。
+使用 `async def`,Python 知道在該函式內需要注意 `await`,並且它可以「暫停」 ⏸ 執行該函式,然後執行其他任務 🔀 後回來。
當你想要呼叫 `async def` 函式時,必須使用「await」。因此,這樣寫將無法運行:
@@ -349,11 +349,11 @@ async def read_burgers():
return burgers
```
-### 更多技術細節
+### 更多技術細節 { #more-technical-details }
你可能已經注意到,`await` 只能在 `async def` 定義的函式內使用。
-但同時,使用 `async def` 定義的函式本身也必須被「等待」。所以,帶有 `async def` 函式只能在其他使用 `async def` 定義的函式內呼叫。
+但同時,使用 `async def` 定義的函式本身也必須被「等待」。所以,帶有 `async def` 的函式只能在其他使用 `async def` 定義的函式內呼叫。
那麼,這就像「先有雞還是先有蛋」的問題,要如何呼叫第一個 `async` 函式呢?
@@ -361,35 +361,37 @@ async def read_burgers():
但如果你想在沒有 FastAPI 的情況下使用 `async` / `await`,你也可以這樣做。
-### 編寫自己的非同步程式碼
+### 編寫自己的非同步程式碼 { #write-your-own-async-code }
-Starlette (和 **FastAPI**) 是基於 AnyIO 實作的,這使得它們與 Python 標準函式庫相容 asyncio 和 Trio。
+Starlette(和 **FastAPI**)是基於 AnyIO 實作的,這使得它們與 Python 標準函式庫 asyncio 和 Trio 相容。
特別是,你可以直接使用 AnyIO 來處理更複雜的並行使用案例,這些案例需要你在自己的程式碼中使用更高階的模式。
-即使你不使用 **FastAPI**,你也可以使用 AnyIO 來撰寫自己的非同步應用程式,並獲得高相容性及一些好處(例如結構化並行)。
+即使你不使用 **FastAPI**,你也可以使用 AnyIO 來撰寫自己的非同步應用程式,並獲得高相容性及一些好處(例如「結構化並行」)。
-### 其他形式的非同步程式碼
+我另外在 AnyIO 之上做了一個薄封裝的函式庫,稍微改進型別註解以獲得更好的**自動補全**、**即時錯誤**等。同時它也提供友善的介紹與教學,幫助你**理解**並撰寫**自己的非同步程式碼**:Asyncer。當你需要**將非同步程式碼與一般**(阻塞/同步)**程式碼整合**時,它特別實用。
+
+### 其他形式的非同步程式碼 { #other-forms-of-asynchronous-code }
使用 `async` 和 `await` 的風格在語言中相對較新。
-但它使處理異步程式碼變得更加容易。
+但它使處理非同步程式碼變得更加容易。
相同的語法(或幾乎相同的語法)最近也被包含在現代 JavaScript(無論是瀏覽器還是 NodeJS)中。
-但在此之前,處理異步程式碼要更加複雜和困難。
+但在此之前,處理非同步程式碼要更加複雜和困難。
在較舊的 Python 版本中,你可能會使用多執行緒或 Gevent。但這些程式碼要更難以理解、調試和思考。
在較舊的 NodeJS / 瀏覽器 JavaScript 中,你會使用「回呼」,這可能會導致“回呼地獄”。
-## 協程
+## 協程 { #coroutines }
-**協程** 只是 `async def` 函式所回傳的非常特殊的事物名稱。Python 知道它是一個類似函式的東西,可以啟動它,並且在某個時刻它會結束,但它也可能在內部暫停 ⏸,只要遇到 `await`。
+「協程」只是 `async def` 函式所回傳的非常特殊的事物名稱。Python 知道它是一個類似函式的東西,可以啟動它,並且在某個時刻它會結束,但它也可能在內部暫停 ⏸,只要遇到 `await`。
這種使用 `async` 和 `await` 的非同步程式碼功能通常被概括為「協程」。這與 Go 語言的主要特性「Goroutines」相似。
-## 結論
+## 結論 { #conclusion }
讓我們再次回顧之前的句子:
@@ -397,9 +399,9 @@ Starlette (和 **FastAPI**) 是基於 I/O 的程式碼。
+如果你來自於其他不以這種方式運作的非同步框架,而且你習慣於使用普通的 `def` 定義僅進行簡單計算的*路徑操作函式*,目的是獲得微小的性能增益(大約 100 奈秒),請注意,在 FastAPI 中,效果會完全相反。在這些情況下,最好使用 `async def`,除非你的*路徑操作函式*執行阻塞的 I/O 的程式碼。
-不過,在這兩種情況下,**FastAPI** [仍然很快](index.md#_11){.internal-link target=_blank}至少與你之前的框架相當(或者更快)。
+不過,在這兩種情況下,**FastAPI** [仍然很快](index.md#performance){.internal-link target=_blank},至少與你之前的框架相當(或者更快)。
-### 依賴項(Dependencies)
+### 依賴項(Dependencies) { #dependencies }
同樣適用於[依賴項](tutorial/dependencies/index.md){.internal-link target=_blank}。如果依賴項是一個標準的 `def` 函式,而不是 `async def`,那麼它在外部的執行緒池被運行。
-### 子依賴項
+### 子依賴項 { #sub-dependencies }
-你可以擁有多個相互依賴的依賴項和[子依賴項](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作為函式定義的參數),其中一些可能是用 `async def` 宣告,也可能是用 `def` 宣告。它們仍然可以正常運作,用 `def` 定義的那些將會在外部的執行緒中呼叫(來自執行緒池),而不是被「等待」。
+你可以擁有多個相互依賴的依賴項和[子依賴項](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank}(作為函式定義的參數),其中一些可能是用 `async def` 宣告,也可能是用 `def` 宣告。它們仍然可以正常運作,用 `def` 定義的那些將會在外部的執行緒中呼叫(來自執行緒池),而不是被「等待」。
-### 其他輔助函式
+### 其他輔助函式 { #other-utility-functions }
你可以直接呼叫任何使用 `def` 或 `async def` 建立的其他輔助函式,FastAPI 不會影響你呼叫它們的方式。
@@ -439,4 +441,4 @@ Starlette (和 **FastAPI**) 是基於 趕時間嗎?.
+否則,只需遵循上面提到的指引即可:趕時間嗎?。
diff --git a/docs/zh-hant/docs/benchmarks.md b/docs/zh-hant/docs/benchmarks.md
index df49621c5..c5b76700b 100644
--- a/docs/zh-hant/docs/benchmarks.md
+++ b/docs/zh-hant/docs/benchmarks.md
@@ -6,7 +6,7 @@
## 基準測試和速度 { #benchmarks-and-speed }
-當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。
+當你查看基準測試時,常見到不同類型的多個工具被視為等同來比較。
具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。
@@ -20,7 +20,7 @@
* **Uvicorn**:
* 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。
- * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。
+ * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷,且無法像使用框架那樣減少應用程式程式碼與錯誤。
* 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。
* **Starlette**:
* 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。
diff --git a/docs/zh-hant/docs/deployment/concepts.md b/docs/zh-hant/docs/deployment/concepts.md
new file mode 100644
index 000000000..0cca31d26
--- /dev/null
+++ b/docs/zh-hant/docs/deployment/concepts.md
@@ -0,0 +1,321 @@
+# 部署概念 { #deployments-concepts }
+
+當你要部署一個 FastAPI 應用,或其實任何類型的 Web API 時,有幾個你可能在意的概念。掌握這些概念後,你就能找出最適合部署你應用的方式。
+
+一些重要的概念包括:
+
+- 安全性 - HTTPS
+- 開機自動執行
+- 重新啟動
+- 複本(執行中的行程數量)
+- 記憶體
+- 啟動前的前置步驟
+
+我們將看看它們如何影響部署。
+
+最終目標是能夠以安全、避免中斷,並盡可能高效使用運算資源(例如遠端伺服器/虛擬機)的方式來服務你的 API 用戶端。🚀
+
+我會在這裡多介紹一些這些觀念,希望能幫你建立必要的直覺,讓你能在非常不同、甚至尚未出現的未來環境中決定要如何部署你的 API。
+
+在思考這些概念之後,你將能夠評估與設計最適合部署你自己 API 的方式。
+
+在接下來的章節,我會提供更具體的部署 FastAPI 應用的食譜。
+
+但現在,先來看看這些重要的概念想法。這些概念同樣適用於任何其他類型的 Web API。💡
+
+## 安全性 - HTTPS { #security-https }
+
+在[前一章關於 HTTPS](https.md){.internal-link target=_blank} 中,我們學到 HTTPS 如何為你的 API 提供加密。
+
+我們也看到,HTTPS 通常由應用伺服器外部的元件提供,即 TLS Termination Proxy。
+
+而且必須有某個東西負責續期 HTTPS 憑證,可能是同一個元件,也可能是不同的東西。
+
+### HTTPS 工具範例 { #example-tools-for-https }
+
+你可以用來作為 TLS Termination Proxy 的工具包括:
+
+- Traefik
+ - 自動處理憑證續期 ✨
+- Caddy
+ - 自動處理憑證續期 ✨
+- Nginx
+ - 搭配像 Certbot 這類外部元件進行憑證續期
+- HAProxy
+ - 搭配像 Certbot 這類外部元件進行憑證續期
+- Kubernetes,使用如 Nginx 的 Ingress Controller
+ - 搭配像 cert-manager 這類外部元件進行憑證續期
+- 由雲端供應商在其服務內部處理(見下文 👇)
+
+另一個選項是使用能幫你做更多事情的雲端服務(包含設定 HTTPS)。它可能有一些限制或要額外付費等。但在那種情況下,你就不必自己設定 TLS Termination Proxy。
+
+我會在後續章節展示一些具體例子。
+
+---
+
+接下來要考慮的概念都與實際執行你的 API 的程式(例如 Uvicorn)有關。
+
+## 程式與行程 { #program-and-process }
+
+我們會常提到執行中的「行程(process)」,因此先釐清它的意思,以及與「程式(program)」的差異很有幫助。
+
+### 什麼是程式 { #what-is-a-program }
+
+「程式(program)」一詞常用來描述許多東西:
+
+- 你寫的原始碼,也就是 Python 檔案。
+- 可由作業系統執行的檔案,例如:`python`、`python.exe` 或 `uvicorn`。
+- 在作業系統上執行中的特定程式,使用 CPU 並將資料存於記憶體。這也稱為「行程」。
+
+### 什麼是行程 { #what-is-a-process }
+
+「行程(process)」通常以更特定的方式使用,只指作業系統中正在執行的東西(如上面最後一點):
+
+- 在作業系統上「執行中」的特定程式。
+ - 這不是指檔案或原始碼,而是特指正在被作業系統執行並管理的那個東西。
+- 任何程式、任何程式碼,只有在「被執行」時才能做事。所以,當有「行程在執行」時才能運作。
+- 行程可以被你或作業系統終止(kill)。此時它就停止執行,無法再做任何事。
+- 你電腦上執行的每個應用程式、每個視窗等,背後都有一些行程。而且在電腦開機時,通常會同時有許多行程在跑。
+- 同一個程式可以同時有多個行程在執行。
+
+如果你打開作業系統的「工作管理員」或「系統監控器」(或類似工具),就能看到許多正在執行的行程。
+
+例如,你大概會看到同一個瀏覽器(Firefox、Chrome、Edge 等)會有多個行程在執行。它們通常每個分頁一個行程,外加其他一些額外行程。
+
+
+
+---
+
+現在我們知道「行程」與「程式」的差異了,繼續談部署。
+
+## 開機自動執行 { #running-on-startup }
+
+多數情況下,當你建立一個 Web API,你會希望它「一直在執行」,不中斷,讓客戶端隨時可用。除非你有特定理由只在某些情況下才執行,但大部分時候你會希望它持續運作並且可用。
+
+### 在遠端伺服器上 { #in-a-remote-server }
+
+當你設定一台遠端伺服器(雲端伺服器、虛擬機等),最簡單的作法就是像本機開發時一樣,手動使用 `fastapi run`(它使用 Uvicorn)或類似的方式。
+
+這在「開發期間」會運作良好而且有用。
+
+但如果你與伺服器的連線中斷,正在執行的行程很可能會死掉。
+
+而如果伺服器被重新啟動(例如更新後、或雲端供應商進行遷移),你大概「不會注意到」。因此你甚至不知道要手動重啟行程。你的 API 就會一直掛著。😱
+
+### 開機自動啟動 { #run-automatically-on-startup }
+
+通常你會希望伺服器程式(例如 Uvicorn)在伺服器開機時自動啟動,且不需任何「人工介入」,讓你的 API(例如 Uvicorn 執行你的 FastAPI 應用)總是有行程在跑。
+
+### 獨立程式 { #separate-program }
+
+為了達成這點,你通常會有一個「獨立的程式」來確保你的應用在開機時會被啟動。很多情況下,它也會確保其他元件或應用一併啟動,例如資料庫。
+
+### 開機自動啟動的工具範例 { #example-tools-to-run-at-startup }
+
+能做到這件事的工具包括:
+
+- Docker
+- Kubernetes
+- Docker Compose
+- Docker 的 Swarm 模式
+- Systemd
+- Supervisor
+- 由雲端供應商在其服務內部處理
+- 其他...
+
+我會在後續章節給出更具體的例子。
+
+## 重新啟動 { #restarts }
+
+和確保你的應用在開機時會執行一樣,你大概也會希望在發生失敗之後,它能「自動重新啟動」。
+
+### 人都會犯錯 { #we-make-mistakes }
+
+我們身為人,常常會犯錯。軟體幾乎總是有藏在各處的「臭蟲(bugs)」🐛
+
+而我們開發者會在發現這些 bug 後持續改進程式碼、實作新功能(也可能順便加進新的 bug 😅)。
+
+### 小錯誤自動處理 { #small-errors-automatically-handled }
+
+使用 FastAPI 建構 Web API 時,如果我們的程式碼出錯,FastAPI 通常會把它限制在觸發該錯誤的單次請求之中。🛡
+
+用戶端會收到「500 Internal Server Error」,但應用會繼續處理之後的請求,而不是整個崩潰。
+
+### 更嚴重的錯誤 - 當機 { #bigger-errors-crashes }
+
+然而,仍可能有一些情況,我們寫的程式碼「讓整個應用當機」,使 Uvicorn 與 Python 都崩潰。💥
+
+即便如此,你大概也不會希望應用因為某處錯誤就一直處於死亡狀態,你可能會希望它「繼續運作」,至少讓沒有壞掉的「路徑操作(path operations)」能持續服務。
+
+### 當機後重新啟動 { #restart-after-crash }
+
+在這些會讓「執行中行程」整個崩潰的嚴重錯誤案例裡,你會希望有個外部元件負責「重新啟動」該行程,至少嘗試幾次...
+
+/// tip
+
+...不過,如果整個應用「一啟動就立刻」崩潰,那持續無止境地重啟大概沒有意義。但在這類情況下,你很可能會在開發過程中就發現,或至少在部署後馬上注意到。
+
+所以讓我們專注在主要情境:應用在未來某些特定案例中可能會整體崩潰,但此時重新啟動仍然是有意義的。
+
+///
+
+你大概會希望把負責重新啟動應用的東西放在「外部元件」,因為那個時候,應用本身連同 Uvicorn 與 Python 都已經掛了,在同一個應用的程式碼裡也無法做什麼。
+
+### 自動重新啟動的工具範例 { #example-tools-to-restart-automatically }
+
+多數情況下,用來「在開機時啟動程式」的同一套工具,也會負責處理自動「重新啟動」。
+
+例如,可以由下列工具處理:
+
+- Docker
+- Kubernetes
+- Docker Compose
+- Docker 的 Swarm 模式
+- Systemd
+- Supervisor
+- 由雲端供應商在其服務內部處理
+- 其他...
+
+## 複本:行程與記憶體 { #replication-processes-and-memory }
+
+在 FastAPI 應用中,使用像 `fastapi` 指令(執行 Uvicorn)的伺服器程式,即使只在「一個行程」中執行,也能同時服務多個客戶端。
+
+但很多情況下,你會想同時執行多個工作行程(workers)。
+
+### 多個行程 - Workers { #multiple-processes-workers }
+
+如果你的客戶端比單一行程所能處理的更多(例如虛擬機規格不大),而伺服器 CPU 有「多核心」,那你可以同時執行「多個行程」載入相同的應用,並把所有請求分散給它們。
+
+當你執行同一個 API 程式的「多個行程」時,通常稱為「workers(工作行程)」。
+
+### 工作行程與連接埠 { #worker-processes-and-ports }
+
+還記得文件中[關於 HTTPS](https.md){.internal-link target=_blank} 的說明嗎:在一台伺服器上,一組 IP 與連接埠的組合只能由「一個行程」監聽?
+
+這裡同樣適用。
+
+因此,若要同時擁有「多個行程」,就必須有「單一行程」在該連接埠上監聽,然後以某種方式把通信傳遞給各個工作行程。
+
+### 每個行程的記憶體 { #memory-per-process }
+
+當程式把東西載入記憶體時,例如把機器學習模型存到變數中,或把大型檔案內容讀到變數中,這些都會「消耗一些伺服器的記憶體(RAM)」。
+
+而多個行程通常「不共享記憶體」。這表示每個執行中的行程都有自己的東西、變數與記憶體。如果你的程式碼會用掉大量記憶體,「每個行程」都會消耗等量的記憶體。
+
+### 伺服器記憶體 { #server-memory }
+
+例如,如果你的程式碼載入一個「1 GB 大小」的機器學習模型,當你用一個行程執行你的 API,它就會至少吃掉 1 GB 的 RAM。若你啟動「4 個行程」(4 個 workers),每個會吃 1 GB RAM。總計你的 API 會吃掉「4 GB RAM」。
+
+如果你的遠端伺服器或虛擬機只有 3 GB RAM,嘗試載入超過 4 GB 的 RAM 就會出問題。🚨
+
+### 多個行程 - 範例 { #multiple-processes-an-example }
+
+在這個例子中,有一個「管理行程(Manager Process)」會啟動並控制兩個「工作行程(Worker Processes)」。
+
+這個管理行程大概就是在 IP 的「連接埠」上監聽的那個。它會把所有通信轉發到各個工作行程。
+
+那些工作行程才是實際執行你的應用的,它們會完成主要的計算,接收「請求」並回傳「回應」,也會把你放在變數中的東西載入 RAM。
+
+
+
+當然,同一台機器上除了你的應用之外,通常也會有「其他行程」在執行。
+
+有個有趣的細節是,每個行程的「CPU 使用率」百分比會隨時間大幅「變動」,但「記憶體(RAM)」通常維持相對「穩定」。
+
+如果你的 API 每次做的計算量相近,且客戶很多,那「CPU 使用率」也可能「相對穩定」(而不是快速上下起伏)。
+
+### 複本與擴展的工具與策略範例 { #examples-of-replication-tools-and-strategies }
+
+要達成這些有很多種作法。我會在後續章節(例如談到 Docker 與容器時)介紹更具體的策略。
+
+主要的限制是:必須有「單一」元件負責處理「公開 IP」上的「連接埠」。接著它必須能把通信「轉發」到被複製的「行程/workers」。
+
+以下是一些可能的組合與策略:
+
+- Uvicorn 搭配 `--workers`
+ - 一個 Uvicorn「管理行程」會在「IP」與「連接埠」上監聽,並啟動「多個 Uvicorn 工作行程」。
+- Kubernetes 與其他分散式「容器系統」
+ - 由「Kubernetes」層在「IP」與「連接埠」上監聽。複本的方式是有「多個容器」,每個容器內執行「一個 Uvicorn 行程」。
+- 由「雲端服務」替你處理
+ - 雲端服務很可能「替你處理複本」。它可能讓你定義「要執行的行程」或「容器映像」,無論如何,多半會是「單一 Uvicorn 行程」,而由雲端服務負責進行複製。
+
+/// tip
+
+先別擔心這裡提到的「容器」、Docker 或 Kubernetes 如果現在還不太懂。
+
+我會在未來的章節進一步說明容器映像、Docker、Kubernetes 等等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
+
+///
+
+## 啟動前的前置步驟 { #previous-steps-before-starting }
+
+很多情況下,你會希望在應用「啟動之前」先執行一些步驟。
+
+例如,你可能想先執行「資料庫遷移」。
+
+但在多數情況下,你會希望這些步驟只執行「一次」。
+
+所以,你會希望用「單一行程」來執行那些「前置步驟」,在啟動應用之前完成。
+
+而且即使之後你要為應用本身啟動「多個行程」(多個 workers),你也必須確保只有一個行程在跑那些前置步驟。若由「多個行程」去跑,會在「平行」中重複同樣的工作;而如果那些步驟像是資料庫遷移這類敏感操作,它們之間可能會互相衝突。
+
+當然,也有一些情況,重複執行前置步驟不會有問題;在那種情況下就容易處理得多。
+
+/// tip
+
+另外請記住,依照你的設定,在某些情況下你「甚至可能不需要任何前置步驟」才能啟動應用。
+
+這種情況下,你就不用為此費心了。🤷
+
+///
+
+### 前置步驟策略範例 { #examples-of-previous-steps-strategies }
+
+這會「高度取決於」你「部署系統」的方式,而且很可能與你如何啟動程式、處理重新啟動等有關。
+
+以下是一些可能的做法:
+
+- 在 Kubernetes 中使用一個「Init Container」,它會在你的應用容器之前先執行
+- 一個 bash 腳本先跑前置步驟,然後再啟動你的應用
+ - 你仍然需要有機制來啟動/重新啟動「那個」bash 腳本、偵測錯誤等
+
+/// tip
+
+我會在未來關於容器的章節提供更具體的範例:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
+
+///
+
+## 資源使用率 { #resource-utilization }
+
+你的伺服器(群)是可以被「消耗/利用」的「資源」,你的程式會使用 CPU 的計算時間,以及可用的 RAM 記憶體。
+
+你想要消耗/利用多少系統資源?直覺上可能會想「不要太多」,但實際上,你大概會希望在「不當機」的前提下「盡可能用多一點」。
+
+如果你花錢租了 3 台伺服器,卻只用了它們少量的 RAM 與 CPU,那你可能是在「浪費金錢」💸、也「浪費伺服器電力」🌎 等。
+
+在那種情況下,可能更好的是只用 2 台伺服器,並以更高的比例使用它們的資源(CPU、記憶體、磁碟、網路頻寬等)。
+
+另一方面,如果你有 2 台伺服器,且你使用了它們「100% 的 CPU 與 RAM」,某個時刻一個行程會要求更多記憶體,伺服器就得用磁碟當作「記憶體」(這可能慢上數千倍),甚至「當機」。或是某個行程需要做計算時,必須等到 CPU 再度空閒。
+
+這種情況下,最好是再加一台伺服器,並在上面跑部分行程,讓所有行程都有「足夠的 RAM 與 CPU 時間」。
+
+也有機會因為某些原因,你的 API 使用量出現「尖峰」。也許它爆紅了,或是其他服務或機器人開始使用它。在這些情況下,你可能會希望留有一些額外資源以策安全。
+
+你可以設定一個「目標數字」,例如資源使用率落在「50% 到 90%」之間。重點是,這些大概就是你會想測量並用來調校部署的主要指標。
+
+你可以用像 `htop` 這樣的簡單工具,查看伺服器的 CPU 與 RAM 使用量,或各行程的使用量。也可以用更複雜的監控工具,分散式地監看多台伺服器,等等。
+
+## 重點回顧 { #recap }
+
+這裡介紹了一些你在決定如何部署應用時應該記住的主要概念:
+
+- 安全性 - HTTPS
+- 開機自動執行
+- 重新啟動
+- 複本(執行中的行程數量)
+- 記憶體
+- 啟動前的前置步驟
+
+理解這些想法與如何套用它們,應能給你足夠的直覺,在設定與調整部署時做出各種決策。🤓
+
+在接下來的章節,我會提供更多可行策略的具體範例。🚀
diff --git a/docs/zh-hant/docs/deployment/docker.md b/docs/zh-hant/docs/deployment/docker.md
new file mode 100644
index 000000000..87f4e6f9f
--- /dev/null
+++ b/docs/zh-hant/docs/deployment/docker.md
@@ -0,0 +1,618 @@
+# 在容器中使用 FastAPI - Docker { #fastapi-in-containers-docker }
+
+部署 FastAPI 應用時,一個常見做法是建置一個「Linux 容器映像(container image)」。通常使用 Docker 來完成。之後你可以用多種方式部署該容器映像。
+
+使用 Linux 容器有多種優點,包括安全性、可重現性、簡單性等。
+
+/// tip | 提示
+
+趕時間而且已經懂這些?直接跳到下面的 [`Dockerfile` 👇](#build-a-docker-image-for-fastapi)。
+
+///
+
+
Dockerfile 預覽 👀
+
+```Dockerfile
+FROM python:3.14
+
+WORKDIR /code
+
+COPY ./requirements.txt /code/requirements.txt
+
+RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
+
+COPY ./app /code/app
+
+CMD ["fastapi", "run", "app/main.py", "--port", "80"]
+
+# 若在 Nginx 或 Traefik 等代理伺服器後方執行,請加入 --proxy-headers
+# CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"]
+```
+
+
+
+### TLS 握手開始 { #tls-handshake-start }
+
+接著瀏覽器會連線到該 IP 的 **443 埠**(HTTPS 預設埠)。
+
+通訊的第一部分是建立用戶端與伺服器之間的連線,並協商要使用哪些金鑰等密碼參數。
+
+
+
+用戶端與伺服器為建立 TLS 連線而進行的這段互動稱為 **TLS 握手**。
+
+### 帶 SNI 擴充的 TLS { #tls-with-sni-extension }
+
+在特定的**IP 位址**與特定**埠**上,同一時間**只能有一個行程**在監聽。可以在同一個 IP 上監聽不同埠,但每個 IP 與埠的組合只能有一個行程。
+
+TLS(HTTPS)預設使用 `443` 埠,因此我們需要用到這個埠。
+
+由於只能有一個行程監聽該埠,負責監聽的會是 **TLS 終止代理**。
+
+TLS 終止代理會存取一張或多張 **TLS 憑證**(HTTPS 憑證)。
+
+透過上面提到的 **SNI 擴充**,TLS 終止代理會根據用戶端預期的網域,從可用的 TLS(HTTPS)憑證中挑選本次連線要用的憑證。
+
+在這個例子中,會使用 `someapp.example.com` 的憑證。
+
+
+
+用戶端**信任**簽發該 TLS 憑證的單位(本例為 Let's Encrypt,稍後會再談),因此可以**驗證**憑證有效。
+
+接著,用戶端與 TLS 終止代理會以該憑證為基礎,**協商後續如何加密**整段 **TCP 通訊**。至此完成 **TLS 握手**。
+
+之後,用戶端與伺服器之間就有一條**已加密的 TCP 連線**,這就是 TLS 所提供的能力。接著他們可以在這條連線上開始實際的 **HTTP** 通訊。
+
+這也就是 **HTTPS** 的本質:在**安全的 TLS 連線**內傳送一般的 **HTTP**,而非在純(未加密)的 TCP 連線上。
+
+/// tip
+
+請注意,加密發生在 **TCP 層**,不是在 HTTP 層。
+
+///
+
+### HTTPS 請求 { #https-request }
+
+現在用戶端與伺服器(更精確地說,是瀏覽器與 TLS 終止代理)之間已有**加密的 TCP 連線**,他們可以開始進行 **HTTP** 通訊。
+
+因此,用戶端送出一個 **HTTPS 請求**。它其實就是透過加密的 TLS 連線發送的一個 HTTP 請求。
+
+
+
+### 解密請求 { #decrypt-the-request }
+
+TLS 終止代理會依照先前協商的方式**解密請求**,並將**純(已解密)的 HTTP 請求**轉交給運行應用的行程(例如以 Uvicorn 執行的 FastAPI 應用行程)。
+
+
+
+### HTTP 回應 { #http-response }
+
+應用會處理該請求,並將**純(未加密)的 HTTP 回應**送回 TLS 終止代理。
+
+
+
+### HTTPS 回應 { #https-response }
+
+TLS 終止代理接著會依照先前協商(起點是 `someapp.example.com` 的憑證)的方式**加密回應**,並傳回給瀏覽器。
+
+接著,瀏覽器會驗證回應是否合法、是否使用正確的金鑰加密等。然後**解密回應**並處理。
+
+
+
+用戶端(瀏覽器)會知道回應來自正確的伺服器,因為它使用了先前依據 **HTTPS 憑證**所協商的密碼機制。
+
+### 多個應用 { #multiple-applications }
+
+同一台(或多台)伺服器上可以有**多個應用**,例如其他 API 程式或資料庫。
+
+雖然只有一個行程可以處理特定 IP 與埠的組合(本例中的 TLS 終止代理),但其他應用/行程也都能在伺服器上運行,只要它們不使用相同的**公用 IP 與埠**組合即可。
+
+
+
+如此一來,TLS 終止代理就能為**多個網域**、多個應用處理 HTTPS 與憑證,並把請求轉發到對應的應用。
+
+### 憑證續期 { #certificate-renewal }
+
+在未來某個時間點,每張憑證都會**過期**(自取得起約 3 個月)。
+
+之後,會有另一個程式(有時是另一個程式,有時也可能就是同一個 TLS 終止代理)與 Let's Encrypt 溝通並續期憑證。
+
+
+
+**TLS 憑證**是**綁定網域名稱**,不是綁定 IP 位址。
+
+因此,要續期憑證時,續期程式需要向憑證機構(Let's Encrypt)**證明**它的確**擁有並控制該網域**。
+
+為了達成這點、並兼顧不同應用情境,有幾種常見方式:
+
+* **修改部分 DNS 紀錄**。
+ * 為此,續期程式需要支援該 DNS 供應商的 API,因此依你使用的 DNS 供應商不同,這方式可能可行或不可行。
+* **作為伺服器運行**(至少在憑證申請過程中)於該網域對應的公用 IP 上。
+ * 如前所述,同一時間只有一個行程能在特定 IP 與埠上監聽。
+ * 這也是為什麼讓同一個 TLS 終止代理一併處理憑證續期非常實用的原因之一。
+ * 否則你可能得暫停 TLS 終止代理、啟動續期程式申請憑證、將憑證配置到 TLS 終止代理,然後再重啟 TLS 終止代理。這並不理想,因為在 TLS 終止代理停機期間,你的應用將不可用。
+
+在不中斷服務的同時完成整個續期流程,是你會想用**獨立系統(TLS 終止代理)來處理 HTTPS**、而不是直接把 TLS 憑證掛在應用伺服器(例如 Uvicorn)上的主要原因之一。
+
+## 代理轉發標頭 { #proxy-forwarded-headers }
+
+當你使用代理處理 HTTPS 時,你的**應用伺服器**(例如透過 FastAPI CLI 啟動的 Uvicorn)其實不知道任何 HTTPS 的處理流程,它是用純 HTTP 與 **TLS 終止代理**通訊。
+
+這個**代理**通常會在把請求轉發給**應用伺服器**之前,臨時加入一些 HTTP 標頭,讓應用伺服器知道該請求是由代理**轉發**過來的。
+
+/// note | 技術細節
+
+這些代理標頭包括:
+
+* X-Forwarded-For
+* X-Forwarded-Proto
+* X-Forwarded-Host
+
+///
+
+然而,因為**應用伺服器**並不知道自己在受信任的**代理**之後,預設情況下它不會信任這些標頭。
+
+但你可以設定**應用伺服器**去信任由**代理**送來的「轉發」標頭。若你使用 FastAPI CLI,可以用 *CLI 參數* `--forwarded-allow-ips` 指定應信任哪些 IP 來的「轉發」標頭。
+
+例如,如果**應用伺服器**只會接收來自受信任**代理**的連線,你可以設定 `--forwarded-allow-ips="*"`,也就是信任所有來源 IP,因為實際上它只會收到**代理**那個 IP 送來的請求。
+
+如此一來,應用就能知道自己的對外 URL、是否使用 HTTPS、網域為何等資訊。
+
+這在正確處理重新導向等情境時很有用。
+
+/// tip
+
+你可以在文件 [在代理後方 - 啟用代理轉發標頭](../advanced/behind-a-proxy.md#enable-proxy-forwarded-headers){.internal-link target=_blank} 中了解更多。
+
+///
+
+## 重點回顧 { #recap }
+
+擁有 **HTTPS** 非常重要,而且在多數情況都相當**關鍵**。作為開發者,你在 HTTPS 上的大部分投入其實是**理解這些概念**及其運作方式。
+
+一旦掌握了**給開發者的 HTTPS 基礎**,你就能輕鬆組合並設定不同工具,讓一切管理變得簡單。
+
+在接下來的章節中,我會示範幾個為 **FastAPI** 應用設定 **HTTPS** 的具體例子。🔒
diff --git a/docs/zh-hant/docs/deployment/index.md b/docs/zh-hant/docs/deployment/index.md
index 9edd3368b..ddf533efc 100644
--- a/docs/zh-hant/docs/deployment/index.md
+++ b/docs/zh-hant/docs/deployment/index.md
@@ -8,7 +8,7 @@
對於一個 **Web API**,部署通常涉及將其放置在**遠端伺服器**上,並使用性能優良且穩定的**伺服器程式**,確保使用者能夠高效、無中斷地存取應用程式,且不會遇到問題。
-這與**開發**階段形成鮮明對比,在**開發**階段,你會不斷更改程式碼、破壞程式碼、修復程式碼,然後停止和重新啟動伺服器等。
+這與**開發**階段形成鮮明對比,在**開發**階段,你會不斷更改程式碼、破壞程式碼、修復程式碼,然後停止和重新啟動開發伺服器等。
## 部署策略 { #deployment-strategies }
diff --git a/docs/zh-hant/docs/deployment/manually.md b/docs/zh-hant/docs/deployment/manually.md
new file mode 100644
index 000000000..bf9f6a93f
--- /dev/null
+++ b/docs/zh-hant/docs/deployment/manually.md
@@ -0,0 +1,157 @@
+# 手動執行伺服器 { #run-a-server-manually }
+
+## 使用 `fastapi run` 指令 { #use-the-fastapi-run-command }
+
+簡而言之,使用 `fastapi run` 來啟動你的 FastAPI 應用:
+
+
+
+若沒有他人的前期成果,就不會有 **FastAPI**。
+
+先前已有許多工具啟發了它的誕生。
+
+我曾經多年避免再去打造一個新框架。起初我嘗試用各種不同的框架、外掛與工具,來滿足 **FastAPI** 涵蓋的所有功能。
+
+但在某個時刻,別無選擇,只能打造一個同時提供所有這些功能的東西,取過去工具之長,並以可能的最佳方式加以結合,還運用了以往甚至不存在的語言功能(Python 3.6+ 的型別提示)。
+
+
+
+## 調研 { #investigation }
+
+透過實際使用這些替代方案,我得以向它們學習、汲取想法,並以我能為自己與合作開發團隊找到的最佳方式加以整合。
+
+例如,很清楚理想上應以標準的 Python 型別提示為基礎。
+
+同時,最佳做法就是採用現有標準。
+
+因此,在開始撰寫 **FastAPI** 之前,我花了好幾個月研究 OpenAPI、JSON Schema、OAuth2 等規範,了解它們之間的關係、重疊與差異。
+
+## 設計 { #design }
+
+接著,我花時間設計作為使用者(作為使用 FastAPI 的開發者)時希望擁有的開發者「API」。
+
+我在最受歡迎的 Python 編輯器中測試了多個想法:PyCharm、VS Code、基於 Jedi 的編輯器。
+
+根據最新的 Python 開發者調查,這些工具涵蓋約 80% 的使用者。
+
+這表示 **FastAPI** 已針對 80% 的 Python 開發者所使用的編輯器進行過專門測試。而由於其他多數編輯器的行為也類似,這些優點幾乎在所有編輯器上都能生效。
+
+藉此我找到了盡可能減少程式碼重複、在各處提供自動補全、型別與錯誤檢查等的最佳方式。
+
+一切都是為了讓所有開發者都能擁有最佳的開發體驗。
+
+## 需求 { #requirements }
+
+在測試多種替代方案後,我決定採用 **Pydantic**,因為它的優勢。
+
+隨後我也對它做出貢獻,使其完全符合 JSON Schema、支援以不同方式定義約束,並依據在多款編輯器中的測試結果改進編輯器支援(型別檢查、自動補全)。
+
+在開發過程中,我也對 **Starlette**(另一個關鍵依賴)做出貢獻。
+
+## 開發 { #development }
+
+當我開始著手實作 **FastAPI** 本身時,多數拼圖已經就緒,設計已定,需求與工具已備齊,對各項標準與規範的理解也清晰且新鮮。
+
+## 未來 { #future }
+
+到目前為止,**FastAPI** 及其理念已經對許多人有幫助。
+
+相較先前的替代方案,它更適合許多使用情境,因而被選用。
+
+許多開發者與團隊(包括我和我的團隊)已經在他們的專案中依賴 **FastAPI**。
+
+但仍有許多改進與功能即將到來。
+
+**FastAPI** 的前景非常光明。
+
+也非常感謝[你的幫助](help-fastapi.md){.internal-link target=_blank}。
diff --git a/docs/zh-hant/docs/how-to/authentication-error-status-code.md b/docs/zh-hant/docs/how-to/authentication-error-status-code.md
new file mode 100644
index 000000000..9a8de4c91
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/authentication-error-status-code.md
@@ -0,0 +1,15 @@
+# 使用舊的 403 身分驗證錯誤狀態碼 { #use-old-403-authentication-error-status-codes }
+
+在 FastAPI 版本 `0.122.0` 之前,當內建的安全工具在身分驗證失敗後回傳錯誤給用戶端時,會使用 HTTP 狀態碼 `403 Forbidden`。
+
+從 FastAPI 版本 `0.122.0` 起,改為使用更合適的 HTTP 狀態碼 `401 Unauthorized`,並在回應中依據 HTTP 規範加上合理的 `WWW-Authenticate` 標頭,參考 RFC 7235、RFC 9110。
+
+但如果你的用戶端因某些原因依賴於舊行為,你可以在你的 security 類別中覆寫 `make_not_authenticated_error` 方法以恢復舊的行為。
+
+例如,你可以建立 `HTTPBearer` 的子類別,讓它回傳 `403 Forbidden` 錯誤,而不是預設的 `401 Unauthorized` 錯誤:
+
+{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *}
+
+/// tip
+注意這個函式回傳的是例外物件本身,而不是直接拋出它。拋出的動作會在其餘的內部程式碼中處理。
+///
diff --git a/docs/zh-hant/docs/how-to/conditional-openapi.md b/docs/zh-hant/docs/how-to/conditional-openapi.md
new file mode 100644
index 000000000..5c091e5b7
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/conditional-openapi.md
@@ -0,0 +1,56 @@
+# 條件式 OpenAPI { #conditional-openapi }
+
+如果需要,你可以用設定與環境變數,依據執行環境有條件地調整 OpenAPI,甚至完全停用它。
+
+## 關於安全性、API 與文件 { #about-security-apis-and-docs }
+
+在正式環境中隱藏文件 UI *不應該* 是用來保護 API 的方式。
+
+這並不會為你的 API 增添任何額外的安全性,*路徑操作* 仍舊照常可用。
+
+若你的程式碼有安全性缺陷,它依然會存在。
+
+隱藏文件只會讓他人更難理解如何與你的 API 互動,也可能讓你在正式環境除錯更困難。這通常僅被視為一種 以隱匿求安全。
+
+如果你想保護 API,有許多更好的作法,例如:
+
+- 確保針對請求本文與回應,具備定義良好的 Pydantic 模型。
+- 透過依賴設定所需的權限與角色。
+- 切勿儲存明文密碼,只儲存密碼雜湊。
+- 實作並使用成熟且廣為人知的密碼學工具,例如 pwdlib 與 JWT 權杖等。
+- 視需要以 OAuth2 scopes 新增更細緻的權限控管。
+- ...等。
+
+儘管如此,在某些特定情境下,你可能確實需要在某些環境(例如正式環境)停用 API 文件,或依據環境變數的設定來決定是否啟用。
+
+## 透過設定與環境變數的條件式 OpenAPI { #conditional-openapi-from-settings-and-env-vars }
+
+你可以用相同的 Pydantic 設定,來配置產生的 OpenAPI 與文件 UI。
+
+例如:
+
+{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *}
+
+這裡我們宣告 `openapi_url` 設定,預設值同樣是 `"/openapi.json"`。
+
+接著在建立 `FastAPI` 應用時使用它。
+
+然後你可以將環境變數 `OPENAPI_URL` 設為空字串,以停用 OpenAPI(包含文件 UI),如下:
+
+
+
+但你可以將 `syntaxHighlight` 設為 `False` 來停用它:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+...然後 Swagger UI 就不會再顯示語法醒目提示:
+
+
+
+## 更換主題 { #change-the-theme }
+
+同樣地,你可以用鍵 `"syntaxHighlight.theme"` 設定語法醒目提示主題(注意中間有一個點):
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+這個設定會變更語法醒目提示的配色主題:
+
+
+
+## 更改預設的 Swagger UI 參數 { #change-default-swagger-ui-parameters }
+
+FastAPI 內建一些預設參數,適用於大多數情境。
+
+包含以下預設設定:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+你可以在 `swagger_ui_parameters` 參數中提供不同的值來覆蓋其中任一項。
+
+例如,要停用 `deepLinking`,可以在 `swagger_ui_parameters` 傳入以下設定:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## 其他 Swagger UI 參數 { #other-swagger-ui-parameters }
+
+若要查看所有可用的設定,請參考官方的 Swagger UI 參數文件。
+
+## 僅限 JavaScript 的設定 { #javascript-only-settings }
+
+Swagger UI 也允許某些設定是僅限 JavaScript 的物件(例如 JavaScript 函式)。
+
+FastAPI 也包含以下僅限 JavaScript 的 `presets` 設定:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+這些是 JavaScript 物件,而不是字串,因此無法直接從 Python 程式碼傳遞。
+
+若需要使用這類僅限 JavaScript 的設定,你可以使用上面介紹的方法:覆寫所有 Swagger UI 的路徑操作(path operation),並手動撰寫所需的 JavaScript。
diff --git a/docs/zh-hant/docs/how-to/custom-docs-ui-assets.md b/docs/zh-hant/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 000000000..4b5394589
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# 自訂文件 UI 靜態資源(自我託管) { #custom-docs-ui-static-assets-self-hosting }
+
+API 文件使用 Swagger UI 與 ReDoc,它們各自需要一些 JavaScript 與 CSS 檔案。
+
+預設情況下,這些檔案會從 CDN 提供。
+
+但你可以自訂:你可以指定特定的 CDN,或自行提供這些檔案。
+
+## 為 JavaScript 和 CSS 使用自訂 CDN { #custom-cdn-for-javascript-and-css }
+
+假設你想使用不同的 CDN,例如使用 `https://unpkg.com/`。
+
+若你所在的國家限制部分網址,這會很有用。
+
+### 停用自動產生的文件 { #disable-the-automatic-docs }
+
+第一步是停用自動文件,因為預設會使用預設的 CDN。
+
+要停用它們,建立 `FastAPI` 應用時把相關 URL 設為 `None`:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### 加入自訂文件 { #include-the-custom-docs }
+
+現在你可以為自訂文件建立「路徑操作(path operation)」。
+
+你可以重用 FastAPI 的內部函式來建立文件的 HTML 頁面,並傳入所需參數:
+
+* `openapi_url`:文件 HTML 頁面用來取得你 API 的 OpenAPI schema 的 URL。可使用屬性 `app.openapi_url`。
+* `title`:你的 API 標題。
+* `oauth2_redirect_url`:可使用 `app.swagger_ui_oauth2_redirect_url` 以沿用預設值。
+* `swagger_js_url`:Swagger UI 文件 HTML 用來取得「JavaScript」檔案的 URL。這是你的自訂 CDN 位址。
+* `swagger_css_url`:Swagger UI 文件 HTML 用來取得「CSS」檔案的 URL。這是你的自訂 CDN 位址。
+
+ReDoc 也類似...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip
+
+當你使用 OAuth2 時,`swagger_ui_redirect` 的路徑操作是個輔助端點。
+
+如果你把 API 與 OAuth2 提供者整合,便能完成認證並帶著取得的憑證回到 API 文件,接著以真正的 OAuth2 驗證與之互動。
+
+Swagger UI 會在背後幫你處理,不過它需要這個「redirect」輔助端點。
+
+///
+
+### 建立路徑操作以進行測試 { #create-a-path-operation-to-test-it }
+
+現在,為了測試一切是否正常,建立一個路徑操作:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### 測試 { #test-it }
+
+現在你應該能造訪 http://127.0.0.1:8000/docs,重新載入頁面後,資源會從新的 CDN 載入。
+
+## 自行託管文件所需的 JavaScript 與 CSS { #self-hosting-javascript-and-css-for-docs }
+
+若你需要應用在離線、無公共網路或僅在區域網路中也能運作,自行託管 JavaScript 與 CSS 會很實用。
+
+以下示範如何在同一個 FastAPI 應用中自行提供這些檔案,並設定文件使用它們。
+
+### 專案檔案結構 { #project-file-structure }
+
+假設你的專案檔案結構如下:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+現在建立一個目錄來存放這些靜態檔案。
+
+新的檔案結構可能如下:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### 下載檔案 { #download-the-files }
+
+下載文件所需的靜態檔案並放到 `static/` 目錄中。
+
+你可以在各連結上按右鍵,選擇類似「另存連結為...」的選項。
+
+Swagger UI 需要以下檔案:
+
+* `swagger-ui-bundle.js`
+* `swagger-ui.css`
+
+而 ReDoc 需要以下檔案:
+
+* `redoc.standalone.js`
+
+之後,你的檔案結構可能如下:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### 提供靜態檔案 { #serve-the-static-files }
+
+* 匯入 `StaticFiles`。
+* 在特定路徑「掛載」一個 `StaticFiles()` 實例。
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### 測試靜態檔案 { #test-the-static-files }
+
+啟動你的應用並前往 http://127.0.0.1:8000/static/redoc.standalone.js。
+
+你應該會看到一個很長的 **ReDoc** JavaScript 檔案。
+
+它可能會以如下內容開頭:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+這表示你的應用已能提供靜態檔案,且文件用的靜態檔已放在正確位置。
+
+接著把應用設定為讓文件使用這些靜態檔。
+
+### 為靜態檔案停用自動文件 { #disable-the-automatic-docs-for-static-files }
+
+和使用自訂 CDN 一樣,第一步是停用自動文件,因為預設會使用 CDN。
+
+要停用它們,建立 `FastAPI` 應用時把相關 URL 設為 `None`:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### 加入使用靜態檔案的自訂文件 { #include-the-custom-docs-for-static-files }
+
+同樣地,現在你可以為自訂文件建立路徑操作。
+
+再次重用 FastAPI 的內部函式來建立文件的 HTML 頁面,並傳入所需參數:
+
+* `openapi_url`:文件 HTML 頁面用來取得你 API 的 OpenAPI schema 的 URL。可使用屬性 `app.openapi_url`。
+* `title`:你的 API 標題。
+* `oauth2_redirect_url`:可使用 `app.swagger_ui_oauth2_redirect_url` 以沿用預設值。
+* `swagger_js_url`:Swagger UI 文件 HTML 用來取得「JavaScript」檔案的 URL。這就是你的應用現在提供的檔案。
+* `swagger_css_url`:Swagger UI 文件 HTML 用來取得「CSS」檔案的 URL。這就是你的應用現在提供的檔案。
+
+ReDoc 也類似...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip
+
+當你使用 OAuth2 時,`swagger_ui_redirect` 的路徑操作是個輔助端點。
+
+如果你把 API 與 OAuth2 提供者整合,便能完成認證並帶著取得的憑證回到 API 文件,接著以真正的 OAuth2 驗證與之互動。
+
+Swagger UI 會在背後幫你處理,不過它需要這個「redirect」輔助端點。
+
+///
+
+### 建立路徑操作以測試靜態檔案 { #create-a-path-operation-to-test-static-files }
+
+現在,為了測試一切是否正常,建立一個路徑操作:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### 測試使用靜態檔案的 UI { #test-static-files-ui }
+
+現在,你應該可以關閉 WiFi,造訪你的文件 http://127.0.0.1:8000/docs,並重新載入頁面。
+
+即使沒有網際網路,也能看到你的 API 文件並與之互動。
diff --git a/docs/zh-hant/docs/how-to/custom-request-and-route.md b/docs/zh-hant/docs/how-to/custom-request-and-route.md
new file mode 100644
index 000000000..99c3410e4
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# 自訂 Request 與 APIRoute 類別 { #custom-request-and-apiroute-class }
+
+在某些情況下,你可能想要覆寫 `Request` 與 `APIRoute` 類別所使用的邏輯。
+
+特別是,這可能是替代中介軟體(middleware)中實作邏輯的一個好方法。
+
+例如,如果你想在應用程式處理之前讀取或操作請求本文(request body)。
+
+/// danger
+
+這是進階功能。
+
+如果你剛開始使用 **FastAPI**,可以先跳過本節。
+
+///
+
+## 使用情境 { #use-cases }
+
+可能的使用情境包括:
+
+* 將非 JSON 的請求本文轉換為 JSON(例如 `msgpack`)。
+* 解壓縮以 gzip 壓縮的請求本文。
+* 自動記錄所有請求本文。
+
+## 處理自訂請求本文編碼 { #handling-custom-request-body-encodings }
+
+讓我們看看如何使用自訂的 `Request` 子類別來解壓縮 gzip 請求。
+
+並透過 `APIRoute` 子類別來使用該自訂的請求類別。
+
+### 建立自訂的 `GzipRequest` 類別 { #create-a-custom-gziprequest-class }
+
+/// tip
+
+這是一個示範用的簡化範例;如果你需要 Gzip 支援,可以直接使用提供的 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}。
+
+///
+
+首先,我們建立 `GzipRequest` 類別,它會覆寫 `Request.body()` 方法,當存在對應的標頭時解壓縮本文。
+
+如果標頭中沒有 `gzip`,它就不會嘗試解壓縮本文。
+
+如此一來,相同的路由類別即可同時處理經 gzip 壓縮與未壓縮的請求.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### 建立自訂的 `GzipRoute` 類別 { #create-a-custom-gziproute-class }
+
+接著,我們建立 `fastapi.routing.APIRoute` 的自訂子類別,讓它使用 `GzipRequest`。
+
+這次,它會覆寫 `APIRoute.get_route_handler()` 方法。
+
+這個方法會回傳一個函式,而該函式會接收請求並回傳回應。
+
+在這裡,我們用它將原始的請求包裝成 `GzipRequest`。
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | 技術細節
+
+`Request` 具有 `request.scope` 屬性,它其實就是一個 Python 的 `dict`,包含與該請求相關的中繼資料。
+
+`Request` 也有 `request.receive`,那是一個用來「接收」請求本文的函式。
+
+`scope` 這個 `dict` 與 `receive` 函式都是 ASGI 規格的一部分。
+
+而 `scope` 與 `receive` 這兩者,就是建立一個新的 `Request` 實例所需的資料。
+
+想了解更多 `Request`,請參考 Starlette 的 Request 文件。
+
+///
+
+由 `GzipRequest.get_route_handler` 回傳的函式,唯一不同之處在於它會把 `Request` 轉換成 `GzipRequest`。
+
+這麼做之後,`GzipRequest` 會在把資料交給 *路徑操作* 之前(若有需要)先負責解壓縮。
+
+之後的處理邏輯完全相同。
+
+但由於我們修改了 `GzipRequest.body`,在 **FastAPI** 需要讀取本文時,請求本文會自動解壓縮。
+
+## 在例外處理器中存取請求本文 { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip
+
+要解決相同問題,使用針對 `RequestValidationError` 的自訂處理器來讀取 `body` 通常更簡單([處理錯誤](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank})。
+
+但本範例仍然有效,並示範了如何與內部元件互動。
+
+///
+
+我們也可以用同樣的方法,在例外處理器中存取請求本文。
+
+我們只需要在 `try`/`except` 區塊中處理請求即可:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+若發生例外,`Request` 實例依然在作用域內,因此在處理錯誤時我們仍可讀取並使用請求本文:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## 在路由器中自訂 `APIRoute` 類別 { #custom-apiroute-class-in-a-router }
+
+你也可以在 `APIRouter` 上設定 `route_class` 參數:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+在此範例中,`router` 底下的路徑操作會使用自訂的 `TimedRoute` 類別,並在回應中多加上一個 `X-Response-Time` 標頭,標示產生該回應所花費的時間:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/zh-hant/docs/how-to/extending-openapi.md b/docs/zh-hant/docs/how-to/extending-openapi.md
new file mode 100644
index 000000000..c51e896f3
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# 擴充 OpenAPI { #extending-openapi }
+
+有些情況你可能需要修改自動產生的 OpenAPI 結構(schema)。
+
+本章將示範如何做。
+
+## 一般流程 { #the-normal-process }
+
+一般(預設)的流程如下。
+
+`FastAPI` 應用程式(實例)有一個 `.openapi()` 方法,會回傳 OpenAPI 結構。
+
+在建立應用物件時,會同時註冊一個 `/openapi.json`(或你在 `openapi_url` 設定的路徑)的路徑操作(path operation)。
+
+這個路徑只會回傳一個 JSON 回應,內容就是應用的 `.openapi()` 方法結果。
+
+預設情況下,`.openapi()` 會先檢查 `.openapi_schema` 屬性是否已有內容,有的話就直接回傳。
+
+若沒有,則會呼叫 `fastapi.openapi.utils.get_openapi` 這個工具函式來產生。
+
+`get_openapi()` 函式會接收以下參數:
+
+* `title`:OpenAPI 的標題,會顯示在文件中。
+* `version`:你的 API 版本,例如 `2.5.0`。
+* `openapi_version`:所使用的 OpenAPI 規格版本。預設為最新版本:`3.1.0`。
+* `summary`:API 的簡短摘要。
+* `description`:API 的描述,可包含 Markdown,會顯示在文件中。
+* `routes`:路由列表,也就是所有已註冊的路徑操作。來源為 `app.routes`。
+
+/// info
+
+`summary` 參數在 OpenAPI 3.1.0 以上可用,且需 FastAPI 0.99.0 以上版本支援。
+
+///
+
+## 覆寫預設行為 { #overriding-the-defaults }
+
+基於上述資訊,你可以用相同的工具函式來產生 OpenAPI 結構,並覆寫你需要客製的部分。
+
+例如,我們要加入 ReDoc 的 OpenAPI 擴充,插入自訂 logo。
+
+### 一般的 **FastAPI** { #normal-fastapi }
+
+先照常撰寫你的 **FastAPI** 應用:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### 產生 OpenAPI 結構 { #generate-the-openapi-schema }
+
+接著,在 `custom_openapi()` 函式內,使用相同的工具函式來產生 OpenAPI 結構:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### 修改 OpenAPI 結構 { #modify-the-openapi-schema }
+
+現在可以加入 ReDoc 擴充,在 OpenAPI 結構的 `info`「物件」中新增自訂的 `x-logo`:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### 快取 OpenAPI 結構 { #cache-the-openapi-schema }
+
+你可以把 `.openapi_schema` 屬性當作「快取」來儲存已產生的結構。
+
+這樣使用者每次開啟 API 文件時,應用就不必重複產生結構。
+
+結構只會產生一次,之後的請求都會使用相同的快取結果。
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### 覆寫方法 { #override-the-method }
+
+現在你可以用新的函式取代 `.openapi()` 方法。
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### 檢查看看 { #check-it }
+
+造訪 http://127.0.0.1:8000/redoc 後,你會看到自訂的 logo(此例為 **FastAPI** 的 logo):
+
+
diff --git a/docs/zh-hant/docs/how-to/general.md b/docs/zh-hant/docs/how-to/general.md
new file mode 100644
index 000000000..96a71d62d
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/general.md
@@ -0,0 +1,39 @@
+# 通用 - 操作指南 - 實用範例 { #general-how-to-recipes }
+
+以下是文件中其他位置的指引連結,適用於一般或常見問題。
+
+## 篩選資料 - 安全性 { #filter-data-security }
+
+為確保你不會回傳超出應有的資料,請參閱[教學 - 回應模型 - 回傳型別](../tutorial/response-model.md){.internal-link target=_blank}。
+
+## 文件標籤 - OpenAPI { #documentation-tags-openapi }
+
+要在你的*路徑操作(path operation)*加入標籤,並在文件 UI 中分組,請參閱[教學 - 路徑操作設定 - 標籤](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}。
+
+## 文件摘要與描述 - OpenAPI { #documentation-summary-and-description-openapi }
+
+要為你的*路徑操作*加入摘要與描述,並在文件 UI 中顯示,請參閱[教學 - 路徑操作設定 - 摘要與描述](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank}。
+
+## 文件回應描述 - OpenAPI { #documentation-response-description-openapi }
+
+要定義在文件 UI 中顯示的回應描述,請參閱[教學 - 路徑操作設定 - 回應描述](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank}。
+
+## 文件將*路徑操作*標記為已棄用 - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+要將*路徑操作*標記為已棄用,並在文件 UI 中顯示,請參閱[教學 - 路徑操作設定 - 棄用](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank}。
+
+## 將任意資料轉換為 JSON 相容格式 { #convert-any-data-to-json-compatible }
+
+要將任意資料轉換為 JSON 相容格式,請參閱[教學 - JSON 相容編碼器](../tutorial/encoder.md){.internal-link target=_blank}。
+
+## OpenAPI 中繼資料 - 文件 { #openapi-metadata-docs }
+
+要在你的 OpenAPI 綱要中加入中繼資料(包含授權、版本、聯絡方式等),請參閱[教學 - 中繼資料與文件 URL](../tutorial/metadata.md){.internal-link target=_blank}。
+
+## 自訂 OpenAPI URL { #openapi-custom-url }
+
+要自訂(或移除)OpenAPI 的 URL,請參閱[教學 - 中繼資料與文件 URL](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}。
+
+## OpenAPI 文件 URL { #openapi-docs-urls }
+
+要更新自動產生的文件使用者介面所使用的 URL,請參閱[教學 - 中繼資料與文件 URL](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}。
diff --git a/docs/zh-hant/docs/how-to/graphql.md b/docs/zh-hant/docs/how-to/graphql.md
new file mode 100644
index 000000000..51933210c
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+由於 FastAPI 基於 ASGI 標準,整合任何與 ASGI 相容的 GraphQL 函式庫都很容易。
+
+你可以在同一個應用程式中同時使用一般的 FastAPI 路徑操作 (path operation) 與 GraphQL。
+
+/// tip
+
+GraphQL 解決某些非常特定的使用情境。
+
+與一般的 Web API 相比,它有優點也有缺點。
+
+請確認在你的使用情境中,這些效益是否足以彌補其限制。 🤓
+
+///
+
+## GraphQL 函式庫 { #graphql-libraries }
+
+下面是支援 ASGI 的部分 GraphQL 函式庫,你可以與 FastAPI 一起使用:
+
+* Strawberry 🍓
+ * 提供 FastAPI 文件
+* Ariadne
+ * 提供 FastAPI 文件
+* Tartiflette
+ * 使用 Tartiflette ASGI 提供 ASGI 整合
+* Graphene
+ * 搭配 starlette-graphene3
+
+## 使用 Strawberry 的 GraphQL { #graphql-with-strawberry }
+
+如果你需要或想使用 GraphQL,Strawberry 是推薦的函式庫,因為它的設計與 FastAPI 最接近,全部都基於型別註解 (type annotations)。
+
+視你的使用情境而定,你可能會偏好其他函式庫,但如果你問我,我大概會建議你先試試 Strawberry。
+
+以下是如何將 Strawberry 與 FastAPI 整合的一個小例子:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+你可以在 Strawberry 文件 中進一步了解 Strawberry。
+
+也可以參考關於 Strawberry 與 FastAPI 的文件。
+
+## 來自 Starlette 的較舊 `GraphQLApp` { #older-graphqlapp-from-starlette }
+
+早期版本的 Starlette 提供 `GraphQLApp` 類別以整合 Graphene。
+
+它已在 Starlette 中被棄用,但如果你的程式碼使用了它,可以輕鬆遷移到 starlette-graphene3,涵蓋相同的使用情境,且介面幾乎相同。
+
+/// tip
+
+如果你需要 GraphQL,我仍建議你看看 Strawberry,因為它基於型別註解,而不是自訂的類別與型別。
+
+///
+
+## 進一步了解 { #learn-more }
+
+你可以在 官方 GraphQL 文件 中進一步了解 GraphQL。
+
+你也可以透過上述連結閱讀各個函式庫的更多內容。
diff --git a/docs/zh-hant/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/zh-hant/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 000000000..109e57bc8
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# 從 Pydantic v1 遷移到 Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+如果你有一個舊的 FastAPI 應用,可能正在使用 Pydantic 1 版。
+
+FastAPI 0.100.0 同時支援 Pydantic v1 或 v2,會使用你已安裝的那個版本。
+
+FastAPI 0.119.0 透過 Pydantic v2 內的 `pydantic.v1` 提供對 Pydantic v1 的部分支援,以便遷移到 v2。
+
+FastAPI 0.126.0 移除了對 Pydantic v1 的支援,但在一段時間內仍支援 `pydantic.v1`。
+
+/// warning
+
+Pydantic 團隊自 **Python 3.14** 起,已停止在最新的 Python 版本中支援 Pydantic v1。
+
+這也包含 `pydantic.v1`,在 Python 3.14 及以上版本不再支援。
+
+如果你想使用最新的 Python 功能,就需要確保使用 Pydantic v2。
+
+///
+
+如果你的舊 FastAPI 應用仍使用 Pydantic v1,這裡會示範如何遷移到 Pydantic v2,並介紹 **FastAPI 0.119.0** 中可協助你逐步遷移的功能。
+
+## 官方指南 { #official-guide }
+
+Pydantic 提供從 v1 遷移到 v2 的官方遷移指南。
+
+其中包含變更內容、驗證如何更正確且更嚴格、可能的注意事項等。
+
+你可以先閱讀以更好理解具體變更。
+
+## 測試 { #tests }
+
+確保你的應用有[測試](../tutorial/testing.md){.internal-link target=_blank},並在 CI(持續整合)上執行。
+
+如此一來,你可以升級後確認一切仍如預期運作。
+
+## `bump-pydantic` { #bump-pydantic }
+
+在許多情況下,若你使用的是未自訂的標準 Pydantic 模型,多數遷移步驟都能自動化完成。
+
+你可以使用 Pydantic 團隊提供的 `bump-pydantic`。
+
+這個工具會自動修改大部分需要變更的程式碼。
+
+之後執行測試確認一切正常即可完成。😎
+
+## v2 中的 Pydantic v1 { #pydantic-v1-in-v2 }
+
+Pydantic v2 內含子模組 `pydantic.v1`,提供 Pydantic v1 的所有內容。但在 Python 3.13 以上版本不再支援。
+
+這表示你可以安裝最新的 Pydantic v2,並從該子模組匯入並使用舊的 Pydantic v1 元件,就像安裝了舊版 Pydantic v1 一樣。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### FastAPI 對 v2 中 Pydantic v1 的支援 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+自 FastAPI 0.119.0 起,也支援透過 Pydantic v2 內的 Pydantic v1(部分)以協助遷移至 v2。
+
+因此,你可以先升級到最新的 Pydantic v2,並將匯入改為使用 `pydantic.v1` 子模組,在多數情況下即可正常運作。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning
+
+請注意,由於 Pydantic 團隊自 Python 3.14 起不再支援 Pydantic v1,因此在 Python 3.14 及以上版本中也不支援使用 `pydantic.v1`。
+
+///
+
+### 同一應用同時使用 Pydantic v1 與 v2 { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic 不支援在 Pydantic v2 模型的欄位中使用 Pydantic v1 模型,反之亦然。
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...但你可以在同一應用中同時存在分開的 Pydantic v1 與 v2 模型。
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+在某些情況下,你甚至可以在同一個 FastAPI 路徑操作(path operation)中同時使用 Pydantic v1 與 v2 模型:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+在上面的範例中,輸入模型是 Pydantic v1,輸出模型(於 `response_model=ItemV2` 定義)是 Pydantic v2。
+
+### Pydantic v1 參數 { #pydantic-v1-parameters }
+
+若你需要在 Pydantic v1 模型上使用 FastAPI 的參數工具(例如 `Body`、`Query`、`Form` 等),在完成遷移到 Pydantic v2 之前,可以從 `fastapi.temp_pydantic_v1_params` 匯入:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### 分步遷移 { #migrate-in-steps }
+
+/// tip
+
+先嘗試使用 `bump-pydantic`,如果測試通過且一切正常,你就能用一條指令完成遷移。✨
+
+///
+
+若 `bump-pydantic` 不適用於你的情境,可以利用在同一應用同時支援 Pydantic v1 與 v2 的能力,逐步完成遷移。
+
+你可以先升級 Pydantic 到最新 v2,並將所有模型的匯入改為使用 `pydantic.v1`。
+
+接著按群組逐步把模型從 Pydantic v1 遷移到 v2。🚶
diff --git a/docs/zh-hant/docs/how-to/separate-openapi-schemas.md b/docs/zh-hant/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 000000000..2ecb6afbc
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# 是否將輸入與輸出使用不同的 OpenAPI 結構描述 { #separate-openapi-schemas-for-input-and-output-or-not }
+
+自從 Pydantic v2 發佈後,生成的 OpenAPI 比以往更精確也更正確。😎
+
+實際上,在某些情況下,同一個 Pydantic 模型在 OpenAPI 中會同時有兩個 JSON Schema:分別用於輸入與輸出,這取決於它是否有預設值。
+
+來看看它如何運作,以及若需要時該如何調整。
+
+## 作為輸入與輸出的 Pydantic 模型 { #pydantic-models-for-input-and-output }
+
+假設你有一個帶有預設值的 Pydantic 模型,如下所示:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### 輸入用模型 { #model-for-input }
+
+如果你把這個模型用作輸入,如下所示:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+...則 `description` 欄位將不是必填。因為它的預設值是 `None`。
+
+### 文件中的輸入模型 { #input-model-in-docs }
+
+你可以在文件中確認,`description` 欄位沒有紅色星號,表示不是必填:
+
+
+
+
+
+
+httpx - 若要使用 `TestClient` 必須安裝。
* jinja2 - 若要使用預設的模板設定必須安裝。
-* python-multipart - 若要支援表單 "解析",搭配 `request.form()`。
+* python-multipart - 若要支援表單 "解析",搭配 `request.form()`。
FastAPI 會使用:
diff --git a/docs/zh-hant/docs/project-generation.md b/docs/zh-hant/docs/project-generation.md
new file mode 100644
index 000000000..7fa92ce55
--- /dev/null
+++ b/docs/zh-hant/docs/project-generation.md
@@ -0,0 +1,28 @@
+# 全端 FastAPI 範本 { #full-stack-fastapi-template }
+
+範本通常附帶特定的設定,但設計上具有彈性且可自訂。這讓你可以依專案需求調整與擴充,因此非常適合作為起點。🏁
+
+你可以使用此範本快速起步,裡面已替你完成大量初始設定、安全性、資料庫,以及部分 API 端點。
+
+GitHub 儲存庫:全端 FastAPI 範本
+
+## 全端 FastAPI 範本 - 技術堆疊與功能 { #full-stack-fastapi-template-technology-stack-and-features }
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com/zh-hant) 作為 Python 後端 API。
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) 作為 Python 與 SQL 資料庫互動(ORM)。
+ - 🔍 [Pydantic](https://docs.pydantic.dev)(由 FastAPI 使用)用於資料驗證與設定管理。
+ - 💾 [PostgreSQL](https://www.postgresql.org) 作為 SQL 資料庫。
+- 🚀 [React](https://react.dev) 作為前端。
+ - 💃 使用 TypeScript、hooks、Vite,以及現代前端技術堆疊的其他組件。
+ - 🎨 [Tailwind CSS](https://tailwindcss.com) 與 [shadcn/ui](https://ui.shadcn.com) 作為前端元件。
+ - 🤖 自動產生的前端用戶端。
+ - 🧪 [Playwright](https://playwright.dev) 用於端到端測試。
+ - 🦇 支援深色模式。
+- 🐋 [Docker Compose](https://www.docker.com) 用於開發與正式環境。
+- 🔒 預設即採用安全的密碼雜湊。
+- 🔑 JWT(JSON Web Token)驗證。
+- 📫 以 Email 為基礎的密碼重設。
+- ✅ 使用 [Pytest](https://pytest.org) 的測試。
+- 📞 [Traefik](https://traefik.io) 作為反向代理/負載平衡器。
+- 🚢 使用 Docker Compose 的部署指引,包含如何設定前端 Traefik 代理以自動處理 HTTPS 憑證。
+- 🏭 基於 GitHub Actions 的 CI(持續整合)與 CD(持續部署)。
diff --git a/docs/zh-hant/docs/python-types.md b/docs/zh-hant/docs/python-types.md
new file mode 100644
index 000000000..4f498ab73
--- /dev/null
+++ b/docs/zh-hant/docs/python-types.md
@@ -0,0 +1,348 @@
+# Python 型別入門 { #python-types-intro }
+
+Python 支援可選用的「型別提示」(也稱為「型別註記」)。
+
+這些「型別提示」或註記是一種特殊語法,用來宣告變數的型別。
+
+為你的變數宣告型別後,編輯器與工具就能提供更好的支援。
+
+這裡只是關於 Python 型別提示的快速教學/複習。它只涵蓋使用在 **FastAPI** 時所需的最低限度...其實非常少。
+
+**FastAPI** 完全是以這些型別提示為基礎,並因此帶來許多優勢與好處。
+
+但就算你從不使用 **FastAPI**,學一點型別提示也會有幫助。
+
+/// note | 注意
+
+如果你是 Python 專家,而且已經完全了解型別提示,可以直接跳到下一章。
+
+///
+
+## 動機 { #motivation }
+
+先從一個簡單的例子開始:
+
+{* ../../docs_src/python_types/tutorial001_py310.py *}
+
+執行這個程式會輸出:
+
+```
+John Doe
+```
+
+這個函式會做以下事情:
+
+* 接收 `first_name` 與 `last_name`。
+* 用 `title()` 把每個字的第一個字母轉成大寫。
+* 用一個空白把它們串接起來。
+
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
+
+### 編輯它 { #edit-it }
+
+這是一個非常簡單的程式。
+
+但現在想像你正從零開始寫它。
+
+在某個時間點你會開始定義函式,參數都準備好了...
+
+接著你需要呼叫「那個把第一個字母轉大寫的方法」。
+
+是 `upper`?還是 `uppercase`?`first_uppercase`?`capitalize`?
+
+然後你試著用老牌程式設計師的好朋友——編輯器自動完成。
+
+你輸入函式的第一個參數 `first_name`,接著打一個點(`.`),然後按下 `Ctrl+Space` 觸發自動完成。
+
+但很遺憾,你什麼有用的也沒得到:
+
+
+
+### 加上型別 { #add-types }
+
+我們來修改前一版中的一行。
+
+我們只要把函式參數這一段,從:
+
+```Python
+ first_name, last_name
+```
+
+改成:
+
+```Python
+ first_name: str, last_name: str
+```
+
+就這樣。
+
+那些就是「型別提示」:
+
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
+
+這和宣告預設值不同,例如:
+
+```Python
+ first_name="john", last_name="doe"
+```
+
+這是不同的東西。
+
+我們使用的是冒號(`:`),不是等號(`=`)。
+
+而且加上型別提示通常不會改變執行結果,和不加時是一樣的。
+
+不過現在,想像你又在撰寫那個函式,但這次有型別提示。
+
+在同樣的地方,你按 `Ctrl+Space` 嘗試自動完成,然後你會看到:
+
+
+
+有了這些,你可以往下捲動查看選項,直到找到一個「看起來眼熟」的:
+
+
+
+## 更多動機 { #more-motivation }
+
+看這個函式,它已經有型別提示了:
+
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
+
+因為編輯器知道變數的型別,你不只會得到自動完成,還會得到錯誤檢查:
+
+
+
+現在你知道要修正它,把 `age` 用 `str(age)` 轉成字串:
+
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
+
+## 宣告型別 { #declaring-types }
+
+你剛剛看到宣告型別提示的主要位置:函式參數。
+
+這也是你在 **FastAPI** 中最常使用它們的地方。
+
+### 簡單型別 { #simple-types }
+
+你可以宣告所有標準的 Python 型別,不只 `str`。
+
+例如你可以用:
+
+* `int`
+* `float`
+* `bool`
+* `bytes`
+
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
+
+### `typing` 模組 { #typing-module }
+
+在一些其他情境中,你可能需要從標準程式庫的 `typing` 模組匯入一些東西,比如當你想宣告某個東西可以是「任何型別」時,可以用 `typing` 裡的 `Any`:
+
+```python
+from typing import Any
+
+
+def some_function(data: Any):
+ print(data)
+```
+
+### 泛型(Generic types) { #generic-types }
+
+有些型別可以在方括號中接收「型別參數」,以定義其內部元素的型別,例如「字串的 list」可以宣告為 `list[str]`。
+
+這些能接收型別參數的型別稱為「泛型(Generic types)」或「Generics」。
+
+你可以將相同的內建型別用作泛型(使用方括號並在裡面放型別):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+#### List { #list }
+
+例如,讓我們定義一個變數是 `str` 的 `list`。
+
+宣告變數,使用相同的冒號(`:`)語法。
+
+型別填 `list`。
+
+由於 list 是一種包含內部型別的型別,你要把內部型別放在方括號中:
+
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
+
+/// info | 資訊
+
+方括號裡的那些內部型別稱為「型別參數」。
+
+在這個例子中,`str` 是傳給 `list` 的型別參數。
+
+///
+
+這表示:「變數 `items` 是一個 `list`,而這個清單中的每個元素都是 `str`」。
+
+這麼做之後,你的編輯器甚至在處理清單裡的項目時也能提供支援:
+
+
+
+沒有型別時,幾乎不可能做到這點。
+
+請注意,變數 `item` 是清單 `items` 中的一個元素。
+
+即便如此,編輯器仍然知道它是 `str`,並提供相應的支援。
+
+#### Tuple 與 Set { #tuple-and-set }
+
+你也可以用相同方式來宣告 `tuple` 與 `set`:
+
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
+
+這代表:
+
+* 變數 `items_t` 是一個有 3 個項目的 `tuple`,分別是 `int`、`int` 和 `str`。
+* 變數 `items_s` 是一個 `set`,而其中每個項目都是 `bytes` 型別。
+
+#### Dict { #dict }
+
+定義 `dict` 時,你需要傳入 2 個以逗號分隔的型別參數。
+
+第一個型別參數是 `dict` 的鍵(key)。
+
+第二個型別參數是 `dict` 的值(value):
+
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
+
+這代表:
+
+* 變數 `prices` 是個 `dict`:
+ * 這個 `dict` 的鍵是 `str`(例如每個項目的名稱)。
+ * 這個 `dict` 的值是 `float`(例如每個項目的價格)。
+
+#### Union { #union }
+
+你可以宣告一個變數可以是「多種型別」中的任一種,例如 `int` 或 `str`。
+
+要這麼定義,你使用豎線(`|`)來分隔兩種型別。
+
+這稱為「union」,因為變數可以是這兩種型別集合的聯集中的任一種。
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+這表示 `item` 可以是 `int` 或 `str`。
+
+#### 可能為 `None` { #possibly-none }
+
+你可以宣告某個值可以是某個型別(例如 `str`),但它也可能是 `None`。
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
+
+使用 `str | None` 而不是單純的 `str`,可以讓編輯器幫你偵測錯誤,例如你以為某個值一定是 `str`,但它其實也可能是 `None`。
+
+### 類別作為型別 { #classes-as-types }
+
+你也可以用類別來宣告變數的型別。
+
+假設你有一個 `Person` 類別,帶有名稱:
+
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
+
+接著你可以宣告一個變數為 `Person` 型別:
+
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
+
+然後,你一樣會得到完整的編輯器支援:
+
+
+
+請注意,這表示「`one_person` 是類別 `Person` 的『實例(instance)』」。
+
+並不是「`one_person` 就是名為 `Person` 的『類別(class)』」。
+
+## Pydantic 模型 { #pydantic-models }
+
+Pydantic 是一個用來做資料驗證的 Python 程式庫。
+
+你以帶有屬性的類別來宣告資料的「形狀」。
+
+而每個屬性都有其型別。
+
+接著你用一些值建立這個類別的實例,它會驗證這些值、在需要時把它們轉換成適當的型別,然後回給你一個包含所有資料的物件。
+
+你也會對這個產生的物件得到完整的編輯器支援。
+
+以下是來自 Pydantic 官方文件的例子:
+
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info | 資訊
+
+想了解更多 Pydantic,請查看它的文件。
+
+///
+
+**FastAPI** 完全是以 Pydantic 為基礎。
+
+你會在[教學 - 使用者指南](tutorial/index.md){.internal-link target=_blank}中看到更多實際範例。
+
+## 含中繼資料的型別提示 { #type-hints-with-metadata-annotations }
+
+Python 也有一個功能,允許使用 `Annotated` 在這些型別提示中放入額外的中繼資料。
+
+你可以從 `typing` 匯入 `Annotated`。
+
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
+
+Python 本身不會對這個 `Annotated` 做任何事。對編輯器與其他工具而言,該型別仍然是 `str`。
+
+但你可以利用 `Annotated` 這個空間,來提供 **FastAPI** 額外的中繼資料,告訴它你希望應用程式如何運作。
+
+重要的是要記住,傳給 `Annotated` 的「第一個型別參數」才是「真正的型別」。其餘的,都是給其他工具用的中繼資料。
+
+目前你只需要知道 `Annotated` 的存在,而且它是標準的 Python。😎
+
+之後你會看到它有多「強大」。
+
+/// tip | 提示
+
+因為這是「標準 Python」,所以你在編輯器、分析與重構程式碼的工具等方面,仍然能獲得「最佳的開發體驗」。✨
+
+而且你的程式碼也會與許多其他 Python 工具與程式庫非常相容。🚀
+
+///
+
+## 在 **FastAPI** 中的型別提示 { #type-hints-in-fastapi }
+
+**FastAPI** 善用這些型別提示來完成多項工作。
+
+在 **FastAPI** 中,你用型別提示來宣告參數,然後你會得到:
+
+* 編輯器支援
+* 型別檢查
+
+...而 **FastAPI** 也會用同樣的宣告來:
+
+* 定義需求:來自請求的路徑參數、查詢參數、標頭、主體(body)、相依性等
+* 轉換資料:把請求中的資料轉成所需型別
+* 驗證資料:來自每個請求的資料:
+ * 當資料無效時,自動產生錯誤並回傳給用戶端
+* 使用 OpenAPI 書寫 API 文件:
+ * 之後會由自動的互動式文件介面所使用
+
+這些現在聽起來可能有點抽象。別擔心。你會在[教學 - 使用者指南](tutorial/index.md){.internal-link target=_blank}中看到它們的實際運作。
+
+重點是,透過在單一位置使用標準的 Python 型別(而不是新增更多類別、裝飾器等),**FastAPI** 會幫你完成很多工作。
+
+/// info | 資訊
+
+如果你已經完整讀完整個教學,並回來想多看一些關於型別的內容,一個不錯的資源是 `mypy` 的「小抄」。
+
+///
diff --git a/docs/zh-hant/docs/translation-banner.md b/docs/zh-hant/docs/translation-banner.md
new file mode 100644
index 000000000..58b49965a
--- /dev/null
+++ b/docs/zh-hant/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 AI 與人類共同完成的翻譯
+
+此翻譯由人類指導的 AI 完成。🤝
+
+可能會有對原意的誤解,或讀起來不自然等問題。🤖
+
+你可以透過[協助我們更好地引導 AI LLM](https://fastapi.tiangolo.com/zh-hant/contributing/#translations)來改進此翻譯。
+
+[英文版](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/zh-hant/docs/tutorial/background-tasks.md b/docs/zh-hant/docs/tutorial/background-tasks.md
new file mode 100644
index 000000000..63e4e5a16
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/background-tasks.md
@@ -0,0 +1,84 @@
+# 背景任務 { #background-tasks }
+
+你可以定義背景任務,讓它們在傳回回應之後執行。
+
+這對於那些需要在請求之後發生、但用戶端其實不必在收到回應前等它完成的操作很有用。
+
+例如:
+
+* 在執行某個動作後發送電子郵件通知:
+ * 由於連線到郵件伺服器並寄送郵件通常較「慢」(數秒),你可以先立即回應,並在背景中發送郵件通知。
+* 處理資料:
+ * 例如,收到一個需要經過較慢處理流程的檔案時,你可以先回應「Accepted」(HTTP 202),再在背景處理該檔案。
+
+## 使用 `BackgroundTasks` { #using-backgroundtasks }
+
+首先,匯入 `BackgroundTasks`,並在你的路徑操作函式中定義一個型別為 `BackgroundTasks` 的參數:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
+
+**FastAPI** 會為你建立 `BackgroundTasks` 物件,並以該參數傳入。
+
+## 建立任務函式 { #create-a-task-function }
+
+建立一個作為背景任務執行的函式。
+
+它只是個可接收參數的一般函式。
+
+它可以是 `async def`,也可以是一般的 `def`,**FastAPI** 都能正確處理。
+
+在此例中,任務函式會寫入檔案(模擬寄送電子郵件)。
+
+由於寫入操作未使用 `async` 與 `await`,因此以一般的 `def` 定義該函式:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
+
+## 新增背景任務 { #add-the-background-task }
+
+在路徑操作函式內,使用 `.add_task()` 將任務函式加入背景任務物件:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
+
+`.add_task()` 的引數包括:
+
+* 要在背景執行的任務函式(`write_notification`)。
+* 依序傳給任務函式的位置引數(`email`)。
+* 要傳給任務函式的關鍵字引數(`message="some notification"`)。
+
+## 相依性注入 { #dependency-injection }
+
+在相依性注入系統中也可使用 `BackgroundTasks`。你可以在多個層級宣告 `BackgroundTasks` 型別的參數:路徑操作函式、相依項(dependable)、次級相依項等。
+
+**FastAPI** 會在各種情況下正確處理並重用同一個物件,將所有背景任務合併,並在之後於背景執行:
+
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
+
+在此範例中,訊息會在回應送出之後寫入 `log.txt` 檔案。
+
+如果請求中有查詢參數,會以背景任務寫入日誌。
+
+接著,在路徑操作函式中建立的另一個背景任務會使用 `email` 路徑參數寫入訊息。
+
+## 技術細節 { #technical-details }
+
+類別 `BackgroundTasks` 直接來自 `starlette.background`。
+
+它被直接匯入/包含到 FastAPI 中,因此你可以從 `fastapi` 匯入它,並避免不小心從 `starlette.background` 匯入另一個同名的 `BackgroundTask`(結尾沒有 s)。
+
+只使用 `BackgroundTasks`(而非 `BackgroundTask`)時,你就能把它當作路徑操作函式的參數,並讓 **FastAPI** 幫你處理其餘部分,就像直接使用 `Request` 物件一樣。
+
+在 FastAPI 中仍可單獨使用 `BackgroundTask`,但你需要在程式碼中自行建立該物件,並回傳包含它的 Starlette `Response`。
+
+更多細節請參閱 Starlette 官方的 Background Tasks 文件。
+
+## 注意事項 { #caveat }
+
+如果你需要執行繁重的背景計算,且不一定要由同一個行程執行(例如不需要共用記憶體、變數等),可以考慮使用更大型的工具,例如 Celery。
+
+這類工具通常需要較複雜的設定,以及訊息/工作佇列管理器(如 RabbitMQ 或 Redis),但它們允許你在多個行程,甚至多台伺服器上執行背景任務。
+
+但如果你需要存取同一個 **FastAPI** 應用中的變數與物件,或只需執行小型的背景任務(例如寄送郵件通知),僅使用 `BackgroundTasks` 即可。
+
+## 重點回顧 { #recap }
+
+在路徑操作函式與相依項中匯入並使用 `BackgroundTasks` 參數,以新增背景任務。
diff --git a/docs/zh-hant/docs/tutorial/bigger-applications.md b/docs/zh-hant/docs/tutorial/bigger-applications.md
new file mode 100644
index 000000000..d8b8c9bff
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/bigger-applications.md
@@ -0,0 +1,504 @@
+# 更大型的應用程式 - 多個檔案 { #bigger-applications-multiple-files }
+
+如果你正在建置一個應用程式或 Web API,很少會把所有東西都放在單一檔案裡。
+
+FastAPI 提供了一個方便的工具,讓你在維持彈性的同時,幫你組織應用程式的結構。
+
+/// info | 資訊
+
+如果你來自 Flask,這相當於 Flask 的 Blueprints。
+
+///
+
+## 範例檔案結構 { #an-example-file-structure }
+
+假設你有如下的檔案結構:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | 提示
+
+有好幾個 `__init__.py` 檔案:每個目錄或子目錄各一個。
+
+這讓我們可以把一個檔案中的程式碼匯入到另一個檔案。
+
+例如,在 `app/main.py` 你可以有一行:
+
+```
+from app.routers import items
+```
+
+///
+
+* `app` 目錄包含所有內容。它有一個空的 `app/__init__.py` 檔案,所以它是一個「Python 套件」(「Python 模組」的集合):`app`。
+* 它包含一個 `app/main.py` 檔案。因為它在一個 Python 套件中(有 `__init__.py` 檔案的目錄),它是該套件的一個「模組」:`app.main`。
+* 還有一個 `app/dependencies.py` 檔案,就像 `app/main.py` 一樣,它是一個「模組」:`app.dependencies`。
+* 有一個子目錄 `app/routers/`,裡面有另一個 `__init__.py` 檔案,所以它是一個「Python 子套件」:`app.routers`。
+* 檔案 `app/routers/items.py` 在一個套件 `app/routers/` 內,因此它是一個子模組:`app.routers.items`。
+* 同樣地,`app/routers/users.py` 是另一個子模組:`app.routers.users`。
+* 還有一個子目錄 `app/internal/`,裡面有另一個 `__init__.py` 檔案,所以它又是一個「Python 子套件」:`app.internal`。
+* 檔案 `app/internal/admin.py` 是另一個子模組:`app.internal.admin`。
+
+
+
+同樣的檔案結構,附上註解:
+
+```bash
+.
+├── app # 「app」是一個 Python 套件
+│ ├── __init__.py # 這個檔案讓「app」成為「Python 套件」
+│ ├── main.py # 「main」模組,例如 import app.main
+│ ├── dependencies.py # 「dependencies」模組,例如 import app.dependencies
+│ └── routers # 「routers」是一個「Python 子套件」
+│ │ ├── __init__.py # 讓「routers」成為「Python 子套件」
+│ │ ├── items.py # 「items」子模組,例如 import app.routers.items
+│ │ └── users.py # 「users」子模組,例如 import app.routers.users
+│ └── internal # 「internal」是一個「Python 子套件」
+│ ├── __init__.py # 讓「internal」成為「Python 子套件」
+│ └── admin.py # 「admin」子模組,例如 import app.internal.admin
+```
+
+## `APIRouter` { #apirouter }
+
+假設專門處理使用者的檔案是位於 `/app/routers/users.py` 的子模組。
+
+你希望把與使用者相關的「路徑操作 (path operation)」從其他程式碼分離,讓結構更有條理。
+
+但它仍然是同一個 FastAPI 應用程式 / Web API 的一部分(屬於同一個「Python 套件」)。
+
+你可以使用 `APIRouter` 為該模組建立路徑操作。
+
+### 匯入 `APIRouter` { #import-apirouter }
+
+你可以像對 `FastAPI` 類別那樣匯入並建立一個「實例」:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+
+### 使用 `APIRouter` 宣告路徑操作 { #path-operations-with-apirouter }
+
+然後用它來宣告你的路徑操作。
+
+用法就和 `FastAPI` 類別一樣:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+
+你可以把 `APIRouter` 想成是「迷你版的 `FastAPI`」類別。
+
+所有相同的選項都支援。
+
+同樣的 `parameters`、`responses`、`dependencies`、`tags` 等全都可用。
+
+/// tip | 提示
+
+在這個範例中,變數名叫 `router`,但你可以用任何你想用的名稱。
+
+///
+
+我們稍後會把這個 `APIRouter` 加進主要的 `FastAPI` 應用程式中,但先來看看相依性與另一個 `APIRouter`。
+
+## 相依性 { #dependencies }
+
+我們發現應用程式的多個地方會用到一些相依性。
+
+所以把它們放進獨立的 `dependencies` 模組(`app/dependencies.py`)。
+
+接下來我們會用一個簡單的相依性來讀取自訂的 `X-Token` 標頭:
+
+{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+
+/// tip | 提示
+
+為了簡化範例,我們使用了一個虛構的標頭。
+
+但在真實情況下,使用內建的[安全工具](security/index.md){.internal-link target=_blank}會有更好的效果。
+
+///
+
+## 另一個帶有 `APIRouter` 的模組 { #another-module-with-apirouter }
+
+假設你還有一個模組 `app/routers/items.py`,專門處理應用程式中的「items」。
+
+你有以下路徑操作:
+
+* `/items/`
+* `/items/{item_id}`
+
+其結構與 `app/routers/users.py` 相同。
+
+但我們想要更聰明地簡化一些程式碼。
+
+我們知道這個模組中的所有路徑操作都有相同的:
+
+* 路徑 `prefix`:`/items`
+* `tags`:(只有一個標籤:`items`)
+* 額外的 `responses`
+* `dependencies`:它們都需要我們先前建立的 `X-Token` 相依性
+
+因此,我們可以不必把這些都加在每個路徑操作上,而是把它們加在 `APIRouter` 上。
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+
+由於每個路徑操作的路徑都必須以 `/` 開頭,例如:
+
+```Python hl_lines="1"
+@router.get("/{item_id}")
+async def read_item(item_id: str):
+ ...
+```
+
+...所以 prefix 末尾不能帶有 `/`。
+
+因此,此處的 prefix 是 `/items`。
+
+我們也可以加上一個 `tags` 清單,以及會套用在此 router 內所有路徑操作上的額外 `responses`。
+
+我們還可以加上一個 `dependencies` 清單,這些相依性會加入此 router 內所有的路徑操作,並在對它們的每個請求上執行 / 解決。
+
+/// tip | 提示
+
+請注意,就像在[路徑操作裝飾器中的相依性](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}一樣,不會把任何值傳遞給你的路徑操作函式(path operation function)。
+
+///
+
+最後的結果是這些 item 的路徑如下:
+
+* `/items/`
+* `/items/{item_id}`
+
+...正如我們預期的。
+
+* 它們會被標記為只有一個字串 `"items"` 的標籤清單。
+ * 這些「標籤」對自動互動式文件系統(使用 OpenAPI)特別有用。
+* 它們都會包含預先定義的 `responses`。
+* 這些路徑操作都會在執行前評估 / 執行其 `dependencies` 清單。
+ * 如果你也在特定的路徑操作中宣告了相依性,這些相依性也會被執行。
+ * Router 的相依性會先執行,然後是[裝飾器中的 `dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank},最後是一般參數相依性。
+ * 你也可以加入帶有 `scopes` 的 [`Security` 相依性](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}。
+
+/// tip | 提示
+
+在 `APIRouter` 中設定 `dependencies`,例如可以用來對一整組路徑操作要求驗證。即使沒有在每個路徑操作個別加入相依性也沒關係。
+
+///
+
+/// check | 檢查
+
+`prefix`、`tags`、`responses` 與 `dependencies` 參數(就像許多其他情況一樣)只是 FastAPI 提供的功能,幫助你避免重複程式碼。
+
+///
+
+### 匯入相依性 { #import-the-dependencies }
+
+這段程式碼在模組 `app.routers.items`(檔案 `app/routers/items.py`)中。
+
+我們需要從模組 `app.dependencies`(檔案 `app/dependencies.py`)取得相依性函式。
+
+因此我們用 `..` 做相對匯入相依性:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}
+
+#### 相對匯入如何運作 { #how-relative-imports-work }
+
+/// tip | 提示
+
+如果你對匯入的運作方式十分了解,可以直接跳到下一節。
+
+///
+
+單一的點號 `.`,如下:
+
+```Python
+from .dependencies import get_token_header
+```
+
+代表:
+
+* 從此模組(檔案 `app/routers/items.py`)所在的相同套件(目錄 `app/routers/`)開始...
+* 找到模組 `dependencies`(想像的檔案 `app/routers/dependencies.py`)...
+* 並從中匯入函式 `get_token_header`。
+
+但那個檔案不存在,我們的相依性在 `app/dependencies.py`。
+
+回想一下我們的應用 / 檔案結構長這樣:
+
+
+
+---
+
+兩個點號 `..`,如下:
+
+```Python
+from ..dependencies import get_token_header
+```
+
+代表:
+
+* 從此模組(檔案 `app/routers/items.py`)所在的相同套件(目錄 `app/routers/`)開始...
+* 前往其父套件(目錄 `app/`)...
+* 然後在那裡找到模組 `dependencies`(檔案 `app/dependencies.py`)...
+* 並從中匯入函式 `get_token_header`。
+
+這就正確了!🎉
+
+---
+
+同樣地,如果我們用三個點號 `...`,如下:
+
+```Python
+from ...dependencies import get_token_header
+```
+
+就代表:
+
+* 從此模組(檔案 `app/routers/items.py`)所在的相同套件(目錄 `app/routers/`)開始...
+* 前往其父套件(目錄 `app/`)...
+* 再前往那個套件的父層(沒有更上層的套件了,`app` 已是最上層 😱)...
+* 然後在那裡找到模組 `dependencies`(檔案 `app/dependencies.py`)...
+* 並從中匯入函式 `get_token_header`。
+
+那會指向 `app/` 之上的某個套件,該套件需有自己的 `__init__.py` 等等。但我們沒有。所以在這個例子中會丟出錯誤。🚨
+
+不過現在你知道它的運作方式了,因此無論你的應用有多複雜,你都可以使用相對匯入。🤓
+
+### 加上一些自訂的 `tags`、`responses` 與 `dependencies` { #add-some-custom-tags-responses-and-dependencies }
+
+我們沒有把 `/items` 的 prefix 以及 `tags=["items"]` 加在每個路徑操作上,因為我們已經把它們加在 `APIRouter` 上了。
+
+但我們仍可以在特定的路徑操作上再加上更多的 `tags`,以及一些只屬於該路徑操作的額外 `responses`:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+
+/// tip | 提示
+
+這最後一個路徑操作會有組合後的標籤:`["items", "custom"]`。
+
+而且在文件中同時會有 `404` 與 `403` 兩種回應。
+
+///
+
+## 主程式 `FastAPI` { #the-main-fastapi }
+
+現在,來看看 `app/main.py` 這個模組。
+
+你會在這裡匯入並使用 `FastAPI` 類別。
+
+這會是你的應用程式中把一切串起來的主檔案。
+
+而隨著大多數的邏輯都放在各自的模組中,主檔案會相當簡潔。
+
+### 匯入 `FastAPI` { #import-fastapi }
+
+照常匯入並建立 `FastAPI` 類別。
+
+我們甚至可以宣告[全域相依性](dependencies/global-dependencies.md){.internal-link target=_blank},它們會與各 `APIRouter` 的相依性合併:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
+
+### 匯入 `APIRouter` { #import-the-apirouter }
+
+現在我們匯入包含 `APIRouter` 的其他子模組:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}
+
+由於 `app/routers/users.py` 與 `app/routers/items.py` 是同一個 Python 套件 `app` 的子模組,我們可以用單一的點號 `.` 來進行「相對匯入」。
+
+### 匯入如何運作 { #how-the-importing-works }
+
+這段:
+
+```Python
+from .routers import items, users
+```
+
+代表:
+
+* 從此模組(檔案 `app/main.py`)所在的相同套件(目錄 `app/`)開始...
+* 尋找子套件 `routers`(目錄 `app/routers/`)...
+* 並從中匯入子模組 `items`(檔案 `app/routers/items.py`)與 `users`(檔案 `app/routers/users.py`)...
+
+模組 `items` 會有一個變數 `router`(`items.router`)。這就是我們在 `app/routers/items.py` 建立的那個 `APIRouter` 物件。
+
+接著我們對 `users` 模組做一樣的事。
+
+我們也可以這樣匯入:
+
+```Python
+from app.routers import items, users
+```
+
+/// info | 資訊
+
+第一種是「相對匯入」:
+
+```Python
+from .routers import items, users
+```
+
+第二種是「絕對匯入」:
+
+```Python
+from app.routers import items, users
+```
+
+想了解更多關於 Python 套件與模組,請閱讀官方的模組說明文件。
+
+///
+
+### 避免名稱衝突 { #avoid-name-collisions }
+
+我們直接匯入子模組 `items`,而不是只匯入它的變數 `router`。
+
+這是因為在子模組 `users` 中也有另一個名為 `router` 的變數。
+
+如果我們像下面這樣一個接一個匯入:
+
+```Python
+from .routers.items import router
+from .routers.users import router
+```
+
+來自 `users` 的 `router` 會覆蓋掉 `items` 的 `router`,我們就無法同時使用兩者。
+
+因此,為了能在同一個檔案中同時使用它們,我們直接匯入子模組:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}
+
+### 將 `users` 與 `items` 的 `APIRouter` 納入 { #include-the-apirouters-for-users-and-items }
+
+現在,把子模組 `users` 與 `items` 的 `router` 納入:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}
+
+/// info | 資訊
+
+`users.router` 是位於 `app/routers/users.py` 檔案內的 `APIRouter`。
+
+而 `items.router` 是位於 `app/routers/items.py` 檔案內的 `APIRouter`。
+
+///
+
+透過 `app.include_router()`,我們可以把每個 `APIRouter` 加到主要的 `FastAPI` 應用程式。
+
+它會把該 router 的所有路由都納入成為應用的一部分。
+
+/// note | 技術細節
+
+實際上,它會在內部為 `APIRouter` 中宣告的每一個「路徑操作」建立一個對應的「路徑操作」。
+
+所以在幕後,它實際運作起來就像是一個單一的應用。
+
+///
+
+/// check | 檢查
+
+把 router 納入時不需要擔心效能。
+
+這只會在啟動時花費微秒等級,且只發生一次。
+
+因此不會影響效能。⚡
+
+///
+
+### 以自訂的 `prefix`、`tags`、`responses` 與 `dependencies` 納入一個 `APIRouter` { #include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies }
+
+現在,假設你的組織提供了一個 `app/internal/admin.py` 檔案給你。
+
+它包含一個帶有一些管理員路徑操作的 `APIRouter`,並在組織內多個專案之間共用。
+
+為了這個範例它會非常簡單。但假設因為它會與組織內的其他專案共用,我們不能直接修改它並把 `prefix`、`dependencies`、`tags` 等加在 `APIRouter` 上:
+
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+
+但當我們把這個 `APIRouter` 納入時,仍然希望設定自訂的 `prefix`,讓它所有的路徑操作都以 `/admin` 開頭;我們想用這個專案已經有的 `dependencies` 來保護它,並且要加入 `tags` 與 `responses`。
+
+我們可以在不修改原始 `APIRouter` 的情況下,將這些參數傳給 `app.include_router()` 來達成:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}
+
+如此一來,原始的 `APIRouter` 將保持不變,因此我們仍然可以把同一個 `app/internal/admin.py` 檔案與組織中的其他專案共用。
+
+結果是在我們的應用中,來自 `admin` 模組的每個路徑操作都會有:
+
+* 前綴 `/admin`
+* 標籤 `admin`
+* 相依性 `get_token_header`
+* 回應 `418` 🍵
+
+但這只會影響我們應用中的那個 `APIRouter`,不會影響任何其他使用它的程式碼。
+
+例如,其他專案可以用不同的驗證方式搭配相同的 `APIRouter`。
+
+### 加上一個路徑操作 { #include-a-path-operation }
+
+我們也可以直接把路徑操作加到 `FastAPI` 應用中。
+
+這裡我們就加一下... 只是為了示範可以這麼做 🤷:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}
+
+而且它會和透過 `app.include_router()` 加入的其他路徑操作正確地一起運作。
+
+/// info | 非常技術細節
+
+注意:這是個非常技術性的細節,你大概可以直接略過。
+
+---
+
+`APIRouter` 不是被「掛載 (mount)」的,它們不會與應用的其他部分隔離開來。
+
+這是因為我們要把它們的路徑操作包含進 OpenAPI 結構與使用者介面中。
+
+由於無法將它們隔離並獨立「掛載」,所以這些路徑操作會被「複製」(重新建立),而不是直接包含進來。
+
+///
+
+## 檢查自動產生的 API 文件 { #check-the-automatic-api-docs }
+
+現在,執行你的應用:
+
+
+
+## 以不同的 `prefix` 多次納入同一個 router { #include-the-same-router-multiple-times-with-different-prefix }
+
+你也可以用不同的前綴,對同一個 router 多次呼叫 `.include_router()`。
+
+例如,這對於在不同前綴下提供相同的 API 很有用,如 `/api/v1` 與 `/api/latest`。
+
+這是進階用法,你可能不會需要,但若有需要它就在那裡。
+
+## 在另一個 `APIRouter` 中納入一個 `APIRouter` { #include-an-apirouter-in-another }
+
+就像你可以在 `FastAPI` 應用中納入一個 `APIRouter` 一樣,你也可以在另一個 `APIRouter` 中納入一個 `APIRouter`,用法如下:
+
+```Python
+router.include_router(other_router)
+```
+
+請確保在把 `router` 納入 `FastAPI` 應用之前先這麼做,這樣 `other_router` 的路徑操作也會被包含進去。
diff --git a/docs/zh-hant/docs/tutorial/body-fields.md b/docs/zh-hant/docs/tutorial/body-fields.md
new file mode 100644
index 000000000..a16e756b7
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/body-fields.md
@@ -0,0 +1,61 @@
+# Body - 欄位 { #body-fields }
+
+就像你可以在「路徑操作函式 (path operation function)」的參數中用 `Query`、`Path` 和 `Body` 宣告額外的驗證與中繼資料一樣,你也可以在 Pydantic 模型中使用 Pydantic 的 `Field` 來宣告驗證與中繼資料。
+
+## 匯入 `Field` { #import-field }
+
+首先,你需要匯入它:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
+
+
+/// warning
+
+請注意,`Field` 是直接從 `pydantic` 匯入的,不像其他(如 `Query`、`Path`、`Body` 等)是從 `fastapi` 匯入。
+
+///
+
+## 宣告模型屬性 { #declare-model-attributes }
+
+接著你可以在模型屬性上使用 `Field`:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
+
+`Field` 的用法與 `Query`、`Path`、`Body` 相同,擁有相同的參數等。
+
+/// note | 技術細節
+
+實際上,你接下來會看到的 `Query`、`Path` 等,會建立共同父類別 `Param` 的子類別物件,而 `Param` 本身是 Pydantic 的 `FieldInfo` 類別的子類別。
+
+而 Pydantic 的 `Field` 也會回傳一個 `FieldInfo` 的實例。
+
+`Body` 也會直接回傳 `FieldInfo` 子類別的物件。稍後你會看到還有其他類別是 `Body` 類別的子類別。
+
+記得,當你從 `fastapi` 匯入 `Query`、`Path` 等時,它們其實是回傳特殊類別的函式。
+
+///
+
+/// tip
+
+注意,每個帶有型別、預設值與 `Field` 的模型屬性,其結構和「路徑操作函式」的參數相同,只是把 `Path`、`Query`、`Body` 換成了 `Field`。
+
+///
+
+## 加入額外資訊 { #add-extra-information }
+
+你可以在 `Field`、`Query`、`Body` 等中宣告額外資訊。這些資訊會被包含在產生的 JSON Schema 中。
+
+你會在後續文件中學到更多關於加入額外資訊的內容,特別是在宣告範例時。
+
+/// warning
+
+傳入 `Field` 的額外鍵也會出現在你的應用程式所產生的 OpenAPI schema 中。
+由於這些鍵不一定屬於 OpenAPI 規格的一部分,一些 OpenAPI 工具(例如 [OpenAPI 驗證器](https://validator.swagger.io/))可能無法處理你產生的 schema。
+
+///
+
+## 回顧 { #recap }
+
+你可以使用 Pydantic 的 `Field` 為模型屬性宣告額外的驗證與中繼資料。
+
+你也可以使用額外的關鍵字引數來傳遞額外的 JSON Schema 中繼資料。
diff --git a/docs/zh-hant/docs/tutorial/body-multiple-params.md b/docs/zh-hant/docs/tutorial/body-multiple-params.md
new file mode 100644
index 000000000..1c334f51f
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,165 @@
+# Body - 多個參數 { #body-multiple-parameters }
+
+現在我們已經知道如何使用 `Path` 與 `Query`,接下來看看更進階的請求主體(request body)宣告用法。
+
+## 混用 `Path`、`Query` 與 Body 參數 { #mix-path-query-and-body-parameters }
+
+首先,當然你可以自由混用 `Path`、`Query` 與請求 Body 參數的宣告,**FastAPI** 會知道該怎麼做。
+
+你也可以將 Body 參數宣告為可選,方法是將預設值設為 `None`:
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// note | 注意
+
+請注意,在此情況下,從 body 取得的 `item` 是可選的,因為它的預設值是 `None`。
+
+///
+
+## 多個 Body 參數 { #multiple-body-parameters }
+
+在前一個範例中,路徑操作(path operation)會期望一個包含 `Item` 屬性的 JSON 主體,例如:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+但你也可以宣告多個 Body 參數,例如 `item` 與 `user`:
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+在此情況下,**FastAPI** 會注意到函式中有多個 Body 參數(有兩個參數是 Pydantic 模型)。
+
+因此,它會使用參數名稱作為 body 中的鍵(欄位名稱),並期望如下的主體:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ }
+}
+```
+
+/// note | 注意
+
+儘管 `item` 的宣告方式與先前相同,現在預期它會位於 body 內,且鍵為 `item`。
+
+///
+
+**FastAPI** 會自動從請求中進行轉換,讓參數 `item` 收到對應內容,`user` 亦同。
+
+它會對複合資料進行驗證,並在 OpenAPI 結構與自動文件中如此描述。
+
+## Body 中的單一值 { #singular-values-in-body }
+
+就像你可以用 `Query` 與 `Path` 為查詢與路徑參數定義額外資訊一樣,**FastAPI** 也提供對應的 `Body`。
+
+例如,延伸前述模型,你可以決定在相同的 Body 中,除了 `item` 與 `user` 外,還要有另一個鍵 `importance`。
+
+如果直接這樣宣告,因為它是單一值,**FastAPI** 會將其視為查詢參數。
+
+但你可以使用 `Body` 指示 **FastAPI** 將其視為另一個 Body 鍵:
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+在此情況下,**FastAPI** 會期望如下的主體:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+
+同樣地,它會進行型別轉換、驗證、文件化等。
+
+## 多個 Body 參數與 Query { #multiple-body-params-and-query }
+
+當然,你也可以在任何 Body 參數之外,視需要宣告額外的查詢參數。
+
+由於預設情況下,單一值會被解讀為查詢參數,你不必明確使用 `Query`,直接這樣寫即可:
+
+```Python
+q: str | None = None
+```
+
+例如:
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
+
+/// info | 注意
+
+`Body` 也具有與 `Query`、`Path` 以及之後你會看到的其他工具相同的額外驗證與中繼資料參數。
+
+///
+
+## 嵌入單一 Body 參數 { #embed-a-single-body-parameter }
+
+假設你只有一個來自 Pydantic 模型 `Item` 的單一 `item` Body 參數。
+
+預設情況下,**FastAPI** 會直接期望該模型的內容作為請求主體。
+
+但如果你想讓它像宣告多個 Body 參數時那樣,期望一個帶有 `item` 鍵、其內含模型內容的 JSON,你可以使用 `Body` 的特殊參數 `embed`:
+
+```Python
+item: Item = Body(embed=True)
+```
+
+如下:
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+在此情況下 **FastAPI** 會期望如下的主體:
+
+```JSON hl_lines="2"
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ }
+}
+```
+
+而不是:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+## 小結 { #recap }
+
+即便一個請求只能有單一主體,你仍可在你的路徑操作函式中宣告多個 Body 參數。
+
+但 **FastAPI** 會處理好這一切,在你的函式中提供正確的資料,並在路徑操作中驗證與文件化正確的結構。
+
+你也可以將單一值宣告為 Body 的一部分來接收。
+
+即使只宣告了一個參數,也可以指示 **FastAPI** 將 Body 以某個鍵進行嵌入。
diff --git a/docs/zh-hant/docs/tutorial/body-nested-models.md b/docs/zh-hant/docs/tutorial/body-nested-models.md
new file mode 100644
index 000000000..df4aff697
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/body-nested-models.md
@@ -0,0 +1,220 @@
+# Body - 巢狀模型 { #body-nested-models }
+
+使用 **FastAPI**,你可以定義、驗證、文件化,並使用任意深度的巢狀模型(感謝 Pydantic)。
+
+## 列表欄位 { #list-fields }
+
+你可以將屬性定義為某個子型別。例如,Python 的 `list`:
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+這會讓 `tags` 成為一個列表,儘管尚未宣告列表元素的型別。
+
+## 具有型別參數的列表欄位 { #list-fields-with-type-parameter }
+
+不過,Python 有一種專門的方式來宣告具有內部型別(「型別參數」)的列表:
+
+### 宣告帶有型別參數的 `list` { #declare-a-list-with-a-type-parameter }
+
+要宣告具有型別參數(內部型別)的型別,例如 `list`、`dict`、`tuple`,使用方括號 `[` 與 `]` 傳入內部型別作為「型別參數」:
+
+```Python
+my_list: list[str]
+```
+
+以上都是標準的 Python 型別宣告語法。
+
+對於具有內部型別的模型屬性,也使用相同的標準語法。
+
+因此,在我們的範例中,可以讓 `tags` 明確成為「字串的列表」:
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## 集合型別 { #set-types }
+
+但進一步思考後,我們會意識到 `tags` 不應該重覆,應該是唯一的字串。
+
+而 Python 有一種用於唯一元素集合的特殊資料型別:`set`。
+
+因此我們可以將 `tags` 宣告為字串的 `set`:
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+這樣一來,即使收到包含重覆資料的請求,也會被轉換為由唯一元素組成的 `set`。
+
+之後只要輸出該資料,即使來源有重覆,也會以唯一元素的 `set` 輸出。
+
+並且也會在註解/文件中相應標示。
+
+## 巢狀模型 { #nested-models }
+
+每個 Pydantic 模型的屬性都有型別。
+
+而該型別本身也可以是另一個 Pydantic 模型。
+
+因此,你可以宣告具有特定屬性名稱、型別與驗證的深度巢狀 JSON「物件」。
+
+而且可以任意深度巢狀。
+
+### 定義子模型 { #define-a-submodel }
+
+例如,我們可以定義一個 `Image` 模型:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### 將子模型作為型別使用 { #use-the-submodel-as-a-type }
+
+然後把它作為某個屬性的型別使用:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+這表示 **FastAPI** 會期望一個類似如下的本文:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": ["rock", "metal", "bar"],
+ "image": {
+ "url": "http://example.com/baz.jpg",
+ "name": "The Foo live"
+ }
+}
+```
+
+只需進行上述宣告,使用 **FastAPI** 你就能獲得:
+
+- 編輯器支援(自動完成等),即使是巢狀模型
+- 資料轉換
+- 資料驗證
+- 自動產生文件
+
+## 特殊型別與驗證 { #special-types-and-validation }
+
+除了 `str`、`int`、`float` 等一般的單一型別外,你也可以使用繼承自 `str` 的更複雜單一型別。
+
+若要查看所有可用選項,請參閱 Pydantic 的型別總覽。你會在下一章看到一些範例。
+
+例如,在 `Image` 模型中有一個 `url` 欄位,我們可以將其宣告為 Pydantic 的 `HttpUrl`,而不是 `str`:
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+該字串會被檢查是否為有效的 URL,並在 JSON Schema / OpenAPI 中相應註記。
+
+## 具有子模型列表的屬性 { #attributes-with-lists-of-submodels }
+
+你也可以將 Pydantic 模型作為 `list`、`set` 等的子型別使用:
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+這會期望(並進行轉換、驗證、文件化等)如下的 JSON 本文:
+
+```JSON hl_lines="11"
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": [
+ "rock",
+ "metal",
+ "bar"
+ ],
+ "images": [
+ {
+ "url": "http://example.com/baz.jpg",
+ "name": "The Foo live"
+ },
+ {
+ "url": "http://example.com/dave.jpg",
+ "name": "The Baz"
+ }
+ ]
+}
+```
+
+/// info
+
+注意 `images` 鍵現在是一個由 image 物件組成的列表。
+
+///
+
+## 深度巢狀模型 { #deeply-nested-models }
+
+你可以定義任意深度的巢狀模型:
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info
+
+請注意,`Offer` 具有一個 `Item` 的列表,而每個 `Item` 又有一個可選的 `Image` 列表。
+
+///
+
+## 純列表的本文 { #bodies-of-pure-lists }
+
+如果你期望的 JSON 本文頂層值是一個 JSON `array`(Python 的 `list`),可以像在 Pydantic 模型中那樣,直接在函式參數上宣告其型別:
+
+```Python
+images: list[Image]
+```
+
+如下所示:
+
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
+
+## 隨處可得的編輯器支援 { #editor-support-everywhere }
+
+你將在各處獲得編輯器支援。
+
+即使是列表中的項目也一樣:
+
+
+
+若直接操作 `dict` 而不是使用 Pydantic 模型,就無法獲得這種等級的編輯器支援。
+
+但你也不必擔心,傳入的 dict 會自動被轉換,而你的輸出也會自動轉換為 JSON。
+
+## 任意 `dict` 的本文 { #bodies-of-arbitrary-dicts }
+
+你也可以將本文宣告為一個 `dict`,其鍵為某種型別、值為另一種型別。
+
+如此一來,你無需事先知道有效的欄位/屬性名稱為何(不像使用 Pydantic 模型時需要)。
+
+這在你想接收尚未預知的鍵時很有用。
+
+---
+
+另一個實用情境是當你希望鍵是其他型別(例如,`int`)時。
+
+這正是我們在此要示範的。
+
+在此情況下,只要是擁有 `int` 鍵且對應 `float` 值的 `dict` 都會被接受:
+
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
+
+/// tip
+
+請記住,JSON 只支援 `str` 作為鍵。
+
+但 Pydantic 具有自動資料轉換。
+
+這表示即使你的 API 用戶端只能以字串作為鍵,只要這些字串是純整數,Pydantic 會自動轉換並驗證它們。
+
+而你作為 `weights` 所接收的 `dict`,實際上會擁有 `int` 鍵與 `float` 值。
+
+///
+
+## 總結 { #recap }
+
+使用 **FastAPI**,你在保持程式碼簡潔優雅的同時,亦可擁有 Pydantic 模型所提供的高度彈性。
+
+同時還具備以下優點:
+
+- 編輯器支援(到處都有自動完成!)
+- 資料轉換(亦即 parsing/serialization)
+- 資料驗證
+- 結構描述(Schema)文件
+- 自動產生文件
diff --git a/docs/zh-hant/docs/tutorial/body-updates.md b/docs/zh-hant/docs/tutorial/body-updates.md
new file mode 100644
index 000000000..a309e3522
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Body - 更新 { #body-updates }
+
+## 使用 `PUT` 取代式更新 { #update-replacing-with-put }
+
+要更新一個項目,你可以使用 HTTP `PUT` 操作。
+
+你可以使用 `jsonable_encoder` 將輸入資料轉換為可儲存為 JSON 的資料(例如用於 NoSQL 資料庫)。例如把 `datetime` 轉成 `str`。
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+`PUT` 用於接收應該取代現有資料的資料。
+
+### 關於取代的警告 { #warning-about-replacing }
+
+這表示,如果你想用 `PUT` 並在 body 中包含以下內容來更新項目 `bar`:
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+由於這裡沒有包含已儲存的屬性 `"tax": 20.2`,輸入的模型會採用預設值 `"tax": 10.5`。
+
+最終資料會以這個「新的」 `tax` 值 `10.5` 被儲存。
+
+## 使用 `PATCH` 進行部分更新 { #partial-updates-with-patch }
+
+你也可以使用 HTTP `PATCH` 操作來進行*部分*更新。
+
+這表示你只需傳送想要更新的資料,其餘保持不變。
+
+/// note | 注意
+
+`PATCH` 相較於 `PUT` 較少被使用、也較不為人知。
+
+許多團隊甚至在部分更新時也只用 `PUT`。
+
+你可以依需求自由選用,**FastAPI** 不會強制規範。
+
+但本指南會大致示範它們各自的設計用法。
+
+///
+
+### 使用 Pydantic 的 `exclude_unset` 參數 { #using-pydantics-exclude-unset-parameter }
+
+如果要接收部分更新,在 Pydantic 模型的 `.model_dump()` 中使用 `exclude_unset` 參數非常實用。
+
+例如 `item.model_dump(exclude_unset=True)`。
+
+這會產生一個只包含建立 `item` 模型時實際設定過之欄位的 `dict`,不含預設值。
+
+接著你可以用它來生成只包含實際設定(請求中傳來)的資料之 `dict`,省略預設值:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### 使用 Pydantic 的 `update` 參數 { #using-pydantics-update-parameter }
+
+接著,你可以用 `.model_copy()` 建立現有模型的副本,並傳入含有要更新資料之 `dict` 到 `update` 參數。
+
+例如 `stored_item_model.model_copy(update=update_data)`:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### 部分更新摘要 { #partial-updates-recap }
+
+總結一下,若要套用部分更新,你可以:
+
+*(可選)使用 `PATCH` 取代 `PUT`。
+* 取回已儲存的資料。
+* 將該資料放入一個 Pydantic 模型。
+* 從輸入模型產生一個不含預設值的 `dict`(使用 `exclude_unset`)。
+ * 如此即可只更新使用者實際設定的值,而不會以模型的預設值覆寫已儲存的值。
+* 建立已儲存模型的副本,並以收到的部分更新值更新其屬性(使用 `update` 參數)。
+* 將該副本模型轉成可儲存到資料庫的型別(例如使用 `jsonable_encoder`)。
+ * 這與再次使用模型的 `.model_dump()` 類似,但它會確保(並轉換)所有值為可轉為 JSON 的資料型別,例如把 `datetime` 轉為 `str`。
+* 將資料儲存到資料庫。
+* 回傳更新後的模型。
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | 提示
+
+其實你也可以在 HTTP `PUT` 操作中使用同一套技巧。
+
+但此處示例使用 `PATCH`,因為它正是為這類情境設計的。
+
+///
+
+/// note | 注意
+
+請注意,輸入的模型依然會被驗證。
+
+因此,如果你希望接收可以省略所有屬性的部分更新,你需要一個所有屬性皆為可選(具預設值或為 `None`)的模型。
+
+為了區分用於更新(全部可選)與用於建立(欄位為必填)的模型,你可以參考 [額外模型](extra-models.md){.internal-link target=_blank} 中的做法。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/body.md b/docs/zh-hant/docs/tutorial/body.md
new file mode 100644
index 000000000..bddcbbf43
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/body.md
@@ -0,0 +1,164 @@
+# 請求本文 { #request-body }
+
+當你需要從用戶端(例如瀏覽器)將資料傳送到你的 API 時,會把它作為**請求本文**送出。
+
+**請求**本文是用戶端傳給你的 API 的資料。**回應**本文是你的 API 傳回給用戶端的資料。
+
+你的 API 幾乎總是需要傳回**回應**本文。但用戶端不一定每次都要送出**請求本文**,有時只會請求某個路徑,可能帶一些查詢參數,但不會傳送本文。
+
+要宣告**請求**本文,你會使用 Pydantic 模型,享受其完整的功能與優點。
+
+/// info
+
+要傳送資料,應使用下列其中一種方法:`POST`(最常見)、`PUT`、`DELETE` 或 `PATCH`。
+
+在規範中,於 `GET` 請求中攜帶本文的行為是未定義的。不過,FastAPI 仍支援它,但僅適用於非常複雜/極端的情境。
+
+由於不建議這麼做,使用 Swagger UI 的互動式文件在使用 `GET` 時不會顯示本文的文件,而且中間的代理伺服器也可能不支援。
+
+///
+
+## 匯入 Pydantic 的 `BaseModel` { #import-pydantics-basemodel }
+
+首先,從 `pydantic` 匯入 `BaseModel`:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
+
+## 建立你的資料模型 { #create-your-data-model }
+
+接著,你將資料模型宣告為繼承自 `BaseModel` 的類別。
+
+對所有屬性使用標準的 Python 型別:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
+
+就和宣告查詢參數時一樣,當模型屬性有預設值時,它就不是必填;否則就是必填。使用 `None` 可使其成為選填。
+
+例如,上述模型對應的 JSON「`object`」(或 Python `dict`)如下:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "An optional description",
+ "price": 45.2,
+ "tax": 3.5
+}
+```
+
+...由於 `description` 與 `tax` 是選填(預設為 `None`),以下這個 JSON「`object`」也有效:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 45.2
+}
+```
+
+## 將它宣告為參數 { #declare-it-as-a-parameter }
+
+要把它加到你的*路徑操作(path operation)*中,宣告方式與路徑與查詢參數相同:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
+
+...並將其型別宣告為你建立的模型 `Item`。
+
+## 效果 { #results }
+
+只靠這樣的 Python 型別宣告,**FastAPI** 會:
+
+- 將請求本文讀取為 JSON。
+- (必要時)轉換為對應的型別。
+- 驗證資料。
+ - 若資料無效,會回傳清楚易懂的錯誤,指出哪裡、哪筆資料不正確。
+- 把接收到的資料放在參數 `item` 中提供給你。
+ - 由於你在函式中將其宣告為 `Item` 型別,你也會獲得完整的編輯器支援(自動完成等)以及所有屬性與其型別。
+- 為你的模型產生 JSON Schema 定義,如有需要,你也可以在專案中的其他地方使用。
+- 這些 schema 會成為產生的 OpenAPI schema 的一部分,並由自動文件 UIs 使用。
+
+## 自動文件 { #automatic-docs }
+
+你的模型的 JSON Schema 會納入產生的 OpenAPI schema,並顯示在互動式 API 文件中:
+
+
+
+也會用於每個需要它們的*路徑操作*內的 API 文件:
+
+
+
+## 編輯器支援 { #editor-support }
+
+在編輯器裡、於你的函式中,你會在各處獲得型別提示與自動完成(如果你接收的是 `dict` 而不是 Pydantic 模型,就不會有這些):
+
+
+
+你也會獲得對不正確型別操作的錯誤檢查:
+
+
+
+這不是偶然,整個框架就是圍繞這個設計而建。
+
+而且在實作之前的設計階段就已徹底測試,確保能在各種編輯器中運作良好。
+
+甚至為了支援這點,Pydantic 本身也做了些修改。
+
+前面的螢幕截圖是使用 Visual Studio Code 拍的。
+
+但你在 PyCharm 與大多數其它 Python 編輯器中也會得到相同的編輯器支援:
+
+
+
+/// tip
+
+如果你使用 PyCharm 作為編輯器,可以安裝 Pydantic PyCharm Plugin。
+
+它能增強 Pydantic 模型的編輯器支援,包含:
+
+- 自動完成
+- 型別檢查
+- 重構
+- 搜尋
+- 程式碼檢查
+
+///
+
+## 使用該模型 { #use-the-model }
+
+在函式內,你可以直接存取模型物件的所有屬性:
+
+{* ../../docs_src/body/tutorial002_py310.py *}
+
+## 請求本文 + 路徑參數 { #request-body-path-parameters }
+
+你可以同時宣告路徑參數與請求本文。
+
+**FastAPI** 會辨識出與路徑參數相符的函式參數應該從**路徑**取得,而宣告為 Pydantic 模型的函式參數應該從**請求本文**取得。
+
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
+
+## 請求本文 + 路徑 + 查詢參數 { #request-body-path-query-parameters }
+
+你也可以同時宣告**本文**、**路徑**與**查詢**參數。
+
+**FastAPI** 會分別辨識並從正確的位置取得資料。
+
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
+
+函式參數的辨識方式如下:
+
+- 如果參數同時在**路徑**中宣告,則作為路徑參數。
+- 如果參數是**單一型別**(像是 `int`、`float`、`str`、`bool` 等),會被視為**查詢**參數。
+- 如果參數宣告為 **Pydantic 模型** 型別,會被視為請求**本文**。
+
+/// note
+
+FastAPI 會因為預設值 `= None` 而知道 `q` 的值不是必填。
+
+`str | None` 並非 FastAPI 用來判斷是否必填的依據;它會因為有預設值 `= None` 而知道不是必填。
+
+但加入這些型別註解能讓你的編輯器提供更好的支援與錯誤偵測。
+
+///
+
+## 不使用 Pydantic { #without-pydantic }
+
+若你不想使用 Pydantic 模型,也可以使用 **Body** 參數。請參考[Body - 多個參數:本文中的單一值](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}。
diff --git a/docs/zh-hant/docs/tutorial/cookie-param-models.md b/docs/zh-hant/docs/tutorial/cookie-param-models.md
new file mode 100644
index 000000000..8997903e3
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Cookie 參數模型 { #cookie-parameter-models }
+
+如果你有一組彼此相關的「**Cookie**」,你可以建立一個「**Pydantic 模型**」來宣告它們。🍪
+
+這樣你就能在**多處**重複使用該模型,並且能一次性為所有參數宣告**驗證**與**中繼資料**。😎
+
+/// note | 注意
+
+自 FastAPI 版本 `0.115.0` 起支援。🤓
+
+///
+
+/// tip
+
+同樣的技巧也適用於 `Query`、`Cookie` 與 `Header`。😎
+
+///
+
+## 以 Pydantic 模型宣告 Cookie { #cookies-with-a-pydantic-model }
+
+在 **Pydantic 模型**中宣告所需的 **Cookie** 參數,接著將參數宣告為 `Cookie`:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** 會從請求收到的 **Cookie** 中擷取 **每個欄位** 的資料,並交給你定義的 Pydantic 模型。
+
+## 查看文件 { #check-the-docs }
+
+你可以在 `/docs` 的文件介面中看到已定義的 Cookie:
+
+
+
+
+---
+
+如果你使用 PyCharm,你可以:
+
+* 開啟 "Run" 選單
+* 選擇 "Debug..."
+* 會出現一個情境選單
+* 選擇要偵錯的檔案(此例為 `main.py`)
+
+接著它會用你的 **FastAPI** 程式碼啟動伺服器、在你的中斷點停下等。
+
+可能會長這樣:
+
+
diff --git a/docs/zh-hant/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh-hant/docs/tutorial/dependencies/classes-as-dependencies.md
new file mode 100644
index 000000000..34b873210
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,288 @@
+# 以類別作為相依性 { #classes-as-dependencies }
+
+在更深入了解 **相依性注入(Dependency Injection)** 系統之前,我們先把前一個範例升級一下。
+
+## 前一個範例中的 `dict` { #a-dict-from-the-previous-example }
+
+在前一個範例中,我們從相依項("dependable")回傳了一個 `dict`:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}
+
+但接著我們在路徑操作函式(*path operation function*)的參數 `commons` 中取得的是一個 `dict`。
+
+而我們知道,編輯器對 `dict` 無法提供太多輔助(例如自動完成),因為它無法預先知道其中的鍵與值的型別。
+
+我們可以做得更好...
+
+## 什麼算是相依性 { #what-makes-a-dependency }
+
+到目前為止,你看到的相依性都是宣告成函式。
+
+但那不是宣告相依性的唯一方式(雖然那大概是最常見的)。
+
+關鍵在於,相依性應該要是「callable」。
+
+在 Python 中,「**callable**」指的是任何可以像函式一樣被 Python「呼叫」的東西。
+
+因此,如果你有一個物件 `something`(它可能不是函式),而你可以像這樣「呼叫」(執行)它:
+
+```Python
+something()
+```
+
+或是
+
+```Python
+something(some_argument, some_keyword_argument="foo")
+```
+
+那它就是一個「callable」。
+
+## 以類別作為相依性 { #classes-as-dependencies_1 }
+
+你可能已經注意到,建立一個 Python 類別的實例時,你用的語法也是一樣的。
+
+例如:
+
+```Python
+class Cat:
+ def __init__(self, name: str):
+ self.name = name
+
+
+fluffy = Cat(name="Mr Fluffy")
+```
+
+在這個例子中,`fluffy` 是 `Cat` 類別的一個實例。
+
+而要建立 `fluffy`,你其實是在「呼叫」`Cat`。
+
+所以,Python 類別本身也是一種 **callable**。
+
+因此,在 **FastAPI** 中,你可以將 Python 類別作為相依性。
+
+FastAPI 其實檢查的是它是否為「callable」(函式、類別或其他),以及它所定義的參數。
+
+如果你在 **FastAPI** 中傳入一個「callable」作為相依性,FastAPI 會分析該「callable」的參數,並以與路徑操作函式參數相同的方式來處理它們,包括子相依性。
+
+這也適用於完全沒有參數的 callable,就和沒有參數的路徑操作函式一樣。
+
+接著,我們可以把上面的相依項(dependable)`common_parameters` 改成類別 `CommonQueryParams`:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}
+
+注意用來建立該類別實例的 `__init__` 方法:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}
+
+...它的參數與我們之前的 `common_parameters` 相同:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}
+
+**FastAPI** 會用這些參數來「解析」該相依性。
+
+兩種情況下都會有:
+
+- 一個可選的查詢參數 `q`,型別為 `str`。
+- 一個查詢參數 `skip`,型別為 `int`,預設為 `0`。
+- 一個查詢參數 `limit`,型別為 `int`,預設為 `100`。
+
+兩種情況下,資料都會被轉換、驗證,並記錄到 OpenAPI schema 中等。
+
+## 如何使用 { #use-it }
+
+現在你可以用這個類別來宣告你的相依性。
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}
+
+**FastAPI** 會呼叫 `CommonQueryParams` 類別。這會建立該類別的一個「實例」,而該實例會以參數 `commons` 的形式傳給你的函式。
+
+## 型別註解與 `Depends` { #type-annotation-vs-depends }
+
+注意上面程式碼裡我們寫了兩次 `CommonQueryParams`:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+最後面的 `CommonQueryParams`,在:
+
+```Python
+... Depends(CommonQueryParams)
+```
+
+...才是 **FastAPI** 實際用來知道相依性是什麼的依據。
+
+FastAPI 會從這個物件中提取宣告的參數,並且實際呼叫它。
+
+---
+
+在這個例子中,前面的 `CommonQueryParams`,於:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
+
+...對 **FastAPI** 來說沒有任何特殊意義。FastAPI 不會用它來做資料轉換、驗證等(因為這部分由 `Depends(CommonQueryParams)` 處理)。
+
+其實你可以只寫:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
+
+...像是:
+
+{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}
+
+但仍建議宣告型別,這樣你的編輯器就知道會以何種型別作為參數 `commons` 傳入,進而幫助你做自動完成、型別檢查等:
+
+
+
+## 捷徑 { #shortcut }
+
+不過你會發現這裡有些重複程式碼,我們寫了兩次 `CommonQueryParams`:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+**FastAPI** 為這類情況提供了一個捷徑:當相依性「明確」是一個類別,且 **FastAPI** 會「呼叫」它來建立該類別的實例時。
+
+對這些特定情況,你可以這樣做:
+
+不要寫:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+...而是改為:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+你把相依性宣告為參數的型別,並使用不帶任何參數的 `Depends()`,而不用在 `Depends(CommonQueryParams)` 裡「再」寫一次整個類別。
+
+整個範例就會變成:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+...而 **FastAPI** 會知道該怎麼做。
+
+/// tip
+
+如果你覺得這樣比幫助更令人困惑,那就忽略它吧,你並不「需要」這個技巧。
+
+這只是個捷徑。因為 **FastAPI** 在意幫你減少重複的程式碼。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh-hant/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 000000000..e30c38537
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# 路徑操作裝飾器中的依賴 { #dependencies-in-path-operation-decorators }
+
+有時在你的路徑操作函式中,其實不需要某個依賴的回傳值。
+
+或是該依賴根本沒有回傳值。
+
+但你仍需要它被執行/解析。
+
+這種情況下,你可以不在路徑操作函式的參數上使用 `Depends`,而是在路徑操作裝飾器加入一個 `dependencies` 的 `list`。
+
+## 在路徑操作裝飾器加入 `dependencies` { #add-dependencies-to-the-path-operation-decorator }
+
+路徑操作裝飾器可接受一個可選參數 `dependencies`。
+
+它應該是由 `Depends()` 組成的 `list`:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+這些依賴會以與一般依賴相同的方式被執行/解析。但它們的值(如果有回傳)不會傳遞給你的路徑操作函式。
+
+/// tip
+
+有些編輯器會檢查未使用的函式參數,並將其標示為錯誤。
+
+把這些依賴放在路徑操作裝飾器中,可以確保它們被執行,同時避免編輯器/工具報錯。
+
+這也有助於避免讓新加入的開發者看到未使用的參數時,以為它是不必要的而感到困惑。
+
+///
+
+/// info
+
+在這個範例中我們使用了自訂的(虛構的)標頭 `X-Key` 與 `X-Token`。
+
+但在實際情況下,當你實作安全機制時,使用整合的 [Security utilities(下一章)](../security/index.md){.internal-link target=_blank} 會獲得更多好處。
+
+///
+
+## 依賴的錯誤與回傳值 { #dependencies-errors-and-return-values }
+
+你可以使用與平常相同的依賴函式。
+
+### 依賴的需求 { #dependency-requirements }
+
+它們可以宣告請求需求(例如標頭(headers))或其他子依賴:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### 拋出例外 { #raise-exceptions }
+
+這些依賴可以 `raise` 例外,與一般依賴相同:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### 回傳值 { #return-values }
+
+它們可以回傳值,也可以不回傳;無論如何,回傳值都不會被使用。
+
+因此,你可以重複使用在其他地方已使用過的一般依賴(會回傳值),即使回傳值不會被使用,該依賴仍會被執行:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## 一組路徑操作的依賴 { #dependencies-for-a-group-of-path-operations }
+
+之後在閱讀如何組織較大的應用程式([較大型應用程式——多個檔案](../../tutorial/bigger-applications.md){.internal-link target=_blank})時,你會學到如何為一組路徑操作宣告一個共同的 `dependencies` 參數。
+
+## 全域依賴 { #global-dependencies }
+
+接著我們會看看如何把依賴加到整個 `FastAPI` 應用程式,使其套用到每個路徑操作。
diff --git a/docs/zh-hant/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh-hant/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 000000000..2339c6ef3
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,288 @@
+# 使用 yield 的相依 { #dependencies-with-yield }
+
+FastAPI 支援在完成後執行一些額外步驟的相依。
+
+要做到這點,使用 `yield` 取代 `return`,並把額外步驟(程式碼)寫在其後。
+
+/// tip
+
+請確保每個相依內只使用一次 `yield`。
+
+///
+
+/// note | 技術細節
+
+任何可用於下列裝飾器的函式:
+
+* `@contextlib.contextmanager` 或
+* `@contextlib.asynccontextmanager`
+
+都可以作為 **FastAPI** 的相依。
+
+事實上,FastAPI 內部就是使用這兩個裝飾器。
+
+///
+
+## 使用 `yield` 的資料庫相依 { #a-database-dependency-with-yield }
+
+例如,你可以用它建立一個資料庫 session,並在完成後關閉。
+
+只有 `yield` 之前(含 `yield` 本身)的程式碼會在產生回應之前執行:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+由 `yield` 產生的值會被注入到路徑操作(path operation)與其他相依中:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+位於 `yield` 之後的程式碼會在回應之後執行:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip
+
+你可以使用 `async` 或一般函式。
+
+**FastAPI** 都會正確處理,和一般相依相同。
+
+///
+
+## 同時使用 `yield` 與 `try` 的相依 { #a-dependency-with-yield-and-try }
+
+如果在含 `yield` 的相依中使用 `try` 區塊,你會接收到使用該相依時拋出的任何例外。
+
+例如,如果在中途的某段程式碼、其他相依,或某個路徑操作中,讓資料庫交易「rollback」或產生了任何例外,你都會在你的相依中接收到該例外。
+
+因此,你可以在相依內用 `except SomeException` 來攔截特定例外。
+
+同樣地,你可以使用 `finally` 來確保無論是否有例外都會執行結束步驟。
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## 含 `yield` 的子相依 { #sub-dependencies-with-yield }
+
+你可以擁有任何大小與形狀的子相依與相依樹,而它們都可以(或不)使用 `yield`。
+
+**FastAPI** 會確保每個使用 `yield` 的相依,其「結束程式碼」會以正確的順序執行。
+
+例如,`dependency_c` 可以相依於 `dependency_b`,而 `dependency_b` 相依於 `dependency_a`:
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+而且它們都可以使用 `yield`。
+
+在這個例子中,`dependency_c` 為了執行它的結束程式碼,需要來自 `dependency_b`(此處命名為 `dep_b`)的值仍然可用。
+
+同理,`dependency_b` 為了執行它的結束程式碼,需要來自 `dependency_a`(此處命名為 `dep_a`)的值可用。
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+同樣地,你可以同時擁有使用 `yield` 的相依與使用 `return` 的相依,並讓其中一些相依彼此相依。
+
+你也可以有一個相依同時需要多個使用 `yield` 的其他相依,等等。
+
+你可以擁有任何你需要的相依組合。
+
+**FastAPI** 會確保一切都以正確的順序執行。
+
+/// note | 技術細節
+
+這能運作,多虧了 Python 的 Context Managers。
+
+**FastAPI** 在內部使用它們來達成這點。
+
+///
+
+## 含 `yield` 與 `HTTPException` 的相依 { #dependencies-with-yield-and-httpexception }
+
+你已看到可以在含 `yield` 的相依中使用 `try` 區塊,嘗試執行一些程式碼,然後在 `finally` 後執行結束程式碼。
+
+你也可以用 `except` 來攔截被拋出的例外並加以處理。
+
+例如,你可以拋出不同的例外,如 `HTTPException`。
+
+/// tip
+
+這算是進階技巧;多數情況你並不需要,因為你可以在應用程式其他程式碼中(例如在路徑操作函式(path operation function)中)直接拋出例外(包含 `HTTPException`)。
+
+但如果你需要,它就在這裡。🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+如果你想攔截例外並據此回傳自訂回應,請建立一個[自訂例外處理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}。
+
+## 含 `yield` 與 `except` 的相依 { #dependencies-with-yield-and-except }
+
+如果你在含 `yield` 的相依中用 `except` 攔截了例外,且沒有再次拋出它(或拋出新的例外),FastAPI 將無法察覺有例外發生,就像在一般的 Python 中一樣:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+在這種情況下,客戶端會如預期地看到一個 *HTTP 500 Internal Server Error* 回應(因為我們沒有拋出 `HTTPException` 或類似的東西),但伺服器將不會有任何日誌或其他錯誤線索。😱
+
+### 在含 `yield` 與 `except` 的相依中務必 `raise` { #always-raise-in-dependencies-with-yield-and-except }
+
+如果你在含 `yield` 的相依中攔截到了例外,除非你要拋出另一個 `HTTPException` 或類似的例外,否則**你應該重新拋出原本的例外**。
+
+你可以使用 `raise` 重新拋出同一個例外:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+現在客戶端仍會獲得同樣的 *HTTP 500 Internal Server Error* 回應,但伺服器的日誌中會有我們自訂的 `InternalError`。😎
+
+## 含 `yield` 的相依執行順序 { #execution-of-dependencies-with-yield }
+
+執行順序大致如下圖。時間從上往下流動,每一欄代表一個互動或執行程式碼的部分。
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant handler as Exception handler
+participant dep as Dep with yield
+participant operation as Path Operation
+participant tasks as Background tasks
+
+ Note over client,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ end
+
+ operation ->> client: Return response to client
+ Note over client,operation: Response is already sent, can't change it anymore
+ opt Tasks
+ operation -->> tasks: Send background tasks
+ end
+ opt Raise other exception
+ tasks -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info
+
+只會向用戶端送出「一個回應」。可能是其中一個錯誤回應,或是來自該路徑操作的回應。
+
+一旦送出了其中一個回應,就不能再送出其他回應。
+
+///
+
+/// tip
+
+如果你在路徑操作函式的程式碼中拋出任何例外,它會被傳遞到使用 `yield` 的相依中(包含 `HTTPException`)。大多數情況你會想在該使用 `yield` 的相依中重新拋出相同的例外或一個新的例外,以確保它被正確處理。
+
+///
+
+## 提早關閉與 `scope` { #early-exit-and-scope }
+
+通常,含 `yield` 的相依之結束程式碼會在回應送出給用戶端之後才執行。
+
+但如果你確定在從路徑操作函式返回後就不會再使用該相依,你可以使用 `Depends(scope="function")`,告訴 FastAPI 應在路徑操作函式返回之後、但在回應送出之前關閉該相依。
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` 接受一個 `scope` 參數,可以是:
+
+* `"function"`:在處理請求的路徑操作函式之前啟動相依,在路徑操作函式結束之後結束相依,但在回應送回用戶端之前。所以,相依函式會在路徑操作**函式**的「周圍」執行。
+* `"request"`:在處理請求的路徑操作函式之前啟動相依(與使用 `"function"` 類似),但在回應送回用戶端之後才結束相依。所以,相依函式會在整個**請求**與回應循環的「周圍」執行。
+
+如果未指定且相依使用了 `yield`,則預設 `scope` 為 `"request"`。
+
+### 子相依的 `scope` { #scope-for-sub-dependencies }
+
+當你宣告一個 `scope="request"`(預設值)的相依時,任何子相依也需要有 `"request"` 的 `scope`。
+
+但一個 `scope` 為 `"function"` 的相依,可以擁有 `scope` 為 `"function"` 或 `"request"` 的子相依。
+
+這是因為任何相依都需要能在子相依之前執行其結束程式碼,因為它可能在結束程式碼中仍需要使用那些子相依。
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## 含 `yield`、`HTTPException`、`except` 與背景任務的相依 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+含 `yield` 的相依隨時間演進,以涵蓋不同的使用情境並修正一些問題。
+
+如果你想了解在不同 FastAPI 版本中改了哪些內容,可以在進階指南中閱讀:[進階相依 — 含 `yield`、`HTTPException`、`except` 與背景任務的相依](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks){.internal-link target=_blank}。
+## 情境管理器 { #context-managers }
+
+### 什麼是「情境管理器」 { #what-are-context-managers }
+
+「情境管理器」是那些你可以在 `with` 陳述式中使用的 Python 物件。
+
+例如,你可以用 `with` 來讀取檔案:
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+在底層,`open("./somefile.txt")` 會建立一個稱為「情境管理器」的物件。
+
+當 `with` 區塊結束時,它會確保關閉檔案,即使發生了例外也一樣。
+
+當你建立一個含 `yield` 的相依時,**FastAPI** 會在內部為它建立一個情境管理器,並與其他相關工具結合。
+
+### 在含 `yield` 的相依中使用情境管理器 { #using-context-managers-in-dependencies-with-yield }
+
+/// warning
+
+這大致算是一個「進階」概念。
+
+如果你剛開始學習 **FastAPI**,此處可以先跳過。
+
+///
+
+在 Python 中,你可以透過建立一個擁有 `__enter__()` 與 `__exit__()` 兩個方法的類別來建立情境管理器。
+
+你也可以在 **FastAPI** 的含 `yield` 相依中,於相依函式內使用 `with` 或 `async with` 陳述式來使用它們:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip
+
+建立情境管理器的另一種方式是:
+
+* `@contextlib.contextmanager` 或
+* `@contextlib.asynccontextmanager`
+
+用它們裝飾一個只包含單一 `yield` 的函式。
+
+這正是 **FastAPI** 在內部為含 `yield` 的相依所使用的方法。
+
+但你不需要(而且也不該)在 FastAPI 的相依上使用這些裝飾器。
+
+FastAPI 會在內部替你處理好。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/dependencies/global-dependencies.md b/docs/zh-hant/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 000000000..3aac1a228
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,15 @@
+# 全域依賴 { #global-dependencies }
+
+在某些類型的應用程式中,你可能想為整個應用程式新增依賴。
+
+類似於你可以在[路徑操作(path operation)的裝飾器中新增 `dependencies`](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 的方式,你也可以把它們加到 `FastAPI` 應用程式上。
+
+在這種情況下,它們會套用到應用程式中的所有路徑操作:
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+而且,在[將 `dependencies` 新增到路徑操作裝飾器](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 那一節中的所有概念依然適用,只是這裡是套用到整個應用中的所有路徑操作。
+
+## 路徑操作群組的依賴 { #dependencies-for-groups-of-path-operations }
+
+之後,在閱讀如何組織更大的應用程式([更大的應用程式 - 多個檔案](../../tutorial/bigger-applications.md){.internal-link target=_blank})時,可能會有多個檔案,你將會學到如何為一組路徑操作宣告單一的 `dependencies` 參數。
diff --git a/docs/zh-hant/docs/tutorial/dependencies/index.md b/docs/zh-hant/docs/tutorial/dependencies/index.md
new file mode 100644
index 000000000..39c05ab05
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/index.md
@@ -0,0 +1,248 @@
+# 依賴 { #dependencies }
+
+**FastAPI** 內建一套強大且直覺的 **依賴注入** 系統。
+
+它被設計為易於使用,使任何開發者都能輕鬆將其他元件與 **FastAPI** 整合。
+
+## 什麼是「依賴注入」 { #what-is-dependency-injection }
+
+在程式設計中,「依賴注入」的意思是:你的程式碼(此處指你的「路徑操作函式 (path operation functions)」)可以宣告它為了正常運作所需要的各種東西:也就是「依賴」。
+
+接著,這個系統(此處是 **FastAPI**)會負責做任何必要的事,將這些所需的依賴提供給你的程式碼(「注入」依賴)。
+
+當你需要以下情境時,這特別有用:
+
+* 共享邏輯(相同的邏輯一次又一次地使用)。
+* 共用資料庫連線。
+* 強制套用安全性、驗證、角色要求等。
+* 以及許多其他事情...
+
+同時把重複的程式碼降到最低。
+
+## 入門 { #first-steps }
+
+先看一個非常簡單的範例。它現在還不太實用,但夠簡單,讓我們能專注在 **依賴注入** 的運作方式。
+
+### 建立一個依賴,或稱「dependable」 { #create-a-dependency-or-dependable }
+
+先專注在依賴本身。
+
+它就是一個函式,可以接受與「路徑操作函式」相同的各種參數:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+就這樣。
+
+僅僅兩行。
+
+而且它的外觀與結構和你的所有「路徑操作函式」一樣。
+
+你可以把它想成一個沒有「裝飾器」(沒有 `@app.get("/some-path")`)的「路徑操作函式」。
+
+它可以回傳你想要的任何東西。
+
+在這個例子中,這個依賴會期望:
+
+* 一個選用的查詢參數 `q`,型別為 `str`。
+* 一個選用的查詢參數 `skip`,型別為 `int`,預設為 `0`。
+* 一個選用的查詢參數 `limit`,型別為 `int`,預設為 `100`。
+
+然後它只會回傳一個包含這些值的 `dict`。
+
+/// info | 說明
+
+FastAPI 在 0.95.0 版新增了對 `Annotated` 的支援(並開始建議使用)。
+
+如果你使用較舊的版本,嘗試使用 `Annotated` 時會出現錯誤。
+
+在使用 `Annotated` 之前,請先[升級 FastAPI 版本](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}到至少 0.95.1。
+
+///
+
+### 匯入 `Depends` { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### 在「被依賴者」(dependant)中宣告依賴 { #declare-the-dependency-in-the-dependant }
+
+和你在「路徑操作函式」參數上使用 `Body`、`Query` 等方式一樣,針對新參數使用 `Depends`:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+雖然你在函式參數上使用 `Depends` 的方式和 `Body`、`Query` 等相同,但 `Depends` 的運作方式有點不同。
+
+你只需要傳給 `Depends` 一個參數。
+
+這個參數必須是類似函式的東西。
+
+你不需要直接呼叫它(不要在後面加上括號),只要把它作為參數傳給 `Depends()` 即可。
+
+而該函式的參數宣告方式與「路徑操作函式」相同。
+
+/// tip | 提示
+
+除了函式之外,還有其他「東西」也能當作依賴,會在下一章介紹。
+
+///
+
+當有新的請求到達時,**FastAPI** 會負責:
+
+* 以正確的參數呼叫你的依賴(dependable)函式。
+* 取得該函式的回傳結果。
+* 將結果指定給你的「路徑操作函式」中的對應參數。
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+如此一來,你只需撰寫一次共用程式碼,**FastAPI** 會替你的各個「路徑操作」呼叫它。
+
+/// check | 檢查
+
+注意,你不必建立特殊的類別並把它傳到 **FastAPI** 去「註冊」或做類似的事。
+
+只要把它傳給 `Depends`,**FastAPI** 就知道該怎麼處理其餘的部分。
+
+///
+
+## 共用 `Annotated` 依賴 { #share-annotated-dependencies }
+
+在上面的範例中,可以看到有一點點的「重複程式碼」。
+
+當你要使用 `common_parameters()` 這個依賴時,你得寫出完整的型別註解搭配 `Depends()`:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+但因為我們在使用 `Annotated`,我們可以把這個 `Annotated` 的值存到一個變數中,並在多個地方重複使用:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | 提示
+
+這只是標準的 Python,用的是所謂的「型別別名 (type alias)」,其實和 **FastAPI** 本身無關。
+
+但因為 **FastAPI** 是建立在 Python 標準之上(包含 `Annotated`),你就可以在程式碼中使用這個技巧。😎
+
+///
+
+這些依賴依然會如預期運作,而最棒的是「型別資訊會被保留」,代表你的編輯器仍能提供「自動完成」、「即時錯誤」等功能,像 `mypy` 等其他工具也一樣受益。
+
+當你在「大型程式碼庫」中,於許多「路徑操作」反覆使用「相同的依賴」時,這會特別有用。
+
+## 要不要使用 `async` { #to-async-or-not-to-async }
+
+因為依賴也會由 **FastAPI** 呼叫(就像你的「路徑操作函式」),所以在定義函式時套用相同的規則。
+
+你可以使用 `async def` 或一般的 `def`。
+
+而且你可以在一般 `def` 的「路徑操作函式」中宣告 `async def` 的依賴,或在 `async def` 的「路徑操作函式」中宣告 `def` 的依賴,等等。
+
+都沒關係。**FastAPI** 會知道該怎麼做。
+
+/// note | 注意
+
+如果你不熟悉,請參考文件中的 [Async: "In a hurry?"](../../async.md#in-a-hurry){.internal-link target=_blank} 一節,瞭解 `async` 與 `await`。
+
+///
+
+## 與 OpenAPI 整合 { #integrated-with-openapi }
+
+你的依賴(以及其子依賴)所宣告的所有請求參數、驗證與需求,都會整合進同一份 OpenAPI 結構中。
+
+因此,互動式文件也會包含來自這些依賴的所有資訊:
+
+
+
+## 簡單用法 { #simple-usage }
+
+想一想,「路徑操作函式」是宣告好讓框架在「路徑」與「操作」符合時使用的,然後 **FastAPI** 會負責帶入正確的參數、從請求中擷取資料,並呼叫該函式。
+
+其實,所有(或大多數)Web 框架都是這樣運作。
+
+你從不會直接呼叫這些函式。它們是由框架(此處是 **FastAPI**)呼叫的。
+
+透過依賴注入系統,你也可以告訴 **FastAPI**:你的「路徑操作函式」還「依賴」其他東西,應在你的「路徑操作函式」之前執行,**FastAPI** 會負責執行它並「注入」其結果。
+
+這個「依賴注入」概念的其他常見稱呼包括:
+
+* 資源
+* 提供者
+* 服務
+* 可注入項
+* 元件
+
+## **FastAPI** 外掛 { #fastapi-plug-ins }
+
+各種整合與「外掛」都能以 **依賴注入** 系統來構建。但事實上,並不需要真的去打造「外掛」,因為透過依賴,你可以宣告無數的整合與互動,並讓它們供你的「路徑操作函式」使用。
+
+而且依賴可以用非常簡單直覺的方式建立,你只需要匯入所需的 Python 套件,然後用幾行程式碼就能把它們與你的 API 函式整合,真的是「只要幾行」。
+
+在接下來的章節中你會看到這方面的例子,例如關聯式與 NoSQL 資料庫、安全性等。
+
+## **FastAPI** 相容性 { #fastapi-compatibility }
+
+依賴注入系統的簡潔,使 **FastAPI** 能與以下事物相容:
+
+* 所有關聯式資料庫
+* NoSQL 資料庫
+* 外部套件
+* 外部 API
+* 驗證與授權系統
+* API 使用監控系統
+* 回應資料注入系統
+* 等等
+
+## 簡單而強大 { #simple-and-powerful }
+
+雖然階層式的依賴注入系統相當容易定義與使用,但它依然非常強大。
+
+你可以定義會進一步依賴其他依賴的依賴。
+
+最終會形成一棵階層式的依賴樹,而 **依賴注入** 系統會負責為你解決所有這些依賴(以及它們的子依賴),並在每一步提供(注入)對應的結果。
+
+例如,假設你有 4 個 API 端點(「路徑操作」):
+
+* `/items/public/`
+* `/items/private/`
+* `/users/{user_id}/activate`
+* `/items/pro/`
+
+那麼你就能只透過依賴與子依賴,為每個端點加入不同的權限需求:
+
+```mermaid
+graph TB
+
+current_user(["current_user"])
+active_user(["active_user"])
+admin_user(["admin_user"])
+paying_user(["paying_user"])
+
+public["/items/public/"]
+private["/items/private/"]
+activate_user["/users/{user_id}/activate"]
+pro_items["/items/pro/"]
+
+current_user --> active_user
+active_user --> admin_user
+active_user --> paying_user
+
+current_user --> public
+active_user --> private
+admin_user --> activate_user
+paying_user --> pro_items
+```
+
+## 與 **OpenAPI** 整合 { #integrated-with-openapi_1 }
+
+所有這些依賴在宣告其需求的同時,也會為你的「路徑操作」新增參數、驗證等。
+
+**FastAPI** 會負責把這一切加入 OpenAPI 結構中,讓它們顯示在互動式文件系統裡。
diff --git a/docs/zh-hant/docs/tutorial/dependencies/sub-dependencies.md b/docs/zh-hant/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 000000000..50c4e1790
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# 子相依 { #sub-dependencies }
+
+你可以建立具有「子相依」的相依項。
+
+它們可以按你的需要,層級任意加深。
+
+**FastAPI** 會負責解析它們。
+
+## 第一個相依項 "dependable" { #first-dependency-dependable }
+
+你可以建立第一個相依項("dependable")如下:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+它宣告了一個可選的查詢參數 `q`(型別為 `str`),然後直接回傳它。
+
+這很簡單(不太實用),但有助於我們專注於子相依如何運作。
+
+## 第二個相依,同時是 "dependable" 也是 "dependant" { #second-dependency-dependable-and-dependant }
+
+接著你可以建立另一個相依函式("dependable"),同時它也宣告了自己的相依(因此它同時也是 "dependant"):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+來看它所宣告的參數:
+
+- 即使這個函式本身是個相依項("dependable"),它也宣告了另一個相依(它「相依於」其他東西)。
+ - 它相依 `query_extractor`,並把其回傳值指定給參數 `q`。
+- 它還宣告了一個可選的 `last_query` cookie,型別為 `str`。
+ - 如果使用者沒有提供查詢 `q`,我們就使用先前儲存在 cookie 中的最後一次查詢值。
+
+## 使用相依項 { #use-the-dependency }
+
+然後我們可以這樣使用這個相依項:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info
+
+注意,在路徑操作函式中我們只宣告了一個相依項 `query_or_cookie_extractor`。
+
+但 **FastAPI** 會知道它必須先解析 `query_extractor`,在呼叫 `query_or_cookie_extractor` 時把其結果傳入。
+
+///
+
+```mermaid
+graph TB
+
+query_extractor(["query_extractor"])
+query_or_cookie_extractor(["query_or_cookie_extractor"])
+
+read_query["/items/"]
+
+query_extractor --> query_or_cookie_extractor --> read_query
+```
+
+## 多次使用同一個相依項 { #using-the-same-dependency-multiple-times }
+
+如果你的某個相依項在同一個路徑操作中被宣告了多次,例如多個相依共用同一個子相依,**FastAPI** 會知道只需在每次請求中呼叫該子相依一次。
+
+它會把回傳值儲存在一個 「快取」 中,並在該次請求中傳遞給所有需要它的「相依者」,而不是為同一個請求多次呼叫相同的相依項。
+
+在進階情境下,如果你確定需要在同一次請求的每個步驟都呼叫該相依(可能呼叫多次),而不是使用「快取」的值,你可以在使用 `Depends` 時設定參數 `use_cache=False`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ 未使用 Annotated
+
+/// tip
+
+若可行,建議使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## 回顧 { #recap }
+
+撇開這裡用到的術語不談,**相依性注入(Dependency Injection)** 系統其實很簡單。
+
+它只是一些與路徑操作函式外觀相同的函式。
+
+但它非常強大,允許你宣告任意深度巢狀的相依「圖」(樹)。
+
+/// tip
+
+用這些簡單的例子看起來可能不那麼有用。
+
+但在關於安全性的章節中,你會看到它有多實用。
+
+你也會看到它能為你省下多少程式碼。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/encoder.md b/docs/zh-hant/docs/tutorial/encoder.md
new file mode 100644
index 000000000..03b7db639
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/encoder.md
@@ -0,0 +1,35 @@
+# JSON 相容編碼器 { #json-compatible-encoder }
+
+在某些情況下,你可能需要將某種資料型別(例如 Pydantic 模型)轉換為與 JSON 相容的類型(例如 `dict`、`list` 等)。
+
+例如,當你需要把它儲存在資料庫中。
+
+為此,**FastAPI** 提供了 `jsonable_encoder()` 函式。
+
+## 使用 `jsonable_encoder` { #using-the-jsonable-encoder }
+
+想像你有一個只接受與 JSON 相容資料的資料庫 `fake_db`。
+
+例如,它不接受 `datetime` 物件,因為那與 JSON 不相容。
+
+因此,必須將 `datetime` 物件轉為一個以 ISO 格式 表示資料的 `str`。
+
+同樣地,這個資料庫不會接受 Pydantic 模型(帶有屬性的物件),只接受 `dict`。
+
+你可以使用 `jsonable_encoder` 來處理。
+
+它接收一個物件(例如 Pydantic 模型),並回傳一個與 JSON 相容的版本:
+
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
+
+在此範例中,它會把 Pydantic 模型轉成 `dict`,並將 `datetime` 轉成 `str`。
+
+呼叫後的結果可以用 Python 標準的 `json.dumps()` 進行編碼。
+
+它不會回傳一個包含 JSON 內容的大型 `str`(字串)。它會回傳 Python 標準的資料結構(例如 `dict`),其中的值與子值都與 JSON 相容。
+
+/// note
+
+事實上,`jsonable_encoder` 在 **FastAPI** 內部也被用來轉換資料。不過在許多其他情境中它同樣實用。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/extra-data-types.md b/docs/zh-hant/docs/tutorial/extra-data-types.md
new file mode 100644
index 000000000..f516d965a
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/extra-data-types.md
@@ -0,0 +1,62 @@
+# 額外的資料型別 { #extra-data-types }
+
+到目前為止,你一直在使用常見的資料型別,例如:
+
+* `int`
+* `float`
+* `str`
+* `bool`
+
+但你也可以使用更複雜的資料型別。
+
+而且你仍然會擁有目前為止所見的同樣功能:
+
+* 極佳的編輯器支援。
+* 將傳入請求的資料轉換。
+* 回應資料的轉換。
+* 資料驗證。
+* 自動產生註解與文件。
+
+## 其他資料型別 { #other-data-types }
+
+以下是你可以使用的一些其他資料型別:
+
+* `UUID`:
+ * 一種標準的「通用唯一識別碼 (Universally Unique Identifier)」,常見於許多資料庫與系統的 ID。
+ * 在請求與回應中會以 `str` 表示。
+* `datetime.datetime`:
+ * Python 的 `datetime.datetime`。
+ * 在請求與回應中會以 ISO 8601 格式的 `str` 表示,例如:`2008-09-15T15:53:00+05:00`。
+* `datetime.date`:
+ * Python 的 `datetime.date`。
+ * 在請求與回應中會以 ISO 8601 格式的 `str` 表示,例如:`2008-09-15`。
+* `datetime.time`:
+ * Python 的 `datetime.time`。
+ * 在請求與回應中會以 ISO 8601 格式的 `str` 表示,例如:`14:23:55.003`。
+* `datetime.timedelta`:
+ * Python 的 `datetime.timedelta`。
+ * 在請求與回應中會以總秒數的 `float` 表示。
+ * Pydantic 也允許用「ISO 8601 time diff encoding」來表示,詳情見文件。
+* `frozenset`:
+ * 在請求與回應中與 `set` 相同處理:
+ * 在請求中,會讀取一個 list,去除重複並轉為 `set`。
+ * 在回應中,`set` 會被轉為 `list`。
+ * 生成的 schema 會指定 `set` 的值為唯一(使用 JSON Schema 的 `uniqueItems`)。
+* `bytes`:
+ * 標準的 Python `bytes`。
+ * 在請求與回應中會被當作 `str` 處理。
+ * 生成的 schema 會指定其為 `str`,且 "format" 為 `binary`。
+* `Decimal`:
+ * 標準的 Python `Decimal`。
+ * 在請求與回應中,與 `float` 的處理方式相同。
+* 你可以在此查閱所有可用的 Pydantic 資料型別:Pydantic 資料型別。
+
+## 範例 { #example }
+
+以下是一個帶有參數、使用上述部分型別的 *路徑操作 (path operation)* 範例。
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
+
+請注意,函式內的參數會是它們的自然資料型別,因此你可以進行一般的日期運算,例如:
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/zh-hant/docs/tutorial/extra-models.md b/docs/zh-hant/docs/tutorial/extra-models.md
new file mode 100644
index 000000000..8aae62f8e
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# 額外的模型 { #extra-models }
+
+延續前一個範例,通常會有不只一個彼此相關的模型。
+
+對使用者模型尤其如此,因為:
+
+* 「輸入模型」需要能包含密碼。
+* 「輸出模型」不應包含密碼。
+* 「資料庫模型」通常需要儲存雜湊後的密碼。
+
+/// danger
+
+切勿儲存使用者的明文密碼。務必只儲存可供驗證的「安全雜湊」。
+
+若你還不清楚,稍後會在[安全性章節](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}學到什麼是「密碼雜湊」。
+
+///
+
+## 多個模型 { #multiple-models }
+
+以下是模型大致長相、與其密碼欄位以及它們被使用的位置:
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### 關於 `**user_in.model_dump()` { #about-user-in-model-dump }
+
+#### Pydantic 的 `.model_dump()` { #pydantics-model-dump }
+
+`user_in` 是一個 `UserIn` 類別的 Pydantic 模型。
+
+Pydantic 模型有 `.model_dump()` 方法,會回傳包含該模型資料的 `dict`。
+
+因此,若我們建立一個 Pydantic 物件 `user_in` 如:
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+接著呼叫:
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+此時變數 `user_dict` 會是一個承載資料的 `dict`(也就是 `dict`,而非 Pydantic 模型物件)。
+
+若再呼叫:
+
+```Python
+print(user_dict)
+```
+
+我們會得到一個 Python `dict`:
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### 解包 `dict` { #unpacking-a-dict }
+
+若將像 `user_dict` 這樣的 `dict` 以 `**user_dict` 傳給函式(或類別),Python 會將其「解包」,把 `user_dict` 的鍵和值直接當作具名引數傳入。
+
+因此,延續上面的 `user_dict`,寫成:
+
+```Python
+UserInDB(**user_dict)
+```
+
+效果等同於:
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ full_name=None,
+)
+```
+
+更精確地說,直接使用 `user_dict`(未來內容可能有所不同)則等同於:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+)
+```
+
+#### 由另一個模型內容建立 Pydantic 模型 { #a-pydantic-model-from-the-contents-of-another }
+
+如上例我們從 `user_in.model_dump()` 得到 `user_dict`,以下程式碼:
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+等同於:
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+...因為 `user_in.model_dump()` 回傳的是 `dict`,接著在傳給 `UserInDB` 時以 `**` 前綴讓 Python 進行解包。
+
+因此,我們可以用一個 Pydantic 模型的資料建立另一個 Pydantic 模型。
+
+#### 解包 `dict` 並加入額外參數 { #unpacking-a-dict-and-extra-keywords }
+
+接著加入額外的具名引數 `hashed_password=hashed_password`,如下:
+
+```Python
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
+```
+
+...結果等同於:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ hashed_password = hashed_password,
+)
+```
+
+/// warning
+
+輔助函式 `fake_password_hasher` 與 `fake_save_user` 只是用來示範資料流程,並不提供任何實際的安全性。
+
+///
+
+## 減少重複 { #reduce-duplication }
+
+減少程式碼重複是 FastAPI 的核心理念之一。
+
+因為重複的程式碼會提高發生錯誤、安全性問題、程式不同步(某處更新但其他處未更新)等風險。
+
+而這些模型共享大量資料,重複了屬性名稱與型別。
+
+我們可以做得更好。
+
+我們可以宣告一個作為基底的 `UserBase` 模型,其他模型繼承它成為子類別,沿用其屬性(型別宣告、驗證等)。
+
+所有資料轉換、驗證、文件產生等仍可正常運作。
+
+如此一來,我們只需要宣告模型之間的差異(含明文 `password`、含 `hashed_password`、或不含密碼):
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` 或 `anyOf` { #union-or-anyof }
+
+你可以將回應宣告為多個型別的 `Union`,表示回應可能是其中任一型別。
+
+在 OpenAPI 中會以 `anyOf` 定義。
+
+要達成這點,使用標準的 Python 型別提示 `typing.Union`:
+
+/// note
+
+在定義 `Union` 時,請先放置「更具體」的型別,再放「較不具體」的型別。以下範例中,較具體的 `PlaneItem` 置於 `CarItem` 之前:`Union[PlaneItem, CarItem]`。
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### Python 3.10 中的 `Union` { #union-in-python-3-10 }
+
+此範例中,我們將 `Union[PlaneItem, CarItem]` 作為引數 `response_model` 的值。
+
+由於這裡是把它當作引數的「值」傳入,而非用於型別註記,因此即使在 Python 3.10 也必須使用 `Union`。
+
+若用於型別註記,則可以使用直線(|),如下:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+但若寫成指定值 `response_model=PlaneItem | CarItem` 會發生錯誤,因為 Python 會嘗試在 `PlaneItem` 與 `CarItem` 之間執行「無效運算」,而非將其視為型別註記。
+
+## 模型的清單 { #list-of-models }
+
+同樣地,你可以將回應宣告為物件的 `list`。
+
+為此,使用標準的 Python `list`:
+
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
+
+## 以任意 `dict` 作為回應 { #response-with-arbitrary-dict }
+
+你也可以用一般的任意 `dict` 宣告回應,只需指定鍵和值的型別,而不必使用 Pydantic 模型。
+
+當你事先不知道可用的欄位/屬性名稱(定義 Pydantic 模型所需)時,這很實用。
+
+此時可使用 `dict`:
+
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
+
+## 重點回顧 { #recap }
+
+依情境使用多個 Pydantic 模型並靈活繼承。
+
+當一個實體需要呈現不同「狀態」時,不必侷限於一個資料模型。例如使用者這個實體,可能有包含 `password`、包含 `password_hash`,或不含密碼等不同狀態。
diff --git a/docs/zh-hant/docs/tutorial/first-steps.md b/docs/zh-hant/docs/tutorial/first-steps.md
index 6bcb453bf..3aa2d39ae 100644
--- a/docs/zh-hant/docs/tutorial/first-steps.md
+++ b/docs/zh-hant/docs/tutorial/first-steps.md
@@ -2,7 +2,7 @@
最簡單的 FastAPI 檔案可能看起來像這樣:
-{* ../../docs_src/first_steps/tutorial001_py39.py *}
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
將其複製到一個名為 `main.py` 的文件中。
@@ -183,7 +183,7 @@ Deploying to FastAPI Cloud...
### 第一步:引入 `FastAPI` { #step-1-import-fastapi }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[1] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[1] *}
`FastAPI` 是一個 Python 類別,提供所有 API 的全部功能。
@@ -197,7 +197,7 @@ Deploying to FastAPI Cloud...
### 第二步:建立一個 `FastAPI`「實例」 { #step-2-create-a-fastapi-instance }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[3] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[3] *}
這裡的 `app` 變數將會是 `FastAPI` 類別的「實例」。
@@ -266,12 +266,12 @@ https://example.com/items/foo
#### 定義一個「路徑操作裝飾器」 { #define-a-path-operation-decorator }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[6] *}
`@app.get("/")` 告訴 **FastAPI** 那個函式負責處理請求:
* 路徑 `/`
-* 使用 get操作
+* 使用 get 操作
/// info | `@decorator` 說明
@@ -320,7 +320,7 @@ Python 中的 `@something` 語法被稱為「裝飾器」。
* **operation**:是 `get`。
* **function**:是裝飾器下面的函式(在 `@app.get("/")` 下面)。
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
這就是一個 Python 函式。
@@ -332,7 +332,7 @@ Python 中的 `@something` 語法被稱為「裝飾器」。
你也可以將它定義為一般函式,而不是 `async def`:
-{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
/// note
@@ -342,7 +342,7 @@ Python 中的 `@something` 語法被稱為「裝飾器」。
### 第五步:回傳內容 { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
你可以返回一個 `dict`、`list`、單個值作為 `str`、`int` 等。
diff --git a/docs/zh-hant/docs/tutorial/handling-errors.md b/docs/zh-hant/docs/tutorial/handling-errors.md
new file mode 100644
index 000000000..f3a7573cd
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# 錯誤處理 { #handling-errors }
+
+在許多情況下,你需要通知使用你 API 的用戶端發生錯誤。
+
+這個用戶端可能是帶有前端的瀏覽器、他人的程式碼、IoT 裝置等。
+
+你可能需要告訴用戶端:
+
+* 用戶端沒有足夠權限執行該操作。
+* 用戶端沒有權限存取該資源。
+* 用戶端嘗試存取的項目不存在。
+* 等等。
+
+在這些情況下,通常會回傳範圍為 400(400 到 499)的 HTTP 狀態碼。
+
+這類似於 200 範圍的 HTTP 狀態碼(200 到 299)。那些「200」狀態碼表示請求在某種程度上是「成功」的。
+
+400 範圍的狀態碼表示用戶端錯誤。
+
+還記得那些「404 Not Found」錯誤(和梗)嗎?
+
+## 使用 `HTTPException` { #use-httpexception }
+
+要向用戶端回傳帶有錯誤的 HTTP 回應,使用 `HTTPException`。
+
+### 匯入 `HTTPException` { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
+
+### 在程式中 raise 一個 `HTTPException` { #raise-an-httpexception-in-your-code }
+
+`HTTPException` 是一般的 Python 例外,但包含與 API 相關的附加資料。
+
+因為它是 Python 的例外,你不是 `return`,而是 `raise`。
+
+這也表示,如果你在某個工具函式中(該函式被你的「路徑操作函式」呼叫),並在該工具函式裡 raise `HTTPException`,那麼「路徑操作函式」剩下的程式碼將不會執行;該請求會立刻被終止,並將 `HTTPException` 的 HTTP 錯誤傳回給用戶端。
+
+為何選擇 raise 例外而非回傳值的好處,會在相依性與安全性章節更為明顯。
+
+在這個範例中,當用戶端以不存在的 ID 請求項目時,raise 一個狀態碼為 `404` 的例外:
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+
+### 回應結果 { #the-resulting-response }
+
+如果用戶端請求 `http://example.com/items/foo`(`item_id` 為 `"foo"`),會收到 200 的 HTTP 狀態碼,以及以下 JSON 回應:
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+但如果用戶端請求 `http://example.com/items/bar`(不存在的 `item_id` `"bar"`),會收到 404("not found")的 HTTP 狀態碼,以及以下 JSON 回應:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip
+
+在 raise 一個 `HTTPException` 時,你可以將任何可轉為 JSON 的值作為 `detail` 參數,不只限於 `str`。
+
+你可以傳入 `dict`、`list` 等。
+
+**FastAPI** 會自動處理並轉為 JSON。
+
+///
+
+## 新增自訂標頭 { #add-custom-headers }
+
+有些情況需要在 HTTP 錯誤回應中加入自訂標頭,例如某些安全性情境。
+
+你大概不需要在程式碼中直接使用。
+
+但若你在進階情境中需要,可以這樣加入自訂標頭:
+
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
+
+## 安裝自訂例外處理器 { #install-custom-exception-handlers }
+
+你可以使用 Starlette 的相同例外工具 來加入自訂例外處理器。
+
+假設你有一個自訂例外 `UnicornException`,你(或你使用的函式庫)可能會 `raise` 它。
+
+而你想用 FastAPI 全域處理這個例外。
+
+你可以使用 `@app.exception_handler()` 加入自訂例外處理器:
+
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
+
+在這裡,如果你請求 `/unicorns/yolo`,該「路徑操作」會 `raise` 一個 `UnicornException`。
+
+但它會被 `unicorn_exception_handler` 所處理。
+
+因此你會得到一個乾淨的錯誤回應,HTTP 狀態碼為 `418`,JSON 內容如下:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.requests import Request` 與 `from starlette.responses import JSONResponse`。
+
+**FastAPI** 以便利性為由,提供和 `starlette.responses` 相同的介面於 `fastapi.responses`。但大多數可用的回應類型其實直接來自 Starlette。`Request` 也一樣。
+
+///
+
+## 覆寫預設例外處理器 { #override-the-default-exception-handlers }
+
+**FastAPI** 內建了一些預設例外處理器。
+
+這些處理器負責在你 `raise` 一個 `HTTPException` 或請求帶有無效資料時,回傳預設的 JSON 回應。
+
+你可以用自己的處理器來覆寫它們。
+
+### 覆寫請求驗證例外 { #override-request-validation-exceptions }
+
+當請求包含無效資料時,**FastAPI** 會在內部 raise 一個 `RequestValidationError`。
+
+它同時也包含了對應的預設例外處理器。
+
+要覆寫它,匯入 `RequestValidationError`,並用 `@app.exception_handler(RequestValidationError)` 來裝飾你的例外處理器。
+
+例外處理器會接收一個 `Request` 和該例外。
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
+
+現在,如果你前往 `/items/foo`,預設的 JSON 錯誤本應為:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+你將會改而得到文字版:
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### 覆寫 `HTTPException` 的錯誤處理器 { #override-the-httpexception-error-handler }
+
+同樣地,你也可以覆寫 `HTTPException` 的處理器。
+
+例如,你可能想在這些錯誤時回傳純文字而非 JSON:
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import PlainTextResponse`。
+
+**FastAPI** 以便利性為由,提供和 `starlette.responses` 相同的介面於 `fastapi.responses`。但大多數可用的回應類型其實直接來自 Starlette。
+
+///
+
+/// warning
+
+請注意,`RequestValidationError` 內含驗證錯誤發生的檔名與行號,如果你願意,可以在日誌中顯示這些相關資訊。
+
+但這也代表如果你只是把它轉成字串並直接回傳,可能會洩漏一些關於你系統的資訊。因此這裡的程式碼會分別擷取並顯示每個錯誤。
+
+///
+
+### 使用 `RequestValidationError` 的 body { #use-the-requestvalidationerror-body }
+
+`RequestValidationError` 包含它收到的(但無效的)`body`。
+
+在開發應用時,你可以用它來記錄 body 並除錯、回傳給使用者等。
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
+
+現在嘗試送出一個無效的項目,例如:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+你會收到一個告知資料無效、且包含所收到 body 的回應:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### FastAPI 的 `HTTPException` 與 Starlette 的 `HTTPException` { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI** 有自己定義的 `HTTPException`。
+
+而 **FastAPI** 的 `HTTPException` 錯誤類別是繼承自 Starlette 的 `HTTPException` 錯誤類別。
+
+唯一的差異是,**FastAPI** 的 `HTTPException` 在 `detail` 欄位接受任何可轉為 JSON 的資料,而 Starlette 的 `HTTPException` 只接受字串。
+
+因此,在你的程式碼中,你可以一如往常地 raise **FastAPI** 的 `HTTPException`。
+
+但當你註冊例外處理器時,應該針對 Starlette 的 `HTTPException` 來註冊。
+
+如此一來,如果 Starlette 的內部程式碼,或任何 Starlette 擴充/外掛 raise 了 Starlette 的 `HTTPException`,你的處理器就能攔截並處理它。
+
+在這個範例中,為了能在同一份程式碼中同時使用兩種 `HTTPException`,我們把 Starlette 的例外重新命名為 `StarletteHTTPException`:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### 重用 **FastAPI** 的例外處理器 { #reuse-fastapis-exception-handlers }
+
+如果你想在使用例外的同時,沿用 **FastAPI** 的預設例外處理器,你可以從 `fastapi.exception_handlers` 匯入並重用預設的處理器:
+
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
+
+在這個範例中,你只是用一段很生動的訊息把錯誤印出來,不過重點是:你可以使用該例外,然後直接重用預設的例外處理器。
diff --git a/docs/zh-hant/docs/tutorial/header-param-models.md b/docs/zh-hant/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..ca2b1f8de
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# 標頭參數模型 { #header-parameter-models }
+
+如果你有一組相關的標頭參數,可以建立一個 Pydantic 模型來宣告它們。
+
+這能讓你在多處重複使用該模型,並一次性為所有參數宣告驗證與中繼資料。😎
+
+/// note | 注意
+
+自 FastAPI 版本 `0.115.0` 起支援。🤓
+
+///
+
+## 以 Pydantic 模型宣告標頭參數 { #header-parameters-with-a-pydantic-model }
+
+在 Pydantic 模型中宣告你需要的標頭參數,然後將參數宣告為 `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+FastAPI 會從請求的標頭為每個欄位擷取資料,並交給你已定義的 Pydantic 模型實例。
+
+## 檢視文件 { #check-the-docs }
+
+你可以在 `/docs` 的文件介面看到所需的標頭:
+
+
+contact 欄位參數 型別 說明 namestr聯絡人/組織的識別名稱。 urlstr指向聯絡資訊的 URL。必須是 URL 格式。 emailstr聯絡人/組織的電子郵件地址。必須是電子郵件格式。 license_info 欄位參數 型別 說明 namestr必填(若有設定 license_info)。API 使用的授權名稱。identifierstrAPI 的 SPDX 授權表示式。 identifier 欄位與 url 欄位互斥。自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。urlstrAPI 所採用授權的 URL。必須是 URL 格式。
+
+## 授權識別碼 { #license-identifier }
+
+自 OpenAPI 3.1.0 與 FastAPI 0.99.0 起,你也可以在 `license_info` 中使用 `identifier` 來取代 `url`。
+
+例如:
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## 標籤的中繼資料 { #metadata-for-tags }
+
+你也可以透過 `openapi_tags` 參數,為用來分組你的路徑操作(path operation)的各個標籤加入額外中繼資料。
+
+它接收一個 list,其中每個標籤對應一個 dictionary。
+
+每個 dictionary 可包含:
+
+* `name`(**必填**):一個 `str`,其值需與你在路徑操作與 `APIRouter`s 的 `tags` 參數中使用的標籤名稱相同。
+* `description`:一個 `str`,為該標籤的簡短描述。可使用 Markdown,並會顯示在文件介面中。
+* `externalDocs`:一個 `dict`,描述外部文件,包含:
+ * `description`:一個 `str`,外部文件的簡短描述。
+ * `url`(**必填**):一個 `str`,外部文件的 URL。
+
+### 建立標籤的中繼資料 { #create-metadata-for-tags }
+
+我們用 `users` 與 `items` 兩個標籤來示範。
+
+先為你的標籤建立中繼資料,然後將它傳給 `openapi_tags` 參數:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+注意你可以在描述中使用 Markdown,例如「login」會以粗體(**login**)顯示,而「fancy」會以斜體(_fancy_)顯示。
+
+/// tip | 提示
+
+你不必為你使用到的每個標籤都加入中繼資料。
+
+///
+
+### 使用你的標籤 { #use-your-tags }
+
+在你的路徑操作(以及 `APIRouter`s)上使用 `tags` 參數,將它們歸類到不同標籤下:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info | 資訊
+
+在[路徑操作設定]中閱讀更多關於標籤的內容:[Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank}。
+
+///
+
+### 檢視文件 { #check-the-docs }
+
+現在檢視文件時,會看到所有額外的中繼資料:
+
+
+
+### 標籤順序 { #order-of-tags }
+
+每個標籤中繼資料 dictionary 在清單中的順序,也會決定它們在文件介面中的顯示順序。
+
+例如,雖然按字母排序時 `users` 會排在 `items` 之後,但因為我們在清單中將它的中繼資料放在第一個,所以它會先顯示。
+
+## OpenAPI URL { #openapi-url }
+
+預設情況下,OpenAPI 綱要(schema)會提供在 `/openapi.json`。
+
+但你可以用 `openapi_url` 參數來調整。
+
+例如,將它設定為提供在 `/api/v1/openapi.json`:
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+如果你想完全停用 OpenAPI 綱要,可以設定 `openapi_url=None`,同時也會停用依賴它的文件使用者介面。
+
+## 文件 URL { #docs-urls }
+
+你可以設定內建的兩個文件使用者介面:
+
+* Swagger UI:提供於 `/docs`。
+ * 可用 `docs_url` 參數設定其 URL。
+ * 設定 `docs_url=None` 可停用。
+* ReDoc:提供於 `/redoc`。
+ * 可用 `redoc_url` 參數設定其 URL。
+ * 設定 `redoc_url=None` 可停用。
+
+例如,將 Swagger UI 提供於 `/documentation`,並停用 ReDoc:
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/zh-hant/docs/tutorial/middleware.md b/docs/zh-hant/docs/tutorial/middleware.md
new file mode 100644
index 000000000..ac6f5367d
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# 中介軟體 { #middleware }
+
+你可以在 **FastAPI** 應用程式中加入中介軟體。
+
+「中介軟體」是一個函式,在任何特定的*路徑操作*處理之前先處理每個**請求**;在回傳之前,也會處理每個**回應**。
+
+- 它會攔截進到應用程式的每個**請求**。
+- 然後可以對該**請求**做一些處理或執行所需的程式碼。
+- 接著把**請求**傳遞給應用程式的其餘部分(某個*路徑操作*)處理。
+- 之後再接收應用程式(某個*路徑操作*)所產生的**回應**。
+- 可以對該**回應**做一些處理或執行所需的程式碼。
+- 然後回傳**回應**。
+
+/// note | 技術細節
+
+如果你有使用帶有 `yield` 的相依性,其釋放階段的程式碼會在中介軟體之後執行。
+
+若有背景工作(在[背景工作](background-tasks.md){.internal-link target=_blank}一節會介紹,你稍後會看到),它們會在所有中介軟體之後執行。
+
+///
+
+## 建立中介軟體 { #create-a-middleware }
+
+要建立中介軟體,將裝飾器 `@app.middleware("http")` 加在函式上方。
+
+中介軟體函式會接收:
+
+- `request`。
+- 一個函式 `call_next`,會以 `request` 作為參數。
+ - 這個函式會把 `request` 傳給對應的*路徑操作*。
+ - 然後回傳對應*路徑操作*所產生的 `response`。
+- 然後你可以在回傳之前進一步修改 `response`。
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip
+
+請記得,自訂的非標準標頭可以使用 `X-` 前綴。
+
+但如果你有自訂標頭並希望瀏覽器端的用戶端能看到它們,你需要在 CORS 設定([CORS(Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})中使用 Starlette 的 CORS 文件所記載的參數 `expose_headers` 將它們加入。
+
+///
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.requests import Request`。
+
+**FastAPI** 為了方便開發者而提供了它,但實際上它直接來自 Starlette。
+
+///
+
+### 在 `response` 之前與之後 { #before-and-after-the-response }
+
+你可以在任何*路徑操作*接收 `request` 之前,加入要執行的程式碼。
+
+也可以在產生出 `response` 之後、回傳之前執行程式碼。
+
+例如,你可以新增一個自訂標頭 `X-Process-Time`,其內容為處理請求並產生回應所花費的秒數:
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip
+
+這裡我們使用 `time.perf_counter()` 而不是 `time.time()`,因為在這些用例中它可能更精確。🤓
+
+///
+
+## 多個中介軟體的執行順序 { #multiple-middleware-execution-order }
+
+當你使用 `@app.middleware()` 裝飾器或 `app.add_middleware()` 方法加入多個中介軟體時,每個新的中介軟體都會包裹應用程式,形成一個堆疊。最後加入的中介軟體位於最外層,最先加入的位於最內層。
+
+在請求路徑上,最外層的中介軟體最先執行。
+
+在回應路徑上,它最後執行。
+
+例如:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+執行順序如下:
+
+- **請求**:MiddlewareB → MiddlewareA → 路由
+
+- **回應**:路由 → MiddlewareA → MiddlewareB
+
+這種堆疊行為可確保中介軟體以可預期且可控制的順序執行。
+
+## 其他中介軟體 { #other-middlewares }
+
+你之後可以在[進階使用者指南:進階中介軟體](../advanced/middleware.md){.internal-link target=_blank}閱讀更多關於其他中介軟體的內容。
+
+下一節你將會讀到如何使用中介軟體處理 CORS。
diff --git a/docs/zh-hant/docs/tutorial/path-operation-configuration.md b/docs/zh-hant/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 000000000..45c101434
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# 路徑操作設定 { #path-operation-configuration }
+
+你可以在你的「路徑操作裝飾器」中傳入多個參數來進行設定。
+
+/// warning | 警告
+
+請注意,這些參數是直接傳給「路徑操作裝飾器」,而不是傳給你的「路徑操作函式」。
+
+///
+
+## 回應狀態碼 { #response-status-code }
+
+你可以為「路徑操作」的回應設定 (HTTP) `status_code`。
+
+你可以直接傳入整數代碼,例如 `404`。
+
+如果不記得每個數字代碼代表什麼,你可以使用 `status` 中的速記常數:
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+該狀態碼會用於回應,並被加入至 OpenAPI 結構描述中。
+
+/// note | 技術細節
+
+你也可以使用 `from starlette import status`。
+
+**FastAPI** 提供與 `starlette.status` 相同的 `fastapi.status`,僅為了方便你這位開發者,但它其實直接來自 Starlette。
+
+///
+
+## 標籤 { #tags }
+
+你可以為「路徑操作」加入標籤,傳入參數 `tags`,其值為由 `str` 組成的 `list`(通常只是一個 `str`):
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+這些標籤會被加入到 OpenAPI 結構描述,並由自動化文件介面使用:
+
+
+
+### 含 Enum 的標籤 { #tags-with-enums }
+
+如果你的應用很大,可能會累積數個標籤,你會希望對相關的「路徑操作」始終使用相同的標籤。
+
+在這種情況下,可以考慮把標籤存放在 `Enum` 中。
+
+**FastAPI** 對此的支援方式與使用普通字串相同:
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
+
+## 摘要與描述 { #summary-and-description }
+
+你可以加入 `summary` 與 `description`:
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## 從 docstring 取得描述 { #description-from-docstring }
+
+由於描述常常較長、跨越多行,你可以在函式的 文件字串(docstring) 中宣告「路徑操作」的描述,**FastAPI** 會從那裡讀取。
+
+你可以在 docstring 中書寫 Markdown,它會被正確解析並顯示(會考慮 docstring 的縮排)。
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+這會用於互動式文件:
+
+
+
+## 回應描述 { #response-description }
+
+你可以用參數 `response_description` 指定回應的描述:
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info | 資訊
+
+請注意,`response_description` 專指回應,而 `description` 則是針對整個「路徑操作」的一般描述。
+
+///
+
+/// check | 檢查
+
+OpenAPI 規範要求每個「路徑操作」都必須有一個回應描述。
+
+因此,如果你未提供,**FastAPI** 會自動產生 "Successful response"。
+
+///
+
+
+
+## 將「路徑操作」標記為已棄用 { #deprecate-a-path-operation }
+
+若需要將「路徑操作」標記為 已棄用,但不移除它,請傳入參數 `deprecated`:
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
+
+在互動式文件中,它會被清楚標示為已棄用:
+
+
+
+比較已棄用與未棄用的「路徑操作」在文件中的呈現:
+
+
+
+## 總結 { #recap }
+
+你可以透過將參數傳給「路徑操作裝飾器」,輕鬆地設定並為你的「路徑操作」加入中繼資料。
diff --git a/docs/zh-hant/docs/tutorial/path-params-numeric-validations.md b/docs/zh-hant/docs/tutorial/path-params-numeric-validations.md
new file mode 100644
index 000000000..a07f825b0
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,154 @@
+# 路徑參數與數值驗證 { #path-parameters-and-numeric-validations }
+
+就像使用 `Query` 為查詢參數宣告更多驗證與中繼資料一樣,你也可以用 `Path` 為路徑參數宣告相同類型的驗證與中繼資料。
+
+## 匯入 `Path` { #import-path }
+
+首先,從 `fastapi` 匯入 `Path`,並匯入 `Annotated`:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
+
+/// info
+
+FastAPI 在 0.95.0 版加入並開始推薦使用 `Annotated`。
+
+如果你使用更舊的版本,嘗試使用 `Annotated` 會出錯。
+
+請確保在使用 `Annotated` 前,先[升級 FastAPI 版本](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}到至少 0.95.1。
+
+///
+
+## 宣告中繼資料 { #declare-metadata }
+
+你可以宣告與 `Query` 相同的所有參數。
+
+例如,若要為路徑參數 `item_id` 宣告 `title` 中繼資料,可以這樣寫:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
+
+/// note
+
+路徑參數一定是必填,因為它必須是路徑的一部分。即使你將其宣告為 `None` 或設定預設值,也不會有任何影響,它仍然是必填。
+
+///
+
+## 依需求調整參數順序 { #order-the-parameters-as-you-need }
+
+/// tip
+
+如果你使用 `Annotated`,這點大概沒那麼重要或必要。
+
+///
+
+假設你想把查詢參數 `q` 宣告為必要的 `str`。
+
+而你不需要為該參數宣告其他內容,所以其實不需要用 `Query`。
+
+但你仍需要為路徑參數 `item_id` 使用 `Path`,而且基於某些理由你不想用 `Annotated`。
+
+如果你把有「預設值」的參數放在沒有「預設值」的參數之前,Python 會抱怨。
+
+但你可以調整它們的順序,先放沒有預設值(查詢參數 `q`)的參數。
+
+對 **FastAPI** 來說沒差。它會依參數名稱、型別與預設宣告(`Query`、`Path` 等)來辨識參數,並不在意順序。
+
+因此,你可以這樣宣告你的函式:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
+
+但請記住,若使用 `Annotated`,你就不會有這個問題,因為你不是用函式參數預設值來放 `Query()` 或 `Path()`。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
+
+## 依需求調整參數順序的技巧 { #order-the-parameters-as-you-need-tricks }
+
+/// tip
+
+如果你使用 `Annotated`,這點大概沒那麼重要或必要。
+
+///
+
+這裡有個小技巧偶爾很好用,不過你大概不常需要。
+
+如果你想要:
+
+* 不用 `Query`、也不給預設值就宣告查詢參數 `q`
+* 使用 `Path` 宣告路徑參數 `item_id`
+* 讓它們的順序不同
+* 不使用 `Annotated`
+
+…Python 有個小語法可以做到。
+
+在函式的參數列表最前面放一個 `*`。
+
+Python 不會對這個 `*` 做任何事,但它會知道後續的所有參數都必須以關鍵字引數(key-value pairs)方式呼叫,也就是所謂的 kwargs。即便它們沒有預設值也一樣。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
+
+### 使用 `Annotated` 更好 { #better-with-annotated }
+
+記住,如果你使用 `Annotated`,因為不是用函式參數預設值,所以你不會遇到這個問題,也可能不需要使用 `*`。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
+
+## 數值驗證:大於或等於 { #number-validations-greater-than-or-equal }
+
+使用 `Query` 和 `Path`(以及你之後會看到的其他類別)可以宣告數值限制。
+
+這裡用 `ge=1`,代表 `item_id` 必須是「大於(`g`reater)或等於(`e`qual)」`1` 的整數。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
+
+## 數值驗證:大於與小於或等於 { #number-validations-greater-than-and-less-than-or-equal }
+
+同樣也適用於:
+
+* `gt`:大於(`g`reater `t`han)
+* `le`:小於或等於(`l`ess than or `e`qual)
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
+
+## 數值驗證:浮點數、大於與小於 { #number-validations-floats-greater-than-and-less-than }
+
+數值驗證也適用於 `float`。
+
+這時就能看出能宣告 gt(不只是 ge)的重要性。因為你可以要求數值必須大於 `0`,即便它小於 `1`。
+
+所以,`0.5` 是有效的值,但 `0.0` 或 `0` 則無效。
+
+lt 也是同樣的道理。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
+
+## 小結 { #recap }
+
+使用 `Query`、`Path`(以及你尚未看到的其他類別)時,你可以像在[查詢參數與字串驗證](query-params-str-validations.md){.internal-link target=_blank}中一樣,宣告中繼資料與字串驗證。
+
+你也可以宣告數值驗證:
+
+* `gt`:大於(`g`reater `t`han)
+* `ge`:大於或等於(`g`reater than or `e`qual)
+* `lt`:小於(`l`ess `t`han)
+* `le`:小於或等於(`l`ess than or `e`qual)
+
+/// info
+
+你之後會看到的 `Query`、`Path` 與其他類別,都是共同父類別 `Param` 的子類別。
+
+它們共享你已經看到的那些用於額外驗證與中繼資料的參數。
+
+///
+
+/// note | 技術細節
+
+當你從 `fastapi` 匯入 `Query`、`Path` 等時,它們其實是函式。
+
+呼叫它們時,會回傳同名類別的實例。
+
+也就是說,你匯入的是名為 `Query` 的函式,而當你呼叫它時,它會回傳同名的 `Query` 類別實例。
+
+這些函式之所以存在(而不是直接使用類別),是為了避免編輯器標記它們的型別錯誤。
+
+如此一來,你就能使用一般的編輯器與開發工具,而不需要額外設定來忽略那些錯誤。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/path-params.md b/docs/zh-hant/docs/tutorial/path-params.md
new file mode 100644
index 000000000..373f430cd
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/path-params.md
@@ -0,0 +1,251 @@
+# 路徑參數 { #path-parameters }
+
+你可以用與 Python 格式化字串相同的語法來宣告路徑「參數」或「變數」:
+
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
+
+路徑參數 `item_id` 的值會作為引數 `item_id` 傳入你的函式。
+
+所以,如果你執行這個範例並前往 http://127.0.0.1:8000/items/foo,你會看到這樣的回應:
+
+```JSON
+{"item_id":"foo"}
+```
+
+## 具型別的路徑參數 { #path-parameters-with-types }
+
+你可以在函式中使用標準的 Python 型別註記為路徑參數宣告型別:
+
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
+
+在這個例子裡,`item_id` 被宣告為 `int`。
+
+/// check
+
+這會在你的函式中提供編輯器支援,包括錯誤檢查、自動完成等。
+
+///
+
+## 資料 轉換 { #data-conversion }
+
+如果你執行這個範例並在瀏覽器開啟 http://127.0.0.1:8000/items/3,你會看到這樣的回應:
+
+```JSON
+{"item_id":3}
+```
+
+/// check
+
+注意你的函式接收(並回傳)的值是 `3`,也就是 Python 的 `int`,而不是字串 `"3"`。
+
+因此,有了這個型別宣告,**FastAPI** 會自動為你處理請求的 「解析」。
+
+///
+
+## 資料驗證 { #data-validation }
+
+但如果你在瀏覽器前往 http://127.0.0.1:8000/items/foo,你會看到漂亮的 HTTP 錯誤:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
+}
+```
+
+因為路徑參數 `item_id` 的值是 `"foo"`,它不是 `int`。
+
+同樣的錯誤也會在你提供 `float` 而不是 `int` 時出現,例如:http://127.0.0.1:8000/items/4.2
+
+/// check
+
+因此,搭配相同的 Python 型別宣告,**FastAPI** 會為你進行資料驗證。
+
+注意錯誤也清楚指出驗證未通過的確切位置。
+
+這在開發與除錯與你的 API 互動的程式碼時非常有幫助。
+
+///
+
+## 文件 { #documentation }
+
+當你在瀏覽器開啟 http://127.0.0.1:8000/docs,你會看到自動產生、可互動的 API 文件,例如:
+
+
+
+/// check
+
+同樣地,只要使用那個 Python 型別宣告,**FastAPI** 就會提供自動、互動式的文件(整合 Swagger UI)。
+
+注意路徑參數被宣告為整數。
+
+///
+
+## 基於標準的優勢與替代文件 { #standards-based-benefits-alternative-documentation }
+
+而且因為產生的 schema 來自 OpenAPI 標準,有很多相容的工具可用。
+
+因此,**FastAPI** 本身也提供另一種 API 文件(使用 ReDoc),你可以在 http://127.0.0.1:8000/redoc 存取:
+
+
+
+同樣地,也有許多相容工具可用,包括支援多種語言的程式碼產生工具。
+
+## Pydantic { #pydantic }
+
+所有資料驗證都由 Pydantic 在底層處理,因此你能直接受惠。而且你可以放心使用。
+
+你可以用相同的型別宣告搭配 `str`、`float`、`bool` 與許多更複雜的資料型別。
+
+這些之中的好幾個會在接下來的教學章節中介紹。
+
+## 順序很重要 { #order-matters }
+
+在建立「路徑操作」時,你可能會遇到有固定路徑的情況。
+
+像是 `/users/me`,假設它用來取得目前使用者的資料。
+
+然後你也可能有一個路徑 `/users/{user_id}` 用來依使用者 ID 取得特定使用者的資料。
+
+因為「路徑操作」會依宣告順序來比對,你必須確保 `/users/me` 的路徑在 `/users/{user_id}` 之前宣告:
+
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
+
+否則,`/users/{user_id}` 的路徑也會匹配 `/users/me`,並「認為」它收到一個值為 `"me"` 的 `user_id` 參數。
+
+同樣地,你不能重新定義同一路徑操作:
+
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
+
+因為第一個會被優先使用(路徑先匹配到)。
+
+## 預先定義的值 { #predefined-values }
+
+如果你有一個接收「路徑參數」的「路徑操作」,但你希望可用的「路徑參數」值是預先定義好的,你可以使用標準的 Python `Enum`。
+
+### 建立 `Enum` 類別 { #create-an-enum-class }
+
+匯入 `Enum` 並建立一個同時繼承自 `str` 與 `Enum` 的子類別。
+
+繼承自 `str` 之後,API 文件就能知道這些值的型別必須是 `string`,並能正確地呈現。
+
+然後建立具有固定值的類別屬性,這些就是可用的有效值:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
+
+/// tip
+
+如果你在想,「AlexNet」、「ResNet」和「LeNet」只是一些機器學習 模型 的名字。
+
+///
+
+### 宣告一個「路徑參數」 { #declare-a-path-parameter }
+
+接著使用你建立的列舉類別(`ModelName`)作為型別註記,建立一個「路徑參數」:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
+
+### 查看文件 { #check-the-docs }
+
+因為「路徑參數」的可用值是預先定義的,互動式文件可以很漂亮地顯示它們:
+
+
+
+### 使用 Python「列舉」 { #working-with-python-enumerations }
+
+「路徑參數」的值會是一個「列舉成員」。
+
+#### 比較「列舉成員」 { #compare-enumeration-members }
+
+你可以把它與你建立的列舉 `ModelName` 中的「列舉成員」比較:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
+
+#### 取得「列舉值」 { #get-the-enumeration-value }
+
+你可以用 `model_name.value` 取得實際的值(在這個例子中是 `str`),一般而言就是 `your_enum_member.value`:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
+
+/// tip
+
+你也可以用 `ModelName.lenet.value` 取得值 `"lenet"`。
+
+///
+
+#### 回傳「列舉成員」 { #return-enumeration-members }
+
+你可以從「路徑操作」回傳「列舉成員」,即使是巢狀在 JSON 主體(例如 `dict`)裡。
+
+在回傳給用戶端之前,它們會被轉成對應的值(此例為字串):
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
+
+你的用戶端會收到像這樣的 JSON 回應:
+
+```JSON
+{
+ "model_name": "alexnet",
+ "message": "Deep Learning FTW!"
+}
+```
+
+## 包含路徑的路徑參數 { #path-parameters-containing-paths }
+
+假設你有一個路徑為 `/files/{file_path}` 的「路徑操作」。
+
+但你需要 `file_path` 本身就包含一個「路徑」,像是 `home/johndoe/myfile.txt`。
+
+所以,該檔案的 URL 會是:`/files/home/johndoe/myfile.txt`。
+
+### OpenAPI 支援 { #openapi-support }
+
+OpenAPI 並不支援直接宣告一個「路徑參數」內再包含一個「路徑」,因為那會導致難以測試與定義的情況。
+
+然而,你仍可在 **FastAPI** 中這樣做,方法是使用 Starlette 的其中一個內部工具。
+
+而文件依然能運作,只是它不會額外說明該參數應該包含一個路徑。
+
+### 路徑轉換器 { #path-convertor }
+
+使用 Starlette 提供的選項,你可以用像這樣的 URL 來宣告一個包含「路徑」的「路徑參數」:
+
+```
+/files/{file_path:path}
+```
+
+在這個例子裡,參數名稱是 `file_path`,而最後面的 `:path` 表示該參數應該匹配任意「路徑」。
+
+所以你可以這樣使用它:
+
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip
+
+你可能需要這個參數包含 `/home/johndoe/myfile.txt`,也就是前面帶有斜線(`/`)。
+
+在那種情況下,URL 會是:`/files//home/johndoe/myfile.txt`,在 `files` 與 `home` 之間有兩個斜線(`//`)。
+
+///
+
+## 回顧 { #recap }
+
+使用 **FastAPI**,只要撰寫簡短、直覺且標準的 Python 型別宣告,你就能獲得:
+
+* 編輯器支援:錯誤檢查、自動完成等
+* 資料 "解析"
+* 資料驗證
+* API 註解與自動產生文件
+
+而且你只要宣告一次就好。
+
+這大概是 **FastAPI** 相較於其他框架最明顯的優勢之一(除了原始效能之外)。
diff --git a/docs/zh-hant/docs/tutorial/query-params-str-validations.md b/docs/zh-hant/docs/tutorial/query-params-str-validations.md
new file mode 100644
index 000000000..ea84234c0
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/query-params-str-validations.md
@@ -0,0 +1,449 @@
+# 查詢參數與字串驗證 { #query-parameters-and-string-validations }
+
+FastAPI 允許你為參數宣告額外的資訊與驗證。
+
+以下面這個應用為例:
+
+{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *}
+
+查詢參數 `q` 的型別是 `str | None`,表示它是 `str` 但也可以是 `None`,而且預設值就是 `None`,因此 FastAPI 會知道它不是必填。
+
+/// note | 注意
+
+FastAPI 會因為預設值是 `= None` 而知道 `q` 不是必填。
+
+使用 `str | None` 也能讓你的編輯器提供更好的支援並偵測錯誤。
+
+///
+
+## 額外驗證 { #additional-validation }
+
+我們要強制:即使 `q` 是可選,只要提供了,長度就不能超過 50 個字元。
+
+### 匯入 `Query` 與 `Annotated` { #import-query-and-annotated }
+
+要達成這點,先匯入:
+
+- 從 `fastapi` 匯入 `Query`
+- 從 `typing` 匯入 `Annotated`
+
+{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[1,3] *}
+
+/// info | 說明
+
+FastAPI 自 0.95.0 版起加入並開始推薦使用 `Annotated`。
+
+如果你的版本較舊,嘗試使用 `Annotated` 會出錯。
+
+請先至少 [升級 FastAPI 版本](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} 到 0.95.1 再使用 `Annotated`。
+
+///
+
+## 在 `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` 為參數加入中繼資料嗎?
+
+現在就用在 FastAPI 上吧。🚀
+
+我們原本的型別註記是:
+
+```Python
+q: str | None = None
+```
+
+接著把它用 `Annotated` 包起來,變成:
+
+```Python
+q: Annotated[str | None] = None
+```
+
+這兩種寫法代表的意思相同:`q` 可以是 `str` 或 `None`,且預設是 `None`。
+
+現在來做有趣的部分。🎉
+
+## 在 `q` 參數的 `Annotated` 中加入 `Query` { #add-query-to-annotated-in-the-q-parameter }
+
+既然我們有可以放更多資訊的 `Annotated`(在此是額外驗證),就把 `Query` 放進 `Annotated`,並把參數 `max_length` 設為 `50`:
+
+{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *}
+
+注意預設值仍然是 `None`,所以這個參數仍是可選。
+
+不過,現在在 `Annotated` 裡有 `Query(max_length=50)`,我們就告訴 FastAPI 要對這個值做「額外驗證」,最多 50 個字元即可。😎
+
+/// tip | 提示
+
+這裡用的是 `Query()`,因為這是「查詢參數」。稍後你會看到 `Path()`、`Body()`、`Header()`、`Cookie()` 等,它們也接受與 `Query()` 相同的參數。
+
+///
+
+FastAPI 現在會:
+
+- 驗證資料,確保長度最多 50 個字元
+- 當資料不合法時,回給用戶端清楚的錯誤
+- 在 OpenAPI 的路徑操作中文件化該參數(因此會出現在自動文件 UI)
+
+## 替代方式(舊):將 `Query` 作為預設值 { #alternative-old-query-as-the-default-value }
+
+舊版 FastAPI(0.95.0 以前)需要把 `Query` 當成參數的預設值,而不是放在 `Annotated` 裡。你很可能會在各處看到這種寫法,所以我也會說明一下。
+
+/// tip | 提示
+
+新程式碼且在可能的情況下,請依上面說明使用 `Annotated`。它有多項優點(如下所述),而沒有缺點。🍰
+
+///
+
+這是把 `Query()` 作為函式參數預設值的寫法,並把參數 `max_length` 設為 50:
+
+{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *}
+
+在這種情況下(未使用 `Annotated`),我們必須用 `Query()` 取代函式中的預設值 `None`,因此需要用 `Query(default=None)` 來設定預設值;對 FastAPI 而言,這達到相同目的。
+
+所以:
+
+```Python
+q: str | None = Query(default=None)
+```
+
+…會讓參數變為可選、預設值是 `None`,等同於:
+
+```Python
+q: str | None = None
+```
+
+但用 `Query` 的版本會明確宣告它是查詢參數。
+
+接著,我們可以傳更多參數給 `Query`。此例中是用於字串的 `max_length` 參數:
+
+```Python
+q: str | None = Query(default=None, max_length=50)
+```
+
+這一樣會驗證資料、在資料不合法時顯示清楚錯誤,並在 OpenAPI 的路徑操作中文件化該參數。
+
+### 將 `Query` 作為預設值或放在 `Annotated` 中 { #query-as-the-default-value-or-in-annotated }
+
+注意,把 `Query` 放在 `Annotated` 內時,不能使用 `Query` 的 `default` 參數。
+
+請改用函式參數的實際預設值。否則會不一致。
+
+例如,這是不允許的:
+
+```Python
+q: Annotated[str, Query(default="rick")] = "morty"
+```
+
+…因為不清楚預設值到底該是 `"rick"` 還是 `"morty"`。
+
+因此,你可以(且更推薦)這樣寫:
+
+```Python
+q: Annotated[str, Query()] = "rick"
+```
+
+…或在較舊的程式碼中你會看到:
+
+```Python
+q: str = Query(default="rick")
+```
+
+### `Annotated` 的優點 { #advantages-of-annotated }
+
+建議使用 `Annotated`,而不是在函式參數上使用(舊式的)預設值寫法,理由很多,且更好。🤓
+
+函式參數的「預設值」就是「實際的預設值」,這在 Python 的直覺上更一致。😌
+
+你也可以在沒有 FastAPI 的其他地方「直接呼叫」同一個函式,而且能「如預期」運作。若有「必填」參數(沒有預設值),你的「編輯器」會提示錯誤,「Python」在執行時也會抱怨你未傳遞必填參數。
+
+若不使用 `Annotated`、改用「(舊式)預設值」寫法,你在沒有 FastAPI 的「其他地方」呼叫該函式時,就得「記得」傳入正確參數,否則值會和預期不同(例如會得到 `QueryInfo` 或類似的東西,而不是 `str`)。你的編輯器不會提示,Python 執行該函式時也不會抱怨,只有在內部操作失敗時才會出錯。
+
+因為 `Annotated` 可以有多個中繼資料註解,你甚至可以用同一個函式配合其他工具,例如 Typer。🚀
+
+## 加入更多驗證 { #add-more-validations }
+
+你也可以加入 `min_length` 參數:
+
+{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *}
+
+## 加入正規表示式 { #add-regular-expressions }
+
+你可以定義參數必須符合的 regular expression `pattern`:
+
+{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
+
+這個特定的正規表示式樣式會檢查收到的參數值是否:
+
+- `^`:以後續的字元開頭,前面不能有其他字元。
+- `fixedquery`:必須正好等於 `fixedquery`。
+- `$`:在此結束,`fixedquery` 後面不能再有其他字元。
+
+如果你對「正規表示式」感到困惑,別擔心。這對很多人來說都不容易。你仍然可以先不使用正規表示式就完成很多事情。
+
+現在你知道,當你需要它們時,可以在 FastAPI 中使用它們。
+
+## 預設值 { #default-values }
+
+當然,你可以使用 `None` 以外的預設值。
+
+假設你想宣告查詢參數 `q` 的 `min_length` 是 `3`,且預設值是 `"fixedquery"`:
+
+{* ../../docs_src/query_params_str_validations/tutorial005_an_py310.py hl[9] *}
+
+/// note | 注意
+
+只要有任何型別的預設值(包含 `None`),參數就是可選(非必填)。
+
+///
+
+## 必填參數 { #required-parameters }
+
+當我們不需要宣告更多的驗證或中繼資料時,只要不提供預設值,就能讓查詢參數 `q` 成為必填,例如:
+
+```Python
+q: str
+```
+
+而不是:
+
+```Python
+q: str | None = None
+```
+
+但現在我們要搭配 `Query` 來宣告,例如:
+
+```Python
+q: Annotated[str | None, Query(min_length=3)] = None
+```
+
+因此,在使用 `Query` 時若要宣告值為必填,只要不要宣告預設值即可:
+
+{* ../../docs_src/query_params_str_validations/tutorial006_an_py310.py hl[9] *}
+
+### 必填,但可為 `None` { #required-can-be-none }
+
+你可以宣告參數可以接受 `None`,但仍然是必填。這會強制用戶端一定要送出一個值,即使該值是 `None`。
+
+要做到這點,你可以宣告 `None` 是合法型別,但不要宣告預設值:
+
+{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *}
+
+## 查詢參數清單/多個值 { #query-parameter-list-multiple-values }
+
+當你用 `Query` 明確定義查詢參數時,也可以讓它接收一個值的清單;換句話說,就是「多個值」。
+
+例如,要宣告查詢參數 `q` 可以在 URL 中出現多次,你可以這樣寫:
+
+{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *}
+
+若使用這樣的 URL:
+
+```
+http://localhost:8000/items/?q=foo&q=bar
+```
+
+你會在路徑操作函式的參數 `q` 中,收到多個 `q` 查詢參數的值(`foo` 與 `bar`),以 Python 的 `list` 形式。
+
+因此,對該 URL 的回應會是:
+
+```JSON
+{
+ "q": [
+ "foo",
+ "bar"
+ ]
+}
+```
+
+/// tip | 提示
+
+要宣告型別為 `list` 的查詢參數(如上例),需要明確使用 `Query`,否則它會被解讀為請求本文。
+
+///
+
+互動式 API 文件也會相應更新,以便支援多個值:
+
+
+
+### 查詢參數清單/多個值的預設值 { #query-parameter-list-multiple-values-with-defaults }
+
+也可以在未提供任何值時,定義 `list` 型別的預設值:
+
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
+
+如果你前往:
+
+```
+http://localhost:8000/items/
+```
+
+`q` 的預設值會是:`["foo", "bar"]`,而回應會是:
+
+```JSON
+{
+ "q": [
+ "foo",
+ "bar"
+ ]
+}
+```
+
+#### 只使用 `list` { #using-just-list }
+
+你也可以直接使用 `list`,而不是 `list[str]`:
+
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
+
+/// note | 注意
+
+注意,在這種情況下,FastAPI 不會檢查清單的內容。
+
+例如,`list[int]` 會檢查(並文件化)清單內容為整數;但單獨使用 `list` 則不會。
+
+///
+
+## 宣告更多中繼資料 { #declare-more-metadata }
+
+你可以為參數加入更多資訊。
+
+這些資訊會被包含在產生的 OpenAPI 中,供文件 UI 與外部工具使用。
+
+/// note | 注意
+
+請留意,不同工具對 OpenAPI 的支援程度可能不同。
+
+有些工具可能暫時還不會顯示所有額外資訊;不過多半這些缺漏功能已在開發規劃中。
+
+///
+
+你可以加入 `title`:
+
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
+
+以及 `description`:
+
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
+
+## 別名參數 { #alias-parameters }
+
+想像你希望參數名稱是 `item-query`。
+
+像這樣:
+
+```
+http://127.0.0.1:8000/items/?item-query=foobaritems
+```
+
+但 `item-query` 不是合法的 Python 變數名稱。
+
+最接近的大概是 `item_query`。
+
+但你仍然需要它就是 `item-query`...
+
+那你可以宣告一個 `alias`,實際上就會用這個別名來讀取參數值:
+
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
+
+## 棄用參數 { #deprecating-parameters }
+
+現在假設你不再喜歡這個參數了。
+
+你必須暫時保留它,因為還有用戶端在用,但你希望文件能清楚標示它是已棄用。
+
+接著把參數 `deprecated=True` 傳給 `Query`:
+
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
+
+文件會這樣顯示:
+
+
+
+## 從 OpenAPI 排除參數 { #exclude-parameters-from-openapi }
+
+若要把某個查詢參數從產生的 OpenAPI(以及自動文件系統)中排除,將 `Query` 的 `include_in_schema` 設為 `False`:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## 自訂驗證 { #custom-validation }
+
+有時你需要做一些上述參數無法處理的「自訂驗證」。
+
+這種情況下,你可以使用「自訂驗證函式」,它會在一般驗證之後套用(例如先確認值是 `str` 之後)。
+
+你可以在 `Annotated` 中使用 Pydantic 的 `AfterValidator` 來達成。
+
+/// tip | 提示
+
+Pydantic 也有 `BeforeValidator` 等等。🤓
+
+///
+
+例如,以下自訂驗證器會檢查項目 ID 是否以 `isbn-` 開頭(ISBN 書籍編號),或以 `imdb-` 開頭(IMDB 電影 URL 的 ID):
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | 說明
+
+這需搭配 Pydantic 2 或以上版本。😎
+
+///
+
+/// tip | 提示
+
+如果你需要做任何需要與「外部元件」溝通的驗證(例如資料庫或其他 API),應該改用「FastAPI 依賴」(FastAPI Dependencies),你稍後會學到。
+
+這些自訂驗證器適用於只需使用請求中「同一份資料」即可完成的檢查。
+
+///
+
+### 理解這段程式碼 { #understand-that-code }
+
+重點就是在 `Annotated` 中使用「`AfterValidator` 搭配函式」。如果你願意,可以略過這一節。🤸
+
+---
+
+但如果你對這個範例感到好奇且仍有興致,以下是一些額外細節。
+
+#### 使用 `value.startswith()` 的字串 { #string-with-value-startswith }
+
+你注意到了嗎?字串的 `value.startswith()` 可以接收一個 tuple,並逐一檢查 tuple 中的每個值:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### 隨機項目 { #a-random-item }
+
+透過 `data.items()` 我們會得到一個包含每個字典項目鍵值對 tuple 的 iterable object。
+
+我們用 `list(data.items())` 把這個可疊代物件轉成正式的 `list`。
+
+接著用 `random.choice()` 從清單中取得一個「隨機值」,也就是一個 `(id, name)` 的 tuple。可能像是 `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`。
+
+然後把這個 tuple 的兩個值分別指定給變數 `id` 和 `name`。
+
+因此,即使使用者沒有提供 item ID,仍然會收到一個隨機建議。
+
+……而這全部只用一行簡單的程式碼完成。🤯 你不愛 Python 嗎?🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## 重點回顧 { #recap }
+
+你可以為參數宣告額外的驗證與中繼資料。
+
+通用的驗證與中繼資料:
+
+- `alias`
+- `title`
+- `description`
+- `deprecated`
+
+字串專用的驗證:
+
+- `min_length`
+- `max_length`
+- `pattern`
+
+使用 `AfterValidator` 的自訂驗證。
+
+在這些範例中,你看到了如何為 `str` 值宣告驗證。
+
+接下來的章節會示範如何為其他型別(像是數字)宣告驗證。
diff --git a/docs/zh-hant/docs/tutorial/query-params.md b/docs/zh-hant/docs/tutorial/query-params.md
new file mode 100644
index 000000000..f21bf4050
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/query-params.md
@@ -0,0 +1,187 @@
+# 查詢參數 { #query-parameters }
+
+當你宣告不是路徑參數的其他函式參數時,會自動被視為「查詢(query)」參數。
+
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
+
+查詢是出現在 URL 中 `?` 之後的一組鍵值對,以 `&` 字元分隔。
+
+例如,URL:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+...查詢參數為:
+
+* `skip`:值為 `0`
+* `limit`:值為 `10`
+
+因為它們是 URL 的一部分,天生是字串。
+
+但當你以 Python 型別宣告它們(如上例中的 `int`),它們會被轉換成該型別並據此驗證。
+
+對於查詢參數,會套用與路徑參數相同的處理流程:
+
+* 編輯器支援(當然)
+* 資料 「解析」
+* 資料驗證
+* 自動文件
+
+## 預設值 { #defaults }
+
+由於查詢參數不是路徑的固定部分,因此可以是選填並具有預設值。
+
+在上面的例子中,預設值為 `skip=0` 與 `limit=10`。
+
+因此,造訪下列 URL:
+
+```
+http://127.0.0.1:8000/items/
+```
+
+等同於造訪:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+但如果你改為造訪:
+
+```
+http://127.0.0.1:8000/items/?skip=20
+```
+
+函式中的參數值會是:
+
+* `skip=20`:因為你在 URL 中設定了它
+* `limit=10`:因為那是預設值
+
+## 選用參數 { #optional-parameters }
+
+同樣地,你可以將預設值設為 `None` 來宣告選用的查詢參數:
+
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
+
+在這種情況下,函式參數 `q` 為選用,且預設為 `None`。
+
+/// check | 注意
+
+另外請注意,FastAPI 能辨識出路徑參數 `item_id` 是路徑參數,而 `q` 不是,因此 `q` 會被當作查詢參數。
+
+///
+
+## 查詢參數型別轉換 { #query-parameter-type-conversion }
+
+你也可以宣告 `bool` 型別,值會被自動轉換:
+
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
+
+在這種情況下,如果你造訪:
+
+```
+http://127.0.0.1:8000/items/foo?short=1
+```
+
+或
+
+```
+http://127.0.0.1:8000/items/foo?short=True
+```
+
+或
+
+```
+http://127.0.0.1:8000/items/foo?short=true
+```
+
+或
+
+```
+http://127.0.0.1:8000/items/foo?short=on
+```
+
+或
+
+```
+http://127.0.0.1:8000/items/foo?short=yes
+```
+
+或任何其他大小寫變化(全大寫、首字母大寫等),你的函式會將參數 `short` 視為 `bool` 值 `True`。否則為 `False`。
+
+## 多個路徑與查詢參數 { #multiple-path-and-query-parameters }
+
+你可以同時宣告多個路徑參數與查詢參數,FastAPI 會自動分辨。
+
+而且不必按特定順序宣告。
+
+會依名稱辨識:
+
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
+
+## 必填查詢參數 { #required-query-parameters }
+
+當你為非路徑參數(目前我們只看到查詢參數)宣告了預設值時,它就不是必填。
+
+若你不想提供特定預設值、只想讓它為選填,將預設值設為 `None`。
+
+但若你要讓查詢參數成為必填,只要不要宣告任何預設值:
+
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
+
+此處查詢參數 `needy` 是必填的 `str`。
+
+如果你在瀏覽器中開啟如下的 URL:
+
+```
+http://127.0.0.1:8000/items/foo-item
+```
+
+...沒有加上必填的 `needy` 參數,你會看到類似這樣的錯誤:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
+}
+```
+
+由於 `needy` 是必填參數,你需要在 URL 中設定它:
+
+```
+http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
+```
+
+...這樣就會成功:
+
+```JSON
+{
+ "item_id": "foo-item",
+ "needy": "sooooneedy"
+}
+```
+
+當然,你可以同時定義部分參數為必填、部分有預設值、部分為選填:
+
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
+
+在此例中,有 3 個查詢參數:
+
+* `needy`,必填的 `str`。
+* `skip`,具有預設值 `0` 的 `int`。
+* `limit`,選填的 `int`。
+
+/// tip | 提示
+
+你也可以像在[路徑參數](path-params.md#predefined-values){.internal-link target=_blank}中一樣使用 `Enum`。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/request-files.md b/docs/zh-hant/docs/tutorial/request-files.md
new file mode 100644
index 000000000..c8606a3f2
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/request-files.md
@@ -0,0 +1,176 @@
+# 請求中的檔案 { #request-files }
+
+你可以使用 `File` 定義由用戶端上傳的檔案。
+
+/// info
+
+若要接收上傳的檔案,請先安裝 `python-multipart`。
+
+請先建立並啟用一個[虛擬環境](../virtual-environments.md){.internal-link target=_blank},然後安裝,例如:
+
+```console
+$ pip install python-multipart
+```
+
+因為上傳的檔案是以「表單資料」送出的。
+
+///
+
+## 匯入 `File` { #import-file }
+
+從 `fastapi` 匯入 `File` 與 `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
+
+## 定義 `File` 參數 { #define-file-parameters }
+
+和 `Body` 或 `Form` 一樣的方式建立檔案參數:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info
+
+`File` 是直接繼承自 `Form` 的類別。
+
+但請記住,當你從 `fastapi` 匯入 `Query`、`Path`、`File` 等時,它們其實是回傳特殊類別的函式。
+
+///
+
+/// tip
+
+要宣告檔案本文,必須使用 `File`,否則參數會被解讀為查詢參數或本文(JSON)參數。
+
+///
+
+檔案會以「表單資料」上傳。
+
+如果你將路徑操作函式(path operation function)的參數型別宣告為 `bytes`,**FastAPI** 會替你讀取檔案,你會以 `bytes` 取得內容。
+
+請注意,這表示整個內容會存放在記憶體中,適合小檔案。
+
+但在許多情況下,使用 `UploadFile` 會更好。
+
+## 使用 `UploadFile` 的檔案參數 { #file-parameters-with-uploadfile }
+
+將檔案參數型別設為 `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
+
+使用 `UploadFile` 相較於 `bytes` 有數個優點:
+
+* 你不必在參數的預設值使用 `File()`。
+* 它使用「spooled」檔案:
+ * 檔案在記憶體中保存到某個大小上限,超過上限後會存到磁碟。
+* 因此適合處理大型檔案(例如圖片、影片、大型二進位檔等),而不會耗盡記憶體。
+* 你可以取得上傳檔案的中繼資料。
+* 它提供一個類檔案的 `async` 介面。
+* 它會提供實際的 Python `SpooledTemporaryFile` 物件,你可以直接傳給需要類檔案物件的其他函式或函式庫。
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` 具有以下屬性:
+
+* `filename`:一個 `str`,為上傳的原始檔名(例如 `myimage.jpg`)。
+* `content_type`:一個 `str`,為內容類型(MIME type / media type)(例如 `image/jpeg`)。
+* `file`:一個 `SpooledTemporaryFile`(類檔案物件)。這是真正的 Python 檔案物件,你可以直接傳給期待「類檔案」物件的其他函式或函式庫。
+
+`UploadFile` 有以下 `async` 方法。它們底層會呼叫對應的檔案方法(使用內部的 `SpooledTemporaryFile`)。
+
+* `write(data)`:將 `data`(`str` 或 `bytes`)寫入檔案。
+* `read(size)`:讀取檔案的 `size`(`int`)個位元組/字元。
+* `seek(offset)`:移動到檔案中的位元組位置 `offset`(`int`)。
+ * 例如,`await myfile.seek(0)` 會移到檔案開頭。
+ * 當你已經執行過 `await myfile.read()`,之後需要再次讀取內容時特別有用。
+* `close()`:關閉檔案。
+
+由於這些都是 `async` 方法,你需要以 await 呼叫它們。
+
+例如,在 `async` 的路徑操作函式中可這樣讀取內容:
+
+```Python
+contents = await myfile.read()
+```
+
+若是在一般的 `def` 路徑操作函式中,你可以直接存取 `UploadFile.file`,例如:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | `async` 技術細節
+
+當你使用這些 `async` 方法時,**FastAPI** 會在執行緒池中執行對應的檔案方法並等待結果。
+
+///
+
+/// note | Starlette 技術細節
+
+**FastAPI** 的 `UploadFile` 直接繼承自 **Starlette** 的 `UploadFile`,但新增了一些必要部分,使其與 **Pydantic** 及 FastAPI 其他部分相容。
+
+///
+
+## 什麼是「表單資料」 { #what-is-form-data }
+
+HTML 表單(``)送到伺服器的資料通常使用一種「特殊」編碼,與 JSON 不同。
+
+**FastAPI** 會從正確的位置讀取該資料,而不是當作 JSON。
+
+/// note | 技術細節
+
+表單資料在不包含檔案時,通常使用媒體型別 `application/x-www-form-urlencoded` 編碼。
+
+但當表單包含檔案時,會使用 `multipart/form-data` 編碼。若你使用 `File`,**FastAPI** 會知道要從請求本文的正確部分取得檔案。
+
+若想進一步了解這些編碼與表單欄位,請參考 MDN Web Docs 的 POST。
+
+///
+
+/// warning
+
+你可以在一個路徑操作中宣告多個 `File` 與 `Form` 參數,但不能同時宣告預期以 JSON 接收的 `Body` 欄位,因為此請求的本文會使用 `multipart/form-data` 而不是 `application/json`。
+
+這不是 **FastAPI** 的限制,而是 HTTP 協定本身的規範。
+
+///
+
+## 可選的檔案上傳 { #optional-file-upload }
+
+可透過一般型別註解並將預設值設為 `None` 使檔案成為可選:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` 搭配額外中繼資料 { #uploadfile-with-additional-metadata }
+
+你也可以在 `UploadFile` 上搭配 `File()`,例如用來設定額外的中繼資料:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## 多檔案上傳 { #multiple-file-uploads }
+
+可以同時上傳多個檔案。
+
+它們會同屬於以「表單資料」送出的同一個表單欄位。
+
+要這麼做,將型別宣告為 `bytes` 或 `UploadFile` 的 `list`:
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+你會如宣告所示,收到由 `bytes` 或 `UploadFile` 組成的 `list`。
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import HTMLResponse`。
+
+**FastAPI** 為了讓你(開發者)更方便,提供與 `starlette.responses` 相同的內容作為 `fastapi.responses`。但大多數可用的回應類型其實直接來自 Starlette。
+
+///
+
+### 多檔案上傳且包含額外中繼資料 { #multiple-file-uploads-with-additional-metadata }
+
+同樣地,即使對 `UploadFile`,你也可以用 `File()` 設定額外參數:
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## 小結 { #recap }
+
+使用 `File`、`bytes` 與 `UploadFile` 來宣告請求中要上傳的檔案,這些檔案會以表單資料送出。
diff --git a/docs/zh-hant/docs/tutorial/request-form-models.md b/docs/zh-hant/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..8cf4a7c5e
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# 表單模型 { #form-models }
+
+你可以使用 **Pydantic 模型** 在 FastAPI 中宣告 **表單欄位**。
+
+/// info | 說明
+
+要使用表單,首先安裝 `python-multipart`。
+
+請先建立[虛擬環境](../virtual-environments.md){.internal-link target=_blank}、啟用後再安裝,例如:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | 注意
+
+此功能自 FastAPI 版本 `0.113.0` 起支援。🤓
+
+///
+
+## 針對表單的 Pydantic 模型 { #pydantic-models-for-forms }
+
+你只需要宣告一個 **Pydantic 模型**,包含你要接收為 **表單欄位** 的欄位,然後將參數宣告為 `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** 會從請求中的 **表單資料** 擷取 **各欄位** 的資料,並將這些資料組成你定義的 Pydantic 模型實例。
+
+## 檢視文件 { #check-the-docs }
+
+你可以在 `/docs` 的文件 UI 中驗證:
+
+
+POST 網頁文件。
+
+///
+
+/// warning
+
+你可以在一個 *路徑操作(path operation)* 中宣告多個 `Form` 參數,但不能同時再宣告期望以 JSON 接收的 `Body` 欄位,因為該請求的本文會使用 `application/x-www-form-urlencoded` 編碼,而不是 `application/json`。
+
+這不是 **FastAPI** 的限制,而是 HTTP 協定本身的規定。
+
+///
+
+## 回顧 { #recap }
+
+使用 `Form` 來宣告表單資料的輸入參數。
diff --git a/docs/zh-hant/docs/tutorial/response-model.md b/docs/zh-hant/docs/tutorial/response-model.md
new file mode 100644
index 000000000..d22402e18
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/response-model.md
@@ -0,0 +1,343 @@
+# 回應模型 - 回傳型別 { #response-model-return-type }
+
+你可以在「路徑操作函式」的回傳型別上加上註解,宣告用於回應的型別。
+
+你可以像在函式「參數」的輸入資料那樣使用型別註解,你可以使用 Pydantic 模型、list、dictionary、整數、布林等純量值。
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+FastAPI 會使用這個回傳型別來:
+
+* 驗證回傳的資料。
+ * 如果資料無效(例如缺少欄位),代表你的應用程式程式碼有問題,沒有回傳應該回傳的內容,FastAPI 會回傳伺服器錯誤,而不是回傳不正確的資料。如此你和你的用戶端都能確定會收到預期的資料與資料結構。
+* 在 OpenAPI 的「路徑操作」中為回應新增 JSON Schema。
+ * 這會被自動文件使用。
+ * 也會被自動用戶端程式碼產生工具使用。
+
+但更重要的是:
+
+* 它會將輸出資料限制並過濾為回傳型別中定義的內容。
+ * 這對安全性特別重要,下面會再看到更多細節。
+
+## `response_model` 參數 { #response-model-parameter }
+
+有些情況下,你需要或想要回傳的資料與你宣告的型別不完全相同。
+
+例如,你可能想要回傳一個 dictionary 或資料庫物件,但把回應宣告為一個 Pydantic 模型。這樣 Pydantic 模型就會替你回傳的物件(例如 dictionary 或資料庫物件)處理所有的資料文件、驗證等。
+
+如果你加了回傳型別註解,工具與編輯器會(正確地)抱怨你的函式回傳的型別(例如 dict)與你宣告的(例如 Pydantic 模型)不同。
+
+在這些情況下,你可以使用「路徑操作裝飾器」參數 `response_model`,而不是函式的回傳型別。
+
+你可以在任何「路徑操作」上使用 `response_model` 參數:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* 等等。
+
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
+
+/// note | 注意
+
+注意 `response_model` 是「裝飾器」方法(`get`、`post` 等)的參數。不是你的「路徑操作函式」的參數(像其他參數與請求主體那樣)。
+
+///
+
+`response_model` 接受的型別與你在 Pydantic 模型欄位中宣告的相同,所以它可以是一個 Pydantic 模型,也可以是例如由 Pydantic 模型組成的 `list`,像是 `List[Item]`。
+
+FastAPI 會使用這個 `response_model` 來做所有的資料文件、驗證等,並且也會將輸出資料轉換與過濾為其型別宣告。
+
+/// tip | 提示
+
+如果你在編輯器、mypy 等中有嚴格型別檢查,你可以把函式回傳型別宣告為 `Any`。
+
+這樣你是在告訴編輯器你是刻意回傳任意型別。但 FastAPI 仍會用 `response_model` 做資料文件、驗證、過濾等。
+
+///
+
+### `response_model` 優先權 { #response-model-priority }
+
+如果同時宣告了回傳型別與 `response_model`,`response_model` 會有優先權並由 FastAPI 使用。
+
+如此一來,即便你回傳的實際型別與回應模型不同,你仍可在函式上加上正確的型別註解,供編輯器與如 mypy 的工具使用。同時仍由 FastAPI 使用 `response_model` 做資料驗證、文件化等。
+
+你也可以使用 `response_model=None` 來停用該「路徑操作」的回應模型產生;當你為不是有效 Pydantic 欄位的東西加上型別註解時,可能需要這麼做,你會在下方某節看到範例。
+
+## 回傳與輸入相同的資料 { #return-the-same-input-data }
+
+這裡我們宣告一個 `UserIn` 模型,其中會包含明文密碼:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
+
+/// info | 說明
+
+要使用 `EmailStr`,請先安裝 `email-validator`。
+
+請先建立一個[虛擬環境](../virtual-environments.md){.internal-link target=_blank}、啟用它,然後安裝,例如:
+
+```console
+$ pip install email-validator
+```
+
+或:
+
+```console
+$ pip install "pydantic[email]"
+```
+
+///
+
+而我們使用這個模型同時宣告輸入與輸出:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
+
+現在,當瀏覽器建立一個帶有密碼的使用者時,API 會在回應中回傳相同的密碼。
+
+在這個例子中可能不是問題,因為是同一個使用者送出該密碼。
+
+但如果我們對其他「路徑操作」使用相同的模型,我們可能會把使用者密碼送給所有用戶端。
+
+/// danger | 警告
+
+除非你非常清楚所有影響並確定自己在做什麼,否則永遠不要儲存使用者的明文密碼,也不要像這樣在回應中傳送。
+
+///
+
+## 新增一個輸出模型 { #add-an-output-model }
+
+我們可以改為建立一個包含明文密碼的輸入模型,以及一個不含密碼的輸出模型:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
+
+在這裡,雖然「路徑操作函式」回傳的是同一個包含密碼的輸入使用者:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
+
+...我們把 `response_model` 宣告為不包含密碼的 `UserOut` 模型:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
+
+因此,FastAPI 會負責(透過 Pydantic)過濾掉輸出模型中未宣告的所有資料。
+
+### `response_model` 或回傳型別 { #response-model-or-return-type }
+
+在這種情況下,因為兩個模型不同,如果我們把函式回傳型別註解為 `UserOut`,編輯器和工具會抱怨我們回傳了無效的型別,因為它們是不同的類別。
+
+這就是為什麼在這個例子中我們必須在 `response_model` 參數中宣告它。
+
+...但繼續往下讀看看如何克服這個問題。
+
+## 回傳型別與資料過濾 { #return-type-and-data-filtering }
+
+讓我們延續前一個範例。我們想要用一種型別來註解函式,但實際上希望能夠從函式回傳包含更多資料的內容。
+
+我們希望 FastAPI 仍然用回應模型來過濾資料。這樣即使函式回傳更多資料,回應中也只會包含回應模型中宣告的欄位。
+
+在前一個例子中,因為類別不同,我們必須使用 `response_model` 參數。但這也代表我們失去了編輯器與工具對函式回傳型別的檢查支援。
+
+不過在大多數需要這樣做的情況下,我們只是想要像這個例子一樣,讓模型過濾/移除部分資料。
+
+在這些情況下,我們可以利用類別與繼承,搭配函式的型別註解,取得更好的編輯器與工具支援,同時仍能讓 FastAPI 做資料過濾。
+
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
+
+這樣我們能得到工具支援,對於編輯器與 mypy 來說,這段程式碼在型別上是正確的,同時我們也能得到 FastAPI 的資料過濾。
+
+這是怎麼運作的?來看一下。🤓
+
+### 型別註解與工具支援 { #type-annotations-and-tooling }
+
+先看看編輯器、mypy 與其他工具會怎麼看這件事。
+
+`BaseUser` 有基礎欄位。然後 `UserIn` 繼承自 `BaseUser` 並新增 `password` 欄位,因此它會包含兩個模型的所有欄位。
+
+我們把函式回傳型別註解為 `BaseUser`,但實際上回傳的是 `UserIn` 實例。
+
+編輯器、mypy 與其他工具不會抱怨,因為就型別學而言,`UserIn` 是 `BaseUser` 的子類別,這代表當預期任何 `BaseUser` 時,`UserIn` 是一個有效的型別。
+
+### FastAPI 的資料過濾 { #fastapi-data-filtering }
+
+對 FastAPI 而言,它會查看回傳型別,並確保你回傳的內容只包含該型別中宣告的欄位。
+
+FastAPI 在內部會搭配 Pydantic 做一些事情,來確保不會把類別繼承的那些規則直接用在回傳資料的過濾上,否則你可能會回傳比預期更多的資料。
+
+如此,你就能同時擁有兩種好處:具備工具支援的型別註解,以及資料過濾。
+
+## 在文件中查看 { #see-it-in-the-docs }
+
+在自動文件中,你可以看到輸入模型與輸出模型各自都有自己的 JSON Schema:
+
+
+
+而且兩個模型都會用在互動式 API 文件中:
+
+
+
+## 其他回傳型別註解 { #other-return-type-annotations }
+
+有時你回傳的東西不是有效的 Pydantic 欄位,你仍會在函式上加上註解,只為了獲得工具(編輯器、mypy 等)提供的支援。
+
+### 直接回傳 Response { #return-a-response-directly }
+
+最常見的情況是[直接回傳 Response(在進階文件中稍後會解釋)](../advanced/response-directly.md){.internal-link target=_blank}。
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+這個簡單情境會由 FastAPI 自動處理,因為回傳型別註解是 `Response` 類別(或其子類別)。
+
+而工具也會滿意,因為 `RedirectResponse` 與 `JSONResponse` 都是 `Response` 的子類別,所以型別註解是正確的。
+
+### 註解為某個 Response 的子類別 { #annotate-a-response-subclass }
+
+你也可以在型別註解中使用 `Response` 的子類別:
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+這同樣可行,因為 `RedirectResponse` 是 `Response` 的子類別,而 FastAPI 會自動處理這種簡單情況。
+
+### 無效的回傳型別註解 { #invalid-return-type-annotations }
+
+但當你回傳其他任意物件(例如資料庫物件),它不是有效的 Pydantic 型別,並且你在函式上也這樣註解時,FastAPI 會嘗試從該型別註解建立一個 Pydantic 回應模型,因而失敗。
+
+如果你有像是多種型別的聯集,其中一個或多個不是有效的 Pydantic 型別,也會發生相同的事情,例如這個就會失敗 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+...這會失敗,因為該型別註解不是 Pydantic 型別,且它也不只是一個單一的 `Response` 類別或其子類別,而是 `Response` 與 `dict` 的聯集(兩者任一)。
+
+### 停用回應模型 { #disable-response-model }
+
+延續上面的例子,你可能不想要 FastAPI 執行預設的資料驗證、文件化、過濾等動作。
+
+但你可能仍想在函式上保留回傳型別註解,以獲得編輯器與型別檢查工具(例如 mypy)的支援。
+
+這種情況下,你可以設定 `response_model=None` 來停用回應模型的產生:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+這會讓 FastAPI 略過回應模型的產生,如此你就能使用任何你需要的回傳型別註解,而不會影響你的 FastAPI 應用程式。🤓
+
+## 回應模型編碼參數 { #response-model-encoding-parameters }
+
+你的回應模型可能有預設值,例如:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None`(或在 Python 3.10 中的 `str | None = None`)預設為 `None`。
+* `tax: float = 10.5` 預設為 `10.5`。
+* `tags: List[str] = []` 預設為空的 list:`[]`。
+
+但如果這些值其實沒有被儲存,你可能想要在結果中省略它們。
+
+例如,如果你在 NoSQL 資料庫中有包含許多選擇性屬性的模型,但你不想傳送充滿預設值的冗長 JSON 回應。
+
+### 使用 `response_model_exclude_unset` 參數 { #use-the-response-model-exclude-unset-parameter }
+
+你可以在「路徑操作裝飾器」上設定 `response_model_exclude_unset=True`:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+如此這些預設值就不會被包含在回應中,只有實際被設定的值才會包含。
+
+因此,如果你對該「路徑操作」發送針對 ID 為 `foo` 的項目的請求,回應(不包含預設值)會是:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | 說明
+
+你也可以使用:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+如 Pydantic 文件中對 `exclude_defaults` 與 `exclude_none` 的說明。
+
+///
+
+#### 對於有預設值欄位也有實際值的資料 { #data-with-values-for-fields-with-defaults }
+
+但如果你的資料在模型中對於有預設值的欄位也有實際值,例如 ID 為 `bar` 的項目:
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+它們會被包含在回應中。
+
+#### 與預設值相同的資料 { #data-with-the-same-values-as-the-defaults }
+
+如果資料的值與預設值相同,例如 ID 為 `baz` 的項目:
+
+```Python hl_lines="3 5-6"
+{
+ "name": "Baz",
+ "description": None,
+ "price": 50.2,
+ "tax": 10.5,
+ "tags": []
+}
+```
+
+FastAPI 足夠聰明(其實是 Pydantic 足夠聰明)去判斷,儘管 `description`、`tax` 與 `tags` 的值與預設值相同,但它們是被明確設定的(而不是取自預設值)。
+
+因此,它們會被包含在 JSON 回應中。
+
+/// tip | 提示
+
+注意預設值可以是任何東西,不只有 `None`。
+
+它們可以是一個 list(`[]`)、一個 `float` 的 `10.5`,等等。
+
+///
+
+### `response_model_include` 與 `response_model_exclude` { #response-model-include-and-response-model-exclude }
+
+你也可以使用「路徑操作裝飾器」參數 `response_model_include` 與 `response_model_exclude`。
+
+它們接受一個由屬性名稱字串所組成的 `set`,分別用來包含(省略其他)或排除(包含其他)屬性。
+
+如果你只有一個 Pydantic 模型並且想從輸出移除部分資料,這可以作為一個快速捷徑。
+
+/// tip | 提示
+
+但仍建議使用上面提到的作法,使用多個類別,而不是這些參數。
+
+因為在你的應用程式 OpenAPI(與文件)中所產生的 JSON Schema 仍會是完整模型的,即便你使用 `response_model_include` 或 `response_model_exclude` 省略了一些屬性。
+
+`response_model_by_alias` 也有類似的情況。
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | 提示
+
+語法 `{"name", "description"}` 會建立一個包含這兩個值的 `set`。
+
+它等同於 `set(["name", "description"])`。
+
+///
+
+#### 使用 `list` 來代替 `set` { #using-lists-instead-of-sets }
+
+如果你忘了使用 `set` 而用了 `list` 或 `tuple`,FastAPI 仍會把它轉換成 `set`,並能正確運作:
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## 重點回顧 { #recap }
+
+使用「路徑操作裝飾器」的 `response_model` 參數來定義回應模型,特別是為了確保私有資料被過濾掉。
+
+使用 `response_model_exclude_unset` 僅回傳被明確設定的值。
diff --git a/docs/zh-hant/docs/tutorial/response-status-code.md b/docs/zh-hant/docs/tutorial/response-status-code.md
new file mode 100644
index 000000000..cbcc67ca5
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/response-status-code.md
@@ -0,0 +1,101 @@
+# 回應狀態碼 { #response-status-code }
+
+就像你可以指定回應模型一樣,你也可以在任一個「路徑操作(path operation)」的參數 `status_code` 中宣告回應所使用的 HTTP 狀態碼:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* 等等
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+/// note | 注意
+
+請注意,`status_code` 是「裝飾器(decorator)」方法(`get`、`post` 等等)的參數,而不是你的「路徑操作函式」的參數,就像所有的參數與 body 一樣。
+
+///
+
+參數 `status_code` 接受一個數字作為 HTTP 狀態碼。
+
+/// info | 資訊
+
+`status_code` 也可以接收一個 `IntEnum`,例如 Python 的 `http.HTTPStatus`。
+
+///
+
+它會:
+
+* 在回應中傳回該狀態碼。
+* 在 OpenAPI 結構中如此記錄(因此也會反映在使用者介面中):
+
+
+
+/// note | 注意
+
+有些回應碼(見下一節)表示回應不包含本文(body)。
+
+FastAPI 知道這點,並會產生聲明「無回應本文」的 OpenAPI 文件。
+
+///
+
+## 關於 HTTP 狀態碼 { #about-http-status-codes }
+
+/// note | 注意
+
+如果你已經知道什麼是 HTTP 狀態碼,可以直接跳到下一節。
+
+///
+
+在 HTTP 中,你會在回應的一部分傳回 3 位數的狀態碼。
+
+這些狀態碼有對應的名稱以便辨識,但重點是數字本身。
+
+簡而言之:
+
+* `100 - 199` 表示「資訊」。你很少會直接使用它們。這些狀態碼的回應不可包含本文。
+* **`200 - 299`** 表示「成功」。這是你最常使用的一組。
+ * `200` 是預設狀態碼,表示一切「OK」。
+ * 另一個例子是 `201`,代表「已建立」。常用於在資料庫中建立新紀錄之後。
+ * 一個特殊情況是 `204`,代表「無內容」。當沒有內容要回傳給用戶端時使用,因此回應不得有本文。
+* **`300 - 399`** 表示「重新導向」。這些狀態碼的回應可能有或沒有本文,唯獨 `304`(「未修改」)必須沒有本文。
+* **`400 - 499`** 表示「用戶端錯誤」。這大概是你第二常用的一組。
+ * 例如 `404`,代表「找不到」。
+ * 對於一般性的用戶端錯誤,你可以使用 `400`。
+* `500 - 599` 表示伺服器錯誤。你幾乎不會直接使用它們。當你的應用程式或伺服器某處出錯時,會自動回傳其中一個狀態碼。
+
+/// tip | 提示
+
+想深入瞭解各狀態碼與其用途,請參考 MDN 關於 HTTP 狀態碼的文件。
+
+///
+
+## 快速記住名稱 { #shortcut-to-remember-the-names }
+
+再看一次前面的範例:
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+`201` 是「已建立(Created)」的狀態碼。
+
+但你不需要背下每個代碼代表什麼。
+
+你可以使用 `fastapi.status` 提供的便利變數。
+
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
+
+它們只是方便用的常數,值與數字相同,但這樣你可以用編輯器的自動完成來找到它們:
+
+
+
+/// note | 技術細節
+
+你也可以使用 `from starlette import status`。
+
+**FastAPI** 將同一個 `starlette.status` 以 `fastapi.status` 形式提供,純粹是為了讓你(開發者)方便。但它直接來自 Starlette。
+
+///
+
+## 變更預設值 { #changing-the-default }
+
+稍後在 [進階使用者指南](../advanced/response-change-status-code.md){.internal-link target=_blank} 中,你會看到如何回傳一個不同於此處所宣告預設值的狀態碼。
diff --git a/docs/zh-hant/docs/tutorial/schema-extra-example.md b/docs/zh-hant/docs/tutorial/schema-extra-example.md
new file mode 100644
index 000000000..661938ac2
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# 宣告請求範例資料 { #declare-request-example-data }
+
+你可以宣告你的應用程式可接收資料的 examples。
+
+以下有數種方式可達成。
+
+## Pydantic 模型中的額外 JSON Schema 資料 { #extra-json-schema-data-in-pydantic-models }
+
+你可以為 Pydantic 模型宣告 `examples`,它們會加入到產生出的 JSON Schema 中。
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+這些額外資訊會原封不動加入該模型輸出的 JSON Schema,並且會用在 API 文件裡。
+
+你可以使用屬性 `model_config`(接收一個 `dict`),詳見 Pydantic 文件:Configuration。
+
+你可以將 `"json_schema_extra"` 設為一個 `dict`,其中包含你想在產生的 JSON Schema 中出現的任何額外資料,包括 `examples`。
+
+/// tip
+
+你可以用相同技巧擴充 JSON Schema,加入你自己的自訂額外資訊。
+
+例如,你可以用它為前端使用者介面新增中繼資料等。
+
+///
+
+/// info
+
+OpenAPI 3.1.0(自 FastAPI 0.99.0 起使用)新增了對 `examples` 的支援,這是 **JSON Schema** 標準的一部分。
+
+在那之前,只支援使用單一範例的關鍵字 `example`。OpenAPI 3.1.0 仍然支援 `example`,但它已被棄用,且不是 JSON Schema 標準的一部分。因此建議你將 `example` 遷移為 `examples`。🤓
+
+你可以在本頁結尾閱讀更多。
+
+///
+
+## `Field` 其他參數 { #field-additional-arguments }
+
+在 Pydantic 模型中使用 `Field()` 時,你也可以宣告額外的 `examples`:
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## JSON Schema 的 `examples` - OpenAPI { #examples-in-json-schema-openapi }
+
+當使用下列任一項:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+你也可以宣告一組 `examples`,包含會加入到 **OpenAPI** 中它們各自 **JSON Schemas** 的額外資訊。
+
+### `Body` 搭配 `examples` { #body-with-examples }
+
+這裡我們傳入 `examples`,其中包含 `Body()` 預期資料的一個範例:
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### 文件 UI 中的範例 { #example-in-the-docs-ui }
+
+使用以上任一方法,在 `/docs` 中看起來會像這樣:
+
+
+
+### `Body` 搭配多個 `examples` { #body-with-multiple-examples }
+
+當然,你也可以傳入多個 `examples`:
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+這麼做時,這些範例會成為該 body 資料內部 **JSON Schema** 的一部分。
+
+然而,撰寫本文時,負責呈現文件 UI 的工具 Swagger UI 並不支援在 **JSON Schema** 中顯示多個範例。不過請繼續往下閱讀以取得變通方式。
+
+### OpenAPI 特定的 `examples` { #openapi-specific-examples }
+
+在 **JSON Schema** 支援 `examples` 之前,OpenAPI 就已支援另一個同名的欄位 `examples`。
+
+這個「OpenAPI 特定」的 `examples` 位於 OpenAPI 規範的另一個區塊:在每個「路徑操作」的詳細資訊中,而不是在各個 JSON Schema 內。
+
+而 Swagger UI 早已支援這個欄位,因此你可以用它在文件 UI 中顯示不同的範例。
+
+這個 OpenAPI 特定欄位 `examples` 的結構是一個包含「多個範例」的 `dict`(而非 `list`),每個範例都可包含會一併加入到 **OpenAPI** 的額外資訊。
+
+它不會出現在 OpenAPI 所含的各個 JSON Schema 內,而是直接放在對應的「路徑操作」上。
+
+### 使用 `openapi_examples` 參數 { #using-the-openapi-examples-parameter }
+
+你可以在 FastAPI 中透過參數 `openapi_examples` 為下列項目宣告 OpenAPI 特定的 `examples`:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+該 `dict` 的鍵用來識別各個範例,而每個值則是另一個 `dict`。
+
+在 `examples` 中,每個範例的 `dict` 可以包含:
+
+* `summary`:範例的簡短描述。
+* `description`:較長的描述,可包含 Markdown 文字。
+* `value`:實際顯示的範例,例如一個 `dict`。
+* `externalValue`:`value` 的替代方案,為指向範例的 URL。儘管這可能不如 `value` 被工具廣泛支援。
+
+你可以這樣使用:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### 文件 UI 中的 OpenAPI 範例 { #openapi-examples-in-the-docs-ui }
+
+當在 `Body()` 加上 `openapi_examples`,`/docs` 會顯示為:
+
+
+
+## 技術細節 { #technical-details }
+
+/// tip
+
+如果你已經在使用 **FastAPI** **0.99.0 或以上**的版本,大概可以略過這些細節。
+
+這些內容比較與舊版(在 OpenAPI 3.1.0 可用之前)相關。
+
+你可以把這段當作一小堂 OpenAPI 與 JSON Schema 的歷史課。🤓
+
+///
+
+/// warning
+
+以下是關於 **JSON Schema** 與 **OpenAPI** 標準的技術細節。
+
+如果上面的做法對你已經足夠可用,就不需要這些細節,儘管直接跳過。
+
+///
+
+在 OpenAPI 3.1.0 之前,OpenAPI 使用的是較舊且經過修改的 **JSON Schema** 版本。
+
+當時 JSON Schema 沒有 `examples`,因此 OpenAPI 在它自訂修改的版本中新增了自己的 `example` 欄位。
+
+OpenAPI 也在規範的其他部分新增了 `example` 與 `examples` 欄位:
+
+* `Parameter Object`(規範),對應到 FastAPI 的:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* `Request Body Object` 中的 `content` 欄位裡的 `Media Type Object`(規範),對應到 FastAPI 的:
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info
+
+這個舊的、OpenAPI 特定的 `examples` 參數,從 FastAPI `0.103.0` 起改名為 `openapi_examples`。
+
+///
+
+### JSON Schema 的 `examples` 欄位 { #json-schemas-examples-field }
+
+後來 JSON Schema 在新版本規範中新增了 `examples` 欄位。
+
+接著新的 OpenAPI 3.1.0 以最新版本(JSON Schema 2020-12)為基礎,該版本就包含這個新的 `examples` 欄位。
+
+現在這個新的 `examples` 欄位優先於舊的單一(且客製)`example` 欄位,後者已被棄用。
+
+JSON Schema 中新的 `examples` 欄位「就是一個 `list`」的範例集合,而不是像 OpenAPI 其他地方(如上所述)那樣附帶額外中繼資料的 `dict`。
+
+/// info
+
+即使 OpenAPI 3.1.0 已發佈並與 JSON Schema 有更簡潔的整合,一段時間內提供自動文件的 Swagger UI 並不支援 OpenAPI 3.1.0(自 5.0.0 版起支援 🎉)。
+
+因此,FastAPI 0.99.0 之前的版本仍使用 3.1.0 以下的 OpenAPI 版本。
+
+///
+
+### Pydantic 與 FastAPI 的 `examples` { #pydantic-and-fastapi-examples }
+
+當你在 Pydantic 模型中加入 `examples`,不論是用 `schema_extra` 或 `Field(examples=["something"])`,該範例都會被加入該 Pydantic 模型的 **JSON Schema**。
+
+而該 Pydantic 模型的 **JSON Schema** 會被包含到你的 API 的 **OpenAPI** 中,接著用於文件 UI。
+
+在 FastAPI 0.99.0 之前的版本(0.99.0 起使用較新的 OpenAPI 3.1.0)中,當你對其他工具(`Query()`、`Body()` 等)使用 `example` 或 `examples` 時,這些範例不會被加入描述該資料的 JSON Schema(甚至不會加入到 OpenAPI 自己版本的 JSON Schema 中),而是直接加入到 OpenAPI 中的「路徑操作」宣告(在 OpenAPI 使用 JSON Schema 的那些部分之外)。
+
+但現在 FastAPI 0.99.0 以上使用的 OpenAPI 3.1.0 搭配 JSON Schema 2020-12,以及 Swagger UI 5.0.0 以上版本,整體更加一致,範例會包含在 JSON Schema 中。
+
+### Swagger UI 與 OpenAPI 特定的 `examples` { #swagger-ui-and-openapi-specific-examples }
+
+由於在(2023-08-26 時)Swagger UI 不支援多個 JSON Schema 範例,使用者無法在文件中顯示多個範例。
+
+為了解決此問題,FastAPI `0.103.0` 透過新參數 `openapi_examples` **新增支援** 宣告舊的「OpenAPI 特定」`examples` 欄位。🤓
+
+### 總結 { #summary }
+
+我以前常說我不太喜歡歷史……結果現在在這裡講「科技史」。😅
+
+簡而言之,**升級到 FastAPI 0.99.0 或以上**,事情會更**簡單、一致又直覺**,而且你不需要了解這些歷史細節。😎
diff --git a/docs/zh-hant/docs/tutorial/security/first-steps.md b/docs/zh-hant/docs/tutorial/security/first-steps.md
new file mode 100644
index 000000000..109f59a37
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/security/first-steps.md
@@ -0,0 +1,203 @@
+# 安全性 - 入門 { #security-first-steps }
+
+想像你有一個部署在某個網域的後端 API。
+
+還有一個前端在另一個網域,或同一網域的不同路徑(或是行動應用程式)。
+
+你希望前端能用使用者名稱與密碼向後端進行身分驗證。
+
+我們可以用 OAuth2 搭配 FastAPI 來實作。
+
+但不必通讀整份冗長規格只為了找出你需要的幾個重點。
+
+就用 FastAPI 提供的工具處理安全性。
+
+## 看起來如何 { #how-it-looks }
+
+先直接跑範例看效果,再回頭理解其原理。
+
+## 建立 `main.py` { #create-main-py }
+
+將範例複製到檔案 `main.py`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## 執行 { #run-it }
+
+/// info
+
+當你使用 `pip install "fastapi[standard]"` 指令安裝時,`python-multipart` 套件會隨 FastAPI 自動安裝。
+
+不過若只執行 `pip install fastapi`,預設不會包含 `python-multipart`。
+
+若要手動安裝,請先建立並啟用一個[虛擬環境](../../virtual-environments.md){.internal-link target=_blank},接著執行:
+
+```console
+$ pip install python-multipart
+```
+
+因為 OAuth2 會以「form data」傳送 `username` 與 `password`。
+
+///
+
+用以下指令執行範例:
+
+
+
+/// check | Authorize 按鈕!
+
+你會看到一個新的「Authorize」按鈕。
+
+而你的「路徑操作」右上角也會出現一個小鎖頭可以點擊。
+
+///
+
+點擊後會跳出一個小視窗,讓你輸入 `username` 與 `password`(以及其他可選欄位):
+
+
+
+/// note | 注意
+
+不管你在表單輸入什麼,現在都還不會成功;等等我們會把它完成。
+
+///
+
+這當然不是給最終使用者用的前端,但它是用來互動式文件化整個 API 的極佳自動化工具。
+
+前端團隊(也可能就是你)可以使用它。
+
+第三方應用或系統也能使用它。
+
+你也能用它來除錯、檢查與測試同一個應用。
+
+## `password` 流程 { #the-password-flow }
+
+現在回頭理解剛剛那些是什麼。
+
+在 OAuth2 中,`password` 是處理安全與身分驗證的其中一種「流程」(flow)。
+
+OAuth2 的設計讓後端或 API 可以獨立於執行使用者驗證的伺服器。
+
+但在這個例子中,同一個 FastAPI 應用會同時處理 API 與驗證。
+
+簡化來看流程如下:
+
+- 使用者在前端輸入 `username` 與 `password`,按下 `Enter`。
+- 前端(在使用者的瀏覽器中執行)把 `username` 與 `password` 傳到我們 API 的特定 URL(在程式中宣告為 `tokenUrl="token"`)。
+- API 檢查 `username` 與 `password`,並回傳一個「token(權杖)」(我們還沒實作這部分)。
+ - 「token(權杖)」就是一段字串,之後可用來識別並驗證此使用者。
+ - 通常 token 會設定一段時間後失效。
+ - 因此使用者之後需要重新登入。
+ - 若 token 被竊取,風險也較低;它不像永遠有效的萬用鑰匙(多數情況下)。
+- 前端會暫存這個 token。
+- 使用者在前端點擊前往其他頁面/區段。
+- 前端需要再向 API 取得資料。
+ - 但該端點需要驗證。
+ - 因此為了向 API 驗證,請求會帶上一個 `Authorization` 標頭,值為 `Bearer ` 加上 token。
+ - 例如 token 是 `foobar`,則 `Authorization` 標頭內容為:`Bearer foobar`。
+
+## FastAPI 的 `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }
+
+FastAPI 提供多層抽象的工具來實作這些安全機制。
+
+本例將使用 OAuth2 的 Password 流程,並以 Bearer token 進行驗證;我們會用 `OAuth2PasswordBearer` 類別來完成。
+
+/// info
+
+「Bearer」token 不是唯一選項。
+
+但對本例最合適。
+
+通常對多數情境也足夠,除非你是 OAuth2 專家並確信有更適合你的選項。
+
+在那種情況下,FastAPI 也提供相應工具讓你自行組合。
+
+///
+
+當我們建立 `OAuth2PasswordBearer` 類別的實例時,會傳入 `tokenUrl` 參數。這個參數包含了客戶端(在使用者瀏覽器中執行的前端)用來送出 `username` 與 `password` 以取得 token 的 URL。
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip
+
+這裡的 `tokenUrl="token"` 指的是尚未建立的相對 URL `token`。因為是相對 URL,所以等同於 `./token`。
+
+由於使用了相對 URL,若你的 API 位於 `https://example.com/`,那它會指向 `https://example.com/token`;但若你的 API 位於 `https://example.com/api/v1/`,那它會指向 `https://example.com/api/v1/token`。
+
+使用相對 URL 很重要,能確保你的應用在像是[在 Proxy 後方](../../advanced/behind-a-proxy.md){.internal-link target=_blank}這類進階情境中仍能正常運作。
+
+///
+
+這個參數不會建立該端點/「路徑操作」,而是宣告 `/token` 將是客戶端用來取得 token 的 URL。這些資訊會出現在 OpenAPI,並被互動式 API 文件系統使用。
+
+我們很快也會建立實際的路徑操作。
+
+/// info
+
+如果你是非常嚴格的「Pythonista」,可能不喜歡參數名稱用 `tokenUrl` 而不是 `token_url`。
+
+那是因為它沿用了 OpenAPI 規格中的名稱。如此一來,若你要深入查閱這些安全方案,便能直接複製貼上去搜尋更多資訊。
+
+///
+
+變數 `oauth2_scheme` 是 `OAuth2PasswordBearer` 的實例,但同時它也是「可呼叫的」(callable)。
+
+它可以這樣被呼叫:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+因此它可以配合 `Depends` 使用。
+
+### 如何使用 { #use-it }
+
+現在你可以在相依性中傳入 `oauth2_scheme` 與 `Depends` 搭配。
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+此相依性會提供一個 `str`,指派給「路徑操作函式」的參數 `token`。
+
+FastAPI 會知道可以使用這個相依性,在 OpenAPI(以及自動產生的 API 文件)中定義一個「安全性方案」。
+
+/// info | 技術細節
+
+FastAPI 之所以知道可以用(相依性中宣告的)`OAuth2PasswordBearer` 類別,在 OpenAPI 中定義安全性方案,是因為它繼承自 `fastapi.security.oauth2.OAuth2`,而後者又繼承自 `fastapi.security.base.SecurityBase`。
+
+所有能與 OpenAPI(以及自動 API 文件)整合的安全工具都繼承自 `SecurityBase`,FastAPI 才能知道如何把它們整合進 OpenAPI。
+
+///
+
+## 它做了什麼 { #what-it-does }
+
+它會從請求中尋找 `Authorization` 標頭,檢查其值是否為 `Bearer ` 加上一段 token,並將該 token 以 `str` 回傳。
+
+若未找到 `Authorization` 標頭,或其值不是 `Bearer ` token,則會直接回傳 401(`UNAUTHORIZED`)錯誤。
+
+你不必再自行檢查 token 是否存在;你可以確信只要你的函式被執行,該 token 參數就一定會是 `str`。
+
+你可以在互動式文件中試試看:
+
+
+
+我們還沒驗證 token 是否有效,但這已是個開始。
+
+## 小結 { #recap }
+
+只需多寫 3、4 行,就能有一個基本的安全機制。
diff --git a/docs/zh-hant/docs/tutorial/security/get-current-user.md b/docs/zh-hant/docs/tutorial/security/get-current-user.md
new file mode 100644
index 000000000..b223d4823
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# 取得目前使用者 { #get-current-user }
+
+在前一章,基於依賴注入系統的安全機制會把一個 `token`(作為 `str`)提供給*路徑操作函式*:
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+但這還不太有用。
+
+讓它改為回傳目前使用者吧。
+
+## 建立使用者模型 { #create-a-user-model }
+
+先建立一個 Pydantic 的使用者模型。
+
+就像用 Pydantic 宣告請求體一樣,我們也可以在其他地方使用它:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## 建立 `get_current_user` 依賴 { #create-a-get-current-user-dependency }
+
+讓我們建立一個依賴 `get_current_user`。
+
+記得依賴可以有子依賴嗎?
+
+`get_current_user` 會依賴我們先前建立的相同 `oauth2_scheme`。
+
+如同先前在*路徑操作*中直接做的一樣,新的依賴 `get_current_user` 會從子依賴 `oauth2_scheme` 接收一個作為 `str` 的 `token`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## 取得使用者 { #get-the-user }
+
+`get_current_user` 會使用我們建立的(假的)工具函式,它接收一個作為 `str` 的 token,並回傳我們的 Pydantic `User` 模型:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## 注入目前使用者 { #inject-the-current-user }
+
+現在我們可以在*路徑操作*中用相同的 `Depends` 來使用 `get_current_user`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+注意我們把 `current_user` 的型別宣告為 Pydantic 的 `User` 模型。
+
+這能在函式內提供自動補全與型別檢查的協助。
+
+/// tip | 提示
+
+你可能記得,請求體也會用 Pydantic 模型宣告。
+
+這裡因為你使用了 `Depends`,**FastAPI** 不會混淆。
+
+///
+
+/// check | 檢查
+
+這個依賴系統的設計讓我們可以有不同的依賴(不同的 "dependables"),都回傳 `User` 模型。
+
+我們不受限於只能有一個能回傳該類型資料的依賴。
+
+///
+
+## 其他模型 { #other-models }
+
+現在你可以在*路徑操作函式*中直接取得目前使用者,並在**依賴注入**層處理安全機制,使用 `Depends`。
+
+而且你可以為安全需求使用任意模型或資料(本例中是 Pydantic 模型 `User`)。
+
+但你不受限於某個特定的資料模型、類別或型別。
+
+想在模型中只有 `id` 與 `email` 而沒有任何 `username`?當然可以。你可以用同樣的工具達成。
+
+想只用一個 `str`?或只用一個 `dict`?或直接使用資料庫類別的模型實例?都可以,一樣運作。
+
+你的應用其實沒有真人使用者登入,而是機器人、bot,或其他系統,只持有 access token?同樣沒有問題。
+
+只要用任何你的應用需要的模型、類別或資料庫即可。**FastAPI** 的依賴注入系統都支援。
+
+## 程式碼大小 { #code-size }
+
+這個範例看起來可能有點冗長。記住我們把安全、資料模型、工具函式與*路徑操作*混在同一個檔案中。
+
+但重點在這裡。
+
+安全與依賴注入相關的內容只需要寫一次。
+
+你可以把它設計得再複雜都沒問題,仍然只需在單一位置寫一次,依然具備完整的彈性。
+
+但你可以有成千上萬個端點(*路徑操作*)共用同一套安全系統。
+
+而且它們全部(或你想要的一部分)都可以重用這些依賴,或你建立的其他依賴。
+
+而所有這些上千個*路徑操作*都可以小到只要 3 行:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## 回顧 { #recap }
+
+現在你可以在*路徑操作函式*中直接取得目前使用者。
+
+我們已經完成一半了。
+
+我們只需要再新增一個*路徑操作*,讓使用者/用戶端實際送出 `username` 與 `password`。
+
+下一步就會做。
diff --git a/docs/zh-hant/docs/tutorial/security/index.md b/docs/zh-hant/docs/tutorial/security/index.md
new file mode 100644
index 000000000..b5e3738bc
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/security/index.md
@@ -0,0 +1,101 @@
+# 安全性 { #security }
+
+有許多方式可以處理安全性、身分驗證與授權。
+
+而且這通常是一個複雜且「困難」的主題。
+
+在許多框架與系統中,光是處理安全性與身分驗證就要花費大量心力與程式碼(很多情況下可能佔了全部程式碼的 50% 以上)。
+
+**FastAPI** 提供多種工具,讓你能以標準方式輕鬆、快速地處理「安全性」,而不必先研究並學會所有安全性規範。
+
+但在此之前,先釐清幾個小概念。
+
+## 急著上手? { #in-a-hurry }
+
+如果你不在意這些術語,只需要立刻加入以使用者名稱與密碼為基礎的身分驗證與安全性,就直接跳到後續章節。
+
+## OAuth2 { #oauth2 }
+
+OAuth2 是一套規範,定義了多種處理身分驗證與授權的方法。
+
+它相當龐大,涵蓋許多複雜的使用情境。
+
+它也包含使用「第三方」進行身分驗證的方式。
+
+這正是各種「使用 Facebook、Google、X(Twitter)、GitHub 登入」系統在底層採用的機制。
+
+### OAuth 1 { #oauth-1 }
+
+過去有 OAuth 1,和 OAuth2 非常不同,也更複雜,因為它直接規範了如何加密通訊。
+
+它現在並不流行,也很少被使用。
+
+OAuth2 不規範通訊如何加密,而是假設你的應用會透過 HTTPS 提供服務。
+
+/// tip | 提示
+在部署相關章節中,你會看到如何使用 Traefik 與 Let's Encrypt 免費設定 HTTPS。
+///
+
+## OpenID Connect { #openid-connect }
+
+OpenID Connect 是基於 **OAuth2** 的另一套規範。
+
+它只是擴充了 OAuth2,釐清了 OAuth2 中相對模糊的部份,以提升互通性。
+
+例如,Google 登入使用的是 OpenID Connect(其底層使用 OAuth2)。
+
+但 Facebook 登入不支援 OpenID Connect,它有自己風格的 OAuth2。
+
+### OpenID(不是「OpenID Connect」) { #openid-not-openid-connect }
+
+過去也有一個「OpenID」規範。它試圖解決與 **OpenID Connect** 相同的問題,但不是建立在 OAuth2 之上。
+
+因此,它是一套完全額外、獨立的系統。
+
+它現在並不流行,也很少被使用。
+
+## OpenAPI { #openapi }
+
+OpenAPI(先前稱為 Swagger)是一套用於構建 API 的開放規範(現為 Linux 基金會的一部分)。
+
+**FastAPI** 建立在 **OpenAPI** 之上。
+
+這使得它能提供多種自動化的互動式文件介面、程式碼產生等功能。
+
+OpenAPI 提供定義多種安全性「方案」。
+
+透過使用它們,你可以善用這些基於標準的工具,包括這些互動式文件系統。
+
+OpenAPI 定義了下列安全性方案:
+
+* `apiKey`:應用程式特定的金鑰,來源可以是:
+ * 查詢參數。
+ * 標頭(header)。
+ * Cookie。
+* `http`:標準的 HTTP 驗證系統,包括:
+ * `bearer`:使用 `Authorization` 標頭,值為 `Bearer ` 加上一個 token。這是從 OAuth2 延伸而來。
+ * HTTP Basic 驗證。
+ * HTTP Digest 等。
+* `oauth2`:所有 OAuth2 的安全性處理方式(稱為「flows」)。
+ * 其中數個 flow 適合用來建立 OAuth 2.0 身分驗證提供者(如 Google、Facebook、X(Twitter)、GitHub 等):
+ * `implicit`
+ * `clientCredentials`
+ * `authorizationCode`
+ * 但有一個特定的 flow 可直接在同一個應用中處理身分驗證:
+ * `password`:後續幾個章節會示範這個。
+* `openIdConnect`:提供一種方式來定義如何自動發現 OAuth2 的身分驗證資訊。
+ * 這種自動探索機制即由 OpenID Connect 規範定義。
+
+/// tip | 提示
+整合像 Google、Facebook、X(Twitter)、GitHub 等其他身分驗證/授權提供者也是可行而且相對容易。
+
+最複雜的部分其實是打造一個類似那樣的身分驗證/授權提供者,但 **FastAPI** 提供了工具,能替你處理繁重工作,讓你更輕鬆完成。
+///
+
+## **FastAPI** 工具 { #fastapi-utilities }
+
+FastAPI 在 `fastapi.security` 模組中為上述各種安全性方案提供了多種工具,讓這些機制更容易使用。
+
+接下來的章節會示範如何使用這些 **FastAPI** 提供的工具,為你的 API 加入安全性。
+
+你也會看到它如何自動整合到互動式文件系統中。
diff --git a/docs/zh-hant/docs/tutorial/security/oauth2-jwt.md b/docs/zh-hant/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 000000000..d6761a005
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# 使用密碼(與雜湊)的 OAuth2、以 Bearer 搭配 JWT 權杖 { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+現在我們已經有完整的安全流程了,接下來用 JWT 權杖與安全的密碼雜湊,讓應用真正安全。
+
+這份程式碼可以直接用在你的應用中,把密碼雜湊存進資料庫等等。
+
+我們會從上一章的內容繼續往下擴充。
+
+## 關於 JWT { #about-jwt }
+
+JWT 的意思是「JSON Web Tokens」。
+
+它是一種把 JSON 物件編碼成一段長且緊密(沒有空白)的字串的標準。看起來像這樣:
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+它不是加密的,所以任何人都可以從內容還原出資訊。
+
+但它是簽名過的。因此當你收到一個你所簽發的權杖時,你可以驗證確實是你簽發的。
+
+如此一來,你可以建立一個(例如)有效期為 1 週的權杖。當使用者隔天帶著這個權杖回來時,你就知道該使用者仍然登入在你的系統中。
+
+一週後,權杖會過期,使用者就不再被授權,需要再次登入以取得新的權杖。而如果使用者(或第三方)試圖修改權杖來改變有效期,你也能發現,因為簽名不會相符。
+
+如果你想玩玩看 JWT 權杖並了解其運作,請參考 https://jwt.io。
+
+## 安裝 `PyJWT` { #install-pyjwt }
+
+我們需要安裝 `PyJWT` 才能在 Python 中產生與驗證 JWT 權杖。
+
+請先建立並啟用一個[虛擬環境](../../virtual-environments.md){.internal-link target=_blank},然後安裝 `pyjwt`:
+
+
+
+用和先前相同的方式授權應用。
+
+使用下列認證資訊:
+
+Username: `johndoe`
+Password: `secret`
+
+/// check | 檢查
+
+注意在程式碼中完全沒有明文密碼「`secret`」,我們只有雜湊後的版本。
+
+///
+
+
+
+呼叫端點 `/users/me/`,你會得到類似這樣的回應:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+如果你打開開發者工具,可以看到送出的資料只包含權杖;密碼只會在第一次請求(用來驗證使用者並取得 access token)時送出,之後就不會再送:
+
+
+
+/// note | 注意
+
+留意標頭 `Authorization`,其值是以 `Bearer ` 開頭。
+
+///
+
+## 進階用法:`scopes` { #advanced-usage-with-scopes }
+
+OAuth2 有「scopes」的概念。
+
+你可以用它們替 JWT 權杖加上一組特定的權限。
+
+接著你可以把這個權杖直接交給某個使用者或第三方,讓他們在一組受限條件下與你的 API 互動。
+
+你可以在之後的「進階使用者指南」學到如何使用它們,以及它們如何整合進 **FastAPI**。
+
+## 小結 { #recap }
+
+依照你目前學到的內容,你可以用 OAuth2 與 JWT 等標準,設定一個安全的 **FastAPI** 應用。
+
+在幾乎任何框架中,安全性處理都會很快變得相當複雜。
+
+許多能大幅簡化工作的套件,往往必須在資料模型、資料庫與可用功能上做出很多取捨。而有些過度簡化的套件底層其實存在安全弱點。
+
+---
+
+**FastAPI** 不會在任何資料庫、資料模型或工具上做妥協。
+
+它給你完全的彈性,讓你挑選最適合你專案的組合。
+
+而且你可以直接使用許多維護良好且被廣泛採用的套件,例如 `pwdlib` 與 `PyJWT`,因為 **FastAPI** 不需要任何複雜機制就能整合外部套件。
+
+同時它也提供工具來在不犧牲彈性、穩健或安全的前提下,盡可能地簡化流程。
+
+你可以用相對簡單的方式使用並實作像 OAuth2 這樣的安全標準協定。
+
+你可以在「進階使用者指南」進一步了解如何使用 OAuth2 的「scopes」,以實作更細緻的權限系統,並遵循相同的標準。帶有 scopes 的 OAuth2 是許多大型身份驗證供應商(如 Facebook、Google、GitHub、Microsoft、X(Twitter)等)用來授權第三方應用代表其使用者與其 API 互動的機制。
diff --git a/docs/zh-hant/docs/tutorial/security/simple-oauth2.md b/docs/zh-hant/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 000000000..3b9aae341
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# 簡易 OAuth2:Password 與 Bearer { #simple-oauth2-with-password-and-bearer }
+
+現在從上一章延伸,補上缺少的部分,完成整個安全流程。
+
+## 取得 `username` 與 `password` { #get-the-username-and-password }
+
+我們要使用 **FastAPI** 提供的安全性工具來取得 `username` 與 `password`。
+
+OAuth2 規範中,當使用「password flow」(我們現在使用的)時,用戶端/使用者必須以表單資料送出 `username` 與 `password` 欄位。
+
+而且規範要求欄位名稱必須就是這兩個,所以像是 `user-name` 或 `email` 都不行。
+
+但別擔心,你在前端要怎麼呈現給最終使用者都可以。
+
+而你的資料庫模型也可以使用任何你想要的欄位名稱。
+
+不過在登入的路徑操作(path operation)裡,我們需要使用這些名稱,才能符合規範(例如才能使用整合的 API 文件系統)。
+
+規範也說明 `username` 與 `password` 必須以表單資料傳送(也就是這裡不能用 JSON)。
+
+### `scope` { #scope }
+
+規範也說用戶端可以再送一個表單欄位「`scope`」。
+
+欄位名稱是單數的 `scope`,但實際上是由多個以空白分隔的「scopes」組成的一長串字串。
+
+每個「scope」就是一個(不含空白的)字串。
+
+它們通常用來宣告特定的權限,例如:
+
+- `users:read` 或 `users:write` 是常見的例子
+- `instagram_basic` 用在 Facebook / Instagram
+- `https://www.googleapis.com/auth/drive` 用在 Google
+
+/// info
+
+在 OAuth2 裡,「scope」只是用來宣告特定所需權限的一個字串。
+
+不論裡面是否包含像 `:` 之類的字元,或是否是一個 URL,都沒差。
+
+那些都是實作細節。
+
+對 OAuth2 而言,它們就是字串而已。
+
+///
+
+## 取得 `username` 與 `password` 的程式碼 { #code-to-get-the-username-and-password }
+
+現在用 **FastAPI** 提供的工具來處理。
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+先匯入 `OAuth2PasswordRequestForm`,並在 `/token` 的路徑操作中,搭配 `Depends` 當作依賴使用:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` 是一個類別型依賴,它宣告了一個表單本文,包含:
+
+- `username`
+- `password`
+- 可選的 `scope` 欄位,內容是一個由空白分隔的長字串
+- 可選的 `grant_type`
+
+/// tip
+
+依規範,實際上需要一個 `grant_type` 欄位且固定值為 `password`,但 `OAuth2PasswordRequestForm` 並不會強制檢查。
+
+如果你需要強制檢查,請改用 `OAuth2PasswordRequestFormStrict` 取代 `OAuth2PasswordRequestForm`。
+
+///
+
+- 可選的 `client_id`(本例不需要)
+- 可選的 `client_secret`(本例不需要)
+
+/// info
+
+`OAuth2PasswordRequestForm` 並不是像 `OAuth2PasswordBearer` 那樣對 **FastAPI** 來說的特殊類別。
+
+`OAuth2PasswordBearer` 會讓 **FastAPI** 知道它是一個 security scheme,因此會以那種方式加入 OpenAPI。
+
+但 `OAuth2PasswordRequestForm` 只是你也可以自己撰寫的一個類別型依賴,或是你也可以直接宣告 `Form` 參數。
+
+只是因為這是很常見的用例,所以 **FastAPI** 直接內建提供,讓事情更簡單。
+
+///
+
+### 使用表單資料 { #use-the-form-data }
+
+/// tip
+
+`OAuth2PasswordRequestForm` 這個依賴類別的實例不會有以空白分隔長字串的 `scope` 屬性,而是會有一個 `scopes` 屬性,裡面是各個 scope 的實際字串清單。
+
+本示例沒有使用 `scopes`,但如果你需要,功能已經在那裡了。
+
+///
+
+現在,從(假的)資料庫裡用表單欄位的 `username` 取得使用者資料。
+
+如果沒有該使用者,就回傳「Incorrect username or password」的錯誤。
+
+我們用 `HTTPException` 這個例外來回傳錯誤:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### 檢查密碼 { #check-the-password }
+
+這時我們已經有來自資料庫的使用者資料,但還沒檢查密碼。
+
+先把那些資料放進 Pydantic 的 `UserInDB` 模型。
+
+你絕對不要以純文字儲存密碼,所以我們會使用(假的)密碼雜湊系統。
+
+如果密碼不匹配,我們回傳同樣的錯誤。
+
+#### 密碼雜湊(hashing) { #password-hashing }
+
+「雜湊」的意思是:把一些內容(這裡是密碼)轉換成一串看起來像亂碼的位元組序列(就是字串)。
+
+只要你輸入完全相同的內容(完全相同的密碼),就會得到完全相同的亂碼。
+
+但你無法從這串亂碼還原回原本的密碼。
+
+##### 為何要做密碼雜湊 { #why-use-password-hashing }
+
+如果你的資料庫被竊取,攻擊者拿到的不是使用者的純文字密碼,而只是雜湊值。
+
+因此攻擊者無法嘗試把那些密碼用在其他系統上(因為很多使用者在各處都用同一組密碼,這會很危險)。
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### 關於 `**user_dict**` { #about-user-dict }
+
+`UserInDB(**user_dict)` 的意思是:
+
+把 `user_dict` 的鍵和值直接當作具名參數傳入,等同於:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info
+
+想更完整地了解 `**user_dict`,請回到[**額外模型** 的文件](../extra-models.md#about-user-in-dict){.internal-link target=_blank}。
+
+///
+
+## 回傳 token { #return-the-token }
+
+`token` 端點的回應必須是 JSON 物件。
+
+它應該有一個 `token_type`。在本例中,我們使用「Bearer」tokens,token 類型應該是「`bearer`」。
+
+而且它還應該有一個 `access_token`,其值為包含我們存取權杖的字串。
+
+在這個簡單示例中,我們會不安全地直接回傳相同的 `username` 當作 token。
+
+/// tip
+
+下一章你會看到真正安全的實作,包含密碼雜湊與 JWT tokens。
+
+但現在先把注意力放在我們需要的這些細節上。
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip
+
+依照規範,你應該回傳一個包含 `access_token` 與 `token_type` 的 JSON,就像這個範例。
+
+這部分需要你自己在程式中完成,並確保使用這些 JSON key。
+
+這幾乎是你為了符合規範而必須自行記得正確處理的唯一事情。
+
+其餘的 **FastAPI** 都會幫你處理。
+
+///
+
+## 更新依賴項 { #update-the-dependencies }
+
+接著我們要更新依賴項。
+
+我們只想在使用者為啟用狀態時取得 `current_user`。
+
+所以,我們新增一個依賴 `get_current_active_user`,而它本身又依賴 `get_current_user`。
+
+這兩個依賴會在使用者不存在或未啟用時回傳 HTTP 錯誤。
+
+因此,在端點中,只有在使用者存在、已正確驗證且為啟用狀態時,我們才會取得使用者:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info
+
+這裡我們一併回傳值為 `Bearer` 的額外標頭 `WWW-Authenticate`,這也是規範的一部分。
+
+任何 HTTP(錯誤)狀態碼 401「UNAUTHORIZED」都應該同時回傳 `WWW-Authenticate` 標頭。
+
+在 bearer tokens(我們的情況)下,該標頭的值應該是 `Bearer`。
+
+其實你可以省略這個額外標頭,功能仍會正常。
+
+但此處加上它是為了遵循規範。
+
+同時也可能有工具會期待並使用它(現在或未來),而這可能對你或你的使用者有幫助,現在或未來皆然。
+
+這就是標準的好處...
+
+///
+
+## 實際操作看看 { #see-it-in-action }
+
+開啟互動式文件:http://127.0.0.1:8000/docs。
+
+### 驗證身分 { #authenticate }
+
+點選「Authorize」按鈕。
+
+使用下列帳密:
+
+User: `johndoe`
+
+Password: `secret`
+
+
+
+在系統中完成驗證後,你會看到如下畫面:
+
+
+
+### 取得自己的使用者資料 { #get-your-own-user-data }
+
+現在使用 `GET` 方法呼叫路徑 `/users/me`。
+
+你會取得自己的使用者資料,如:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+如果你點擊鎖頭圖示登出,然後再次嘗試相同操作,你會得到 HTTP 401 錯誤:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### 未啟用的使用者 { #inactive-user }
+
+現在改用一個未啟用的使用者,使用以下帳密驗證:
+
+User: `alice`
+
+Password: `secret2`
+
+然後再呼叫 `GET` 方法的 `/users/me`。
+
+你會得到「Inactive user」的錯誤,例如:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## 小結 { #recap }
+
+你現在已經有足夠的工具,能為你的 API 以 `username` 與 `password` 實作一個完整的安全性系統。
+
+使用這些工具,你可以讓安全性系統相容於任何資料庫,以及任何使用者或資料模型。
+
+唯一尚未補上的細節是:它現在其實還不「安全」。
+
+在下一章,你會看到如何使用安全的密碼雜湊函式庫與 JWT tokens。
diff --git a/docs/zh-hant/docs/tutorial/sql-databases.md b/docs/zh-hant/docs/tutorial/sql-databases.md
new file mode 100644
index 000000000..930dc4e8a
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# SQL(關聯式)資料庫 { #sql-relational-databases }
+
+FastAPI 不強制你使用 SQL(關聯式)資料庫。你可以使用任何你想要的資料庫。
+
+這裡我們會用 SQLModel 作為範例。
+
+SQLModel 建立在 SQLAlchemy 與 Pydantic 之上。它由 FastAPI 的作者開發,非常適合需要使用 SQL 資料庫的 FastAPI 應用。
+
+/// tip | 提示
+
+你可以使用任何你想用的 SQL 或 NoSQL 資料庫函式庫(有時稱為 "ORMs"),FastAPI 不會強迫你使用特定工具。😎
+
+///
+
+因為 SQLModel 建立在 SQLAlchemy 之上,你可以輕鬆使用 SQLAlchemy 所支援的任何資料庫(因此 SQLModel 也支援),例如:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server,等等。
+
+在這個範例中,我們會使用 SQLite,因為它只用到單一檔案,而且 Python 內建支援。你可以直接複製這個範例並原樣執行。
+
+之後,在你的正式環境應用中,你可能會想使用像 PostgreSQL 這類的資料庫伺服器。
+
+/// tip | 提示
+
+有一個包含 FastAPI 與 PostgreSQL 的官方專案腳手架,還有前端與更多工具:https://github.com/fastapi/full-stack-fastapi-template
+
+///
+
+這是一份非常簡短的教學,如果你想更全面學習資料庫、SQL,或更進階的功能,請參考 SQLModel 文件。
+
+## 安裝 `SQLModel` { #install-sqlmodel }
+
+首先,請先建立你的[虛擬環境](../virtual-environments.md){.internal-link target=_blank}、啟用它,然後安裝 `sqlmodel`:
+
+
+
+lt
+* XWT
+* PSGI
+
+### Скорочення містить повну фразу та пояснення { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | Інформація
+
+Атрибути "title" елементів "abbr" перекладаються за певними інструкціями.
+
+Переклади можуть додавати власні елементи "abbr", які LLM не повинен прибирати. Наприклад, щоб пояснити англійські слова.
+
+Див. розділ `### HTML abbr elements` в загальній підсказці в `scripts/translate.py`.
+
+////
+
+## Елементи HTML «dfn» { #html-dfn-elements }
+
+* кластер
+* Глибоке навчання
+
+## Заголовки { #headings }
+
+//// tab | Тест
+
+### Розробка вебзастосунку - навчальний посібник { #develop-a-webapp-a-tutorial }
+
+Привіт.
+
+### Підказки типів та - анотації { #type-hints-and-annotations }
+
+Ще раз привіт.
+
+### Супер- та підкласи { #super-and-subclasses }
+
+Ще раз привіт.
+
+////
+
+//// tab | Інформація
+
+Єдине жорстке правило для заголовків - LLM має залишати хеш-частину в фігурних дужках незмінною, щоб посилання не ламалися.
+
+Див. розділ `### Headings` у загальній підсказці в `scripts/translate.py`.
+
+Для деяких мовно-специфічних інструкцій див., наприклад, розділ `### Headings` у `docs/de/llm-prompt.md`.
+
+////
+
+## Терміни, що використовуються в документації { #terms-used-in-the-docs }
+
+//// tab | Тест
+
+* ви
+* ваш
+
+* напр.
+* тощо
+
+* `foo` як `int`
+* `bar` як `str`
+* `baz` як `list`
+
+* навчальний посібник - Керівництво користувача
+* просунутий посібник користувача
+* документація SQLModel
+* документація API
+* автоматична документація
+
+* Наука про дані
+* глибоке навчання
+* машинне навчання
+* впровадження залежностей
+* HTTP базова автентифікація
+* HTTP дайджест
+* формат ISO
+* стандарт Схеми JSON
+* Схема JSON
+* визначення схеми
+* потік паролю
+* мобільний
+
+* застаріле
+* спроєктовано
+* недійсний
+* на льоту
+* стандарт
+* типове
+* чутливий до регістру
+* нечутливий до регістру
+
+* обслуговувати застосунок
+* обслуговувати сторінку
+
+* застосунок
+* застосунок
+
+* запит
+* відповідь
+* відповідь з помилкою
+
+* операція шляху
+* декоратор операції шляху
+* функція операції шляху
+
+* тіло
+* тіло запиту
+* тіло відповіді
+* тіло JSON
+* тіло форми
+* тіло функції
+
+* параметр
+* параметр тіла
+* параметр шляху
+* параметр запиту
+* параметр кукі
+* параметр заголовка
+* параметр форми
+* параметр функції
+
+* подія
+* подія запуску
+* запуск сервера
+* подія вимкнення
+* подія тривалості життя
+
+* обробник
+* обробник події
+* обробник винятків
+* обробляти
+
+* модель
+* модель Pydantic
+* модель даних
+* модель бази даних
+* модель форми
+* об'єкт моделі
+
+* клас
+* базовий клас
+* батьківський клас
+* підклас
+* дочірній клас
+* споріднений клас
+* метод класу
+
+* заголовок
+* заголовки
+* заголовок авторизації
+* заголовок `Authorization`
+* направлений заголовок
+
+* система впровадження залежностей
+* залежність
+* залежний
+* залежний
+
+* I/O-обмежений
+* CPU-обмежений
+* рівночасність
+* паралелізм
+* багатопроцесорність
+
+* змінна оточення
+* змінна оточення
+* `PATH`
+* змінна `PATH`
+
+* автентифікація
+* постачальник автентифікації
+* авторизація
+* форма авторизації
+* постачальник авторизації
+* користувач автентифікується
+* система автентифікує користувача
+
+* CLI
+* інтерфейс командного рядка
+
+* сервер
+* клієнт
+
+* хмарний постачальник
+* хмарний сервіс
+
+* розробка
+* етапи розробки
+
+* словник
+* словник
+* перелік
+* перелік
+* елемент переліку
+
+* кодувальник
+* декодувальник
+* кодувати
+* декодувати
+
+* виняток
+* породжувати
+
+* вираз
+* оператор
+
+* фронтенд
+* бекенд
+
+* обговорення GitHub
+* проблема GitHub
+
+* продуктивність
+* оптимізація продуктивності
+
+* тип, що повертається
+* повернене значення
+
+* безпека
+* схема безпеки
+
+* завдання
+* фонове завдання
+* функція завдання
+
+* шаблон
+* рушій шаблонів
+
+* анотація типу
+* підказка типу
+
+* серверний працівник
+* працівник Uvicorn
+* працівник Gunicorn
+* процес працівника
+* клас працівника
+* робоче навантаження
+
+* розгортання
+* розгортати
+
+* SDK
+* набір для розробки програмного забезпечення
+
+* `APIRouter`
+* `requirements.txt`
+* токен носія
+* несумісна зміна
+* помилка
+* кнопка
+* викликаємий
+* код
+* фіксація
+* менеджер контексту
+* співпрограма
+* сеанс бази даних
+* диск
+* домен
+* рушій
+* фальшивий X
+* метод HTTP GET
+* предмет
+* бібліотека
+* тривалість життя
+* блокування
+* проміжне програмне забезпечення
+* мобільний застосунок
+* модуль
+* монтування
+* мережа
+* джерело
+* переписування
+* корисне навантаження
+* процесор
+* властивість
+* представник
+* запит на витяг
+* запит
+* пам'ять з довільним доступом
+* віддалена машина
+* код статусу
+* строка
+* мітка
+* веб-фреймворк
+* дика карта
+* повертати
+* перевіряти
+
+////
+
+//// tab | Інформація
+
+Це неповний і не нормативний список (переважно) технічних термінів, що зустрічаються в документації. Він може бути корисним автору підсказки, щоб зрозуміти, для яких термінів LLM потрібна допомога. Наприклад, коли він постійно повертає хороший переклад до менш вдалого. Або коли йому складно відмінювати термін вашою мовою.
+
+Див., наприклад, розділ `### List of English terms and their preferred German translations` у `docs/de/llm-prompt.md`.
+
+////
diff --git a/docs/uk/docs/about/index.md b/docs/uk/docs/about/index.md
new file mode 100644
index 000000000..198fd828e
--- /dev/null
+++ b/docs/uk/docs/about/index.md
@@ -0,0 +1,3 @@
+# Про { #about }
+
+Про FastAPI, його проєктування, натхнення та інше. 🤓
diff --git a/docs/uk/docs/advanced/additional-responses.md b/docs/uk/docs/advanced/additional-responses.md
new file mode 100644
index 000000000..089967a51
--- /dev/null
+++ b/docs/uk/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# Додаткові відповіді в OpenAPI { #additional-responses-in-openapi }
+
+/// warning | Попередження
+
+Це доволі просунута тема.
+
+Якщо ви лише починаєте з **FastAPI**, ймовірно, вам це не потрібно.
+
+///
+
+Ви можете оголосити додаткові відповіді з додатковими кодами статусу, типами медіа, описами тощо.
+
+Ці додаткові відповіді буде включено до схеми OpenAPI, тож вони з'являться і в документації API.
+
+Але для таких додаткових відповідей потрібно повертати `Response` на кшталт `JSONResponse` безпосередньо, із потрібним кодом статусу та вмістом.
+
+## Додаткова відповідь з `model` { #additional-response-with-model }
+
+Ви можете передати вашим декораторам операцій шляху параметр `responses`.
+
+Він приймає `dict`: ключі - це коди статусу для кожної відповіді (наприклад, `200`), а значення - інші `dict` з інформацією для кожної з них.
+
+Кожен із цих словників відповіді може мати ключ `model`, що містить Pydantic-модель, подібно до `response_model`.
+
+**FastAPI** візьме цю модель, згенерує її Схему JSON і додасть у відповідне місце в OpenAPI.
+
+Наприклад, щоб оголосити іншу відповідь з кодом статусу `404` і Pydantic-моделлю `Message`, ви можете написати:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | Примітка
+
+Майте на увазі, що потрібно повертати `JSONResponse` безпосередньо.
+
+///
+
+/// info | Інформація
+
+Ключ `model` не є частиною OpenAPI.
+
+**FastAPI** візьме звідти Pydantic-модель, згенерує Схему JSON і помістить у відповідне місце.
+
+Відповідне місце це:
+
+- У ключі `content`, значенням якого є інший JSON-об'єкт (`dict`), що містить:
+ - Ключ із типом медіа, напр. `application/json`, значенням якого є інший JSON-об'єкт, що містить:
+ - Ключ `schema`, значенням якого є Схема JSON з моделі - ось це і є правильне місце.
+ - **FastAPI** додає тут посилання на глобальні Схеми JSON в іншому місці вашого OpenAPI замість прямого включення. Так інші застосунки та клієнти можуть напряму використовувати ці Схеми JSON, надавати кращі інструменти генерації коду тощо.
+
+///
+
+Згенеровані відповіді в OpenAPI для цієї операції шляху будуть такими:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+Схеми посилаються на інше місце всередині схеми OpenAPI:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## Додаткові типи медіа для основної відповіді { #additional-media-types-for-the-main-response }
+
+Можна використати цей самий параметр `responses`, щоб додати різні типи медіа для тієї ж основної відповіді.
+
+Наприклад, можна додати додатковий тип медіа `image/png`, оголосивши, що ваша операція шляху може повертати JSON-об'єкт (з типом медіа `application/json`) або PNG-зображення:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | Примітка
+
+Зверніть увагу, що потрібно повертати зображення безпосередньо за допомогою `FileResponse`.
+
+///
+
+/// info | Інформація
+
+Поки ви явно не вкажете інший тип медіа в параметрі `responses`, FastAPI вважатиме, що відповідь має той самий тип медіа, що й основний клас відповіді (типово `application/json`).
+
+Але якщо ви вказали власний клас відповіді з `None` як типом медіа, FastAPI використає `application/json` для будь-якої додаткової відповіді, що має пов'язану модель.
+
+///
+
+## Комбінування інформації { #combining-information }
+
+Ви також можете поєднувати інформацію про відповіді з кількох місць, зокрема з параметрів `response_model`, `status_code` і `responses`.
+
+Ви можете оголосити `response_model`, використовуючи типовий код статусу `200` (або власний за потреби), а потім оголосити додаткову інформацію для цієї ж відповіді в `responses`, безпосередньо в схемі OpenAPI.
+
+**FastAPI** збереже додаткову інформацію з `responses` і поєднає її зі Схемою JSON з вашої моделі.
+
+Наприклад, ви можете оголосити відповідь з кодом статусу `404`, яка використовує Pydantic-модель і має власний `description`.
+
+І відповідь з кодом статусу `200`, яка використовує ваш `response_model`, але містить власний `example`:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+Усе це буде поєднано та включено до вашого OpenAPI і показано в документації API:
+
+
+
+## Комбінуйте попередньо визначені та власні відповіді { #combine-predefined-responses-and-custom-ones }
+
+Можливо, ви захочете мати кілька попередньо визначених відповідей, що застосовуються до багатьох операцій шляху, але поєднувати їх із власними відповідями, потрібними для кожної операції шляху.
+
+Для таких випадків можна скористатися прийомом Python «розпакування» `dict` за допомогою `**dict_to_unpack`:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+Тут `new_dict` міститиме всі пари ключ-значення з `old_dict` плюс нову пару ключ-значення:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+Цей прийом можна використати, щоб перевикористовувати деякі попередньо визначені відповіді у ваших операціях шляху та поєднувати їх із додатковими власними.
+
+Наприклад:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## Докладніше про відповіді OpenAPI { #more-information-about-openapi-responses }
+
+Щоб побачити, що саме можна включати у відповіді, ознайомтеся з цими розділами специфікації OpenAPI:
+
+- Об'єкт відповідей OpenAPI, він включає `Response Object`.
+- Об'єкт відповіді OpenAPI, ви можете включити будь-що з цього безпосередньо в кожну відповідь у параметрі `responses`. Зокрема `description`, `headers`, `content` (усередині нього ви оголошуєте різні типи медіа та Схеми JSON) і `links`.
diff --git a/docs/uk/docs/advanced/additional-status-codes.md b/docs/uk/docs/advanced/additional-status-codes.md
new file mode 100644
index 000000000..afba933e2
--- /dev/null
+++ b/docs/uk/docs/advanced/additional-status-codes.md
@@ -0,0 +1,41 @@
+# Додаткові коди статусу { #additional-status-codes }
+
+За замовчуванням **FastAPI** повертатиме відповіді за допомогою `JSONResponse`, поміщаючи вміст, який ви повертаєте з вашої *операції шляху*, у цей `JSONResponse`.
+
+Він використовуватиме код статусу за замовчуванням або той, який ви встановите у своїй *операції шляху*.
+
+## Додаткові коди статусу { #additional-status-codes_1 }
+
+Якщо ви хочете повертати додаткові коди статусу, окрім основного, зробіть це, повертаючи `Response` безпосередньо, наприклад `JSONResponse`, і встановіть додатковий код статусу напряму.
+
+Наприклад, припустімо, ви хочете мати *операцію шляху*, яка дозволяє оновлювати предмети та повертає код статусу HTTP 200 «OK» у разі успіху.
+
+Але ви також хочете приймати нові предмети. І коли таких предметів раніше не існувало, операція створює їх і повертає код статусу HTTP 201 «Created».
+
+Щоб це реалізувати, імпортуйте `JSONResponse` і поверніть ваш вміст безпосередньо там, встановивши потрібний `status_code`:
+
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
+
+/// warning | Попередження
+
+Коли ви повертаєте `Response` безпосередньо, як у прикладі вище, він і буде повернений безпосередньо.
+
+Він не буде серіалізований за допомогою моделі тощо.
+
+Переконайтеся, що він містить саме ті дані, які вам потрібні, і що значення є коректним JSON (якщо ви використовуєте `JSONResponse`).
+
+///
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import JSONResponse`.
+
+**FastAPI** надає ті самі `starlette.responses` як `fastapi.responses` просто для вашої зручності як розробника. Але більшість доступних відповідей надходить безпосередньо зі Starlette. Те саме і зі `status`.
+
+///
+
+## OpenAPI і документація API { #openapi-and-api-docs }
+
+Якщо ви повертаєте додаткові коди статусу та відповіді безпосередньо, вони не будуть включені до схеми OpenAPI (документації API), адже FastAPI не має способу заздалегідь знати, що саме ви повернете.
+
+Але ви можете задокументувати це у своєму коді, використовуючи: [Додаткові відповіді](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/uk/docs/advanced/advanced-dependencies.md b/docs/uk/docs/advanced/advanced-dependencies.md
new file mode 100644
index 000000000..0c6f8cbb3
--- /dev/null
+++ b/docs/uk/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# Просунуті залежності { #advanced-dependencies }
+
+## Параметризовані залежності { #parameterized-dependencies }
+
+Усі залежності, які ми бачили, - це фіксована функція або клас.
+
+Але можуть бути випадки, коли ви хочете мати змогу задавати параметри залежності, не оголошуючи багато різних функцій або класів.
+
+Уявімо, що ми хочемо мати залежність, яка перевіряє, чи параметр запиту `q` містить певний фіксований вміст.
+
+Але ми хочемо мати змогу параметризувати цей фіксований вміст.
+
+## Екземпляр «callable» { #a-callable-instance }
+
+У Python є спосіб зробити екземпляр класу «callable».
+
+Не сам клас (який уже є «callable»), а екземпляр цього класу.
+
+Щоб це зробити, оголошуємо метод `__call__`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+У цьому випадку саме `__call__` **FastAPI** використає для перевірки додаткових параметрів і підзалежностей, і саме його буде викликано, щоб передати значення параметру у вашу *функцію операції шляху* пізніше.
+
+## Параметризувати екземпляр { #parameterize-the-instance }
+
+Тепер ми можемо використати `__init__`, щоб оголосити параметри екземпляра, які можна застосувати для «параметризації» залежності:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+У цьому випадку **FastAPI** ніколи не торкається `__init__` і не покладається на нього - ми використовуватимемо його безпосередньо у своєму коді.
+
+## Створити екземпляр { #create-an-instance }
+
+Ми можемо створити екземпляр цього класу так:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+Таким чином ми «параметризуємо» нашу залежність, яка тепер містить «bar» як атрибут `checker.fixed_content`.
+
+## Використовувати екземпляр як залежність { #use-the-instance-as-a-dependency }
+
+Далі ми можемо використати цей `checker` у `Depends(checker)` замість `Depends(FixedContentQueryChecker)`, адже залежністю є екземпляр `checker`, а не сам клас.
+
+Коли залежність розв'язується, **FastAPI** викличе цей `checker` так:
+
+```Python
+checker(q="somequery")
+```
+
+...і передасть усе, що він поверне, як значення залежності у нашій *функції операції шляху* як параметр `fixed_content_included`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | Порада
+
+Усе це може здаватися надуманим. І поки що може бути не дуже зрозуміло, навіщо це корисно.
+
+Ці приклади навмисно прості, але показують, як усе працює.
+
+У розділах про безпеку є утилітарні функції, реалізовані таким самим способом.
+
+Якщо ви все це зрозуміли, ви вже знаєте, як під капотом працюють ті утиліти для безпеки.
+
+///
+
+## Залежності з `yield`, `HTTPException`, `except` та фоновими задачами { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | Попередження
+
+Найімовірніше, вам не знадобляться ці технічні деталі.
+
+Вони корисні головно, якщо у вас був застосунок FastAPI старіший за 0.121.0 і ви стикаєтеся з проблемами залежностей із `yield`.
+
+///
+
+Залежності з `yield` еволюціонували з часом, щоб охопити різні сценарії використання та виправити деякі проблеми, ось підсумок змін.
+
+### Залежності з `yield` і `scope` { #dependencies-with-yield-and-scope }
+
+У версії 0.121.0 **FastAPI** додано підтримку `Depends(scope="function")` для залежностей з `yield`.
+
+З `Depends(scope="function")` завершальний код після `yield` виконується одразу після завершення *функції операції шляху*, до того як відповідь буде надіслана клієнту.
+
+А при використанні `Depends(scope="request")` (типове значення) завершальний код після `yield` виконується після відправлення відповіді.
+
+Докладніше читайте в документації: [Залежності з `yield` - Ранній вихід і `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope).
+
+### Залежності з `yield` і `StreamingResponse`, технічні деталі { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+До **FastAPI** 0.118.0, якщо ви використовували залежність із `yield`, завершальний код виконувався після повернення з *функції операції шляху*, але безпосередньо перед відправленням відповіді.
+
+Метою було уникнути утримання ресурсів довше, ніж потрібно, очікуючи, поки відповідь пройде мережею.
+
+Це також означало, що якщо ви повертали `StreamingResponse`, завершальний код залежності з `yield` уже було б виконано.
+
+Наприклад, якщо у залежності з `yield` була сесія бази даних, `StreamingResponse` не зміг би використовувати цю сесію під час потокової передачі даних, тому що сесію вже закрито в завершальному коді після `yield`.
+
+Цю поведінку змінено у 0.118.0: завершальний код після `yield` знову виконується після відправлення відповіді.
+
+/// info | Інформація
+
+Як побачите нижче, це дуже схоже на поведінку до версії 0.106.0, але з кількома покращеннями та виправленнями помилок у крайових випадках.
+
+///
+
+#### Випадки використання з раннім завершальним кодом { #use-cases-with-early-exit-code }
+
+Є кілька сценаріїв із певними умовами, які можуть виграти від старої поведінки - виконувати завершальний код залежностей з `yield` до надсилання відповіді.
+
+Наприклад, уявіть, що у вас є код, який використовує сесію бази даних у залежності з `yield` лише для перевірки користувача, але сесія більше не використовується у *функції операції шляху*, тільки в залежності, і відправлення відповіді триває довго - як у `StreamingResponse`, що повільно надсилає дані, але з якоїсь причини не використовує базу даних.
+
+У такому разі сесія БД утримувалася б до завершення відправлення відповіді, але якщо ви її не використовуєте, утримувати її немає потреби.
+
+Ось як це може виглядати:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+Завершальний код - автоматичне закриття `Session` у:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...виконається після того, як відповідь завершить надсилати повільні дані:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+Але оскільки `generate_stream()` не використовує сесію бази даних, немає реальної потреби тримати сесію відкритою під час надсилання відповіді.
+
+Якщо у вас саме такий випадок із SQLModel (або SQLAlchemy), ви можете явно закрити сесію, коли вона більше не потрібна:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+Так сесія звільнить з'єднання з базою даних, і його зможуть використовувати інші запити.
+
+Якщо у вас інший сценарій, де потрібно раннє завершення залежності з `yield`, створіть, будь ласка, питання в обговореннях GitHub із вашим конкретним випадком і поясненням, чому вам корисне раннє закриття для залежностей з `yield`.
+
+Якщо будуть переконливі приклади для раннього закриття в залежностях з `yield`, я розгляну додавання нового способу увімкнути раннє закриття.
+
+### Залежності з `yield` і `except`, технічні деталі { #dependencies-with-yield-and-except-technical-details }
+
+До **FastAPI** 0.110.0, якщо ви використовували залежність із `yield`, перехоплювали виняток через `except` у цій залежності і не піднімали його знову, виняток автоматично піднімався/пересилався до будь-яких обробників винятків або внутрішнього обробника помилок сервера.
+
+Це змінено у версії 0.110.0, щоб усунути неконтрольоване споживання пам'яті від пересланих винятків без обробника (внутрішні помилки сервера) та зробити поведінку узгодженою зі звичайним Python-кодом.
+
+### Фонові задачі та залежності з `yield`, технічні деталі { #background-tasks-and-dependencies-with-yield-technical-details }
+
+До **FastAPI** 0.106.0 піднімати винятки після `yield` було неможливо: завершальний код у залежностях з `yield` виконувався після надсилання відповіді, тож [обробники винятків](../tutorial/handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} уже відпрацювали б.
+
+Так було спроєктовано головно для того, щоб дозволити використовувати ті самі об'єкти, «віддані» залежностями через `yield`, усередині фонових задач, оскільки завершальний код виконувався після завершення фонових задач.
+
+У **FastAPI** 0.106.0 це змінено, щоб не утримувати ресурси під час очікування, поки відповідь піде мережею.
+
+/// tip | Порада
+
+Крім того, фонова задача зазвичай є незалежним набором логіки, який слід обробляти окремо, з власними ресурсами (наприклад, власним з'єднанням з базою даних).
+
+Тож так у вас, ймовірно, буде чистіший код.
+
+///
+
+Якщо ви раніше покладалися на цю поведінку, тепер слід створювати ресурси для фонових задач усередині самої фонової задачі та використовувати всередині лише дані, що не залежать від ресурсів залежностей із `yield`.
+
+Наприклад, замість використання тієї самої сесії бази даних ви створюватимете нову сесію в самій фоновій задачі та отримуватимете об'єкти з бази даних, використовуючи цю нову сесію. І далі, замість передавання об'єкта з бази даних як параметра у функцію фонової задачі, ви передасте ідентифікатор цього об'єкта, а потім отримаєте об'єкт знову всередині функції фонової задачі.
diff --git a/docs/uk/docs/advanced/advanced-python-types.md b/docs/uk/docs/advanced/advanced-python-types.md
new file mode 100644
index 000000000..9eedc4856
--- /dev/null
+++ b/docs/uk/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# Просунуті типи Python { #advanced-python-types }
+
+Ось кілька додаткових ідей, які можуть бути корисні під час роботи з типами в Python.
+
+## Використання `Union` або `Optional` { #using-union-or-optional }
+
+Якщо ваш код з якоїсь причини не може використовувати `|`, наприклад, якщо це не анотація типів, а щось на кшталт `response_model=`, замість вертикальної риски (`|`) ви можете використати `Union` з `typing`.
+
+Наприклад, ви можете оголосити, що щось може бути `str` або `None`:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+У `typing` також є скорочення, щоб оголосити, що щось може бути `None`, - `Optional`.
+
+Ось порада з моєї дуже «суб'єктивної» точки зору:
+
+- 🚨 Уникайте використання `Optional[SomeType]`
+- Натомість ✨ **використовуйте `Union[SomeType, None]`** ✨.
+
+Обидва варіанти еквівалентні і під капотом однакові, але я рекомендую `Union` замість `Optional`, тому що слово «**optional**» ніби натякає, що значення є необов'язковим, а насправді означає «може бути `None`», навіть якщо воно не є необов'язковим і все ще обов'язкове.
+
+Вважаю, `Union[SomeType, None]` більш явно це передає.
+
+Йдеться лише про слова та назви. Але ці слова можуть впливати на те, як ви та ваша команда думаєте про код.
+
+Як приклад, розгляньмо цю функцію:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+Параметр `name` визначено як `Optional[str]`, але він не є необов'язковим, ви не можете викликати функцію без цього параметра:
+
+```Python
+say_hi() # О ні, це викликає помилку! 😱
+```
+
+Параметр `name` все ще обов'язковий (не «необов'язковий»), тому що не має значення за замовчуванням. Водночас `name` приймає `None` як значення:
+
+```Python
+say_hi(name=None) # Це працює, None припустимий 🎉
+```
+
+Гарна новина: у більшості випадків ви зможете просто використовувати `|`, щоб визначати об'єднання типів:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+Тож зазвичай вам не доведеться перейматися такими назвами, як `Optional` і `Union`. 😎
diff --git a/docs/uk/docs/advanced/async-tests.md b/docs/uk/docs/advanced/async-tests.md
new file mode 100644
index 000000000..51d0d5761
--- /dev/null
+++ b/docs/uk/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# Асинхронні тести { #async-tests }
+
+Ви вже бачили, як тестувати ваші застосунки **FastAPI** за допомогою наданого `TestClient`. До цього часу ви бачили лише, як писати синхронні тести, без використання функцій `async`.
+
+Можливість використовувати асинхронні функції у тестах може бути корисною, наприклад, коли ви асинхронно звертаєтеся до бази даних. Уявіть, що ви хочете протестувати надсилання запитів до вашого застосунку FastAPI, а потім перевірити, що ваш бекенд успішно записав коректні дані в базу даних, використовуючи асинхронну бібліотеку для бази даних.
+
+Розгляньмо, як це реалізувати.
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+Якщо ми хочемо викликати асинхронні функції у тестах, самі тестові функції мають бути асинхронними. AnyIO надає зручний плагін, який дозволяє вказати, що деякі тестові функції слід виконувати асинхронно.
+
+## HTTPX { #httpx }
+
+Навіть якщо ваш застосунок **FastAPI** використовує звичайні функції `def` замість `async def`, під капотом це все одно `async`-застосунок.
+
+`TestClient` робить певну «магію» всередині, щоб викликати асинхронний застосунок FastAPI у ваших звичайних тестових функціях `def`, використовуючи стандартний pytest. Але ця «магія» більше не працює, коли ми використовуємо його всередині асинхронних функцій. Запускаючи тести асинхронно, ми більше не можемо використовувати `TestClient` у наших тестових функціях.
+
+`TestClient` побудований на основі HTTPX, і на щастя, ми можемо використовувати його безпосередньо для тестування API.
+
+## Приклад { #example }
+
+Для простого прикладу розгляньмо структуру файлів, подібну до описаної в [Більші застосунки](../tutorial/bigger-applications.md){.internal-link target=_blank} та [Тестування](../tutorial/testing.md){.internal-link target=_blank}:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+Файл `main.py` міститиме:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+Файл `test_main.py` міститиме тести для `main.py`, тепер це може виглядати так:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## Запуск { #run-it }
+
+Ви можете запустити тести як зазвичай:
+
+
Host: mysuperapp.com
Path: /items
+
+ Note over Proxy: Proxy adds forwarded headers
+
+ Proxy->>Server: HTTP Request
X-Forwarded-For: [client IP]
X-Forwarded-Proto: https
X-Forwarded-Host: mysuperapp.com
Path: /items
+
+ Note over Server: Server interprets headers
(if --forwarded-allow-ips is set)
+
+ Server->>Proxy: HTTP Response
with correct HTTPS URLs
+
+ Proxy->>Client: HTTPS Response
+```
+
+**Представник** перехоплює початковий запит клієнта і додає спеціальні *направлені* заголовки (`X-Forwarded-*`) перед передачею запиту на **сервер застосунку**.
+
+Ці заголовки зберігають інформацію про оригінальний запит, яка інакше була б втрачена:
+
+- X-Forwarded-For: оригінальна IP-адреса клієнта
+- X-Forwarded-Proto: оригінальний протокол (`https`)
+- X-Forwarded-Host: оригінальний хост (`mysuperapp.com`)
+
+Коли **FastAPI CLI** налаштовано з `--forwarded-allow-ips`, він довіряє цим заголовкам і використовує їх, наприклад, для побудови коректних URL-адрес у перенаправленнях.
+
+## Представник із вилученим префіксом шляху { #proxy-with-a-stripped-path-prefix }
+
+У вас може бути представник, що додає префікс шляху до вашого застосунку.
+
+У таких випадках ви можете використати `root_path` для конфігурації застосунку.
+
+`root_path` - це механізм, наданий специфікацією ASGI (на якій побудовано FastAPI через Starlette).
+
+`root_path` використовується для обробки саме таких випадків.
+
+Його також використано внутрішньо під час монтування підзастосунків.
+
+Наявність представника з вилученим префіксом шляху означає, що ви могли б оголосити шлях `/app` у вашому коді, але потім додати шар зверху (представника), який розмістить ваш застосунок **FastAPI** під шляхом на кшталт `/api/v1`.
+
+У такому разі початковий шлях `/app` фактично буде доступний за `/api/v1/app`.
+
+Хоча весь ваш код написано з припущенням, що є лише `/app`.
+
+{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[6] *}
+
+І представник буде **«зрізати»** **префікс шляху** на льоту перед передачею запиту серверу застосунку (ймовірно, Uvicorn через FastAPI CLI), зберігаючи переконання вашого застосунку, що його обслуговують за `/app`, тож вам не доведеться оновлювати весь код, щоб додати префікс `/api/v1`.
+
+Дотепер усе працювало б як зазвичай.
+
+Але коли ви відкриєте вбудований інтерфейс документації (фронтенд), він очікуватиме отримати схему OpenAPI за `/openapi.json`, замість `/api/v1/openapi.json`.
+
+Отже, фронтенд (що працює у браузері) спробує звернутися до `/openapi.json` і не зможе отримати схему OpenAPI.
+
+Оскільки у нас є представник з префіксом шляху `/api/v1` для нашого застосунку, фронтенду потрібно отримувати схему OpenAPI за `/api/v1/openapi.json`.
+
+```mermaid
+graph LR
+
+browser("Browser")
+proxy["Proxy on http://0.0.0.0:9999/api/v1/app"]
+server["Server on http://127.0.0.1:8000/app"]
+
+browser --> proxy
+proxy --> server
+```
+
+/// tip | Порада
+
+IP `0.0.0.0` зазвичай означає, що програма слухає на всіх IP-адресах, доступних на цій машині/сервері.
+
+///
+
+Інтерфейсу документації також потрібно, щоб схема OpenAPI оголошувала, що цей `server` API розташований за `/api/v1` (за представником). Наприклад:
+
+```JSON hl_lines="4-8"
+{
+ "openapi": "3.1.0",
+ // Ще дещо тут
+ "servers": [
+ {
+ "url": "/api/v1"
+ }
+ ],
+ "paths": {
+ // Ще дещо тут
+ }
+}
+```
+
+У цьому прикладі «Proxy» може бути чимось на кшталт **Traefik**. А сервером буде щось на кшталт FastAPI CLI з **Uvicorn**, який запускає ваш застосунок FastAPI.
+
+### Задання `root_path` { #providing-the-root-path }
+
+Щоб цього досягти, ви можете використати опцію командного рядка `--root-path`, наприклад:
+
+
+
+Але якщо ми звернемося до інтерфейсу документації за «офіційним» URL, використовуючи представника з портом `9999`, за адресою `/api/v1/docs`, усе працює коректно! 🎉
+
+Ви можете перевірити це на http://127.0.0.1:9999/api/v1/docs:
+
+
+
+Саме так, як ми хотіли. ✔️
+
+Це тому, що FastAPI використовує `root_path`, щоб створити типовий `server` в OpenAPI з URL, наданою `root_path`.
+
+## Додаткові сервери { #additional-servers }
+
+/// warning | Попередження
+
+Це більш просунутий випадок використання. Можете пропустити його.
+
+///
+
+За замовчуванням **FastAPI** створить `server` у схемі OpenAPI з URL для `root_path`.
+
+Але ви також можете надати інші альтернативні `servers`, наприклад, якщо хочете, щоб той самий інтерфейс документації взаємодіяв і зі стейджингом, і з продакшном.
+
+Якщо ви передасте власний список `servers`, і є `root_path` (тому що ваш API знаходиться за представником), **FastAPI** вставить «server» з цим `root_path` на початок списку.
+
+Наприклад:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+Буде згенерована схема OpenAPI на кшталт:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // Ще дещо тут
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // Ще дещо тут
+ }
+}
+```
+
+/// tip | Порада
+
+Зверніть увагу на автоматично згенерований сервер із значенням `url` `/api/v1`, взятим із `root_path`.
+
+///
+
+В інтерфейсі документації за адресою http://127.0.0.1:9999/api/v1/docs це виглядатиме так:
+
+
+
+/// tip | Порада
+
+Інтерфейс документації взаємодіятиме з сервером, який ви оберете.
+
+///
+
+/// note | Технічні деталі
+
+Властивість `servers` у специфікації OpenAPI є необовʼязковою.
+
+Якщо ви не вкажете параметр `servers`, і `root_path` дорівнює `/`, властивість `servers` у згенерованій схемі OpenAPI буде повністю пропущено за замовчуванням, що еквівалентно одному серверу зі значенням `url` рівним `/`.
+
+///
+
+### Вимкнути автоматичний сервер із `root_path` { #disable-automatic-server-from-root-path }
+
+Якщо ви не хочете, щоб **FastAPI** додавав автоматичний сервер, використовуючи `root_path`, скористайтеся параметром `root_path_in_servers=False`:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+і тоді він не буде включений у схему OpenAPI.
+
+## Монтування підзастосунку { #mounting-a-sub-application }
+
+Якщо вам потрібно змонтувати підзастосунок (як описано в [Підзастосунки - монтування](sub-applications.md){.internal-link target=_blank}), одночасно використовуючи представника з `root_path`, ви можете робити це звичайним чином, як і очікуєте.
+
+FastAPI внутрішньо розумно використовуватиме `root_path`, тож усе просто працюватиме. ✨
diff --git a/docs/uk/docs/advanced/custom-response.md b/docs/uk/docs/advanced/custom-response.md
new file mode 100644
index 000000000..ebd0ec24a
--- /dev/null
+++ b/docs/uk/docs/advanced/custom-response.md
@@ -0,0 +1,312 @@
+# Користувацька відповідь - HTML, стрім, файл, інше { #custom-response-html-stream-file-others }
+
+Типово **FastAPI** повертатиме відповіді, використовуючи `JSONResponse`.
+
+Ви можете переписати це, повернувши безпосередньо `Response`, як показано в [Повернути відповідь безпосередньо](response-directly.md){.internal-link target=_blank}.
+
+Але якщо ви повертаєте `Response` безпосередньо (або будь-який його підклас, як-от `JSONResponse`), дані не будуть автоматично конвертовані (навіть якщо ви оголосите `response_model`), і документація не буде автоматично згенерована (наприклад, із включенням конкретного «медіа-типу» в HTTP-заголовку `Content-Type` як частини згенерованого OpenAPI).
+
+Ви також можете оголосити `Response`, який слід використовувати (наприклад, будь-який підклас `Response`), у декораторі операції шляху через параметр `response_class`.
+
+Вміст, який ви повертаєте з вашої функції операції шляху, буде поміщений усередину цього `Response`.
+
+І якщо цей `Response` має JSON медіа-тип (`application/json`), як у випадку з `JSONResponse` та `UJSONResponse`, дані, що повертаються, будуть автоматично перетворені (і відфільтровані) з урахуванням будь-якого Pydantic `response_model`, який ви оголосили в декораторі операції шляху.
+
+/// note | Примітка
+
+Якщо ви використовуєте клас відповіді без медіа-типу, FastAPI очікуватиме, що у вашої відповіді не буде вмісту, тож формат відповіді не буде задокументовано в згенерованих OpenAPI-документах.
+
+///
+
+## Використовуйте `ORJSONResponse` { #use-orjsonresponse }
+
+Наприклад, якщо ви максимально оптимізуєте продуктивність, можете встановити та використовувати `orjson` і встановити відповідь як `ORJSONResponse`.
+
+Імпортуйте потрібний клас `Response` (підклас) і оголосіть його в декораторі операції шляху.
+
+Для великих відповідей повернення `Response` безпосередньо значно швидше, ніж повернення словника.
+
+Це тому, що за замовчуванням FastAPI перевірятиме кожен елемент усередині та переконуватиметься, що його можна серіалізувати як JSON, використовуючи той самий [Сумісний кодувальник JSON](../tutorial/encoder.md){.internal-link target=_blank}, описаний у навчальному посібнику. Саме це дозволяє повертати довільні об'єкти, наприклад моделі бази даних.
+
+Але якщо ви впевнені, що вміст, який повертається, серіалізується в JSON, ви можете передати його безпосередньо класу відповіді та уникнути додаткових витрат FastAPI на пропускання вашого вмісту через `jsonable_encoder` перед передаванням його класу відповіді.
+
+{* ../../docs_src/custom_response/tutorial001b_py310.py hl[2,7] *}
+
+/// info | Інформація
+
+Параметр `response_class` також визначатиме «медіа-тип» відповіді.
+
+У цьому випадку HTTP-заголовок `Content-Type` буде встановлено в `application/json`.
+
+І це буде задокументовано відповідно в OpenAPI.
+
+///
+
+/// tip | Порада
+
+`ORJSONResponse` доступний лише у FastAPI, не в Starlette.
+
+///
+
+## HTML-відповідь { #html-response }
+
+Щоб повернути відповідь із HTML безпосередньо з **FastAPI**, використовуйте `HTMLResponse`.
+
+- Імпортуйте `HTMLResponse`.
+- Передайте `HTMLResponse` як параметр `response_class` вашого декоратора операції шляху.
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info | Інформація
+
+Параметр `response_class` також визначатиме «медіа-тип» відповіді.
+
+У цьому випадку HTTP-заголовок `Content-Type` буде встановлено в `text/html`.
+
+І це буде задокументовано відповідно в OpenAPI.
+
+///
+
+### Повернути `Response` { #return-a-response }
+
+Як показано в [Повернути відповідь безпосередньо](response-directly.md){.internal-link target=_blank}, ви також можете переписати відповідь безпосередньо у вашій операції шляху, просто повернувши її.
+
+Той самий приклад вище, що повертає `HTMLResponse`, може виглядати так:
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning | Попередження
+
+`Response`, повернений безпосередньо вашою функцією операції шляху, не буде задокументовано в OpenAPI (наприклад, `Content-Type` не буде задокументовано) і не буде видно в автоматичній інтерактивній документації.
+
+///
+
+/// info | Інформація
+
+Звісно, фактичні заголовок `Content-Type`, код статусу тощо прийдуть з об'єкта `Response`, який ви повернули.
+
+///
+
+### Задокументуйте в OpenAPI і перепишіть `Response` { #document-in-openapi-and-override-response }
+
+Якщо ви хочете переписати відповідь усередині функції, але водночас задокументувати «медіа-тип» в OpenAPI, ви можете використати параметр `response_class` І повернути об'єкт `Response`.
+
+Тоді `response_class` буде використано лише для документування операції шляху в OpenAPI, а ваша `Response` буде використана як є.
+
+#### Повернути `HTMLResponse` безпосередньо { #return-an-htmlresponse-directly }
+
+Наприклад, це може бути щось на кшталт:
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+У цьому прикладі функція `generate_html_response()` уже генерує та повертає `Response` замість повернення HTML як `str`.
+
+Повертаючи результат виклику `generate_html_response()`, ви вже повертаєте `Response`, яка перепише типову поведінку **FastAPI**.
+
+Але оскільки ви також передали `HTMLResponse` у `response_class`, **FastAPI** знатиме, як задокументувати це в OpenAPI та інтерактивній документації як HTML з `text/html`:
+
+
+
+## Доступні відповіді { #available-responses }
+
+Ось деякі з доступних відповідей.
+
+Майте на увазі, що ви можете використовувати `Response`, щоб повертати що завгодно інше, або навіть створити власний підклас.
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import HTMLResponse`.
+
+**FastAPI** надає ті ж `starlette.responses` як `fastapi.responses` лише для вашої зручності як розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette.
+
+///
+
+### `Response` { #response }
+
+Головний клас `Response`, від якого успадковуються всі інші відповіді.
+
+Ви можете повертати його безпосередньо.
+
+Він приймає такі параметри:
+
+- `content` - `str` або `bytes`.
+- `status_code` - `int` - код статусу HTTP.
+- `headers` - `dict` строк.
+- `media_type` - `str`, що задає медіа-тип, напр. `"text/html"`.
+
+FastAPI (насправді Starlette) автоматично додасть заголовок Content-Length. Також буде додано заголовок Content-Type, на основі `media_type` з додаванням набору символів для текстових типів.
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+Приймає текст або байти та повертає HTML-відповідь, як описано вище.
+
+### `PlainTextResponse` { #plaintextresponse }
+
+Приймає текст або байти та повертає відповідь звичайним текстом.
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+Приймає дані та повертає відповідь, закодовану як `application/json`.
+
+Це типова відповідь, яку використовує **FastAPI**, як зазначено вище.
+
+### `ORJSONResponse` { #orjsonresponse }
+
+Швидка альтернативна JSON-відповідь з використанням `orjson`, як описано вище.
+
+/// info | Інформація
+
+Потрібно встановити `orjson`, наприклад `pip install orjson`.
+
+///
+
+### `UJSONResponse` { #ujsonresponse }
+
+Альтернативна JSON-відповідь з використанням `ujson`.
+
+/// info | Інформація
+
+Потрібно встановити `ujson`, наприклад `pip install ujson`.
+
+///
+
+/// warning | Попередження
+
+`ujson` менш обережний, ніж вбудована реалізація Python, у поводженні з деякими крайніми випадками.
+
+///
+
+{* ../../docs_src/custom_response/tutorial001_py310.py hl[2,7] *}
+
+/// tip | Порада
+
+Ймовірно, `ORJSONResponse` може бути швидшою альтернативою.
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+Повертає HTTP-перенаправлення. Типово використовує код статусу 307 (Temporary Redirect).
+
+Ви можете повернути `RedirectResponse` безпосередньо:
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+Або ви можете використати його в параметрі `response_class`:
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+У такому разі ви можете повертати URL безпосередньо з вашої функції операції шляху.
+
+У цьому випадку `status_code` буде типовим для `RedirectResponse`, тобто `307`.
+
+---
+
+Ви також можете використати параметр `status_code` разом із параметром `response_class`:
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+Приймає async-генератор або звичайний генератор/ітератор і транслює тіло відповіді потоково.
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[2,14] *}
+
+#### Використання `StreamingResponse` з об'єктами типу file-like { #using-streamingresponse-with-file-like-objects }
+
+Якщо у вас є file-like об'єкт (наприклад, об'єкт, що повертається `open()`), ви можете створити генераторну функцію для ітерації по цьому file-like об'єкту.
+
+Таким чином, вам не потрібно спочатку читати все в пам'ять, і ви можете передати цю генераторну функцію в `StreamingResponse` і повернути її.
+
+Сюди входить багато бібліотек для взаємодії з хмарними сховищами, обробки відео та інші.
+
+{* ../../docs_src/custom_response/tutorial008_py310.py hl[2,10:12,14] *}
+
+1. Це генераторна функція. Вона є «генераторною функцією», бо містить оператори `yield` усередині.
+2. Використовуючи блок `with`, ми гарантуємо, що file-like об'єкт буде закрито після завершення роботи генераторної функції. Тобто після того, як вона завершить надсилання відповіді.
+3. Цей `yield from` вказує функції ітеруватися по об'єкту з назвою `file_like`. А потім, для кожної ітерованої частини, повертати цю частину, ніби вона надходить з цієї генераторної функції (`iterfile`).
+
+ Тож це генераторна функція, яка всередині передає роботу «генерації» чомусь іншому.
+
+ Роблячи це таким чином, ми можемо помістити її в блок `with` і таким чином гарантувати, що file-like об'єкт буде закрито після завершення.
+
+/// tip | Порада
+
+Зверніть увагу, що тут ми використовуємо стандартний `open()`, який не підтримує `async` та `await`, тому ми оголошуємо операцію шляху звичайною `def`.
+
+///
+
+### `FileResponse` { #fileresponse }
+
+Асинхронно транслює файл як відповідь.
+
+Приймає інший набір аргументів для створення екземпляра, ніж інші типи відповідей:
+
+- `path` - шлях до файлу для трансляції.
+- `headers` - будь-які користувацькі заголовки як словник.
+- `media_type` - строка, що задає медіа-тип. Якщо не встановлено, медіа-тип буде виведено з імені файлу або шляху.
+- `filename` - якщо встановлено, буде включено до `Content-Disposition` відповіді.
+
+Відповіді з файлами включатимуть відповідні заголовки `Content-Length`, `Last-Modified` і `ETag`.
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+Ви також можете використати параметр `response_class`:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+У цьому випадку ви можете повертати шлях до файлу безпосередньо з вашої функції операції шляху.
+
+## Власний клас відповіді { #custom-response-class }
+
+Ви можете створити власний клас відповіді, успадкувавши його від `Response`, і використовувати його.
+
+Наприклад, скажімо, ви хочете використовувати `orjson`, але з деякими користувацькими налаштуваннями, які не використовуються у вбудованому класі `ORJSONResponse`.
+
+Припустімо, ви хочете, щоб повертався відформатований із відступами JSON, тож ви хочете використати опцію orjson `orjson.OPT_INDENT_2`.
+
+Ви можете створити `CustomORJSONResponse`. Головне, що потрібно зробити, це створити метод `Response.render(content)`, який повертає вміст як `bytes`:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+Тепер замість повернення:
+
+```json
+{"message": "Hello World"}
+```
+
+...ця відповідь повертатиме:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+Звісно, ви, ймовірно, знайдете значно кращі способи скористатися цим, ніж просто форматування JSON. 😉
+
+## Типова відповідь за замовчуванням { #default-response-class }
+
+Створюючи екземпляр класу **FastAPI** або `APIRouter`, ви можете вказати, який клас відповіді використовувати за замовчуванням.
+
+Параметр, що це визначає, - `default_response_class`.
+
+У прикладі нижче **FastAPI** використовуватиме `ORJSONResponse` за замовчуванням в усіх операціях шляху замість `JSONResponse`.
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | Порада
+
+Ви все одно можете переписати `response_class` в операціях шляху, як і раніше.
+
+///
+
+## Додаткова документація { #additional-documentation }
+
+Ви також можете оголосити медіа-тип і багато інших деталей в OpenAPI, використовуючи `responses`: [Додаткові відповіді в OpenAPI](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/uk/docs/advanced/dataclasses.md b/docs/uk/docs/advanced/dataclasses.md
new file mode 100644
index 000000000..a41e6e589
--- /dev/null
+++ b/docs/uk/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Використання dataclasses { #using-dataclasses }
+
+FastAPI побудовано поверх **Pydantic**, і я показував вам, як використовувати моделі Pydantic для оголошення запитів і відповідей.
+
+Але FastAPI також підтримує використання `dataclasses` таким самим чином:
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+Це підтримується завдяки **Pydantic**, адже він має внутрішню підтримку `dataclasses`.
+
+Тож навіть із наведеним вище кодом, який явно не використовує Pydantic, FastAPI використовує Pydantic, щоб перетворити стандартні dataclasses у власний варіант dataclasses Pydantic.
+
+І, звісно, підтримується те саме:
+
+* валідація даних
+* серіалізація даних
+* документація даних тощо
+
+Це працює так само, як із моделями Pydantic. Насправді під капотом це також досягається за допомогою Pydantic.
+
+/// info | Інформація
+
+Майте на увазі, що dataclasses не можуть робити все те, що можуть моделі Pydantic.
+
+Тож вам усе ще може знадобитися використовувати моделі Pydantic.
+
+Але якщо у вас вже є чимало dataclasses, це зручний трюк, щоб задіяти їх для веб-API на FastAPI. 🤓
+
+///
+
+## Dataclasses у `response_model` { #dataclasses-in-response-model }
+
+Ви також можете використовувати `dataclasses` у параметрі `response_model`:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+Dataclass буде автоматично перетворено на dataclass Pydantic.
+
+Таким чином його схема з'явиться в інтерфейсі користувача документації API:
+
+
+
+## Dataclasses у вкладених структурах даних { #dataclasses-in-nested-data-structures }
+
+Можна поєднувати `dataclasses` з іншими анотаціями типів, щоб створювати вкладені структури даних.
+
+У деяких випадках вам усе ж доведеться використовувати варіант `dataclasses` від Pydantic. Наприклад, якщо виникають помилки з автоматично згенерованою документацією API.
+
+У такому разі ви можете просто замінити стандартні `dataclasses` на `pydantic.dataclasses`, що є взаємозамінником:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. Ми все ще імпортуємо `field` зі стандартних `dataclasses`.
+
+2. `pydantic.dataclasses` - це взаємозамінник для `dataclasses`.
+
+3. Dataclass `Author` містить список dataclass `Item`.
+
+4. Dataclass `Author` використовується як параметр `response_model`.
+
+5. Ви можете використовувати інші стандартні анотації типів із dataclasses як тіло запиту.
+
+ У цьому випадку це список dataclass `Item`.
+
+6. Тут ми повертаємо словник, що містить `items`, який є списком dataclass.
+
+ FastAPI усе ще здатний серіалізувати дані до JSON.
+
+7. Тут у `response_model` використано анотацію типу список dataclass `Author`.
+
+ Знову ж, ви можете поєднувати `dataclasses` зі стандартними анотаціями типів.
+
+8. Зверніть увагу, що ця *функція операції шляху* використовує звичайний `def` замість `async def`.
+
+ Як завжди, у FastAPI ви можете поєднувати `def` і `async def` за потреби.
+
+ Якщо вам потрібне коротке нагадування, коли що використовувати, перегляньте розділ _«Поспішаєте?»_ у документації про [`async` та `await`](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+9. Ця *функція операції шляху* не повертає dataclasses (хоча могла б), а список словників із внутрішніми даними.
+
+ FastAPI використає параметр `response_model` (що включає dataclasses), щоб перетворити відповідь.
+
+Ви можете поєднувати `dataclasses` з іншими анотаціями типів у багатьох поєднаннях, щоб формувати складні структури даних.
+
+Перегляньте підказки щодо анотацій у коді вище, щоб побачити більше деталей.
+
+## Дізнатися більше { #learn-more }
+
+Можна поєднувати `dataclasses` з іншими моделями Pydantic, наслідувати їх, включати у власні моделі тощо.
+
+Щоб дізнатися більше, перегляньте документацію Pydantic про dataclasses.
+
+## Версія { #version }
+
+Доступно починаючи з версії FastAPI `0.67.0`. 🔖
diff --git a/docs/uk/docs/advanced/events.md b/docs/uk/docs/advanced/events.md
new file mode 100644
index 000000000..7c05ee4a4
--- /dev/null
+++ b/docs/uk/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# Події тривалості життя { #lifespan-events }
+
+Ви можете визначити логіку (код), яку слід виконати перед тим, як застосунок запуститься. Це означає, що цей код буде виконано один раз, перед тим як застосунок почне отримувати запити.
+
+Так само ви можете визначити логіку (код), яку слід виконати під час вимкнення застосунку. У цьому випадку код буде виконано один раз, після обробки можливо багатьох запитів.
+
+Оскільки цей код виконується перед тим, як застосунок почне приймати запити, і одразу після того, як він завершить їх обробку, він охоплює всю тривалість життя застосунку (слово «lifespan» буде важливим за мить 😉).
+
+Це дуже корисно для налаштування ресурсів, які потрібні для всього застосунку, які спільні між запитами, та/або які потрібно потім прибрати. Наприклад, пул з’єднань з базою даних або завантаження спільної моделі машинного навчання.
+
+## Випадок використання { #use-case }
+
+Почнемо з прикладу випадку використання, а потім подивимось, як це вирішити.
+
+Уявімо, що у вас є моделі машинного навчання, якими ви хочете обробляти запити. 🤖
+
+Ті самі моделі спільні між запитами, тобто це не окрема модель на запит чи на користувача.
+
+Уявімо, що завантаження моделі може займати чимало часу, бо треба читати багато даних з диска. Тож ви не хочете робити це для кожного запиту.
+
+Ви могли б завантажити її на верхньому рівні модуля/файлу, але це означало б, що модель завантажиться навіть якщо ви просто запускаєте простий автоматизований тест - тоді тест буде повільним, бо йому доведеться чекати завантаження моделі перед виконанням незалежної частини коду.
+
+Ось це ми й вирішимо: завантажимо модель перед обробкою запитів, але лише безпосередньо перед тим, як застосунок почне отримувати запити, а не під час завантаження коду.
+
+## Тривалість життя { #lifespan }
+
+Ви можете визначити цю логіку запуску і вимкнення за допомогою параметра `lifespan` застосунку `FastAPI` та «менеджера контексту» (зараз покажу, що це).
+
+Почнемо з прикладу, а потім розберемо детально.
+
+Ми створюємо асинхронну функцію `lifespan()` з `yield` так:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+Тут ми імітуємо дорогу операцію запуску із завантаженням моделі, поміщаючи (фальшиву) функцію моделі у словник з моделями машинного навчання перед `yield`. Цей код буде виконано перед тим, як застосунок почне приймати запити, під час запуску.
+
+А одразу після `yield` ми розвантажуємо модель. Цей код буде виконано після того, як застосунок завершить обробку запитів, безпосередньо перед вимкненням. Це, наприклад, може звільнити ресурси на кшталт пам’яті або GPU.
+
+/// tip | Порада
+
+Подія `shutdown` відбувається, коли ви зупиняєте застосунок.
+
+Можливо, вам треба запустити нову версію, або ви просто втомилися її запускати. 🤷
+
+///
+
+### Функція тривалості життя { #lifespan-function }
+
+Перше, на що слід звернути увагу: ми визначаємо асинхронну функцію з `yield`. Це дуже схоже на залежності з `yield`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+Перша частина функції до `yield` буде виконана перед запуском застосунку.
+
+А частина після `yield` буде виконана після завершення роботи застосунку.
+
+### Асинхронний менеджер контексту { #async-context-manager }
+
+Якщо придивитися, функція задекорована за допомогою `@asynccontextmanager`.
+
+Це перетворює функцію на так званий «асинхронний менеджер контексту».
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Менеджер контексту в Python - це те, що можна використовувати в операторі `with`, наприклад, `open()` можна використовувати як менеджер контексту:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+У новіших версіях Python також є асинхронний менеджер контексту. Його використовують з `async with`:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+Коли ви створюєте менеджер контексту або асинхронний менеджер контексту, як вище, перед входом у блок `with` буде виконано код перед `yield`, а після виходу з блоку `with` буде виконано код після `yield`.
+
+У нашому прикладі коду вище ми не використовуємо його напряму, а передаємо його до FastAPI, щоб він його використав.
+
+Параметр `lifespan` застосунку `FastAPI` приймає асинхронний менеджер контексту, тож ми можемо передати йому наш новий асинхронний менеджер контексту `lifespan`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## Альтернативні події (застаріло) { #alternative-events-deprecated }
+
+/// warning | Попередження
+
+Рекомендований спосіб обробляти запуск і вимкнення - використовувати параметр `lifespan` застосунку `FastAPI`, як описано вище. Якщо ви надаєте параметр `lifespan`, обробники подій `startup` і `shutdown` більше не будуть викликані. Або все через `lifespan`, або все через події - не обидва одночасно.
+
+Можете, ймовірно, пропустити цю частину.
+
+///
+
+Є альтернативний спосіб визначити логіку, яку слід виконати під час запуску і під час вимкнення.
+
+Ви можете визначити обробники подій (функції), які потрібно виконати перед запуском застосунку або коли застосунок вимикається.
+
+Ці функції можна оголошувати як з `async def`, так і звичайним `def`.
+
+### Подія `startup` { #startup-event }
+
+Щоб додати функцію, яку слід виконати перед запуском застосунку, оголосіть її з подією `"startup"`:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+У цьому випадку функція-обробник події `startup` ініціалізує «базу даних» предметів (це лише `dict`) деякими значеннями.
+
+Ви можете додати більше ніж один обробник події.
+
+І ваш застосунок не почне приймати запити, доки всі обробники події `startup` не завершаться.
+
+### Подія `shutdown` { #shutdown-event }
+
+Щоб додати функцію, яку слід виконати, коли застосунок вимикається, оголосіть її з подією `"shutdown"`:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+Тут функція-обробник події `shutdown` запише текстовий рядок `"Application shutdown"` у файл `log.txt`.
+
+/// info | Інформація
+
+У функції `open()` параметр `mode="a"` означає «append», тож рядок буде додано після всього, що є у файлі, без перезапису попереднього вмісту.
+
+///
+
+/// tip | Порада
+
+Зауважте, що в цьому випадку ми використовуємо стандартну Python-функцію `open()`, яка працює з файлом.
+
+Тобто вона включає I/O (input/output), де потрібно «чекати», поки дані буде записано на диск.
+
+Але `open()` не використовує `async` і `await`.
+
+Тому ми оголошуємо функцію-обробник події зі стандартним `def`, а не `async def`.
+
+///
+
+### Разом `startup` і `shutdown` { #startup-and-shutdown-together }
+
+Велика ймовірність, що логіка для вашого запуску і вимкнення пов’язана: ви можете хотіти щось запустити, а потім завершити, отримати ресурс, а потім звільнити його тощо.
+
+Робити це в окремих функціях, які не діляться логікою чи змінними, складніше - доведеться зберігати значення у глобальних змінних або вдаватися до подібних трюків.
+
+Тому зараз рекомендується натомість використовувати `lifespan`, як пояснено вище.
+
+## Технічні деталі { #technical-details }
+
+Невелика технічна деталь для допитливих нердів. 🤓
+
+Під капотом, у технічній специфікації ASGI, це частина Протоколу тривалості життя, і там визначені події `startup` і `shutdown`.
+
+/// info | Інформація
+
+Ви можете прочитати більше про обробники `lifespan` у документації Starlette про Lifespan.
+
+Зокрема, як працювати зі станом тривалості життя, який можна використовувати в інших ділянках вашого коду.
+
+///
+
+## Підзастосунки { #sub-applications }
+
+🚨 Майте на увазі, що ці події тривалості життя (startup і shutdown) виконуються лише для головного застосунку, а не для [Підзастосунки - монтування](sub-applications.md){.internal-link target=_blank}.
diff --git a/docs/uk/docs/advanced/generate-clients.md b/docs/uk/docs/advanced/generate-clients.md
new file mode 100644
index 000000000..66e9193ac
--- /dev/null
+++ b/docs/uk/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# Генерація SDK { #generating-sdks }
+
+Оскільки **FastAPI** базується на специфікації **OpenAPI**, його API можна описати у стандартному форматі, який розуміють багато інструментів.
+
+Це спрощує створення актуальної **документації**, клієнтських бібліотек (**SDKs**) багатьма мовами, а також **тестування** чи **автоматизованих робочих процесів**, що залишаються синхронізованими з вашим кодом.
+
+У цьому посібнику ви дізнаєтеся, як згенерувати **TypeScript SDK** для вашого бекенда на FastAPI.
+
+## Генератори SDK з відкритим кодом { #open-source-sdk-generators }
+
+Універсальним варіантом є OpenAPI Generator, який підтримує **багато мов програмування** та може генерувати SDK з вашої специфікації OpenAPI.
+
+Для **клієнтів TypeScript** Hey API — спеціалізоване рішення, що надає оптимізований досвід для екосистеми TypeScript.
+
+Більше генераторів SDK ви можете знайти на OpenAPI.Tools.
+
+/// tip | Порада
+
+FastAPI автоматично генерує специфікації **OpenAPI 3.1**, тож будь-який інструмент, який ви використовуєте, має підтримувати цю версію.
+
+///
+
+## Генератори SDK від спонсорів FastAPI { #sdk-generators-from-fastapi-sponsors }
+
+У цьому розділі представлено рішення від компаній, що спонсорують FastAPI: вони мають **венчурну підтримку** та **корпоративну підтримку**. Ці продукти надають **додаткові можливості** та **інтеграції** поверх високоякісно згенерованих SDK.
+
+Завдяки ✨ [**спонсорству FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨ ці компанії допомагають підтримувати фреймворк та його **екосистему** здоровими та **сталими**.
+
+Їхня підтримка також демонструє сильну відданість **спільноті** FastAPI (вам), показуючи, що їм важливо не лише надавати **відмінний сервіс**, а й підтримувати **міцний і процвітаючий фреймворк**, FastAPI. 🙇
+
+Наприклад, ви можете спробувати:
+
+* Speakeasy
+* Stainless
+* liblab
+
+Деякі з цих рішень також можуть бути з відкритим кодом або мати безкоштовні тарифи, тож ви можете спробувати їх без фінансових зобов'язань. Інші комерційні генератори SDK також доступні й їх можна знайти онлайн. 🤓
+
+## Створити TypeScript SDK { #create-a-typescript-sdk }
+
+Почнімо з простого застосунку FastAPI:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+Зверніть увагу, що *операції шляху* визначають моделі, які вони використовують для корисного навантаження запиту та корисного навантаження відповіді, використовуючи моделі `Item` і `ResponseMessage`.
+
+### Документація API { #api-docs }
+
+Якщо ви перейдете до `/docs`, ви побачите **схеми** даних, які надсилаються в запитах і приймаються у відповідях:
+
+
+
+Ви бачите ці схеми, оскільки їх було оголошено як моделі в застосунку.
+
+Ця інформація доступна у **схемі OpenAPI** застосунку, а потім показується в документації API.
+
+Та сама інформація з моделей, яку включено до OpenAPI, може бути використана для **генерації клієнтського коду**.
+
+### Hey API { #hey-api }
+
+Коли у нас є застосунок FastAPI з моделями, ми можемо використати Hey API для генерації клієнта TypeScript. Найшвидший спосіб зробити це — через npx.
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+Це згенерує TypeScript SDK у `./src/client`.
+
+Ви можете дізнатися, як встановити `@hey-api/openapi-ts`, і почитати про згенерований результат на їхньому сайті.
+
+### Використання SDK { #using-the-sdk }
+
+Тепер ви можете імпортувати та використовувати клієнтський код. Це може виглядати так; зверніть увагу, що ви отримуєте «автодоповнення» для методів:
+
+
+
+Ви також отримаєте автодоповнення для корисного навантаження, яке надсилаєте:
+
+
+
+/// tip | Порада
+
+Зверніть увагу на автодоповнення для `name` і `price`, які були визначені в застосунку FastAPI, у моделі `Item`.
+
+///
+
+Ви бачитимете вбудовані помилки для даних, які надсилаєте:
+
+
+
+Об'єкт відповіді також матиме автодоповнення:
+
+
+
+## Застосунок FastAPI з мітками { #fastapi-app-with-tags }
+
+У багатьох випадках ваш застосунок FastAPI буде більшим, і ви, ймовірно, використовуватимете мітки, щоб розділяти різні групи *операцій шляху*.
+
+Наприклад, у вас може бути секція для **items** і окрема секція для **users**, і їх можна розділити мітками:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### Згенерувати TypeScript-клієнт із мітками { #generate-a-typescript-client-with-tags }
+
+Якщо ви згенеруєте клієнт для застосунку FastAPI, що використовує мітки, зазвичай клієнтський код також буде розділено за цими мітками.
+
+Таким чином, ви матимете правильно впорядковані та згруповані частини клієнтського коду:
+
+
+
+У цьому випадку у вас є:
+
+* `ItemsService`
+* `UsersService`
+
+### Назви методів клієнта { #client-method-names }
+
+Зараз згенеровані назви методів на кшталт `createItemItemsPost` виглядають не дуже охайно:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+...це тому, що генератор клієнта використовує внутрішній OpenAPI **operation ID** для кожної *операції шляху*.
+
+OpenAPI вимагає, щоб кожен operation ID був унікальним для всіх *операцій шляху*, тому FastAPI використовує **назву функції**, **шлях** і **HTTP-метод/операцію** для генерації цього operation ID, адже так воно може гарантувати унікальність operation ID.
+
+Але далі я покажу, як це покращити. 🤓
+
+## Користувацькі operation ID та кращі назви методів { #custom-operation-ids-and-better-method-names }
+
+Ви можете **змінити** спосіб **генерації** цих operation ID, щоб зробити їх простішими та мати **простіші назви методів** у клієнтах.
+
+У цьому випадку вам потрібно буде іншим способом гарантувати, що кожен operation ID є **унікальним**.
+
+Наприклад, ви можете переконатися, що кожна *операція шляху* має мітку, а потім генерувати operation ID на основі **мітки** та **назви** *операції шляху* (назви функції).
+
+### Користувацька функція генерування унікального ID { #custom-generate-unique-id-function }
+
+FastAPI використовує **унікальний ID** для кожної *операції шляху*, який застосовується для **operation ID**, а також для назв будь-яких потрібних користувацьких моделей для запитів чи відповідей.
+
+Ви можете налаштувати цю функцію. Вона приймає `APIRoute` і повертає строку.
+
+Наприклад, тут використовується перша мітка (у вас, ймовірно, буде лише одна мітка) і назва *операції шляху* (назва функції).
+
+Потім ви можете передати цю користувацьку функцію до **FastAPI** як параметр `generate_unique_id_function`:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### Згенерувати TypeScript-клієнт з користувацькими operation ID { #generate-a-typescript-client-with-custom-operation-ids }
+
+Тепер, якщо ви згенеруєте клієнт знову, ви побачите покращені назви методів:
+
+
+
+Як бачите, тепер у назвах методів є мітка, а потім назва функції; вони більше не містять інформації з URL-шляху та HTTP-операції.
+
+### Попередня обробка специфікації OpenAPI для генератора клієнта { #preprocess-the-openapi-specification-for-the-client-generator }
+
+У згенерованому коді все ще є певна **дубльована інформація**.
+
+Ми вже знаємо, що цей метод стосується **items**, адже це слово є в `ItemsService` (взято з мітки), але все ще маємо назву мітки як префікс у назві методу. 😕
+
+Ми, ймовірно, все одно захочемо зберегти це загалом для OpenAPI, адже так гарантується унікальність operation ID.
+
+Але для згенерованого клієнта ми можемо **змінити** operation ID в OpenAPI безпосередньо перед генерацією клієнтів, просто щоб зробити назви методів приємнішими та **чистішими**.
+
+Ми можемо завантажити JSON OpenAPI у файл `openapi.json`, а потім **прибрати цей префікс із міткою** за допомогою такого скрипту:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+Після цього operation ID буде перейменовано з чогось на кшталт `items-get_items` просто на `get_items`, тож генератор клієнта зможе створити простіші назви методів.
+
+### Згенерувати TypeScript-клієнт із попередньо обробленим OpenAPI { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Оскільки кінцевий результат тепер у файлі `openapi.json`, вам потрібно оновити шлях до вхідних даних:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+Після генерації нового клієнта ви отримаєте **чисті назви методів**, із усім **автодоповненням**, **вбудованими помилками** тощо:
+
+
+
+## Переваги { #benefits }
+
+Використовуючи автоматично згенеровані клієнти, ви отримаєте **автодоповнення** для:
+
+* Методів.
+* Корисного навантаження запиту в тілі, параметрах запиту тощо.
+* Корисного навантаження відповіді.
+
+Також ви матимете **вбудовані помилки** для всього.
+
+І щоразу, коли ви оновлюєте код бекенда та **перегенеровуєте** фронтенд, у ньому з'являтимуться нові *операції шляху* як методи, старі буде видалено, а будь-які інші зміни відобразяться у згенерованому коді. 🤓
+
+Це також означає, що якщо щось змінилося, це буде **відображено** в клієнтському коді автоматично. А якщо ви **зіберете** клієнт, буде повідомлено про помилку, якщо є будь-яка **невідповідність** у використаних даних.
+
+Таким чином, ви **виявлятимете багато помилок** дуже рано в циклі розробки, замість того, щоб чекати, поки помилки проявляться у ваших кінцевих користувачів у продакшені, і лише потім намагатися з'ясувати, у чому проблема. ✨
diff --git a/docs/uk/docs/advanced/index.md b/docs/uk/docs/advanced/index.md
new file mode 100644
index 000000000..1cffe0cec
--- /dev/null
+++ b/docs/uk/docs/advanced/index.md
@@ -0,0 +1,21 @@
+# Просунутий посібник користувача { #advanced-user-guide }
+
+## Додаткові можливості { #additional-features }
+
+Основний [Навчальний посібник - Посібник користувача](../tutorial/index.md){.internal-link target=_blank} має бути достатнім, щоб провести вас через усі основні можливості **FastAPI**.
+
+У наступних розділах ви побачите інші опції, конфігурації та додаткові можливості.
+
+/// tip | Порада
+
+Наступні розділи не обов'язково «просунуті».
+
+І можливо, що рішення для вашого випадку використання може бути в одному з них.
+
+///
+
+## Спершу прочитайте навчальний посібник { #read-the-tutorial-first }
+
+Ви все ще можете використовувати більшість можливостей **FastAPI**, маючи знання з основного [Навчального посібника - Посібника користувача](../tutorial/index.md){.internal-link target=_blank}.
+
+А в наступних розділах передбачається, що ви вже його прочитали і знайомі з основними ідеями.
diff --git a/docs/uk/docs/advanced/middleware.md b/docs/uk/docs/advanced/middleware.md
new file mode 100644
index 000000000..207ca96e0
--- /dev/null
+++ b/docs/uk/docs/advanced/middleware.md
@@ -0,0 +1,97 @@
+# Просунуте проміжне програмне забезпечення { #advanced-middleware }
+
+У головному навчальному посібнику ви читали, як додати [Користувацьке проміжне ПЗ](../tutorial/middleware.md){.internal-link target=_blank} до вашого застосунку.
+
+Також ви читали, як обробляти [CORS за допомогою `CORSMiddleware`](../tutorial/cors.md){.internal-link target=_blank}.
+
+У цьому розділі розглянемо, як використовувати інше проміжне ПЗ.
+
+## Додавання middleware ASGI { #adding-asgi-middlewares }
+
+Оскільки **FastAPI** базується на Starlette і реалізує специфікацію ASGI, ви можете використовувати будь-яке проміжне ПЗ ASGI.
+
+Middleware не обов'язково має бути створене саме для FastAPI або Starlette, головне - щоб воно відповідало специфікації ASGI.
+
+Загалом, middleware ASGI — це класи, які очікують отримати застосунок ASGI як перший аргумент.
+
+Тож у документації до сторонніх middleware ASGI вам, імовірно, порадять зробити приблизно так:
+
+```Python
+from unicorn import UnicornMiddleware
+
+app = SomeASGIApp()
+
+new_app = UnicornMiddleware(app, some_config="rainbow")
+```
+
+Але FastAPI (точніше Starlette) надає простіший спосіб, який гарантує, що внутрішнє middleware обробляє помилки сервера, а користувацькі обробники винятків працюють коректно.
+
+Для цього використовуйте `app.add_middleware()` (як у прикладі для CORS).
+
+```Python
+from fastapi import FastAPI
+from unicorn import UnicornMiddleware
+
+app = FastAPI()
+
+app.add_middleware(UnicornMiddleware, some_config="rainbow")
+```
+
+`app.add_middleware()` приймає клас middleware як перший аргумент і будь-які додаткові аргументи, що будуть передані цьому middleware.
+
+## Вбудоване middleware { #integrated-middlewares }
+
+**FastAPI** містить кілька middleware для поширених випадків використання, далі розглянемо, як їх використовувати.
+
+/// note | Технічні деталі
+
+У наступних прикладах ви також можете використовувати `from starlette.middleware.something import SomethingMiddleware`.
+
+**FastAPI** надає кілька middleware у `fastapi.middleware` виключно для зручності розробника. Але більшість доступних middleware походять безпосередньо зі Starlette.
+
+///
+
+## `HTTPSRedirectMiddleware` { #httpsredirectmiddleware }
+
+Примушує, щоб усі вхідні запити були або `https`, або `wss`.
+
+Будь-який вхідний запит до `http` або `ws` буде перенаправлено на захищену схему.
+
+{* ../../docs_src/advanced_middleware/tutorial001_py310.py hl[2,6] *}
+
+## `TrustedHostMiddleware` { #trustedhostmiddleware }
+
+Примушує, щоб усі вхідні запити мали коректно встановлений заголовок `Host`, щоб захиститися від атак HTTP Host Header.
+
+{* ../../docs_src/advanced_middleware/tutorial002_py310.py hl[2,6:8] *}
+
+Підтримуються такі аргументи:
+
+- `allowed_hosts` - Список доменних імен, які слід дозволити як імена хостів. Підтримуються домени з «дикою картою», такі як `*.example.com`, для зіставлення піддоменів. Щоб дозволити будь-яке ім'я хоста, або використовуйте `allowed_hosts=["*"]`, або не додавайте це middleware.
+- `www_redirect` - Якщо встановлено True, запити до не-www версій дозволених хостів буде перенаправлено до їхніх www-варіантів. Типово `True`.
+
+Якщо вхідний запит не проходить перевірку, буде надіслано відповідь `400`.
+
+## `GZipMiddleware` { #gzipmiddleware }
+
+Обробляє відповіді GZip для будь-якого запиту, що містить `"gzip"` у заголовку `Accept-Encoding`.
+
+Middleware обробляє як стандартні, так і потокові відповіді.
+
+{* ../../docs_src/advanced_middleware/tutorial003_py310.py hl[2,6] *}
+
+Підтримуються такі аргументи:
+
+- `minimum_size` - Не GZip-увати відповіді, менші за цей мінімальний розмір у байтах. Типово `500`.
+- `compresslevel` - Використовується під час стиснення GZip. Це ціле число в діапазоні від 1 до 9. Типово `9`. Менше значення дає швидше стиснення, але більший розмір файлів; більше значення дає повільніше стиснення, але менший розмір файлів.
+
+## Інше middleware { #other-middlewares }
+
+Є багато іншого проміжного ПЗ ASGI.
+
+Наприклад:
+
+- `ProxyHeadersMiddleware` з Uvicorn
+- MessagePack
+
+Щоб переглянути інші доступні middleware, ознайомтеся з документацією Starlette щодо middleware та списком ASGI Awesome.
diff --git a/docs/uk/docs/advanced/openapi-callbacks.md b/docs/uk/docs/advanced/openapi-callbacks.md
new file mode 100644
index 000000000..1f2adb1fc
--- /dev/null
+++ b/docs/uk/docs/advanced/openapi-callbacks.md
@@ -0,0 +1,186 @@
+# Зворотні виклики OpenAPI { #openapi-callbacks }
+
+Ви можете створити API з операцією шляху, яка ініціюватиме запит до зовнішнього API, створеного кимось іншим (ймовірно тим самим розробником, який буде використовувати ваш API).
+
+Процес, що відбувається, коли ваш застосунок API викликає зовнішній API, називається «зворотний виклик». Тому що програмне забезпечення, написане зовнішнім розробником, надсилає запит до вашого API, а потім ваш API виконує зворотний виклик, надсилаючи запит до зовнішнього API (його, ймовірно, також створив той самий розробник).
+
+У такому випадку вам може знадобитися задокументувати, яким має бути той зовнішній API: які операції шляху він має мати, яке тіло очікувати, яку відповідь повертати тощо.
+
+## Застосунок зі зворотними викликами { #an-app-with-callbacks }
+
+Розгляньмо це на прикладі.
+
+Уявімо, що ви розробляєте застосунок для створення рахунків.
+
+Ці рахунки матимуть `id`, `title` (необов'язково), `customer` і `total`.
+
+Користувач вашого API (зовнішній розробник) створить рахунок у вашому API за допомогою POST-запиту.
+
+Потім ваш API буде (уявімо):
+
+- Надсилати рахунок деякому клієнту зовнішнього розробника.
+- Отримувати оплату.
+- Надсилати сповіщення назад користувачу API (зовнішньому розробнику).
+ - Це буде зроблено шляхом надсилання POST-запиту (з вашого API) до деякого зовнішнього API, наданого тим зовнішнім розробником (це і є «зворотний виклик»).
+
+## Звичайний застосунок FastAPI { #the-normal-fastapi-app }
+
+Спочатку подивімося, як виглядав би звичайний застосунок API до додавання зворотного виклику.
+
+Він матиме операцію шляху, яка отримуватиме тіло `Invoice`, і параметр запиту `callback_url`, що міститиме URL для зворотного виклику.
+
+Ця частина цілком звична, більшість коду вам, ймовірно, уже знайома:
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[7:11,34:51] *}
+
+/// tip | Порада
+
+Параметр запиту `callback_url` використовує тип Pydantic Url.
+
+///
+
+Єдина нова річ - це `callbacks=invoices_callback_router.routes` як аргумент декоратора операції шляху. Далі розглянемо, що це таке.
+
+## Документування зворотного виклику { #documenting-the-callback }
+
+Фактичний код зворотного виклику сильно залежатиме від вашого застосунку API.
+
+І, ймовірно, сильно відрізнятиметься від застосунку до застосунку.
+
+Це можуть бути лише один-два рядки коду, наприклад:
+
+```Python
+callback_url = "https://example.com/api/v1/invoices/events/"
+httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
+```
+
+Але, можливо, найважливіша частина зворотного виклику - переконатися, що користувач вашого API (зовнішній розробник) правильно реалізує зовнішній API відповідно до даних, які ваш API надсилатиме в тілі запиту зворотного виклику тощо.
+
+Тому далі ми додамо код, щоб задокументувати, яким має бути цей зовнішній API, щоб приймати зворотний виклик від вашого API.
+
+Ця документація з'явиться в Swagger UI за адресою `/docs` у вашому API і дасть змогу зовнішнім розробникам зрозуміти, як створити зовнішній API.
+
+У цьому прикладі сам зворотний виклик не реалізовано (це може бути лише один рядок коду), лише частину з документацією.
+
+/// tip | Порада
+
+Фактичний зворотний виклик - це просто HTTP-запит.
+
+Реалізуючи зворотний виклик самостійно, ви можете скористатися, наприклад, HTTPX або Requests.
+
+///
+
+## Напишіть код документації для зворотного виклику { #write-the-callback-documentation-code }
+
+Цей код не виконуватиметься у вашому застосунку, він потрібен лише, щоб задокументувати, яким має бути зовнішній API.
+
+Але ви вже знаєте, як легко створювати автоматичну документацію для API за допомогою FastAPI.
+
+Тож ми скористаємося цими знаннями, щоб задокументувати, яким має бути зовнішній API... створивши операції шляху, які має реалізувати зовнішній API (ті, які викликатиме ваш API).
+
+/// tip | Порада
+
+Пишучи код для документування зворотного виклику, корисно уявити, що ви - той *зовнішній розробник*. І що ви зараз реалізуєте *зовнішній API*, а не *ваш API*.
+
+Тимчасово прийнявши цю точку зору ( *зовнішнього розробника* ), вам буде очевидніше, куди помістити параметри, яку Pydantic-модель використати для тіла, для відповіді тощо для того *зовнішнього API*.
+
+///
+
+### Створіть callback `APIRouter` { #create-a-callback-apirouter }
+
+Спочатку створіть новий `APIRouter`, який міститиме один або кілька зворотних викликів.
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[1,23] *}
+
+### Створіть операцію шляху зворотного виклику { #create-the-callback-path-operation }
+
+Щоб створити операцію шляху зворотного виклику, використайте той самий `APIRouter`, який ви створили вище.
+
+Вона має виглядати як звичайна операція шляху FastAPI:
+
+- Ймовірно має містити оголошення тіла, яке вона приймає, напр. `body: InvoiceEvent`.
+- І також може містити оголошення відповіді, яку вона повертає, напр. `response_model=InvoiceEventReceived`.
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[14:16,19:20,26:30] *}
+
+Є 2 основні відмінності від звичайної операції шляху:
+
+- Їй не потрібен реальний код, адже ваш застосунок ніколи не викликатиме цей код. Вона використовується лише для документування зовнішнього API. Тому функція може просто містити `pass`.
+- Шлях може містити вираз OpenAPI 3 (див. нижче), де можна використовувати змінні з параметрами та частини оригінального запиту, надісланого до вашого API.
+
+### Вираз шляху зворотного виклику { #the-callback-path-expression }
+
+Шлях зворотного виклику може містити вираз OpenAPI 3, який включає частини оригінального запиту, надісланого до вашого API.
+
+У цьому випадку це строка:
+
+```Python
+"{$callback_url}/invoices/{$request.body.id}"
+```
+
+Отже, якщо користувач вашого API (зовнішній розробник) надішле запит до *вашого API* на:
+
+```
+https://yourapi.com/invoices/?callback_url=https://www.external.org/events
+```
+
+з JSON-тілом:
+
+```JSON
+{
+ "id": "2expen51ve",
+ "customer": "Mr. Richie Rich",
+ "total": "9999"
+}
+```
+
+тоді *ваш API* опрацює рахунок і згодом надішле запит зворотного виклику на `callback_url` ( *зовнішній API* ):
+
+```
+https://www.external.org/events/invoices/2expen51ve
+```
+
+з JSON-тілом на кшталт:
+
+```JSON
+{
+ "description": "Payment celebration",
+ "paid": true
+}
+```
+
+і очікуватиме відповідь від того *зовнішнього API* з JSON-тілом на кшталт:
+
+```JSON
+{
+ "ok": true
+}
+```
+
+/// tip | Порада
+
+Зверніть увагу, що використаний URL зворотного виклику містить URL, отриманий як параметр запиту в `callback_url` (`https://www.external.org/events`), а також `id` рахунку зсередини JSON-тіла (`2expen51ve`).
+
+///
+
+### Додайте маршрутизатор зворотного виклику { #add-the-callback-router }
+
+На цьому етапі ви маєте потрібні операції шляху зворотного виклику (ті, які має реалізувати *зовнішній розробник* у *зовнішньому API*) у створеному вище маршрутизаторі зворотного виклику.
+
+Тепер використайте параметр `callbacks` у декораторі операції шляху вашого API, щоб передати атрибут `.routes` (це насправді просто `list` маршрутів/операцій шляху) з цього маршрутизатора зворотного виклику:
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *}
+
+/// tip | Порада
+
+Зверніть увагу, що ви передаєте не сам маршрутизатор (`invoices_callback_router`) у `callback=`, а атрибут `.routes`, тобто `invoices_callback_router.routes`.
+
+///
+
+### Перевірте документацію { #check-the-docs }
+
+Тепер ви можете запустити застосунок і перейти за адресою http://127.0.0.1:8000/docs.
+
+Ви побачите вашу документацію з розділом «Callbacks» для вашої операції шляху, який показує, як має виглядати зовнішній API:
+
+
diff --git a/docs/uk/docs/advanced/openapi-webhooks.md b/docs/uk/docs/advanced/openapi-webhooks.md
new file mode 100644
index 000000000..0d8a7f4c5
--- /dev/null
+++ b/docs/uk/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# Вебхуки OpenAPI { #openapi-webhooks }
+
+Бувають випадки, коли ви хочете повідомити **користувачів** вашого API, що ваш застосунок може викликати *їхній* застосунок (надсилаючи запит) із деякими даними, зазвичай щоб **сповістити** про певний тип **події**.
+
+Це означає, що замість звичного процесу, коли ваші користувачі надсилають запити до вашого API, саме **ваш API** (або ваш застосунок) може **надсилати запити до їхньої системи** (до їх API, їх застосунку).
+
+Зазвичай це називають **вебхуком**.
+
+## Кроки вебхуків { #webhooks-steps }
+
+Зазвичай процес такий: ви визначаєте у своєму коді, яке повідомлення надсилатимете, тобто **тіло запиту**.
+
+Ви також якимось чином визначаєте моменти, коли ваш застосунок надсилатиме ці запити або події.
+
+А **ваші користувачі** якимось чином (наприклад, у веб-дашборді) визначають **URL**, куди ваш застосунок має надсилати ці запити.
+
+Уся **логіка** щодо реєстрації URL для вебхуків і код для фактичного надсилання цих запитів - на ваш розсуд. Ви пишете це у **власному коді** так, як вважаєте за потрібне.
+
+## Документування вебхуків у **FastAPI** та OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }
+
+У **FastAPI**, використовуючи OpenAPI, ви можете визначити назви цих вебхуків, типи HTTP-операцій, які ваш застосунок може надсилати (наприклад, `POST`, `PUT` тощо), і **тіла** запитів, які ваш застосунок надсилатиме.
+
+Це значно спростить для ваших користувачів **реалізацію їхніх API** для отримання ваших запитів **вебхуків**; вони навіть зможуть згенерувати частину власного коду API автоматично.
+
+/// info | Інформація
+
+Вебхуки доступні в OpenAPI 3.1.0 і вище, підтримуються FastAPI `0.99.0` і вище.
+
+///
+
+## Застосунок із вебхуками { #an-app-with-webhooks }
+
+Коли ви створюєте застосунок **FastAPI**, є атрибут `webhooks`, який можна використати для визначення *вебхуків* так само, як ви визначаєте *операції шляху*, наприклад за допомогою `@app.webhooks.post()`.
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+Визначені вами вебхуки потраплять до **схеми OpenAPI** та автоматичного **інтерфейсу документації**.
+
+/// info | Інформація
+
+Об'єкт `app.webhooks` насправді є просто `APIRouter` - тим самим типом, який ви використовуєте, структуризуючи застосунок у кількох файлах.
+
+///
+
+Зверніть увагу, що з вебхуками ви фактично не оголошуєте *шлях* (на кшталт `/items/`), текст, який ви передаєте там, - це лише **ідентифікатор** вебхука (назва події). Наприклад, у `@app.webhooks.post("new-subscription")` назва вебхука - `new-subscription`.
+
+Це тому, що очікується, що **ваші користувачі** іншим способом (наприклад, у веб-дашборді) визначать фактичний **URL-шлях**, де вони хочуть отримувати запит вебхука.
+
+### Перевірте документацію { #check-the-docs }
+
+Тепер ви можете запустити свій застосунок і перейти за адресою http://127.0.0.1:8000/docs.
+
+Ви побачите у своїй документації звичайні *операції шляху*, а також деякі **вебхуки**:
+
+
diff --git a/docs/uk/docs/advanced/path-operation-advanced-configuration.md b/docs/uk/docs/advanced/path-operation-advanced-configuration.md
new file mode 100644
index 000000000..202f9317e
--- /dev/null
+++ b/docs/uk/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,172 @@
+# Додаткова конфігурація операцій шляху { #path-operation-advanced-configuration }
+
+## OpenAPI operationId { #openapi-operationid }
+
+/// warning | Попередження
+
+Якщо ви не «експерт» з OpenAPI, імовірно, вам це не потрібно.
+
+///
+
+Ви можете встановити OpenAPI `operationId`, який буде використано у вашій *операції шляху*, за допомогою параметра `operation_id`.
+
+Потрібно переконатися, що він унікальний для кожної операції.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
+
+### Використання назви *функції операції шляху* як operationId { #using-the-path-operation-function-name-as-the-operationid }
+
+Якщо ви хочете використовувати назви функцій ваших API як `operationId`, ви можете пройтися по всіх них і переписати `operation_id` кожної *операції шляху*, використовуючи їхній `APIRoute.name`.
+
+Зробіть це після додавання всіх *операцій шляху*.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
+
+/// tip | Порада
+
+Якщо ви вручну викликаєте `app.openapi()`, оновіть значення `operationId` до цього.
+
+///
+
+/// warning | Попередження
+
+Якщо ви робите це, переконайтеся, що кожна з ваших *функцій операцій шляху* має унікальну назву.
+
+Навіть якщо вони в різних модулях (файлах Python).
+
+///
+
+## Виключення з OpenAPI { #exclude-from-openapi }
+
+Щоб виключити *операцію шляху* зі згенерованої Схеми OpenAPI (а отже, і з автоматичних систем документації), використайте параметр `include_in_schema` і встановіть його в `False`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## Розширений опис із docstring { #advanced-description-from-docstring }
+
+Ви можете обмежити кількість рядків із docstring *функції операції шляху*, що використовуються для OpenAPI.
+
+Додавання `\f` (екранованого символу «form feed») змусить **FastAPI** обрізати вивід для OpenAPI в цій точці.
+
+Це не з’явиться в документації, але інші інструменти (такі як Sphinx) зможуть використати решту.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## Додаткові відповіді { #additional-responses }
+
+Ймовірно, ви вже бачили, як оголошувати `response_model` і `status_code` для *операції шляху*.
+
+Це визначає метадані про основну відповідь *операції шляху*.
+
+Також можна оголосити додаткові відповіді з їхніми моделями, кодами статусу тощо.
+
+У документації є цілий розділ про це, ви можете прочитати його тут: [Додаткові відповіді в OpenAPI](additional-responses.md){.internal-link target=_blank}.
+
+## Додатково в OpenAPI { #openapi-extra }
+
+Коли ви оголошуєте *операцію шляху* у своєму застосунку, **FastAPI** автоматично генерує відповідні метадані про цю *операцію шляху* для включення в Схему OpenAPI.
+
+/// note | Технічні деталі
+
+У специфікації OpenAPI це називається Об'єкт Operation.
+
+///
+
+Він містить усю інформацію про *операцію шляху* і використовується для побудови автоматичної документації.
+
+Він включає `tags`, `parameters`, `requestBody`, `responses` тощо.
+
+Цю OpenAPI-схему, специфічну для *операції шляху*, зазвичай генерує **FastAPI** автоматично, але ви також можете її розширити.
+
+/// tip | Порада
+
+Це низькорівнева точка розширення.
+
+Якщо вам потрібно лише оголосити додаткові відповіді, зручніше зробити це через [Додаткові відповіді в OpenAPI](additional-responses.md){.internal-link target=_blank}.
+
+///
+
+Ви можете розширити OpenAPI-схему для *операції шляху*, використовуючи параметр `openapi_extra`.
+
+### Розширення OpenAPI { #openapi-extensions }
+
+`openapi_extra` може бути корисним, наприклад, для оголошення [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+Якщо ви відкриєте автоматичну документацію API, ваше розширення з’явиться внизу конкретної *операції шляху*.
+
+
+
+І якщо ви відкриєте згенерований OpenAPI (за адресою `/openapi.json` у вашому API), ви також побачите своє розширення як частину конкретної *операції шляху*:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### Власна схема OpenAPI для *операції шляху* { #custom-openapi-path-operation-schema }
+
+Словник у `openapi_extra` буде глибоко об’єднано з автоматично згенерованою OpenAPI-схемою для *операції шляху*.
+
+Тож ви можете додати додаткові дані до автоматично згенерованої схеми.
+
+Наприклад, ви можете вирішити читати та перевіряти запит власним кодом, не використовуючи автоматичні можливості FastAPI з Pydantic, але все ж захотіти визначити запит у Схемі OpenAPI.
+
+Ви можете зробити це за допомогою `openapi_extra`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+У цьому прикладі ми не оголошували жодної моделі Pydantic. Насправді тіло запиту навіть не розібрано як JSON, воно читається безпосередньо як `bytes`, а функція `magic_data_reader()` відповідатиме за його розбір певним чином.
+
+Водночас ми можемо оголосити очікувану схему для тіла запиту.
+
+### Власний тип вмісту OpenAPI { #custom-openapi-content-type }
+
+Використовуючи той самий прийом, ви можете застосувати модель Pydantic, щоб визначити Схему JSON, яка потім включається в користувацький розділ OpenAPI-схеми для *операції шляху*.
+
+І ви можете зробити це, навіть якщо тип даних у запиті - не JSON.
+
+Наприклад, у цьому застосунку ми не використовуємо вбудовану функціональність FastAPI для отримання Схеми JSON з моделей Pydantic і не використовуємо автоматичну валідацію для JSON. Насправді ми оголошуємо тип вмісту запиту як YAML, а не JSON:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+Попри те, що ми не використовуємо типову вбудовану функціональність, ми все одно використовуємо модель Pydantic, щоб вручну згенерувати Схему JSON для даних, які хочемо отримати у форматі YAML.
+
+Потім ми працюємо із запитом безпосередньо і отримуємо тіло як `bytes`. Це означає, що FastAPI навіть не намагатиметься розібрати корисне навантаження запиту як JSON.
+
+Далі у нашому коді ми безпосередньо розбираємо цей YAML-вміст і знову використовуємо ту саму модель Pydantic, щоб перевірити YAML-вміст:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip | Порада
+
+Тут ми перевикористовуємо ту саму модель Pydantic.
+
+Але так само ми могли б перевіряти дані іншим способом.
+
+///
diff --git a/docs/uk/docs/advanced/response-change-status-code.md b/docs/uk/docs/advanced/response-change-status-code.md
new file mode 100644
index 000000000..fdf9f81c5
--- /dev/null
+++ b/docs/uk/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# Відповідь - зміна коду статусу { #response-change-status-code }
+
+Ймовірно, ви вже читали, що можна встановити типовий [код статусу відповіді](../tutorial/response-status-code.md){.internal-link target=_blank}.
+
+Але інколи потрібно повернути інший код статусу, ніж типовий.
+
+## Випадок використання { #use-case }
+
+Наприклад, уявімо, що ви хочете за замовчуванням повертати код статусу HTTP «OK» `200`.
+
+Але якщо даних не існувало, ви хочете створити їх і повернути код статусу HTTP «CREATED» `201`.
+
+Водночас ви все одно хочете мати змогу фільтрувати та перетворювати повернені дані за допомогою `response_model`.
+
+Для таких випадків ви можете використати параметр `Response`.
+
+## Використовуйте параметр `Response` { #use-a-response-parameter }
+
+Ви можете оголосити параметр типу `Response` у своїй функції операції шляху (так само, як для кукі та заголовків).
+
+Потім ви можете встановити `status_code` у цьому *тимчасовому* об'єкті відповіді.
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+Після цього ви можете повернути будь-який потрібний об'єкт, як зазвичай (`dict`, модель бази даних тощо).
+
+І якщо ви оголосили `response_model`, він усе одно буде використаний для фільтрації та перетворення поверненого об'єкта.
+
+**FastAPI** використає цей *тимчасовий* об'єкт відповіді, щоб отримати код статусу (а також кукі та заголовки), і помістить їх у фінальну відповідь, що містить повернуте вами значення, відфільтроване за допомогою `response_model`.
+
+Ви також можете оголосити параметр `Response` у залежностях і встановлювати там код статусу. Але майте на увазі: останнє встановлене значення матиме пріоритет.
diff --git a/docs/uk/docs/advanced/response-cookies.md b/docs/uk/docs/advanced/response-cookies.md
new file mode 100644
index 000000000..826602e70
--- /dev/null
+++ b/docs/uk/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# Кукі у відповіді { #response-cookies }
+
+## Використовуйте параметр `Response` { #use-a-response-parameter }
+
+Ви можете оголосити параметр типу `Response` у вашій *функції операції шляху*.
+
+Потім ви можете встановити кукі в цьому *тимчасовому* об'єкті відповіді.
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+Після цього ви можете повернути будь-який потрібний об'єкт, як зазвичай (наприклад, `dict`, модель бази даних тощо).
+
+І якщо ви оголосили `response_model`, він усе одно буде використаний для фільтрації та перетворення об'єкта, який ви повернули.
+
+**FastAPI** використає цю *тимчасову* відповідь, щоб витягнути кукі (а також заголовки та код статусу) і помістить їх у фінальну відповідь, що містить значення, яке ви повернули, відфільтроване будь-якою `response_model`.
+
+Ви також можете оголосити параметр `Response` у залежностях і встановлювати в них кукі (і заголовки).
+
+## Повертайте `Response` безпосередньо { #return-a-response-directly }
+
+Ви також можете створювати кукі, повертаючи `Response` безпосередньо у вашому коді.
+
+Для цього ви можете створити відповідь, як описано в [Повернути відповідь безпосередньо](response-directly.md){.internal-link target=_blank}.
+
+Потім встановіть у ньому кукі і поверніть його:
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip | Порада
+
+Майте на увазі, що якщо ви повертаєте відповідь безпосередньо замість використання параметра `Response`, FastAPI поверне її напряму.
+
+Тому вам потрібно переконатися, що ваші дані мають коректний тип. Наприклад, сумісні з JSON, якщо ви повертаєте `JSONResponse`.
+
+А також що ви не надсилаєте дані, які мали б бути відфільтровані за допомогою `response_model`.
+
+///
+
+### Більше інформації { #more-info }
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import Response` або `from starlette.responses import JSONResponse`.
+
+**FastAPI** надає ті самі `starlette.responses` як `fastapi.responses` лише для зручності для вас, розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette.
+
+І оскільки `Response` часто використовується для встановлення заголовків і кукі, **FastAPI** також надає його як `fastapi.Response`.
+
+///
+
+Щоб побачити всі доступні параметри та опції, перегляньте документацію в Starlette.
diff --git a/docs/uk/docs/advanced/response-directly.md b/docs/uk/docs/advanced/response-directly.md
new file mode 100644
index 000000000..7396ab756
--- /dev/null
+++ b/docs/uk/docs/advanced/response-directly.md
@@ -0,0 +1,65 @@
+# Повернення Response безпосередньо { #return-a-response-directly }
+
+Коли ви створюєте операцію шляху FastAPI, зазвичай ви можете повертати з неї будь-які дані: `dict`, `list`, модель Pydantic, модель бази даних тощо.
+
+Типово FastAPI автоматично перетворить це значення повернення на JSON, використовуючи `jsonable_encoder`, описаний у [Сумісному з JSON кодері](../tutorial/encoder.md){.internal-link target=_blank}.
+
+Потім, за лаштунками, він помістить ці дані, сумісні з JSON (наприклад, `dict`), у `JSONResponse`, який буде використано для надсилання відповіді клієнту.
+
+Але ви можете повертати `JSONResponse` безпосередньо з ваших операцій шляху.
+
+Це може бути корисним, наприклад, щоб повертати власні заголовки або кукі.
+
+## Повернення `Response` { #return-a-response }
+
+Насправді ви можете повертати будь-який `Response` або будь-який його підклас.
+
+/// tip | Порада
+
+`JSONResponse` сам є підкласом `Response`.
+
+///
+
+І коли ви повертаєте `Response`, FastAPI передасть його безпосередньо.
+
+Він не виконуватиме жодних перетворень даних за допомогою моделей Pydantic, не перетворюватиме вміст на будь-який тип тощо.
+
+Це дає вам багато гнучкості. Ви можете повертати будь-які типи даних, переписувати будь-які оголошення або перевірки даних тощо.
+
+## Використання `jsonable_encoder` у `Response` { #using-the-jsonable-encoder-in-a-response }
+
+Оскільки FastAPI не вносить змін у `Response`, який ви повертаєте, вам потрібно впевнитися, що його вміст готовий.
+
+Наприклад, ви не можете покласти модель Pydantic у `JSONResponse`, не перетворивши її спочатку на `dict` з усіма типами даних (як-от `datetime`, `UUID` тощо), перетвореними на типи, сумісні з JSON.
+
+Для таких випадків ви можете використати `jsonable_encoder`, щоб перетворити ваші дані перед тим, як передати їх у відповідь:
+
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import JSONResponse`.
+
+FastAPI надає ті самі `starlette.responses` як `fastapi.responses` просто як зручність для вас, розробника. Але більшість доступних `Response` походять безпосередньо зі Starlette.
+
+///
+
+## Повернення власного `Response` { #returning-a-custom-response }
+
+Наведений вище приклад показує всі необхідні частини, але він ще не дуже корисний, адже ви могли просто повернути `item` безпосередньо, і FastAPI помістив би його у `JSONResponse`, перетворивши на `dict` тощо. Усе це відбувається за замовчуванням.
+
+Тепер подивімося, як це використати, щоб повернути власну відповідь.
+
+Припустімо, ви хочете повернути відповідь XML.
+
+Ви можете помістити свій вміст XML у строку, помістити це в `Response` і повернути:
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## Примітки { #notes }
+
+Коли ви повертаєте `Response` безпосередньо, його дані не перевіряються, не перетворюються (серіалізуються) і не документуються автоматично.
+
+Але ви все ще можете задокументувати це, як описано в [Додаткових відповідях в OpenAPI](additional-responses.md){.internal-link target=_blank}.
+
+У подальших розділах ви побачите, як використовувати/оголошувати ці власні `Response`, водночас зберігаючи автоматичне перетворення даних, документацію тощо.
diff --git a/docs/uk/docs/advanced/response-headers.md b/docs/uk/docs/advanced/response-headers.md
new file mode 100644
index 000000000..1c9d4e677
--- /dev/null
+++ b/docs/uk/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# Заголовки відповіді { #response-headers }
+
+## Використовуйте параметр `Response` { #use-a-response-parameter }
+
+Ви можете оголосити параметр типу `Response` у вашій функції операції шляху (так само, як і для кукі).
+
+Потім ви можете встановлювати заголовки в цьому *тимчасовому* обʼєкті відповіді.
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+Далі ви можете повернути будь-який потрібний обʼєкт, як зазвичай (наприклад, `dict`, модель бази даних тощо).
+
+Якщо ви оголосили `response_model`, його все одно буде використано для фільтрації та перетворення поверненого обʼєкта.
+
+FastAPI використає цей *тимчасовий* обʼєкт відповіді, щоб витягти заголовки (а також кукі та код статусу) і помістить їх у кінцеву відповідь, яка міститиме повернуте вами значення, відфільтроване будь-яким `response_model`.
+
+Також ви можете оголосити параметр `Response` у залежностях і встановлювати в них заголовки (та кукі).
+
+## Поверніть `Response` безпосередньо { #return-a-response-directly }
+
+Ви також можете додавати заголовки, коли повертаєте `Response` безпосередньо.
+
+Створіть відповідь, як описано в [Повернення Response безпосередньо](response-directly.md){.internal-link target=_blank}, і передайте заголовки як додатковий параметр:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import Response` або `from starlette.responses import JSONResponse`.
+
+FastAPI надає ті самі `starlette.responses` як `fastapi.responses` просто для зручності для вас, розробника. Але більшість доступних типів відповідей походять безпосередньо зі Starlette.
+
+Оскільки `Response` часто використовують для встановлення заголовків і кукі, FastAPI також надає його як `fastapi.Response`.
+
+///
+
+## Власні заголовки { #custom-headers }
+
+Майте на увазі, що власні закриті заголовки можна додавати за допомогою префікса `X-`.
+
+Але якщо у вас є власні заголовки, які клієнт у браузері має бачити, вам потрібно додати їх у вашу конфігурацію CORS (докладніше в [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), використовуючи параметр `expose_headers`, задокументований у документації Starlette щодо CORS.
diff --git a/docs/uk/docs/advanced/security/http-basic-auth.md b/docs/uk/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 000000000..e0578772d
--- /dev/null
+++ b/docs/uk/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP Basic Auth { #http-basic-auth }
+
+Для найпростіших випадків ви можете використовувати HTTP Basic Auth.
+
+У HTTP Basic Auth застосунок очікує заголовок, що містить ім'я користувача та пароль.
+
+Якщо він його не отримує, повертається помилка HTTP 401 «Unauthorized».
+
+І повертається заголовок `WWW-Authenticate` зі значенням `Basic` та необов'язковим параметром `realm`.
+
+Це каже браузеру показати вбудовану підсказку для введення імені користувача та пароля.
+
+Потім, коли ви введете це ім'я користувача та пароль, браузер автоматично надішле їх у заголовку.
+
+## Простий HTTP Basic Auth { #simple-http-basic-auth }
+
+- Імпортуйте `HTTPBasic` і `HTTPBasicCredentials`.
+- Створіть «`security` scheme» за допомогою `HTTPBasic`.
+- Використайте цей `security` як залежність у вашій операції шляху.
+- Він повертає об'єкт типу `HTTPBasicCredentials`:
+ - Він містить надіслані `username` і `password`.
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+Коли ви спробуєте відкрити URL вперше (або натиснете кнопку «Execute» у документації), браузер попросить вас ввести ім'я користувача та пароль:
+
+
+
+## Перевірте ім'я користувача { #check-the-username }
+
+Ось більш повний приклад.
+
+Використайте залежність, щоб перевірити, чи правильні ім'я користувача та пароль.
+
+Для цього використайте стандартний модуль Python `secrets`, щоб перевірити ім'я користувача та пароль.
+
+`secrets.compare_digest()` повинен отримувати `bytes` або `str`, що містить лише ASCII-символи (англійські), це означає, що він не працюватиме з символами на кшталт `á`, як у `Sebastián`.
+
+Щоб це обійти, ми спочатку перетворюємо `username` і `password` у `bytes`, кодувавши їх у UTF-8.
+
+Потім ми можемо використати `secrets.compare_digest()`, щоб упевнитися, що `credentials.username` дорівнює `"stanleyjobson"`, а `credentials.password` дорівнює `"swordfish"`.
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+Це було б подібно до:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Return some error
+ ...
+```
+
+Але використовуючи `secrets.compare_digest()`, це буде захищено від типу атак, що називаються «атаки за часом» (timing attacks).
+
+### Атаки за часом { #timing-attacks }
+
+Що таке «атака за часом»?
+
+Уявімо, що зловмисники намагаються вгадати ім'я користувача та пароль.
+
+Вони надсилають запит з ім'ям користувача `johndoe` та паролем `love123`.
+
+Тоді Python-код у вашому застосунку буде еквівалентний чомусь на кшталт:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Але в той момент, коли Python порівнює першу `j` у `johndoe` з першою `s` у `stanleyjobson`, він поверне `False`, тому що вже знає, що ці дві строки не однакові, «немає сенсу витрачати обчислення на порівняння решти літер». І ваш застосунок скаже «Невірні ім'я користувача або пароль».
+
+А потім зловмисники спробують з ім'ям користувача `stanleyjobsox` і паролем `love123`.
+
+І ваш код застосунку зробить щось на кшталт:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Python доведеться порівняти весь `stanleyjobso` у обох `stanleyjobsox` і `stanleyjobson`, перш ніж зрозуміти, що строки різні. Тому відповідь «Невірні ім'я користувача або пароль» займе на кілька мікросекунд довше.
+
+#### Час відповіді допомагає зловмисникам { #the-time-to-answer-helps-the-attackers }
+
+У цей момент, помітивши, що сервер витратив на кілька мікросекунд більше, щоб надіслати відповідь «Невірні ім'я користувача або пароль», зловмисники знатимуть, що вони щось вгадали, деякі початкові літери правильні.
+
+І тоді вони можуть спробувати знову, знаючи, що це, ймовірно, щось більш схоже на `stanleyjobsox`, ніж на `johndoe`.
+
+#### «Професійна» атака { #a-professional-attack }
+
+Звісно, зловмисники не робитимуть усе це вручну, вони напишуть програму, можливо з тисячами або мільйонами перевірок за секунду. І вони отримуватимуть лише по одній правильній літері за раз.
+
+Але так за кілька хвилин або годин зловмисники вгадають правильні ім'я користувача та пароль, «за допомогою» нашого застосунку, просто використовуючи час, потрібний для відповіді.
+
+#### Виправте за допомогою `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }
+
+Але в нашому коді ми насправді використовуємо `secrets.compare_digest()`.
+
+Коротко, він витрачає однаковий час на порівняння `stanleyjobsox` зі `stanleyjobson`, як і на порівняння `johndoe` зі `stanleyjobson`. І так само для пароля.
+
+Таким чином, використовуючи `secrets.compare_digest()` у коді вашого застосунку, він буде захищений від усього цього класу атак безпеки.
+
+### Поверніть помилку { #return-the-error }
+
+Після виявлення, що облікові дані неправильні, поверніть `HTTPException` з кодом статусу 401 (такий самий повертається, коли облікові дані не надані) і додайте заголовок `WWW-Authenticate`, щоб браузер знову показав підсказку входу:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/uk/docs/advanced/security/index.md b/docs/uk/docs/advanced/security/index.md
new file mode 100644
index 000000000..a3479794f
--- /dev/null
+++ b/docs/uk/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# Просунута безпека { #advanced-security }
+
+## Додаткові можливості { #additional-features }
+
+Є кілька додаткових можливостей для роботи з безпекою, окрім тих, що розглянуті в [Навчальний посібник - Посібник користувача: Безпека](../../tutorial/security/index.md){.internal-link target=_blank}.
+
+/// tip | Порада
+
+Наступні розділи не обов'язково «просунуті».
+
+І можливо, що для вашого випадку використання рішення є в одному з них.
+
+///
+
+## Спершу прочитайте навчальний посібник { #read-the-tutorial-first }
+
+У наступних розділах передбачається, що ви вже прочитали основний [Навчальний посібник - Посібник користувача: Безпека](../../tutorial/security/index.md){.internal-link target=_blank}.
+
+Усі вони базуються на тих самих концепціях, але надають деякі додаткові можливості.
diff --git a/docs/uk/docs/advanced/security/oauth2-scopes.md b/docs/uk/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 000000000..34ef04a28
--- /dev/null
+++ b/docs/uk/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2 scopes { #oauth2-scopes }
+
+Ви можете використовувати OAuth2 scopes безпосередньо з **FastAPI**, вони інтегровані для безшовної роботи.
+
+Це дозволить мати більш детальну систему дозволів, відповідно до стандарту OAuth2, інтегровану у ваш застосунок OpenAPI (і документацію API).
+
+OAuth2 зі scopes - це механізм, який використовують багато великих провайдерів автентифікації, як-от Facebook, Google, GitHub, Microsoft, X (Twitter) тощо. Вони застосовують його, щоб надавати конкретні дозволи користувачам і застосункам.
+
+Кожного разу, коли ви «log in with» Facebook, Google, GitHub, Microsoft, X (Twitter), цей застосунок використовує OAuth2 зі scopes.
+
+У цьому розділі ви побачите, як керувати автентифікацією та авторизацією за допомогою того ж OAuth2 зі scopes у вашому застосунку **FastAPI**.
+
+/// warning | Попередження
+
+Це більш-менш просунутий розділ. Якщо ви тільки починаєте, можете пропустити його.
+
+Вам не обов’язково потрібні OAuth2 scopes, ви можете керувати автентифікацією та авторизацією будь-яким зручним способом.
+
+Але OAuth2 зі scopes можна гарно інтегрувати у ваш API (з OpenAPI) і документацію API.
+
+Водночас ви все одно примушуєте виконувати ці scopes або будь-які інші вимоги безпеки/авторизації так, як потрібно, у своєму коді.
+
+У багатьох випадках OAuth2 зі scopes - це надмірність.
+
+Але якщо ви знаєте, що це потрібно, або просто цікаво, читайте далі.
+
+///
+
+## OAuth2 scopes та OpenAPI { #oauth2-scopes-and-openapi }
+
+Специфікація OAuth2 визначає «scopes» як список строк, розділених пробілами.
+
+Вміст кожної з цих строк може мати будь-який формат, але не повинен містити пробілів.
+
+Ці scopes представляють «дозволи».
+
+В OpenAPI (наприклад, у документації API) ви можете визначати «схеми безпеки».
+
+Коли одна з цих схем безпеки використовує OAuth2, ви також можете оголошувати та використовувати scopes.
+
+Кожен «scope» - це просто строка (без пробілів).
+
+Зазвичай їх використовують для оголошення конкретних дозволів безпеки, наприклад:
+
+- `users:read` або `users:write` - поширені приклади.
+- `instagram_basic` використовується Facebook / Instagram.
+- `https://www.googleapis.com/auth/drive` використовується Google.
+
+/// info | Інформація
+
+В OAuth2 «scope» - це просто строка, що декларує конкретний потрібний дозвіл.
+
+Не має значення, чи містить вона інші символи на кшталт `:` або чи це URL.
+
+Ці деталі специфічні для реалізації.
+
+Для OAuth2 це просто строки.
+
+///
+
+## Загальний огляд { #global-view }
+
+Спочатку швидко подивімося на частини, що відрізняються від прикладів у головному **Навчальному посібнику - Керівництві користувача** для [OAuth2 з паролем (і хешуванням), Bearer з JWT-токенами](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Тепер із використанням OAuth2 scopes:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+Тепер розгляньмо ці зміни крок за кроком.
+
+## Схема безпеки OAuth2 { #oauth2-security-scheme }
+
+Перша зміна - тепер ми оголошуємо схему безпеки OAuth2 з двома доступними scopes: `me` і `items`.
+
+Параметр `scopes` приймає `dict`, де кожен scope - це ключ, а опис - значення:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+Оскільки тепер ми оголошуємо ці scopes, вони з’являться в документації API, коли ви увійдете/авторизуєтеся.
+
+І ви зможете обрати, які scopes надати доступ: `me` і `items`.
+
+Це той самий механізм, який використовується, коли ви надаєте дозволи під час входу через Facebook, Google, GitHub тощо:
+
+
+
+## JWT токен зі scopes { #jwt-token-with-scopes }
+
+Тепер змініть операцію шляху токена, щоб повертати запитані scopes.
+
+Ми все ще використовуємо той самий `OAuth2PasswordRequestForm`. Він містить властивість `scopes` зі `list` з `str`, по одному scope, отриманому в запиті.
+
+І ми повертаємо scopes як частину JWT токена.
+
+/// danger | Обережно
+
+Для простоти тут ми просто додаємо отримані scopes безпосередньо до токена.
+
+Але у вашому застосунку, з міркувань безпеки, переконайтеся, що ви додаєте лише ті scopes, які користувач дійсно може мати, або ті, що ви попередньо визначили.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## Оголосіть scopes в операціях шляху та залежностях { #declare-scopes-in-path-operations-and-dependencies }
+
+Тепер ми оголошуємо, що операція шляху для `/users/me/items/` вимагає scope `items`.
+
+Для цього імпортуємо і використовуємо `Security` з `fastapi`.
+
+Ви можете використовувати `Security` для оголошення залежностей (так само як `Depends`), але `Security` також приймає параметр `scopes` зі списком scopes (строк).
+
+У цьому випадку ми передаємо функцію-залежність `get_current_active_user` до `Security` (так само, як зробили б із `Depends`).
+
+А також передаємо `list` scopes, у цьому випадку лише один scope: `items` (їх могло б бути більше).
+
+І функція-залежність `get_current_active_user` також може оголошувати підзалежності не лише з `Depends`, а й з `Security`. Оголошуючи свою підзалежність (`get_current_user`) і додаткові вимоги до scopes.
+
+У цьому випадку вона вимагає scope `me` (вона могла б вимагати більш ніж один scope).
+
+/// note | Примітка
+
+Вам не обов’язково додавати різні scopes у різних місцях.
+
+Ми робимо це тут, щоб показати, як **FastAPI** обробляє scopes, оголошені на різних рівнях.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | Технічні деталі
+
+`Security` насправді є підкласом `Depends`, і має лише один додатковий параметр, який ми побачимо пізніше.
+
+Але використовуючи `Security` замість `Depends`, **FastAPI** знатиме, що можна оголошувати scopes безпеки, використовувати їх внутрішньо та документувати API через OpenAPI.
+
+Коли ви імпортуєте `Query`, `Path`, `Depends`, `Security` та інші з `fastapi`, це насправді функції, що повертають спеціальні класи.
+
+///
+
+## Використовуйте `SecurityScopes` { #use-securityscopes }
+
+Тепер оновіть залежність `get_current_user`.
+
+Вона використовується наведеними вище залежностями.
+
+Тут ми використовуємо ту саму схему OAuth2, створену раніше, оголошуючи її як залежність: `oauth2_scheme`.
+
+Оскільки ця функція-залежність не має власних вимог до scopes, ми можемо використовувати `Depends` з `oauth2_scheme`, немає потреби застосовувати `Security`, коли не потрібно вказувати scopes безпеки.
+
+Ми також оголошуємо спеціальний параметр типу `SecurityScopes`, імпортований з `fastapi.security`.
+
+Клас `SecurityScopes` подібний до `Request` (у `Request` ми напряму отримували об’єкт запиту).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## Використовуйте scopes { #use-the-scopes }
+
+Параметр `security_scopes` матиме тип `SecurityScopes`.
+
+Він матиме властивість `scopes` зі списком, що містить усі scopes, потрібні самій функції та всім залежним, які використовують її як підзалежність. Тобто всім «залежним»... це може звучати заплутано, нижче пояснено ще раз.
+
+Об’єкт `security_scopes` (класу `SecurityScopes`) також надає атрибут `scope_str` з одним рядком, що містить ці scopes, розділені пробілами (ми його використаємо).
+
+Ми створюємо `HTTPException`, який зможемо повторно використати (`raise`) у кількох місцях.
+
+У цьому винятку ми включаємо потрібні scopes (якщо є) як строку, розділену пробілами (використовуючи `scope_str`). Ми поміщаємо цю строку зі scopes в заголовок `WWW-Authenticate` (це частина специфікації).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## Перевірте `username` і структуру даних { #verify-the-username-and-data-shape }
+
+Ми перевіряємо, що отримали `username`, і видобуваємо scopes.
+
+Потім валідовуємо ці дані за допомогою Pydantic-моделі (перехоплюючи виняток `ValidationError`), і якщо виникає помилка читання JWT токена або валідації даних Pydantic, підіймаємо раніше створений `HTTPException`.
+
+Для цього ми оновлюємо Pydantic-модель `TokenData` новою властивістю `scopes`.
+
+Валідувавши дані через Pydantic, ми гарантуємо, що, наприклад, маємо саме `list` із `str` для scopes і `str` для `username`.
+
+Замість, наприклад, `dict` або чогось іншого, що може зламати застосунок далі, створивши ризик безпеки.
+
+Ми також перевіряємо, що існує користувач із цим username, інакше підіймаємо той самий виняток.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## Перевірте `scopes` { #verify-the-scopes }
+
+Тепер перевіряємо, що всі потрібні scopes - для цієї залежності та всіх залежних (включно з операціями шляху) - містяться в scopes, наданих у отриманому токені, інакше підіймаємо `HTTPException`.
+
+Для цього використовуємо `security_scopes.scopes`, що містить `list` із усіма цими scopes як `str`.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## Дерево залежностей і scopes { #dependency-tree-and-scopes }
+
+Ще раз розгляньмо дерево залежностей і scopes.
+
+Оскільки залежність `get_current_active_user` має підзалежність `get_current_user`, scope «me», оголошений у `get_current_active_user`, буде включений до списку потрібних scopes у `security_scopes.scopes`, переданого до `get_current_user`.
+
+Сама операція шляху також оголошує scope «items», отже він також буде у списку `security_scopes.scopes`, переданому до `get_current_user`.
+
+Ось як виглядає ієрархія залежностей і scopes:
+
+- Операція шляху `read_own_items` має:
+ - Потрібні scopes `["items"]` із залежністю:
+ - `get_current_active_user`:
+ - Функція-залежність `get_current_active_user` має:
+ - Потрібні scopes `["me"]` із залежністю:
+ - `get_current_user`:
+ - Функція-залежність `get_current_user` має:
+ - Власних scopes не потребує.
+ - Залежність, що використовує `oauth2_scheme`.
+ - Параметр `security_scopes` типу `SecurityScopes`:
+ - Цей параметр `security_scopes` має властивість `scopes` із `list`, що містить усі наведені вище scopes, отже:
+ - `security_scopes.scopes` міститиме `["me", "items"]` для операції шляху `read_own_items`.
+ - `security_scopes.scopes` міститиме `["me"]` для операції шляху `read_users_me`, адже він оголошений у залежності `get_current_active_user`.
+ - `security_scopes.scopes` міститиме `[]` (нічого) для операції шляху `read_system_status`, бо вона не оголошує жодного `Security` зі `scopes`, і її залежність `get_current_user` також не оголошує жодних `scopes`.
+
+/// tip | Порада
+
+Важливе і «магічне» тут у тому, що `get_current_user` матиме різні списки `scopes` для перевірки для кожної операції шляху.
+
+Усе залежить від `scopes`, оголошених у кожній операції шляху та кожній залежності в дереві залежностей для конкретної операції шляху.
+
+///
+
+## Більше деталей про `SecurityScopes` { #more-details-about-securityscopes }
+
+Ви можете використовувати `SecurityScopes` у будь-якому місці й у кількох місцях, він не обов’язково має бути в «кореневій» залежності.
+
+Він завжди міститиме scopes безпеки, оголошені в поточних залежностях `Security` і всіх залежних для **цієї конкретної** операції шляху і **цього конкретного** дерева залежностей.
+
+Оскільки `SecurityScopes` міститиме всі scopes, оголошені залежними, ви можете використовувати його, щоб перевірити, що токен має потрібні scopes, у центральній функції-залежності, а потім оголошувати різні вимоги до scopes у різних операціях шляху.
+
+Вони перевірятимуться незалежно для кожної операції шляху.
+
+## Перевірте { #check-it }
+
+Якщо ви відкриєте документацію API, ви зможете автентифікуватися і вказати, які scopes хочете авторизувати.
+
+
+
+Якщо ви не оберете жодного scope, ви будете «автентифіковані», але при спробі доступу до `/users/me/` або `/users/me/items/` отримаєте помилку про недостатні дозволи. Ви все ще матимете доступ до `/status/`.
+
+Якщо оберете scope `me`, але не scope `items`, ви зможете отримати доступ до `/users/me/`, але не до `/users/me/items/`.
+
+Так станеться зі стороннім застосунком, який спробує звернутися до однієї з цих операцій шляху з токеном, наданим користувачем, залежно від того, скільки дозволів користувач надав застосунку.
+
+## Про сторонні інтеграції { #about-third-party-integrations }
+
+У цьому прикладі ми використовуємо «потік паролю» OAuth2.
+
+Це доречно, коли ми входимо у власний застосунок, ймовірно, з власним фронтендом.
+
+Адже ми можемо довіряти йому отримання `username` і `password`, бо ми його контролюємо.
+
+Але якщо ви створюєте OAuth2-застосунок, до якого підключатимуться інші (тобто якщо ви створюєте провайдера автентифікації на кшталт Facebook, Google, GitHub тощо), слід використовувати один з інших потоків.
+
+Найпоширеніший - неявний потік (implicit flow).
+
+Найбезпечніший - потік коду (code flow), але його складніше реалізувати, оскільки він потребує більше кроків. Через складність багато провайдерів у підсумку радять неявний потік.
+
+/// note | Примітка
+
+Часто кожен провайдер автентифікації називає свої потоки по-різному, роблячи це частиною свого бренду.
+
+Але зрештою вони реалізують той самий стандарт OAuth2.
+
+///
+
+**FastAPI** містить утиліти для всіх цих потоків автентифікації OAuth2 у `fastapi.security.oauth2`.
+
+## `Security` у параметрі декоратора `dependencies` { #security-in-decorator-dependencies }
+
+Так само як ви можете визначити `list` із `Depends` у параметрі `dependencies` декоратора (як пояснено в [Залежності в декораторах операцій шляху](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), ви також можете використовувати там `Security` зі `scopes`.
diff --git a/docs/uk/docs/advanced/settings.md b/docs/uk/docs/advanced/settings.md
new file mode 100644
index 000000000..dccb4b091
--- /dev/null
+++ b/docs/uk/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# Налаштування та змінні оточення { #settings-and-environment-variables }
+
+У багатьох випадках вашому застосунку можуть знадобитися зовнішні налаштування або конфігурації, наприклад секретні ключі, облікові дані бази даних, облікові дані для email-сервісів тощо.
+
+Більшість із цих налаштувань змінні (можуть змінюватися), як-от URL-адреси баз даних. І багато з них можуть бути чутливими, як-от секрети.
+
+З цієї причини поширено надавати їх у змінних оточення, які зчитуються застосунком.
+
+/// tip | Порада
+
+Щоб зрозуміти змінні оточення, ви можете прочитати [Змінні оточення](../environment-variables.md){.internal-link target=_blank}.
+
+///
+
+## Типи та перевірка { #types-and-validation }
+
+Ці змінні оточення можуть містити лише текстові строки, оскільки вони зовнішні до Python і мають бути сумісні з іншими програмами та рештою системи (і навіть з різними операційними системами, як-от Linux, Windows, macOS).
+
+Це означає, що будь-яке значення, прочитане в Python зі змінної оточення, буде `str`, і будь-яке перетворення в інший тип або будь-яка перевірка мають виконуватися в коді.
+
+## Pydantic `Settings` { #pydantic-settings }
+
+На щастя, Pydantic надає чудовий інструмент для обробки цих налаштувань із змінних оточення - Pydantic: Settings management.
+
+### Встановіть `pydantic-settings` { #install-pydantic-settings }
+
+Спершу переконайтеся, що ви створили [віртуальне оточення](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили пакет `pydantic-settings`:
+
+
+
+А потім відкрийте документацію для підзастосунку за адресою http://127.0.0.1:8000/subapi/docs.
+
+Ви побачите автоматичну документацію API для підзастосунку, що містить лише його власні _операції шляху_, усі з правильним префіксом підшляху `/subapi`:
+
+
+
+Якщо ви спробуєте взаємодіяти з будь-яким із двох інтерфейсів користувача, вони працюватимуть коректно, адже браузер зможе спілкуватися з кожним конкретним застосунком або підзастосунком.
+
+### Технічні деталі: `root_path` { #technical-details-root-path }
+
+Коли ви монтуєте підзастосунок, як описано вище, FastAPI подбає про передачу шляху монтування для підзастосунку, використовуючи механізм зі специфікації ASGI під назвою `root_path`.
+
+Таким чином підзастосунок знатиме, що слід використовувати цей префікс шляху для інтерфейсу документації.
+
+Підзастосунок також може мати власні змонтовані підзастосунки, і все працюватиме коректно, оскільки FastAPI автоматично обробляє всі ці `root_path`.
+
+Ви дізнаєтеся більше про `root_path` і як використовувати його явно в розділі [За представником](behind-a-proxy.md){.internal-link target=_blank}.
diff --git a/docs/uk/docs/advanced/templates.md b/docs/uk/docs/advanced/templates.md
new file mode 100644
index 000000000..9e1ce3709
--- /dev/null
+++ b/docs/uk/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# Шаблони { #templates }
+
+Ви можете використовувати будь-який рушій шаблонів з **FastAPI**.
+
+Поширений вибір - Jinja2, той самий, що використовується у Flask та інших інструментах.
+
+Є утиліти для простої конфігурації, які ви можете використовувати безпосередньо у вашому застосунку **FastAPI** (надає Starlette).
+
+## Встановіть залежності { #install-dependencies }
+
+Переконайтеся, що ви створили [віртуальне оточення](../virtual-environments.md){.internal-link target=_blank}, активували його та встановили `jinja2`:
+
+
+
+Ви можете вводити повідомлення у поле вводу та надсилати їх:
+
+
+
+І ваш застосунок **FastAPI** з WebSockets відповість:
+
+
+
+Ви можете надсилати (і отримувати) багато повідомлень:
+
+
+
+І всі вони використовуватимуть те саме з'єднання WebSocket.
+
+## Використання `Depends` та іншого { #using-depends-and-others }
+
+У кінцевих точках WebSocket ви можете імпортувати з `fastapi` і використовувати:
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+Вони працюють так само, як для інших ендпойнтів FastAPI/*операцій шляху*:
+
+{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info
+
+Оскільки це WebSocket, не має сенсу піднімати `HTTPException`, натомість ми піднімаємо `WebSocketException`.
+
+Ви можете використати код закриття з чинних кодів, визначених у специфікації.
+
+///
+
+### Спробуйте WebSockets із залежностями { #try-the-websockets-with-dependencies }
+
+Якщо ваш файл називається `main.py`, запустіть ваш застосунок командою:
+
+
+
+## Обробка відключень і кількох клієнтів { #handling-disconnections-and-multiple-clients }
+
+Коли з'єднання WebSocket закривається, `await websocket.receive_text()` підніме виняток `WebSocketDisconnect`, який ви можете перехопити й обробити, як у цьому прикладі.
+
+{* ../../docs_src/websockets/tutorial003_py310.py hl[79:81] *}
+
+Щоб спробувати:
+
+* Відкрийте застосунок у кількох вкладках браузера.
+* Надсилайте з них повідомлення.
+* Потім закрийте одну з вкладок.
+
+Це підніме виняток `WebSocketDisconnect`, і всі інші клієнти отримають повідомлення на кшталт:
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip
+
+Застосунок вище - це мінімальний і простий приклад, що демонструє, як обробляти та розсилати повідомлення кільком з'єднанням WebSocket.
+
+Але майте на увазі, що оскільки все обробляється в пам'яті, в одному списку, це працюватиме лише поки процес запущений, і лише з одним процесом.
+
+Якщо вам потрібне щось просте для інтеграції з FastAPI, але більш надійне, з підтримкою Redis, PostgreSQL чи інших, перегляньте encode/broadcaster.
+
+///
+
+## Детальніше { #more-info }
+
+Щоб дізнатися більше про можливості, перегляньте документацію Starlette:
+
+* Клас `WebSocket`.
+* Обробка WebSocket на основі класів.
diff --git a/docs/uk/docs/advanced/wsgi.md b/docs/uk/docs/advanced/wsgi.md
new file mode 100644
index 000000000..896924135
--- /dev/null
+++ b/docs/uk/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# Підключення WSGI - Flask, Django та інші { #including-wsgi-flask-django-others }
+
+Ви можете монтувати застосунки WSGI, як ви бачили в [Підзастосунки - монтування](sub-applications.md){.internal-link target=_blank}, [За представником](behind-a-proxy.md){.internal-link target=_blank}.
+
+Для цього ви можете використати `WSGIMiddleware` і обгорнути ним ваш застосунок WSGI, наприклад Flask, Django тощо.
+
+## Використання `WSGIMiddleware` { #using-wsgimiddleware }
+
+/// info | Інформація
+
+Для цього потрібно встановити `a2wsgi`, наприклад за допомогою `pip install a2wsgi`.
+
+///
+
+Потрібно імпортувати `WSGIMiddleware` з `a2wsgi`.
+
+Потім обгорніть застосунок WSGI (напр., Flask) цим проміжним програмним забезпеченням.
+
+І змонтуйте його під певним шляхом.
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note | Примітка
+
+Раніше рекомендувалося використовувати `WSGIMiddleware` з `fastapi.middleware.wsgi`, але тепер його визнано застарілим.
+
+Замість цього радимо використовувати пакет `a2wsgi`. Використання залишається таким самим.
+
+Просто переконайтеся, що у вас встановлено пакет `a2wsgi`, і імпортуйте `WSGIMiddleware` коректно з `a2wsgi`.
+
+///
+
+## Перевірте { #check-it }
+
+Тепер кожен запит за шляхом `/v1/` оброблятиметься застосунком Flask.
+
+А решта - **FastAPI**.
+
+Якщо ви запустите це й перейдете на http://localhost:8000/v1/, ви побачите відповідь від Flask:
+
+```txt
+Hello, World from Flask!
+```
+
+А якщо ви перейдете на http://localhost:8000/v2, ви побачите відповідь від FastAPI:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/uk/docs/async.md b/docs/uk/docs/async.md
new file mode 100644
index 000000000..baf472054
--- /dev/null
+++ b/docs/uk/docs/async.md
@@ -0,0 +1,444 @@
+# Рівночасність і async / await { #concurrency-and-async-await }
+
+Деталі щодо синтаксису `async def` для функцій операції шляху і деякі відомості про асинхронний код, рівночасність і паралелізм.
+
+## Поспішаєте? { #in-a-hurry }
+
+TL;DR:
+
+Якщо ви використовуєте сторонні бібліотеки, які вимагають виклику з `await`, наприклад:
+
+```Python
+results = await some_library()
+```
+
+Тоді оголошуйте ваші функції операції шляху з `async def`, наприклад:
+
+```Python hl_lines="2"
+@app.get('/')
+async def read_results():
+ results = await some_library()
+ return results
+```
+
+/// note | Примітка
+
+Ви можете використовувати `await` лише всередині функцій, створених з `async def`.
+
+///
+
+---
+
+Якщо ви використовуєте сторонню бібліотеку, яка взаємодіє з чимось (база даних, API, файлова система тощо) і не підтримує використання `await` (наразі це стосується більшості бібліотек баз даних), тоді оголошуйте ваші функції операції шляху як зазвичай, просто з `def`, наприклад:
+
+```Python hl_lines="2"
+@app.get('/')
+def results():
+ results = some_library()
+ return results
+```
+
+---
+
+Якщо ваш застосунок (якимось чином) не має комунікувати з чимось іншим і чекати на відповідь, використовуйте `async def`, навіть якщо вам не потрібно використовувати `await` всередині.
+
+---
+
+Якщо ви не певні, використовуйте звичайний `def`.
+
+---
+
+Примітка: ви можете змішувати `def` і `async def` у ваших функціях операції шляху скільки завгодно і визначати кожну з них найкращим для вас способом. FastAPI зробить з ними все правильно.
+
+У будь-якому з наведених випадків FastAPI все одно працюватиме асинхронно і буде надзвичайно швидким.
+
+Але слідуючи крокам вище, він зможе зробити деякі оптимізації продуктивності.
+
+## Технічні деталі { #technical-details }
+
+Сучасні версії Python мають підтримку «асинхронного коду» за допомогою так званих «співпрограм» з синтаксисом **`async` і `await`**.
+
+Розгляньмо цю фразу по частинах у секціях нижче:
+
+- Асинхронний код
+- `async` і `await`
+- Співпрограми
+
+## Асинхронний код { #asynchronous-code }
+
+Асинхронний код означає, що мова 💬 має спосіб сказати комп’ютеру/програмі 🤖, що в певний момент у коді він 🤖 має почекати, поки «щось інше» завершиться десь ще. Скажімо, це «щось інше» називається «slow-file» 📝.
+
+Отже, в цей час комп’ютер може піти і зробити іншу роботу, доки «slow-file» 📝 завершується.
+
+Далі комп’ютер/програма 🤖 повертатиметься щоразу, коли матиме можливість, бо знову чекає, або коли він 🤖 завершив усю роботу, яка була в нього на той момент. І він 🤖 перевірить, чи якась із задач, на які він чекав, уже завершилася, виконавши все, що потрібно.
+
+Потім він 🤖 бере першу завершену задачу (скажімо, наш «slow-file» 📝) і продовжує робити те, що потрібно було зробити з нею.
+
+Це «чекати на щось інше» зазвичай стосується операцій I/O, які відносно «повільні» (порівняно зі швидкістю процесора та пам’яті з довільним доступом), наприклад, очікування:
+
+- даних від клієнта, що надсилаються мережею
+- даних, надісланих вашим застосунком, які клієнт має отримати мережею
+- вмісту файла на диску, який система має прочитати і передати вашому застосунку
+- вмісту, який ваш застосунок передав системі, щоб він був записаний на диск
+- віддаленої операції API
+- завершення операції бази даних
+- повернення результатів запиту до бази даних
+- тощо
+
+Оскільки час виконання переважно витрачається на очікування операцій I/O, їх називають операціями «I/O bound».
+
+Це називається «асинхронним», тому що комп’ютеру/програмі не потрібно бути «синхронізованими» з повільною задачею, очікуючи точного моменту її завершення, нічого не роблячи, лише щоб отримати результат задачі та продовжити роботу.
+
+Натомість, у «асинхронній» системі щойно завершена задача може трохи зачекати в черзі (кілька мікросекунд), доки комп’ютер/програма завершить те, що пішов робити, а потім повернеться, щоб забрати результати і продовжити роботу з ними.
+
+Для «синхронного» (на противагу «асинхронному») часто також використовують термін «послідовний», бо комп’ютер/програма слідує всім крокам послідовно, перш ніж перемкнутися на іншу задачу, навіть якщо ці кроки включають очікування.
+
+### Рівночасність і бургери { #concurrency-and-burgers }
+
+Ідею **асинхронного** коду, описану вище, інколи також називають **«рівночасністю»**. Вона відрізняється від **«паралелізму»**.
+
+І рівночасність, і паралелізм стосуються «різних речей, що відбуваються більш-менш одночасно».
+
+Але деталі між рівночасністю і паралелізмом досить різні.
+
+Щоб побачити різницю, уявімо таку історію про бургери:
+
+### Рівночасні бургери { #concurrent-burgers }
+
+Ви йдете зі своєю симпатією по фастфуд, стаєте в чергу, доки касир приймає замовлення у людей перед вами. 😍
+
+
+
+Потім ваша черга, ви замовляєте 2 дуже вишукані бургери для вашої симпатії і для себе. 🍔🍔
+
+
+
+Касир каже щось кухарю на кухні, щоб той знав, що треба приготувати ваші бургери (хоча зараз він готує бургери для попередніх клієнтів).
+
+
+
+Ви платите. 💸
+
+Касир дає вам номер вашої черги.
+
+
+
+Поки ви чекаєте, ви з вашою симпатією обираєте столик, сідаєте і довго розмовляєте (адже ваші бургери дуже вишукані і потребують часу на приготування).
+
+Сидячи за столиком із вашою симпатією, доки чекаєте бургери, ви можете витратити цей час, милуючись тим, яка ваша симпатія класна, мила і розумна ✨😍✨.
+
+
+
+Чекаючи і спілкуючись із вашою симпатією, час від часу ви перевіряєте номер на табло біля прилавка, щоб побачити, чи вже ваша черга.
+
+І от нарешті ваша черга. Ви підходите до прилавка, забираєте бургери і повертаєтеся до столика.
+
+
+
+Ви з вашою симпатією їсте бургери і гарно проводите час. ✨
+
+
+
+/// info | Інформація
+
+Прекрасні ілюстрації від Ketrina Thompson. 🎨
+
+///
+
+---
+
+Уявіть, що в цій історії ви - комп’ютер/програма 🤖.
+
+Поки ви в черзі, ви просто бездіяльні 😴, чекаєте своєї черги, нічого «продуктивного» не роблячи. Але черга рухається швидко, бо касир лише приймає замовлення (а не готує їх), тож це нормально.
+
+Коли ж ваша черга, ви виконуєте справді «продуктивну» роботу: переглядаєте меню, вирішуєте, що бажаєте, дізнаєтеся вибір вашої симпатії, платите, перевіряєте, що віддаєте правильну купюру чи картку, що з вас правильно списали кошти, що замовлення містить правильні позиції тощо.
+
+Але потім, хоча у вас ще немає бургерів, ваша взаємодія з касиром «на паузі» ⏸, бо вам доводиться чекати 🕙, поки бургери будуть готові.
+
+Втім, відійшовши від прилавка і сівши за столик із номерком, ви можете перемкнути 🔀 увагу на свою симпатію і «попрацювати» ⏯ 🤓 над цим. Тоді ви знову робите щось дуже «продуктивне» - фліртуєте зі своєю симпатією 😍.
+
+Потім касир 💁 каже «Я закінчив робити бургери», виводячи ваш номер на табло прилавка, але ви не підстрибуєте миттєво, щойно номер змінюється на ваш. Ви знаєте, що ніхто не вкраде ваші бургери, адже у вас є номер вашої черги, а в інших - свій.
+
+Тож ви чекаєте, поки ваша симпатія завершить історію (завершить поточну роботу ⏯/задачу 🤓), лагідно усміхаєтеся і кажете, що підете за бургерами ⏸.
+
+Потім ви йдете до прилавка 🔀, до початкової задачі, яку тепер завершено ⏯, забираєте бургери, дякуєте і несете їх до столу. Це завершує той крок/задачу взаємодії з прилавком ⏹. Натомість з’являється нова задача «їсти бургери» 🔀 ⏯, але попередня «отримати бургери» завершена ⏹.
+
+### Паралельні бургери { #parallel-burgers }
+
+А тепер уявімо, що це не «рівночасні бургери», а «паралельні бургери».
+
+Ви йдете зі своєю симпатією по паралельний фастфуд.
+
+Ви стаєте в чергу, поки кілька (скажімо, 8) касирів, які водночас є кухарями, приймають замовлення у людей перед вами.
+
+Кожен перед вами чекає, поки його бургери будуть готові, перш ніж відійти від прилавка, тому що кожен з 8 касирів одразу йде і готує бургер, перш ніж приймати наступне замовлення.
+
+
+
+Нарешті ваша черга, ви замовляєте 2 дуже вишукані бургери для вашої симпатії і для себе.
+
+Ви платите 💸.
+
+
+
+Касир іде на кухню.
+
+Ви чекаєте, стоячи перед прилавком 🕙, щоб ніхто інший не забрав ваші бургери раніше, ніж ви, адже номерків черги немає.
+
+
+
+Оскільки ви з вашою симпатією зайняті тим, щоб ніхто не став перед вами і не забрав ваші бургери, щойно вони з’являться, ви не можете приділяти увагу своїй симпатії. 😞
+
+Це «синхронна» робота, ви «синхронізовані» з касиром/кухарем 👨🍳. Вам доводиться чекати 🕙 і бути тут у точний момент, коли касир/кухар 👨🍳 завершить бургери і віддасть їх вам, інакше хтось інший може їх забрати.
+
+
+
+Потім ваш касир/кухар 👨🍳 нарешті повертається з вашими бургерами після довгого очікування 🕙 перед прилавком.
+
+
+
+Ви берете бургери і йдете до столика зі своєю симпатією.
+
+Ви просто їх їсте - і все. ⏹
+
+
+
+Багато розмов чи флірту не було, бо більшість часу пішла на очікування 🕙 перед прилавком. 😞
+
+/// info | Інформація
+
+Прекрасні ілюстрації від Ketrina Thompson. 🎨
+
+///
+
+---
+
+У цьому сценарії паралельних бургерів ви - комп’ютер/програма 🤖 з двома процесорами (ви і ваша симпатія), які обидва чекають 🕙 і приділяють увагу ⏯ «очікуванню біля прилавка» 🕙 тривалий час.
+
+У закладу фастфуду 8 процесорів (касира/кухаря). У той час як у закладі з рівночасними бургерами могло бути лише 2 (один касир і один кухар).
+
+Та все одно фінальний досвід не найкращий. 😞
+
+---
+
+Це була б паралельна історія про бургери. 🍔
+
+Для більш «реального» прикладу уявіть банк.
+
+До недавнього часу більшість банків мали кілька касирів 👨💼👨💼👨💼👨💼 і велику чергу 🕙🕙🕙🕙🕙🕙🕙🕙.
+
+Усі касири робили всю роботу з одним клієнтом за іншим 👨💼⏯.
+
+І вам доводилося 🕙 довго стояти в черзі, інакше ви втратите свою чергу.
+
+Ви, напевно, не хотіли б брати свою симпатію 😍 із собою у справи до банку 🏦.
+
+### Висновок про бургери { #burger-conclusion }
+
+У цьому сценарії «фастфуд із вашою симпатією», оскільки є багато очікування 🕙, значно доцільніше мати рівночасну систему ⏸🔀⏯.
+
+Так є у більшості вебзастосунків.
+
+Багато-багато користувачів, але ваш сервер чекає 🕙 на їхнє не надто гарне з’єднання, щоб вони надіслали свої запити.
+
+А потім знову чекає 🕙 на повернення відповідей.
+
+Це «очікування» 🕙 вимірюється у мікросекундах, але все ж, у сумі - це багато очікування в підсумку.
+
+Ось чому дуже логічно використовувати асинхронний ⏸🔀⏯ код для веб API.
+
+Такий тип асинхронності зробив NodeJS популярним (хоча NodeJS не є паралельним), і це сила Go як мови програмування.
+
+І такий самий рівень продуктивності ви отримуєте з **FastAPI**.
+
+А оскільки можна мати паралелізм і асинхронність одночасно, ви отримуєте вищу продуктивність, ніж більшість протестованих фреймворків NodeJS, і на рівні з Go, який є компільованою мовою, ближчою до C (усе завдяки Starlette).
+
+### Чи краща рівночасність за паралелізм? { #is-concurrency-better-than-parallelism }
+
+Ні! Це не мораль історії.
+
+Рівночасність відрізняється від паралелізму. І вона краща у конкретних сценаріях, що містять багато очікування. Через це зазвичай вона значно краща за паралелізм для розробки вебзастосунків. Але не для всього.
+
+Щоб урівноважити це, уявімо коротку історію:
+
+> Ви маєте прибрати великий брудний будинок.
+
+*Так, це вся історія*.
+
+---
+
+Тут немає очікування 🕙 - просто багато роботи, яку треба зробити, у багатьох місцях будинку.
+
+У вас могли б бути «черги» як у прикладі з бургерами: спочатку вітальня, потім кухня. Але оскільки ви ні на що не чекаєте 🕙, а просто прибираєте, «черги» нічого не змінять.
+
+Завершення займе той самий час із «чергами» чи без (рівночасність), і ви виконаєте той самий обсяг роботи.
+
+Але в цьому випадку, якби ви могли привести 8 колишніх касирів/кухарів/тепер прибиральників, і кожен з них (разом із вами) взяв би свою зону будинку для прибирання, ви могли б виконати всю роботу паралельно — з додатковою допомогою — і завершити значно швидше.
+
+У цьому сценарії кожен з прибиральників (включно з вами) був би процесором, що виконує свою частину роботи.
+
+І оскільки більшість часу виконання займає реальна робота (а не очікування), а роботу на комп’ютері виконує CPU, ці проблеми називають «CPU bound».
+
+---
+
+Поширені приклади «CPU bound» операцій - це речі, що потребують складної математичної обробки.
+
+Наприклад:
+
+- **Обробка аудіо** або **зображень**.
+- **Комп’ютерний зір**: зображення складається з мільйонів пікселів, кожен піксель має 3 значення/кольори, обробка зазвичай потребує обчислення чогось над цими пікселями, усіма одночасно.
+- **Машинне навчання**: зазвичай потребує великої кількості множень «матриць» і «векторів». Уявіть величезну таблицю з числами і множення всіх їх разом одночасно.
+- **Глибоке навчання**: це підгалузь машинного навчання, тож те саме застосовується. Просто тут не одна таблиця чисел для множення, а величезний їх набір, і в багатьох випадках ви використовуєте спеціальний процесор для побудови та/або використання цих моделей.
+
+### Рівночасність + паралелізм: веб + машинне навчання { #concurrency-parallelism-web-machine-learning }
+
+З **FastAPI** ви можете скористатися рівночасністю, що дуже поширена у веброзробці (та ж головна принада NodeJS).
+
+Але ви також можете використати переваги паралелізму і багатопроцесорності (наявність кількох процесів, що працюють паралельно) для навантажень «CPU bound», як у системах машинного навчання.
+
+Це, плюс простий факт, що Python є основною мовою для **Data Science**, машинного навчання і особливо глибокого навчання, робить FastAPI дуже вдалим вибором для веб API та застосунків Data Science / машинного навчання (серед багатьох інших).
+
+Щоб побачити, як досягти цього паралелізму у продакшні, див. розділ про [Розгортання](deployment/index.md){.internal-link target=_blank}.
+
+## `async` і `await` { #async-and-await }
+
+Сучасні версії Python мають дуже інтуїтивний спосіб визначення асинхронного коду. Це робить його схожим на звичайний «послідовний» код і виконує «очікування» за вас у відповідні моменти.
+
+Коли є операція, яка вимагатиме очікування перед поверненням результатів і має підтримку цих нових можливостей Python, ви можете написати її так:
+
+```Python
+burgers = await get_burgers(2)
+```
+
+Ключ тут - `await`. Він каже Python, що потрібно почекати ⏸, поки `get_burgers(2)` завершить свою роботу 🕙, перш ніж зберегти результати в `burgers`. Завдяки цьому Python знатиме, що може піти і зробити щось інше 🔀 ⏯ тим часом (наприклад, прийняти інший запит).
+
+Щоб `await` працював, він має бути всередині функції, що підтримує цю асинхронність. Для цього просто оголосіть її як `async def`:
+
+```Python hl_lines="1"
+async def get_burgers(number: int):
+ # Виконайте деякі асинхронні дії, щоб створити бургери
+ return burgers
+```
+
+...замість `def`:
+
+```Python hl_lines="2"
+# Це не асинхронно
+def get_sequential_burgers(number: int):
+ # Виконайте деякі послідовні дії, щоб створити бургери
+ return burgers
+```
+
+З `async def` Python знає, що всередині цієї функції він має відслідковувати вирази `await`, і що він може «ставити на паузу» ⏸ виконання цієї функції і йти робити щось інше 🔀, перш ніж повернутися.
+
+Коли ви хочете викликати функцію, визначену з `async def`, ви маєте «очікувати» її. Тож це не спрацює:
+
+```Python
+# Це не спрацює, тому що get_burgers визначено як: async def
+burgers = get_burgers(2)
+```
+
+---
+
+Отже, якщо ви використовуєте бібліотеку, яку можна викликати з `await`, вам потрібно створити функцію операції шляху, що її використовує, з `async def`, як тут:
+
+```Python hl_lines="2-3"
+@app.get('/burgers')
+async def read_burgers():
+ burgers = await get_burgers(2)
+ return burgers
+```
+
+### Більше технічних деталей { #more-technical-details }
+
+Ви могли помітити, що `await` можна використовувати лише всередині функцій, визначених з `async def`.
+
+А водночас функції, визначені з `async def`, потрібно «очікувати». Тож функції з `async def` також можна викликати лише всередині функцій, визначених з `async def`.
+
+Тож як же викликати першу `async`-функцію - курка чи яйце?
+
+Якщо ви працюєте з **FastAPI**, вам не потрібно про це турбуватися, адже цією «першою» функцією буде ваша функція операції шляху, і FastAPI знатиме, як учинити правильно.
+
+Але якщо ви хочете використовувати `async` / `await` без FastAPI, ви також можете це зробити.
+
+### Пишемо свій власний async-код { #write-your-own-async-code }
+
+Starlette (і **FastAPI**) базуються на AnyIO, що робить їх сумісними як зі стандартною бібліотекою Python asyncio, так і з Trio.
+
+Зокрема, ви можете безпосередньо використовувати AnyIO для ваших просунутих сценаріїв рівночасності, що потребують складніших патернів у вашому коді.
+
+І навіть якщо ви не використовували FastAPI, ви могли б писати свої власні async-застосунки з AnyIO, щоб мати високу сумісність і отримати його переваги (наприклад, *структурована рівночасність*).
+
+Я створив іншу бібліотеку поверх AnyIO, як тонкий шар, щоб дещо покращити анотації типів і отримати кращу **автодопомогу** (autocompletion), **вбудовані помилки** (inline errors) тощо. Вона також має дружній вступ і навчальний посібник, щоб допомогти вам **зрозуміти** і написати **власний async-код**: Asyncer. Вона буде особливо корисною, якщо вам потрібно **поєднувати async-код зі звичайним** (блокуючим/синхронним) кодом.
+
+### Інші форми асинхронного коду { #other-forms-of-asynchronous-code }
+
+Такий стиль використання `async` і `await` відносно новий у мові.
+
+Але він значно полегшує роботу з асинхронним кодом.
+
+Такий самий (або майже ідентичний) синтаксис нещодавно з’явився в сучасних версіях JavaScript (у Browser і NodeJS).
+
+До цього робота з асинхронним кодом була значно складнішою.
+
+У попередніх версіях Python ви могли використовувати потоки (threads) або Gevent. Але код набагато складніший для розуміння, налагодження і мислення про нього.
+
+У попередніх версіях NodeJS/Browser JavaScript ви б використовували «callbacks», що призводить до «callback hell».
+
+## Співпрограми { #coroutines }
+
+**Співпрограма** - це просто дуже вишукана назва для об’єкта, який повертає функція `async def`. Python знає, що це щось на кшталт функції, яку можна запустити і яка завершиться в певний момент, але яку також можна поставити на паузу ⏸ всередині, коли є `await`.
+
+Але всю цю функціональність використання асинхронного коду з `async` і `await` часто підсумовують як використання «співпрограм». Це порівняно з головною ключовою особливістю Go - «Goroutines».
+
+## Висновок { #conclusion }
+
+Погляньмо на ту саму фразу ще раз:
+
+> Сучасні версії Python мають підтримку «асинхронного коду» за допомогою так званих «співпрограм», з синтаксисом **`async` і `await`**.
+
+Тепер це має більше сенсу. ✨
+
+Усе це приводить у дію FastAPI (через Starlette) і дає йому таку вражаючу продуктивність.
+
+## Дуже технічні деталі { #very-technical-details }
+
+/// warning | Попередження
+
+Ймовірно, ви можете пропустити це.
+
+Це дуже технічні деталі про те, як **FastAPI** працює «під капотом».
+
+Якщо у вас є чимало технічних знань (співпрограми, потоки, блокування тощо) і вам цікаво, як FastAPI обробляє `async def` проти звичайного `def`, - вперед.
+
+///
+
+### Функції операції шляху { #path-operation-functions }
+
+Коли ви оголошуєте функцію операції шляху зі звичайним `def` замість `async def`, вона виконується у зовнішньому пулі потоків (threadpool), який потім «очікується», замість прямого виклику (оскільки прямий виклик блокував би сервер).
+
+Якщо ви прийшли з іншого async-фреймворку, який не працює так, як описано вище, і звикли визначати тривіальні, лише обчислювальні функції операції шляху зі звичайним `def` заради крихітного виграшу у продуктивності (близько 100 наносекунд), зверніть увагу, що у **FastAPI** ефект буде протилежним. У таких випадках краще використовувати `async def`, якщо тільки ваші функції операції шляху не використовують код, що виконує блокуюче I/O.
+
+Втім, у будь-якій ситуації є велика ймовірність, що **FastAPI** [все одно буде швидшим](index.md#performance){.internal-link target=_blank} (або принаймні порівнянним) за ваш попередній фреймворк.
+
+### Залежності { #dependencies }
+
+Те саме стосується і [залежностей](tutorial/dependencies/index.md){.internal-link target=_blank}. Якщо залежність є стандартною функцією `def` замість `async def`, вона виконується у зовнішньому пулі потоків.
+
+### Підзалежності { #sub-dependencies }
+
+Ви можете мати кілька залежностей і [підзалежностей](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank}, які вимагають одна одну (як параметри визначень функцій). Деякі з них можуть бути створені з `async def`, а деякі - зі звичайним `def`. Все працюватиме, і ті, що створені зі звичайним `def`, будуть викликані у зовнішньому потоці (з пулу потоків), а не «очікувані».
+
+### Інші допоміжні функції { #other-utility-functions }
+
+Будь-яка інша допоміжна функція, яку ви викликаєте безпосередньо, може бути створена зі звичайним `def` або `async def`, і FastAPI не впливатиме на спосіб її виклику.
+
+Це відрізняється від функцій, які FastAPI викликає за вас: функції операції шляху і залежності.
+
+Якщо ваша допоміжна функція є звичайною функцією з `def`, її буде викликано безпосередньо (як ви написали у своєму коді), не в пулі потоків; якщо функція створена з `async def`, тоді вам слід використовувати `await` при її виклику у вашому коді.
+
+---
+
+Знову ж таки, це дуже технічні деталі, які, ймовірно, стануть у пригоді, якщо ви спеціально їх шукали.
+
+Інакше вам вистачить настанов із розділу вище: Поспішаєте?.
diff --git a/docs/uk/docs/benchmarks.md b/docs/uk/docs/benchmarks.md
new file mode 100644
index 000000000..d53b7ee98
--- /dev/null
+++ b/docs/uk/docs/benchmarks.md
@@ -0,0 +1,34 @@
+# Бенчмарки { #benchmarks }
+
+Незалежні бенчмарки TechEmpower показують, що застосунки FastAPI, запущені під керуванням Uvicorn, є одним із найшвидших доступних фреймворків Python, поступаючись лише самим Starlette і Uvicorn (використовуються FastAPI внутрішньо).
+
+Але переглядаючи бенчмарки та порівняння, майте на увазі таке.
+
+## Бенчмарки та швидкість { #benchmarks-and-speed }
+
+Під час перегляду бенчмарків часто порівнюють кілька інструментів різних типів як рівноцінні.
+
+Зокрема, разом порівнюють Uvicorn, Starlette і FastAPI (серед багатьох інших інструментів).
+
+Чим простіше завдання, яке розв'язує інструмент, тим кращою буде продуктивність. І більшість бенчмарків не перевіряють додаткові можливості, що надає інструмент.
+
+Ієрархія приблизно така:
+
+* Uvicorn: сервер ASGI
+ * Starlette: (використовує Uvicorn) веб-мікрофреймворк
+ * FastAPI: (використовує Starlette) мікрофреймворк для API з низкою додаткових можливостей для створення API, з валідацією даних тощо.
+
+* Uvicorn:
+ * Матиме найвищу продуктивність, адже майже не містить додаткового коду окрім власне сервера.
+ * Ви не писатимете застосунок безпосередньо на Uvicorn. Це означало б, що ваш код мав би включати принаймні приблизно весь код, який надає Starlette (або FastAPI). І якщо зробити так, ваш кінцевий застосунок матиме ті самі накладні витрати, що й під час використання фреймворку, який мінімізує код застосунку та помилки.
+ * Якщо ви порівнюєте Uvicorn, порівнюйте його з Daphne, Hypercorn, uWSGI тощо. Сервери застосунків.
+* Starlette:
+ * Матиме наступну за швидкістю продуктивність після Uvicorn. Насправді Starlette використовує Uvicorn для запуску. Тож вона може бути «повільнішою» за Uvicorn лише через необхідність виконувати більше коду.
+ * Але надає інструменти для створення простих веб-застосунків із маршрутизацією на основі шляхів тощо.
+ * Якщо ви порівнюєте Starlette, порівнюйте її з Sanic, Flask, Django тощо. Веб-фреймворки (або мікрофреймворки).
+* FastAPI:
+ * Аналогічно до того, як Starlette використовує Uvicorn і не може бути швидшою за нього, FastAPI використовує Starlette, тож не може бути швидшою за неї.
+ * FastAPI надає більше можливостей поверх Starlette. Можливості, які майже завжди потрібні під час створення API, як-от валідація та серіалізація даних. І, використовуючи його, ви безкоштовно отримуєте автоматичну документацію (автоматична документація навіть не додає накладних витрат під час роботи застосунку - вона генерується під час запуску).
+ * Якби ви не використовували FastAPI і застосували Starlette безпосередньо (або інший інструмент, наприклад Sanic, Flask, Responder тощо), вам довелося б самостійно реалізувати всю валідацію та серіалізацію даних. Тож ваш кінцевий застосунок усе одно мав би ті самі накладні витрати, ніби він був створений із використанням FastAPI. І в багатьох випадках саме ця валідація та серіалізація даних становить найбільший обсяг коду в застосунках.
+ * Отже, використовуючи FastAPI, ви заощаджуєте час розробки, зменшуєте кількість помилок і рядків коду та, ймовірно, отримуєте таку саму (або кращу) продуктивність, як і без нього (адже інакше вам довелося б реалізувати все це у власному коді).
+ * Якщо ви порівнюєте FastAPI, порівнюйте його з веб-фреймворком (або набором інструментів), який надає валідацію даних, серіалізацію та документацію, наприклад Flask-apispec, NestJS, Molten тощо. Фреймворки з вбудованою автоматичною валідацією даних, серіалізацією та документацією.
diff --git a/docs/uk/docs/deployment/cloud.md b/docs/uk/docs/deployment/cloud.md
new file mode 100644
index 000000000..a17aaf259
--- /dev/null
+++ b/docs/uk/docs/deployment/cloud.md
@@ -0,0 +1,24 @@
+# Розгортання FastAPI у хмарних постачальників { #deploy-fastapi-on-cloud-providers }
+
+Ви можете використовувати практично **будь-якого хмарного постачальника**, щоб розгорнути свій застосунок FastAPI.
+
+У більшості випадків основні хмарні постачальники мають інструкції з розгортання FastAPI у них.
+
+## FastAPI Cloud { #fastapi-cloud }
+
+**FastAPI Cloud** створено тим самим автором і командою, що стоять за **FastAPI**.
+
+Воно спрощує процес **створення**, **розгортання** та **доступу** до API з мінімальними зусиллями.
+
+Воно переносить той самий **досвід розробника** зі створення застосунків із FastAPI на їх **розгортання** у хмарі. 🎉
+
+FastAPI Cloud є основним спонсором і джерелом фінансування проєктів з відкритим кодом *FastAPI and friends*. ✨
+
+## Хмарні постачальники - спонсори { #cloud-providers-sponsors }
+
+Деякі інші хмарні постачальники ✨ [**спонсорують FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨ також. 🙇
+
+Можливо, ви захочете розглянути їх, щоб дотримуватися їхніх інструкцій і спробувати їхні сервіси:
+
+* Render
+* Railway
diff --git a/docs/uk/docs/deployment/concepts.md b/docs/uk/docs/deployment/concepts.md
new file mode 100644
index 000000000..07ad31440
--- /dev/null
+++ b/docs/uk/docs/deployment/concepts.md
@@ -0,0 +1,321 @@
+# Концепції розгортання { #deployments-concepts }
+
+Під час розгортання застосунку **FastAPI** (або будь-якого веб-API) є кілька концепцій, які, ймовірно, вас цікавлять, і, спираючись на них, ви зможете знайти **найвідповідніший** спосіб **розгорнути ваш застосунок**.
+
+Деякі важливі концепції:
+
+- Безпека - HTTPS
+- Запуск під час старту
+- Перезапуски
+- Реплікація (кількість запущених процесів)
+- Пам'ять
+- Попередні кроки перед стартом
+
+Подивимось, як вони впливають на **розгортання**.
+
+Зрештою головна мета - **обслуговувати клієнтів вашого API** так, щоб це було **безпечним**, з **мінімумом перерв у роботі**, і щоб **обчислювальні ресурси** (наприклад, віддалені сервери/віртуальні машини) використовувалися якомога ефективніше. 🚀
+
+Нижче я трохи більше розповім про ці **концепції**, і, сподіваюся, це дасть вам потрібну **інтуїцію**, щоб вирішувати, як розгортати ваш API в дуже різних середовищах, можливо, навіть у **майбутніх**, яких ще не існує.
+
+Враховуючи ці концепції, ви зможете **оцінювати та проєктувати** найкращий спосіб розгортання **ваших власних API**.
+
+У наступних розділах я наведу більш **конкретні рецепти** розгортання застосунків FastAPI.
+
+А поки перегляньмо ці важливі **концептуальні ідеї**. Вони також застосовні до будь-якого іншого типу веб-API. 💡
+
+## Безпека - HTTPS { #security-https }
+
+У [попередньому розділі про HTTPS](https.md){.internal-link target=_blank} ми дізналися, як HTTPS забезпечує шифрування для вашого API.
+
+Ми також бачили, що HTTPS зазвичай надається компонентом, **зовнішнім** щодо вашого серверного застосунку, - **TLS Termination Proxy**.
+
+І має бути щось, що відповідає за **оновлення сертифікатів HTTPS** - це може бути той самий компонент або інший.
+
+### Приклади інструментів для HTTPS { #example-tools-for-https }
+
+Деякі інструменти, які можна використовувати як TLS Termination Proxy:
+
+- Traefik
+ - Автоматично обробляє оновлення сертифікатів ✨
+- Caddy
+ - Автоматично обробляє оновлення сертифікатів ✨
+- Nginx
+ - З зовнішнім компонентом на кшталт Certbot для оновлення сертифікатів
+- HAProxy
+ - З зовнішнім компонентом на кшталт Certbot для оновлення сертифікатів
+- Kubernetes з Ingress Controller, наприклад Nginx
+ - З зовнішнім компонентом на кшталт cert-manager для оновлення сертифікатів
+- Обробляється внутрішньо хмарним провайдером як частина їхніх сервісів (див. нижче 👇)
+
+Ще один варіант - використати **хмарний сервіс**, який зробить більше роботи, зокрема налаштує HTTPS. Можуть бути обмеження або додаткова вартість тощо. Але у такому разі вам не потрібно самостійно налаштовувати TLS Termination Proxy.
+
+У наступних розділах я покажу кілька конкретних прикладів.
+
+---
+
+Далі всі наступні концепції стосуються програми, яка запускає ваш фактичний API (наприклад, Uvicorn).
+
+## Програма і процес { #program-and-process }
+
+Ми багато говоритимемо про запущений «процес», тож корисно чітко розуміти, що це означає, і чим відрізняється від слова «програма».
+
+### Що таке програма { #what-is-a-program }
+
+Слово **програма** зазвичай вживають для опису багатьох речей:
+
+- **Код**, який ви пишете, **файли Python**.
+- **Файл**, який може бути **виконаний** операційною системою, наприклад: `python`, `python.exe` або `uvicorn`.
+- Конкретна програма під час **виконання** в операційній системі, що використовує CPU та зберігає дані в пам'яті. Це також називають **процесом**.
+
+### Що таке процес { #what-is-a-process }
+
+Слово **процес** зазвичай використовують у більш специфічному значенні, маючи на увазі саме те, що виконується в операційній системі (як у попередньому пункті):
+
+- Конкретна програма під час **виконання** в операційній системі.
+ - Це не про файл і не про код, це **конкретно** про те, що **виконується** та керується операційною системою.
+- Будь-яка програма, будь-який код **може щось робити** лише під час **виконання**. Тобто коли **процес запущений**.
+- Процес може бути **завершений** (або «kill») вами чи операційною системою. У цей момент він припиняє виконання і **більше нічого не може робити**.
+- Кожен застосунок, який працює на вашому комп'ютері, має певний процес за собою: кожна запущена програма, кожне вікно тощо. Зазвичай на комп'ютері одночасно працює **багато процесів**.
+- **Кілька процесів** **однієї й тієї самої програми** можуть працювати одночасно.
+
+Якщо ви відкриєте «диспетчер завдань» або «системний монітор» (чи подібні інструменти) в операційній системі, ви побачите багато таких процесів.
+
+Наприклад, ви, ймовірно, побачите кілька процесів того самого браузера (Firefox, Chrome, Edge тощо). Зазвичай він запускає один процес на вкладку плюс деякі додаткові процеси.
+
+
+
+---
+
+Тепер, коли ми знаємо різницю між термінами **процес** і **програма**, продовжимо говорити про розгортання.
+
+## Запуск під час старту { #running-on-startup }
+
+У більшості випадків, коли ви створюєте веб-API, ви хочете, щоб він **працював постійно**, без перерв, щоб клієнти завжди мали до нього доступ. Звісно, якщо немає особливих причин запускати його лише в певних ситуаціях. Але зазвичай ви хочете, щоб він постійно працював і був **доступний**.
+
+### На віддаленому сервері { #in-a-remote-server }
+
+Коли ви налаштовуєте віддалений сервер (хмарний сервер, віртуальну машину тощо), найпростіше - використовувати `fastapi run` (який використовує Uvicorn) або щось схоже, вручну, так само, як під час локальної розробки.
+
+І це працюватиме та буде корисним **під час розробки**.
+
+Але якщо ви втратите з'єднання з сервером, **запущений процес**, найімовірніше, завершиться.
+
+І якщо сервер буде перезавантажено (наприклад, після оновлень або міграцій у хмарного провайдера), ви, ймовірно, **не помітите цього**. І через це ви навіть не знатимете, що треба вручну перезапустити процес. У результаті ваш API просто залишиться «мертвим». 😱
+
+### Автоматичний запуск під час старту { #run-automatically-on-startup }
+
+Загалом ви, напевно, захочете, щоб серверна програма (наприклад, Uvicorn) запускалася автоматично під час старту сервера і без будь-якого **людського втручання**, щоб завжди був запущений процес із вашим API (наприклад, Uvicorn із вашим FastAPI-застосунком).
+
+### Окрема програма { #separate-program }
+
+Щоб цього досягти, зазвичай використовують **окрему програму**, яка гарантує запуск вашого застосунку під час старту. І в багатьох випадках вона також забезпечує запуск інших компонентів або застосунків, наприклад бази даних.
+
+### Приклади інструментів для запуску під час старту { #example-tools-to-run-at-startup }
+
+Приклади інструментів, які можуть це робити:
+
+- Docker
+- Kubernetes
+- Docker Compose
+- Docker у режимі Swarm
+- Systemd
+- Supervisor
+- Обробляється внутрішньо хмарним провайдером як частина їхніх сервісів
+- Інші...
+
+У наступних розділах я наведу більш конкретні приклади.
+
+## Перезапуски { #restarts }
+
+Подібно до забезпечення запуску застосунку під час старту системи, ви, ймовірно, також захочете гарантувати його **перезапуск** після збоїв.
+
+### Ми помиляємося { #we-make-mistakes }
+
+Ми, люди, постійно робимо **помилки**. Майже завжди у програмному забезпеченні є приховані **помилки**. 🐛
+
+І ми як розробники постійно покращуємо код, знаходячи ці помилки та додаючи нові можливості (можливо, теж додаючи нові помилки 😅).
+
+### Невеликі помилки обробляються автоматично { #small-errors-automatically-handled }
+
+Створюючи веб-API з FastAPI, якщо в нашому коді є помилка, FastAPI зазвичай обмежує її одним запитом, який цю помилку спровокував. 🛡
+
+Клієнт отримає **500 Internal Server Error** для цього запиту, але застосунок продовжить працювати для наступних запитів замість повного краху.
+
+### Великі помилки - крахи { #bigger-errors-crashes }
+
+Втім, бувають випадки, коли ми пишемо код, який **падає весь застосунок**, спричиняючи крах Uvicorn і Python. 💥
+
+І все ж ви, ймовірно, не захочете, щоб застосунок залишався «мертвим» через помилку в одному місці - ви, напевно, хочете, щоб він **продовжував працювати** принаймні для тих *операцій шляху*, що не зламані.
+
+### Перезапуск після краху { #restart-after-crash }
+
+Але в таких випадках із серйозними помилками, що призводять до краху запущеного **процесу**, потрібен зовнішній компонент, відповідальний за **перезапуск** процесу, принаймні кілька разів...
+
+/// tip | Порада
+
+...Хоча якщо весь застосунок просто **миттєво падає**, безглуздо перезапускати його безкінечно. Але в таких випадках ви, ймовірно, помітите це під час розробки або принаймні відразу після розгортання.
+
+Тож зосередьмося на основних випадках, коли у майбутньому він може повністю падати за певних обставин, і тоді все ще має сенс його перезапускати.
+
+///
+
+Ймовірно, ви захочете мати відокремлений **зовнішній компонент**, який відповідає за перезапуск застосунку, адже до того моменту сам застосунок з Uvicorn і Python уже впав, і нічого в тому ж коді цієї ж програми зробити не зможе.
+
+### Приклади інструментів для автоматичного перезапуску { #example-tools-to-restart-automatically }
+
+У більшості випадків той самий інструмент, який використовується для **запуску програми під час старту**, також використовується для автоматичних **перезапусків**.
+
+Наприклад, це можуть забезпечувати:
+
+- Docker
+- Kubernetes
+- Docker Compose
+- Docker у режимі Swarm
+- Systemd
+- Supervisor
+- Обробляється внутрішньо хмарним провайдером як частина їхніх сервісів
+- Інші...
+
+## Реплікація - процеси та пам'ять { #replication-processes-and-memory }
+
+У застосунку FastAPI, використовуючи серверну програму, як-от команду `fastapi`, що запускає Uvicorn, один запуск в **одному процесі** може обслуговувати кількох клієнтів рівночасно.
+
+Але часто ви захочете запускати кілька процесів-працівників одночасно.
+
+### Кілька процесів - працівники { #multiple-processes-workers }
+
+Якщо у вас більше клієнтів, ніж може обробити один процес (наприклад, якщо віртуальна машина не надто потужна) і на сервері є **кілька ядер** CPU, тоді ви можете запустити **кілька процесів** із тим самим застосунком паралельно і розподіляти запити між ними.
+
+Коли ви запускаєте **кілька процесів** того самого програмного забезпечення API, їх зазвичай називають **працівниками** (workers).
+
+### Процеси-працівники і порти { #worker-processes-and-ports }
+
+Пам'ятаєте з документації [Про HTTPS](https.md){.internal-link target=_blank}, що на сервері лише один процес може слухати певну комбінацію порту та IP-адреси?
+
+Це досі так.
+
+Отже, щоб мати **кілька процесів** одночасно, має бути **єдиний процес, який слухає порт**, і який далі якимось чином передає комунікацію кожному процесу-працівнику.
+
+### Пам'ять на процес { #memory-per-process }
+
+Коли програма завантажує щось у пам'ять, наприклад модель машинного навчання в змінну або вміст великого файлу в змінну, все це **споживає частину пам'яті (RAM)** сервера.
+
+І кілька процесів зазвичай **не діляться пам'яттю**. Це означає, що кожен запущений процес має власні речі, змінні та пам'ять. І якщо у вашому коді споживається багато пам'яті, **кожен процес** споживатиме еквівалентний обсяг пам'яті.
+
+### Пам'ять сервера { #server-memory }
+
+Наприклад, якщо ваш код завантажує модель машинного навчання розміром **1 GB**, то при запуску одного процесу з вашим API він споживатиме щонайменше 1 GB RAM. А якщо ви запустите **4 процеси** (4 працівники) - кожен споживатиме 1 GB RAM. Отже, загалом ваш API споживатиме **4 GB RAM**.
+
+І якщо ваш віддалений сервер або віртуальна машина має лише 3 GB RAM, спроба використати понад 4 GB призведе до проблем. 🚨
+
+### Кілька процесів - приклад { #multiple-processes-an-example }
+
+У цьому прикладі є **керівний процес** (Manager Process), який запускає і контролює два **процеси-працівники**.
+
+Цей керівний процес, імовірно, саме і слухатиме **порт** на IP. І він передаватиме всю комунікацію процесам-працівникам.
+
+Ці процеси-працівники виконуватимуть ваш застосунок, здійснюватимуть основні обчислення, щоб отримати **запит** і повернути **відповідь**, і завантажуватимуть усе, що ви зберігаєте в змінних у RAM.
+
+
+
+Звісно, на тій самій машині, окрім вашого застосунку, зазвичай працюватимуть **інші процеси**.
+
+Цікавий момент: відсоток **використання CPU** кожним процесом може сильно **варіюватися** з часом, тоді як **пам'ять (RAM)** зазвичай залишається більш-менш **стабільною**.
+
+Якщо у вас API, що виконує порівняний обсяг обчислень щоразу і у вас багато клієнтів, тоді **використання CPU** також, ймовірно, буде *стабільним* (замість постійних швидких коливань).
+
+### Приклади інструментів і стратегій реплікації { #examples-of-replication-tools-and-strategies }
+
+Є кілька підходів для цього, і про конкретні стратегії я розповім у наступних розділах, наприклад, коли говоритимемо про Docker і контейнери.
+
+Головне обмеження: має бути **єдиний** компонент, що обробляє **порт** на **публічній IP-адресі**. А тоді він має мати спосіб **передавати** комунікацію реплікованим **процесам/працівникам**.
+
+Ось кілька можливих комбінацій і стратегій:
+
+- **Uvicorn** з `--workers`
+ - Один **менеджер процесів** Uvicorn слухатиме **IP** і **порт** та запускатиме **кілька процесів-працівників Uvicorn**.
+- **Kubernetes** та інші розподілені **системи контейнерів**
+ - Щось на рівні **Kubernetes** слухатиме **IP** і **порт**. Реплікація відбуватиметься через **кілька контейнерів**, у кожному з яких запущено **один процес Uvicorn**.
+- **Хмарні сервіси**, що роблять це за вас
+ - Хмарний сервіс, ймовірно, **забезпечить реплікацію за вас**. Він може дозволяти визначити **процес для запуску** або **образ контейнера** для використання; у будь-якому разі це, найімовірніше, буде **один процес Uvicorn**, а сервіс відповідатиме за його реплікацію.
+
+/// tip | Порада
+
+Не хвилюйтеся, якщо деякі пункти про **контейнери**, Docker чи Kubernetes поки що не дуже зрозумілі.
+
+Я розповім більше про образи контейнерів, Docker, Kubernetes тощо в майбутньому розділі: [FastAPI у контейнерах - Docker](docker.md){.internal-link target=_blank}.
+
+///
+
+## Попередні кроки перед стартом { #previous-steps-before-starting }
+
+Є багато випадків, коли потрібно виконати деякі кроки **перед стартом** вашого застосунку.
+
+Наприклад, ви можете захотіти запустити **міграції бази даних**.
+
+Але найчастіше ці кроки потрібно виконувати лише **один раз**.
+
+Отже, ви захочете мати **єдиний процес**, який виконає ці **попередні кроки** перед запуском застосунку.
+
+І потрібно переконатися, що їх виконує саме один процес навіть якщо потім ви запускаєте **кілька процесів** (кілька працівників) для самого застосунку. Якщо ці кроки виконуватимуться **кількома процесами**, вони **подвоюватимуть** роботу, виконуючи її **паралельно**, і якщо кроки делікатні, як-от міграції бази даних, це може призвести до конфліктів.
+
+Звісно, бувають випадки, коли немає проблеми запускати попередні кроки кілька разів - тоді все набагато простіше.
+
+/// tip | Порада
+
+Також майте на увазі, що залежно від вашого налаштування інколи **попередні кроки взагалі не потрібні** перед запуском застосунку.
+
+У такому разі про це можна не турбуватися. 🤷
+
+///
+
+### Приклади стратегій попередніх кроків { #examples-of-previous-steps-strategies }
+
+Це **значною мірою залежить** від способу **розгортання вашої системи** і, ймовірно, буде пов'язано зі способом запуску програм, обробки перезапусків тощо.
+
+Ось кілька можливих ідей:
+
+- «Init Container» у Kubernetes, який виконується перед вашим контейнером застосунку
+- bash-скрипт, який виконує попередні кроки, а потім запускає ваш застосунок
+ - Вам усе одно потрібен спосіб запускати/перезапускати цей bash-скрипт, виявляти помилки тощо.
+
+/// tip | Порада
+
+Я наведу більш конкретні приклади для цього з контейнерами у майбутньому розділі: [FastAPI у контейнерах - Docker](docker.md){.internal-link target=_blank}.
+
+///
+
+## Використання ресурсів { #resource-utilization }
+
+Ваш сервер(и) - це **ресурс**, який ви можете споживати/**використовувати** вашими програмами: час обчислень на CPU та доступну RAM.
+
+Скільки системних ресурсів ви хочете споживати/використовувати? Легко подумати «небагато», але насправді ви, ймовірно, захочете споживати **настільки багато, наскільки можливо без краху**.
+
+Якщо ви платите за 3 сервери, але використовуєте лише трохи їх RAM і CPU, ви, ймовірно, **марнуєте гроші** 💸 і, можливо, **електроенергію серверів** 🌎 тощо.
+
+У такому разі може бути краще мати лише 2 сервери й використовувати більший відсоток їхніх ресурсів (CPU, пам'ять, диск, пропускну здатність мережі тощо).
+
+З іншого боку, якщо у вас 2 сервери і ви використовуєте **100% їхнього CPU та RAM**, у певний момент якийсь процес попросить більше пам'яті, і сервер муситиме використати диск як «пам'ять» (що може бути у тисячі разів повільнішим) або навіть **впасти**. Або процесу знадобляться обчислення, і він чекатиме, доки CPU знову звільниться.
+
+У цьому випадку краще додати **ще один сервер** і запустити частину процесів на ньому, щоб у всіх було **достатньо RAM та часу CPU**.
+
+Також можлива ситуація, коли з певної причини ви отримаєте **стрибок** використання вашого API. Можливо, він став вірусним або його почали використовувати інші сервіси чи боти. І ви можете захотіти мати додаткові ресурси на випадок таких ситуацій.
+
+Ви можете встановити **довільний цільовий** рівень, наприклад, **між 50% і 90%** використання ресурсів. Суть у тому, що це, ймовірно, головні речі, які ви захочете вимірювати й використовувати для налаштування розгортань.
+
+Ви можете використати прості інструменти, як-от `htop`, щоб побачити використання CPU і RAM на сервері або кількість, спожиту кожним процесом. Або складніші засоби моніторингу, розподілені між серверами тощо.
+
+## Підсумок { #recap }
+
+Тут ви прочитали про основні концепції, які, ймовірно, потрібно тримати в голові, вирішуючи, як розгортати ваш застосунок:
+
+- Безпека - HTTPS
+- Запуск під час старту
+- Перезапуски
+- Реплікація (кількість запущених процесів)
+- Пам'ять
+- Попередні кроки перед стартом
+
+Розуміння цих ідей і того, як їх застосовувати, має дати вам інтуїцію, необхідну для прийняття рішень під час конфігурування і тонкого налаштування ваших розгортань. 🤓
+
+У наступних розділах я наведу більше конкретних прикладів можливих стратегій, якими ви можете скористатися. 🚀
diff --git a/docs/uk/docs/deployment/docker.md b/docs/uk/docs/deployment/docker.md
new file mode 100644
index 000000000..d6faacfe5
--- /dev/null
+++ b/docs/uk/docs/deployment/docker.md
@@ -0,0 +1,618 @@
+# FastAPI у контейнерах - Docker { #fastapi-in-containers-docker }
+
+Під час розгортання застосунків FastAPI поширений підхід - збирати образи контейнерів Linux. Зазвичай це робиться за допомогою Docker. Потім ви можете розгорнути цей образ контейнера кількома різними способами.
+
+Використання контейнерів Linux має кілька переваг, зокрема безпека, відтворюваність, простота та інші.
+
+/// tip | Порада
+
+Поспішаєте і вже все це знаєте? Перейдіть до [`Dockerfile` нижче 👇](#build-a-docker-image-for-fastapi).
+
+///
+
+
Попередній перегляд Dockerfile 👀
+
+```Dockerfile
+FROM python:3.14
+
+WORKDIR /code
+
+COPY ./requirements.txt /code/requirements.txt
+
+RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
+
+COPY ./app /code/app
+
+CMD ["fastapi", "run", "app/main.py", "--port", "80"]
+
+# Якщо запускаєте за представником на кшталт Nginx або Traefik, додайте --proxy-headers
+# CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"]
+```
+
+
+
+### Початок TLS рукостискання { #tls-handshake-start }
+
+Потім браузер зв'яжеться з цією IP-адресою на порту 443 (порт HTTPS).
+
+Перша частина комунікації - це просто встановлення з'єднання між клієнтом і сервером та узгодження криптографічних ключів тощо.
+
+
+
+Ця взаємодія між клієнтом і сервером для встановлення з'єднання TLS називається TLS рукостисканням.
+
+### TLS із розширенням SNI { #tls-with-sni-extension }
+
+Лише один процес на сервері може слухати конкретний порт на конкретній IP-адресі. Інші процеси можуть слухати інші порти на тій самій IP-адресі, але лише один для кожної комбінації IP-адреси та порту.
+
+TLS (HTTPS) за замовчуванням використовує конкретний порт `443`. Отже, це порт, який нам потрібен.
+
+Оскільки лише один процес може слухати цей порт, процесом, що робитиме це, буде TLS Termination Proxy.
+
+TLS Termination Proxy матиме доступ до одного або кількох сертифікатів TLS (сертифікатів HTTPS).
+
+Використовуючи обговорене вище розширення SNI, TLS Termination Proxy перевірить, який із наявних сертифікатів TLS (HTTPS) слід використати для цього з'єднання, обравши той, що відповідає домену, очікуваному клієнтом.
+
+У цьому випадку він використає сертифікат для `someapp.example.com`.
+
+
+
+Клієнт уже довіряє сутності, яка видала цей сертифікат TLS (у цьому випадку Let's Encrypt, але про це згодом), тож він може перевірити, що сертифікат дійсний.
+
+Потім, використовуючи сертифікат, клієнт і TLS Termination Proxy узгоджують, як шифрувати решту TCP-комунікації. На цьому частина TLS рукостискання завершується.
+
+Після цього клієнт і сервер мають зашифроване TCP-з'єднання - саме це надає TLS. І тоді вони можуть використати це з'єднання, щоб почати власне HTTP-комунікацію.
+
+І це і є HTTPS: це звичайний HTTP усередині захищеного TLS-з'єднання замість чистого (незашифрованого) TCP-з'єднання.
+
+/// tip | Порада
+
+Зверніть увагу, що шифрування комунікації відбувається на рівні TCP, а не на рівні HTTP.
+
+///
+
+### HTTPS-запит { #https-request }
+
+Тепер, коли клієнт і сервер (конкретно браузер і TLS Termination Proxy) мають зашифроване TCP-з'єднання, вони можуть почати HTTP-комунікацію.
+
+Отже, клієнт надсилає HTTPS-запит. Це просто HTTP-запит через зашифроване TLS-з'єднання.
+
+
+
+### Розшифрування запиту { #decrypt-the-request }
+
+TLS Termination Proxy використає узгоджене шифрування, щоб розшифрувати запит, і передасть звичайний (розшифрований) HTTP-запит процесу, що запускає застосунок (наприклад, процесу з Uvicorn, який запускає застосунок FastAPI).
+
+
+
+### HTTP-відповідь { #http-response }
+
+Застосунок обробить запит і надішле звичайну (незашифровану) HTTP-відповідь TLS Termination Proxy.
+
+
+
+### HTTPS-відповідь { #https-response }
+
+Потім TLS Termination Proxy зашифрує відповідь, використовуючи попередньо узгоджену криптографію (що почалася із сертифіката для `someapp.example.com`), і надішле її назад у браузер.
+
+Далі браузер перевірить, що відповідь дійсна й зашифрована правильним криптографічним ключем тощо. Потім він розшифрує відповідь і обробить її.
+
+
+
+Клієнт (браузер) знатиме, що відповідь надходить від правильного сервера, тому що використовується узгоджена раніше криптографія з використанням сертифіката HTTPS.
+
+### Кілька застосунків { #multiple-applications }
+
+На тому самому сервері (або серверах) може бути кілька застосунків, наприклад інші програми API або база даних.
+
+Лише один процес може обробляти конкретну IP-адресу і порт (TLS Termination Proxy у нашому прикладі), але інші застосунки/процеси також можуть працювати на сервері(ах), доки вони не намагаються використати ту саму комбінацію публічної IP-адреси й порту.
+
+
+
+Таким чином, TLS Termination Proxy може обробляти HTTPS і сертифікати для кількох доменів, для кількох застосунків, а потім передавати запити до відповідного застосунку в кожному випадку.
+
+### Поновлення сертифіката { #certificate-renewal }
+
+У певний момент у майбутньому строк дії кожного сертифіката спливе (приблизно через 3 місяці після його отримання).
+
+Потім інша програма (в деяких випадках це інша програма, а в деяких - той самий TLS Termination Proxy) зв'яжеться з Let's Encrypt і поновить сертифікат(и).
+
+
+
+Сертифікати TLS пов'язані з доменним іменем, а не з IP-адресою.
+
+Тому, щоб поновити сертифікати, програма поновлення має довести авторитету (Let's Encrypt), що вона справді «володіє» і контролює цей домен.
+
+Щоб зробити це й задовольнити різні потреби застосунків, є кілька способів. Деякі популярні:
+
+* Змінити деякі записи DNS.
+ * Для цього програма поновлення має підтримувати API провайдера DNS, тож залежно від того, якого провайдера DNS ви використовуєте, це може бути або не бути варіантом.
+* Запуститися як сервер (принаймні під час процесу отримання сертифіката) на публічній IP-адресі, пов'язаній із доменом.
+ * Як ми казали вище, лише один процес може слухати конкретну IP-адресу та порт.
+ * Це одна з причин, чому дуже зручно, коли той самий TLS Termination Proxy також займається процесом поновлення сертифікатів.
+ * Інакше вам, можливо, доведеться на мить зупинити TLS Termination Proxy, запустити програму поновлення, щоб отримати сертифікати, потім налаштувати їх у TLS Termination Proxy і перезапустити TLS Termination Proxy. Це неідеально, оскільки ваші застосунки будуть недоступні під час вимкнення TLS Termination Proxy.
+
+Увесь цей процес поновлення, паралельно з обслуговуванням застосунку, - одна з головних причин, чому ви можете захотіти мати окрему систему для обробки HTTPS за допомогою TLS Termination Proxy замість того, щоб просто використовувати сертифікати TLS безпосередньо з сервером застосунку (наприклад, Uvicorn).
+
+## Направлені заголовки проксі { #proxy-forwarded-headers }
+
+Коли ви використовуєте проксі для обробки HTTPS, ваш сервер застосунку (наприклад, Uvicorn через FastAPI CLI) нічого не знає про процес HTTPS, він спілкується звичайним HTTP із TLS Termination Proxy.
+
+Цей проксі зазвичай динамічно встановлює деякі HTTP-заголовки перед передачею запиту серверу застосунку, щоб дати йому знати, що запит направляється проксі.
+
+/// note | Технічні деталі
+
+Заголовки проксі:
+
+* X-Forwarded-For
+* X-Forwarded-Proto
+* X-Forwarded-Host
+
+///
+
+Втім, оскільки сервер застосунку не знає, що він стоїть за довіреним проксі, за замовчуванням він не довірятиме цим заголовкам.
+
+Але ви можете налаштувати сервер застосунку, щоб довіряти направленим заголовкам, надісланим проксі. Якщо ви використовуєте FastAPI CLI, ви можете скористатися курсивною *опцією CLI* `--forwarded-allow-ips`, щоб повідомити, з яких IP-адрес слід довіряти цим направленим заголовкам.
+
+Наприклад, якщо сервер застосунку отримує комунікацію лише від довіреного проксі, ви можете встановити `--forwarded-allow-ips="*"`, щоб довіряти всім вхідним IP-адресам, оскільки він отримуватиме запити лише з тієї IP-адреси, яку використовує проксі.
+
+Так застосунок зможе знати свою публічну URL-адресу, чи використовує він HTTPS, домен тощо.
+
+Це буде корисно, наприклад, для коректної обробки перенаправлень.
+
+/// tip | Порада
+
+Ви можете дізнатися більше про це в документації [За проксі - Увімкнути направлені заголовки проксі](../advanced/behind-a-proxy.md#enable-proxy-forwarded-headers){.internal-link target=_blank}
+
+///
+
+## Підсумок { #recap }
+
+Наявність HTTPS дуже важлива і в більшості випадків критична. Більшість зусиль, які вам як розробнику доведеться докласти навколо HTTPS, полягають лише в розумінні цих концепцій і того, як вони працюють.
+
+Але як тільки ви знаєте базову інформацію про HTTPS для розробників, ви можете легко комбінувати й налаштовувати різні інструменти, щоб керувати всім просто.
+
+У деяких наступних розділах я покажу кілька конкретних прикладів налаштування HTTPS для застосунків FastAPI. 🔒
diff --git a/docs/uk/docs/deployment/index.md b/docs/uk/docs/deployment/index.md
new file mode 100644
index 000000000..738668139
--- /dev/null
+++ b/docs/uk/docs/deployment/index.md
@@ -0,0 +1,23 @@
+# Розгортання { #deployment }
+
+Розгортання застосунку **FastAPI** відносно просте.
+
+## Що означає розгортання { #what-does-deployment-mean }
+
+Розгорнути застосунок - це виконати необхідні кроки, щоб зробити його доступним для користувачів.
+
+Для **веб API** це зазвичай означає розміщення його на **віддаленій машині** з **серверною програмою**, що забезпечує хорошу продуктивність, стабільність тощо, щоб ваші **користувачі** могли **отримувати доступ** до застосунку ефективно та без перерв чи проблем.
+
+Це відрізняється від етапів **розробки**, коли ви постійно змінюєте код, ламаєте й виправляєте його, зупиняєте та перезапускаєте сервер розробки тощо.
+
+## Стратегії розгортання { #deployment-strategies }
+
+Існує кілька способів зробити це залежно від вашого конкретного випадку використання та інструментів, які ви використовуєте.
+
+Ви можете розгорнути сервер самостійно, використовуючи комбінацію інструментів, можете скористатися **хмарним сервісом**, який виконує частину роботи за вас, або обрати інші варіанти.
+
+Наприклад, ми, команда, що стоїть за FastAPI, створили **FastAPI Cloud**, щоб зробити розгортання застосунків FastAPI у хмарі якомога простішим і з тим самим досвідом розробки, що й під час роботи з FastAPI.
+
+Я покажу вам кілька основних концепцій, про які, ймовірно, варто пам'ятати під час розгортання **FastAPI**-застосунку (хоча більшість із них стосується будь-яких інших типів веб-застосунків).
+
+У наступних розділах ви побачите більше деталей, на які варто зважати, та деякі техніки, як це зробити. ✨
diff --git a/docs/uk/docs/deployment/manually.md b/docs/uk/docs/deployment/manually.md
new file mode 100644
index 000000000..d70ec5d5d
--- /dev/null
+++ b/docs/uk/docs/deployment/manually.md
@@ -0,0 +1,157 @@
+# Запустіть сервер вручну { #run-a-server-manually }
+
+## Використовуйте команду `fastapi run` { #use-the-fastapi-run-command }
+
+Коротко: використовуйте `fastapi run`, щоб запустити ваш застосунок FastAPI:
+
+
+
+**FastAPI** не існував би без попередньої роботи інших.
+
+Було створено багато інструментів, які надихнули на його створення.
+
+Я роками уникав створення нового фреймворку. Спочатку я намагався вирішити всі можливості, які покриває **FastAPI**, використовуючи різні фреймворки, плагіни та інструменти.
+
+Але в певний момент не залишилося іншого варіанту, окрім створити щось, що надає всі ці можливості, узявши найкращі ідеї з попередніх інструментів і поєднавши їх якнайкраще, використовуючи можливості самої мови, яких раніше взагалі не було (підказки типів Python 3.6+).
+
+
+
+## Дослідження { #investigation }
+
+Використовуючи всі попередні альтернативи, я мав змогу повчитися в кожної, узяти ідеї й поєднати їх якнайкраще для себе та команд розробників, з якими працював.
+
+Наприклад, було очевидно, що в ідеалі все має ґрунтуватися на стандартних підказках типів Python.
+
+Також найкращим підходом було використовувати вже наявні стандарти.
+
+Тож, ще до початку написання коду **FastAPI**, я провів кілька місяців, вивчаючи специфікації OpenAPI, Схеми JSON, OAuth2 тощо. Розуміючи їхні взаємозв'язки, перетини та відмінності.
+
+## Проєктування { #design }
+
+Потім я приділив час проєктуванню «API» для розробника, яке я хотів мати як користувач (як розробник, що використовує FastAPI).
+
+Я протестував кілька ідей у найпопулярніших Python-редакторах: PyCharm, VS Code, редакторах на основі Jedi.
+
+За даними Python Developer Survey, це охоплює близько 80% користувачів.
+
+Це означає, що **FastAPI** спеціально тестувався з редакторами, якими користуються 80% розробників Python. І оскільки більшість інших редакторів працюють подібно, усі ці переваги мають працювати практично у всіх редакторах.
+
+Так я зміг знайти найкращі способи максимально зменшити дублювання коду, забезпечити автодоповнення всюди, перевірки типів і помилок тощо.
+
+І все це так, щоб надати найкращий досвід розробки для всіх розробників.
+
+## Вимоги { #requirements }
+
+Після перевірки кількох альтернатив я вирішив використовувати **Pydantic** через його переваги.
+
+Потім я зробив внески до нього, щоб зробити його повністю сумісним із Схемою JSON, додати підтримку різних способів оголошення обмежень і поліпшити підтримку редакторів (перевірки типів, автодоповнення) на основі тестів у кількох редакторах.
+
+Під час розробки я також зробив внески до **Starlette**, іншої ключової залежності.
+
+## Розробка { #development }
+
+Коли я взявся безпосередньо за створення **FastAPI**, більшість складових уже були на місцях: дизайн визначено, вимоги та інструменти підготовлено, знання про стандарти й специфікації - чіткі та свіжі.
+
+## Майбутнє { #future }
+
+На цей момент уже зрозуміло, що **FastAPI** зі своїми ідеями корисний для багатьох.
+
+Його обирають замість попередніх альтернатив, бо він краще відповідає багатьом сценаріям використання.
+
+Багато розробників і команд уже залежать від **FastAPI** у своїх проєктах (включно зі мною та моєю командою).
+
+Але попереду ще багато покращень і можливостей.
+
+**FastAPI** має велике майбутнє.
+
+І [ваша допомога](help-fastapi.md){.internal-link target=_blank} дуже цінується.
diff --git a/docs/uk/docs/how-to/authentication-error-status-code.md b/docs/uk/docs/how-to/authentication-error-status-code.md
new file mode 100644
index 000000000..58016f261
--- /dev/null
+++ b/docs/uk/docs/how-to/authentication-error-status-code.md
@@ -0,0 +1,17 @@
+# Використовуйте старі коди статусу помилки автентифікації 403 { #use-old-403-authentication-error-status-codes }
+
+До версії FastAPI `0.122.0`, коли інтегровані засоби безпеки повертали клієнту помилку після невдалої автентифікації, вони використовували HTTP код статусу `403 Forbidden`.
+
+Починаючи з версії FastAPI `0.122.0`, вони використовують більш доречний HTTP код статусу `401 Unauthorized` і повертають змістовний заголовок `WWW-Authenticate` у відповіді, відповідно до специфікацій HTTP, RFC 7235, RFC 9110.
+
+Але якщо з якоїсь причини ваші клієнти залежать від старої поведінки, ви можете повернутися до неї, переписавши метод `make_not_authenticated_error` у ваших класах безпеки.
+
+Наприклад, ви можете створити підклас `HTTPBearer`, який повертатиме помилку `403 Forbidden` замість типового `401 Unauthorized`:
+
+{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *}
+
+/// tip | Порада
+
+Зверніть увагу, що функція повертає екземпляр винятку, вона не породжує його. Породження відбувається в іншій частині внутрішнього коду.
+
+///
diff --git a/docs/uk/docs/how-to/conditional-openapi.md b/docs/uk/docs/how-to/conditional-openapi.md
new file mode 100644
index 000000000..f8bbaa649
--- /dev/null
+++ b/docs/uk/docs/how-to/conditional-openapi.md
@@ -0,0 +1,56 @@
+# Умовний OpenAPI { #conditional-openapi }
+
+Якщо потрібно, ви можете використовувати налаштування і змінні оточення, щоб умовно налаштовувати OpenAPI залежно від середовища, а також повністю вимикати його.
+
+## Про безпеку, API та документацію { #about-security-apis-and-docs }
+
+Приховування інтерфейсів документації у продукційному середовищі *не має* бути способом захисту вашого API.
+
+Це не додає жодної додаткової безпеки вашому API, *операції шляху* й надалі будуть доступні там, де вони є.
+
+Якщо у вашому коді є вразливість, вона залишиться.
+
+Приховування документації лише ускладнює розуміння того, як взаємодіяти з вашим API, і може ускладнити для вас його налагодження у продакшні. Це можна вважати просто формою Безпека через неясність.
+
+Якщо ви хочете захистити ваш API, є кілька кращих дій, які ви можете зробити, наприклад:
+
+- Переконайтеся, що у вас добре визначені моделі Pydantic для тіл запитів і відповідей.
+- Налаштуйте потрібні дозволи та ролі за допомогою залежностей.
+- Ніколи не зберігайте паролі у відкритому вигляді, лише хеші паролів.
+- Реалізуйте та використовуйте відомі криптографічні інструменти, як-от pwdlib і токени JWT.
+- Додайте більш детальний контроль дозволів із областями OAuth2 там, де це потрібно.
+- ...тощо.
+
+Втім, у вас може бути дуже специфічний випадок використання, коли справді потрібно вимкнути документацію API для певного середовища (наприклад, для продакшну) або залежно від конфігурацій зі змінних оточення.
+
+## Умовний OpenAPI з налаштувань і змінних оточення { #conditional-openapi-from-settings-and-env-vars }
+
+Ви можете легко використати ті самі налаштування Pydantic, щоб налаштувати згенерований OpenAPI та інтерфейси документації.
+
+Наприклад:
+
+{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *}
+
+Тут ми оголошуємо налаштування `openapi_url` з тим самим значенням за замовчуванням `"/openapi.json"`.
+
+Потім ми використовуємо його під час створення застосунку `FastAPI`.
+
+Далі ви можете вимкнути OpenAPI (включно з інтерфейсами документації), встановивши змінну оточення `OPENAPI_URL` у пусту строку, наприклад:
+
+
+
+Але ви можете вимкнути її, встановивши `syntaxHighlight` у `False`:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+...після цього Swagger UI більше не показуватиме підсвітку синтаксису:
+
+
+
+## Змініть тему { #change-the-theme }
+
+Так само ви можете задати тему підсвітки синтаксису ключем `"syntaxHighlight.theme"` (зверніть увагу, що посередині є крапка):
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+Це налаштування змінить колірну тему підсвітки синтаксису:
+
+
+
+## Змініть параметри Swagger UI за замовчуванням { #change-default-swagger-ui-parameters }
+
+FastAPI містить деякі параметри конфігурації за замовчуванням, що підходять для більшості випадків.
+
+Вони включають такі типові налаштування:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+Ви можете переписати будь-яке з них, задавши інше значення в аргументі `swagger_ui_parameters`.
+
+Наприклад, щоб вимкнути `deepLinking`, ви можете передати такі налаштування до `swagger_ui_parameters`:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## Інші параметри Swagger UI { #other-swagger-ui-parameters }
+
+Щоб побачити всі можливі налаштування, які ви можете використовувати, прочитайте офіційну документацію щодо параметрів Swagger UI.
+
+## Налаштування лише для JavaScript { #javascript-only-settings }
+
+Swagger UI також дозволяє інші налаштування як об’єкти, що є тільки для **JavaScript** (наприклад, функції JavaScript).
+
+FastAPI також включає такі налаштування `presets`, що є лише для JavaScript:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+Це об’єкти **JavaScript**, а не строки, тому ви не можете передати їх безпосередньо з коду Python.
+
+Якщо вам потрібно використати такі налаштування лише для JavaScript, скористайтеся одним із методів вище. Повністю перепишіть операцію шляху Swagger UI та вручну напишіть потрібний JavaScript.
diff --git a/docs/uk/docs/how-to/custom-docs-ui-assets.md b/docs/uk/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 000000000..faea3ccc4
--- /dev/null
+++ b/docs/uk/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# Користувацькі статичні ресурси інтерфейсу документації (самохостинг) { #custom-docs-ui-static-assets-self-hosting }
+
+Документація API використовує **Swagger UI** і **ReDoc**, і кожному з них потрібні файли JavaScript та CSS.
+
+Типово ці файли віддаються з CDN.
+
+Але це можна налаштувати: ви можете вказати конкретний CDN або віддавати файли самостійно.
+
+## Власний CDN для JavaScript і CSS { #custom-cdn-for-javascript-and-css }
+
+Припустімо, що ви хочете використовувати інший CDN, наприклад `https://unpkg.com/`.
+
+Це може бути корисно, якщо, наприклад, ви живете в країні, що обмежує деякі URL-адреси.
+
+### Вимкніть автоматичну документацію { #disable-the-automatic-docs }
+
+Перший крок - вимкнути автоматичну документацію, адже типово вона використовує стандартний CDN.
+
+Щоб їх вимкнути, встановіть їхні URL у `None` під час створення вашого застосунку `FastAPI`:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### Додайте користувацьку документацію { #include-the-custom-docs }
+
+Тепер ви можете створити *операції шляху* для користувацької документації.
+
+Ви можете перевикористати внутрішні функції FastAPI для створення HTML-сторінок документації і передати їм потрібні аргументи:
+
+- `openapi_url`: URL, за яким HTML-сторінка документації зможе отримати схему OpenAPI для вашого API. Тут можна використати атрибут `app.openapi_url`.
+- `title`: заголовок вашого API.
+- `oauth2_redirect_url`: тут можна використати `app.swagger_ui_oauth2_redirect_url`, щоб узяти значення за замовчуванням.
+- `swagger_js_url`: URL, за яким HTML для Swagger UI зможе отримати файл **JavaScript**. Це URL вашого користувацького CDN.
+- `swagger_css_url`: URL, за яким HTML для Swagger UI зможе отримати файл **CSS**. Це URL вашого користувацького CDN.
+
+Аналогічно для ReDoc...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | Порада
+
+*Операція шляху* для `swagger_ui_redirect` - це допоміжний маршрут, коли ви використовуєте OAuth2.
+
+Якщо ви інтегруєте ваш API з провайдером OAuth2, ви зможете автентифікуватися і повернутися до документації API з отриманими обліковими даними. І взаємодіяти з ним, використовуючи реальну автентифікацію OAuth2.
+
+Swagger UI впорається з цим «за лаштунками», але йому потрібен цей «redirect» хелпер.
+
+///
+
+### Створіть операцію шляху для перевірки { #create-a-path-operation-to-test-it }
+
+Тепер, щоб перевірити, що все працює, створіть *операцію шляху*:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### Перевірте { #test-it }
+
+Тепер ви маєте змогу відкрити документацію за http://127.0.0.1:8000/docs і перезавантажити сторінку, вона завантажить ці ресурси з нового CDN.
+
+## Самохостинг JavaScript і CSS для документації { #self-hosting-javascript-and-css-for-docs }
+
+Самохостинг JavaScript і CSS може бути корисним, якщо, наприклад, ваш застосунок має працювати офлайн, без доступу до Інтернету, або в локальній мережі.
+
+Тут ви побачите, як віддавати ці файли самостійно, у тому самому застосунку FastAPI, і налаштувати документацію на їх використання.
+
+### Структура файлів проєкту { #project-file-structure }
+
+Припустімо, що структура файлів вашого проєкту виглядає так:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+Тепер створіть каталог для збереження цих статичних файлів.
+
+Нова структура файлів може виглядати так:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### Завантажте файли { #download-the-files }
+
+Завантажте статичні файли, потрібні для документації, і помістіть їх у каталог `static/`.
+
+Ви, ймовірно, можете натиснути правою кнопкою на кожному посиланні і вибрати опцію на кшталт «Зберегти посилання як...».
+
+**Swagger UI** використовує файли:
+
+- `swagger-ui-bundle.js`
+- `swagger-ui.css`
+
+А **ReDoc** використовує файл:
+
+- `redoc.standalone.js`
+
+Після цього ваша структура файлів може виглядати так:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### Обслуговуйте статичні файли { #serve-the-static-files }
+
+- Імпортуйте `StaticFiles`.
+- Змонтуйте екземпляр `StaticFiles()` у певному шляху.
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### Перевірте статичні файли { #test-the-static-files }
+
+Запустіть ваш застосунок і перейдіть до http://127.0.0.1:8000/static/redoc.standalone.js.
+
+Ви маєте побачити дуже довгий файл JavaScript для **ReDoc**.
+
+Він може починатися приблизно так:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+Це підтверджує, що ви можете віддавати статичні файли з вашого застосунку і що ви розмістили статичні файли для документації у правильному місці.
+
+Тепер ми можемо налаштувати застосунок на використання цих статичних файлів для документації.
+
+### Вимкніть автоматичну документацію для статичних файлів { #disable-the-automatic-docs-for-static-files }
+
+Як і при використанні користувацького CDN, першим кроком є вимкнення автоматичної документації, оскільки типово вона використовує CDN.
+
+Щоб їх вимкнути, встановіть їхні URL у `None` під час створення вашого застосунку `FastAPI`:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### Додайте користувацьку документацію для статичних файлів { #include-the-custom-docs-for-static-files }
+
+Аналогічно користувацькому CDN, тепер ви можете створити *операції шляху* для користувацької документації.
+
+Знову ж, ви можете перевикористати внутрішні функції FastAPI для створення HTML-сторінок документації і передати їм потрібні аргументи:
+
+- `openapi_url`: URL, за яким HTML-сторінка документації зможе отримати схему OpenAPI для вашого API. Тут можна використати атрибут `app.openapi_url`.
+- `title`: заголовок вашого API.
+- `oauth2_redirect_url`: тут можна використати `app.swagger_ui_oauth2_redirect_url`, щоб узяти значення за замовчуванням.
+- `swagger_js_url`: URL, за яким HTML для Swagger UI зможе отримати файл **JavaScript**. **Це той файл, який тепер віддає ваш власний застосунок**.
+- `swagger_css_url`: URL, за яким HTML для Swagger UI зможе отримати файл **CSS**. **Це той файл, який тепер віддає ваш власний застосунок**.
+
+Аналогічно для ReDoc...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | Порада
+
+*Операція шляху* для `swagger_ui_redirect` - це допоміжний маршрут, коли ви використовуєте OAuth2.
+
+Якщо ви інтегруєте ваш API з провайдером OAuth2, ви зможете автентифікуватися і повернутися до документації API з отриманими обліковими даними. І взаємодіяти з ним, використовуючи реальну автентифікацію OAuth2.
+
+Swagger UI впорається з цим «за лаштунками», але йому потрібен цей «redirect» хелпер.
+
+///
+
+### Створіть операцію шляху для перевірки статичних файлів { #create-a-path-operation-to-test-static-files }
+
+Тепер, щоб перевірити, що все працює, створіть *операцію шляху*:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### Перевірте UI зі статичними файлами { #test-static-files-ui }
+
+Тепер ви маєте змогу вимкнути WiFi, відкрити документацію за http://127.0.0.1:8000/docs і перезавантажити сторінку.
+
+І навіть без Інтернету ви зможете побачити документацію для вашого API і взаємодіяти з ним.
diff --git a/docs/uk/docs/how-to/custom-request-and-route.md b/docs/uk/docs/how-to/custom-request-and-route.md
new file mode 100644
index 000000000..9f21da7a8
--- /dev/null
+++ b/docs/uk/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# Користувацькі класи Request та APIRoute { #custom-request-and-apiroute-class }
+
+У деяких випадках ви можете захотіти перевизначити логіку, яку використовують класи `Request` та `APIRoute`.
+
+Зокрема, це може бути доброю альтернативою логіці в проміжному програмному забезпеченні.
+
+Наприклад, якщо потрібно прочитати або змінити тіло запиту до того, як його обробить ваш застосунок.
+
+/// danger | Обережно
+
+Це «просунута» можливість.
+
+Якщо ви тільки починаєте працювати з **FastAPI**, можливо, варто пропустити цей розділ.
+
+///
+
+## Випадки використання { #use-cases }
+
+Деякі варіанти використання:
+
+- Перетворення не-JSON тіл запитів на JSON (наприклад, `msgpack`).
+- Розпакування тіл запитів, стиснених gzip.
+- Автоматичне логування всіх тіл запитів.
+
+## Обробка користувацьких кодувань тіла запиту { #handling-custom-request-body-encodings }
+
+Розгляньмо, як використати користувацький підклас `Request` для розпакування gzip-запитів.
+
+А також підклас `APIRoute`, щоб застосувати цей користувацький клас запиту.
+
+### Створіть користувацький клас `GzipRequest` { #create-a-custom-gziprequest-class }
+
+/// tip | Порада
+
+Це навчальний приклад, щоб продемонструвати принцип роботи. Якщо вам потрібна підтримка Gzip, скористайтеся вбудованим [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}.
+
+///
+
+Спочатку створимо клас `GzipRequest`, який перевизначить метод `Request.body()`, щоб розпаковувати тіло за наявності відповідного заголовка.
+
+Якщо в заголовку немає `gzip`, він не намагатиметься розпаковувати тіло.
+
+Таким чином один і той самий клас маршруту зможе обробляти як стиснені gzip, так і нестиснені запити.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### Створіть користувацький клас `GzipRoute` { #create-a-custom-gziproute-class }
+
+Далі створимо користувацький підклас `fastapi.routing.APIRoute`, який використовуватиме `GzipRequest`.
+
+Цього разу він перевизначить метод `APIRoute.get_route_handler()`.
+
+Цей метод повертає функцію. І саме ця функція прийме запит і поверне відповідь.
+
+Тут ми використовуємо її, щоб створити `GzipRequest` з початкового запиту.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | Технічні деталі
+
+У `Request` є атрибут `request.scope` - це просто Python `dict`, що містить метадані, пов'язані із запитом.
+
+Також `Request` має `request.receive` - це функція для «отримання» тіла запиту.
+
+`scope` `dict` і функція `receive` є частиною специфікації ASGI.
+
+І саме ці дві сутності - `scope` та `receive` - потрібні для створення нового екземпляра `Request`.
+
+Щоб дізнатися більше про `Request`, перегляньте документацію Starlette про запити.
+
+///
+
+Єдине, що робить інакше функція, повернена `GzipRequest.get_route_handler`, - перетворює `Request` на `GzipRequest`.
+
+Завдяки цьому наш `GzipRequest` подбає про розпакування даних (за потреби) перед передаванням їх у наші *операції шляху*.
+
+Після цього вся логіка обробки залишається тією самою.
+
+А завдяки змінам у `GzipRequest.body` тіло запиту за потреби буде автоматично розпаковане під час завантаження **FastAPI**.
+
+## Доступ до тіла запиту в обробнику виключень { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | Порада
+
+Щоб розв’язати це саме завдання, скоріш за все, простіше використати `body` у користувацькому обробнику `RequestValidationError` ([Обробка помилок](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}).
+
+Але цей приклад усе ще корисний і показує, як взаємодіяти з внутрішніми компонентами.
+
+///
+
+Ми також можемо скористатися цим підходом, щоб отримати доступ до тіла запиту в обробнику виключень.
+
+Усе, що потрібно, - обробити запит усередині блоку `try`/`except`:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+Якщо станеться виключення, екземпляр `Request` усе ще буде у видимості, тож ми зможемо прочитати й використати тіло запиту під час обробки помилки:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## Користувацький клас `APIRoute` у маршрутизаторі { #custom-apiroute-class-in-a-router }
+
+Можна також встановити параметр `route_class` у `APIRouter`:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+У цьому прикладі *операції шляху* в `router` використовуватимуть користувацький клас `TimedRoute` і матимуть додатковий заголовок відповіді `X-Response-Time` із часом, витраченим на формування відповіді:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/uk/docs/how-to/extending-openapi.md b/docs/uk/docs/how-to/extending-openapi.md
new file mode 100644
index 000000000..1597cbc76
--- /dev/null
+++ b/docs/uk/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# Розширення OpenAPI { #extending-openapi }
+
+У деяких випадках вам може знадобитися змінити згенеровану схему OpenAPI.
+
+У цьому розділі ви побачите як це зробити.
+
+## Звичайний процес { #the-normal-process }
+
+Звичайний (типовий) процес такий.
+
+Застосунок `FastAPI` (екземпляр) має метод `.openapi()`, який має повертати схему OpenAPI.
+
+Під час створення об'єкта застосунку реєструється *операція шляху* для `/openapi.json` (або для того значення, яке ви встановили в `openapi_url`).
+
+Вона просто повертає відповідь JSON з результатом методу `.openapi()` застосунку.
+
+Типово метод `.openapi()` перевіряє властивість `.openapi_schema`, і якщо там вже є дані, повертає їх.
+
+Якщо ні, він генерує їх за допомогою утилітарної функції `fastapi.openapi.utils.get_openapi`.
+
+Функція `get_openapi()` приймає такі параметри:
+
+- `title`: Заголовок OpenAPI, показується в документації.
+- `version`: Версія вашого API, напр. `2.5.0`.
+- `openapi_version`: Версія специфікації OpenAPI, що використовується. Типово остання: `3.1.0`.
+- `summary`: Короткий підсумок API.
+- `description`: Опис вашого API; може містити markdown і буде показаний у документації.
+- `routes`: Список маршрутів, це кожна з зареєстрованих *операцій шляху*. Їх беруть з `app.routes`.
+
+/// info | Інформація
+
+Параметр `summary` доступний в OpenAPI 3.1.0 і вище, підтримується FastAPI 0.99.0 і вище.
+
+///
+
+## Переписування типових значень { #overriding-the-defaults }
+
+Використовуючи наведене вище, ви можете скористатися тією ж утилітарною функцією для генерації схеми OpenAPI і переписати потрібні частини.
+
+Наприклад, додаймо розширення OpenAPI для ReDoc для додавання власного логотипа.
+
+### Звичайний **FastAPI** { #normal-fastapi }
+
+Спочатку напишіть ваш застосунок **FastAPI** як зазвичай:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### Згенерувати схему OpenAPI { #generate-the-openapi-schema }
+
+Далі використайте ту ж утилітарну функцію для генерації схеми OpenAPI всередині функції `custom_openapi()`:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### Змінити схему OpenAPI { #modify-the-openapi-schema }
+
+Тепер можна додати розширення ReDoc, додавши власний `x-logo` до «об'єкта» `info` у схемі OpenAPI:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### Кешувати схему OpenAPI { #cache-the-openapi-schema }
+
+Ви можете використовувати властивість `.openapi_schema` як «кеш» для збереження згенерованої схеми.
+
+Так вашому застосунку не доведеться щоразу генерувати схему, коли користувач відкриває документацію вашого API.
+
+Вона буде згенерована лише один раз, а потім та сама закешована схема використовуватиметься для наступних запитів.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### Переписати метод { #override-the-method }
+
+Тепер ви можете замінити метод `.openapi()` вашою новою функцією.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### Перевірте { #check-it }
+
+Коли ви перейдете за адресою http://127.0.0.1:8000/redoc, побачите, що використовується ваш власний логотип (у цьому прикладі логотип **FastAPI**):
+
+
diff --git a/docs/uk/docs/how-to/general.md b/docs/uk/docs/how-to/general.md
new file mode 100644
index 000000000..f33ae195c
--- /dev/null
+++ b/docs/uk/docs/how-to/general.md
@@ -0,0 +1,39 @@
+# Загальне - Як зробити - Рецепти { #general-how-to-recipes }
+
+Нижче наведено кілька вказівок до інших розділів документації для загальних або частих питань.
+
+## Фільтрування даних - Безпека { #filter-data-security }
+
+Щоб гарантувати, що ви не повертаєте більше даних, ніж слід, прочитайте документацію [Навчальний посібник - Модель відповіді - Тип повернення](../tutorial/response-model.md){.internal-link target=_blank}.
+
+## Мітки документації - OpenAPI { #documentation-tags-openapi }
+
+Щоб додати мітки до ваших *операцій шляху* та згрупувати їх в інтерфейсі документації, прочитайте документацію [Навчальний посібник - Налаштування операції шляху - Мітки](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}.
+
+## Короткий опис і опис - OpenAPI { #documentation-summary-and-description-openapi }
+
+Щоб додати короткий опис і опис до ваших *операцій шляху* і показати їх в інтерфейсі документації, прочитайте документацію [Навчальний посібник - Налаштування операції шляху - Короткий опис і опис](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank}.
+
+## Опис відповіді в документації - OpenAPI { #documentation-response-description-openapi }
+
+Щоб визначити опис відповіді, що відображається в інтерфейсі документації, прочитайте документацію [Навчальний посібник - Налаштування операції шляху - Опис відповіді](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank}.
+
+## Позначити застарілою *операцію шляху* - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+Щоб позначити *операцію шляху* як застарілу і показати це в інтерфейсі документації, прочитайте документацію [Навчальний посібник - Налаштування операції шляху - Позначення як застаріле](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank}.
+
+## Перетворити будь-які дані на сумісні з JSON { #convert-any-data-to-json-compatible }
+
+Щоб перетворити будь-які дані на сумісні з JSON, прочитайте документацію [Навчальний посібник - Кодувальник, сумісний з JSON](../tutorial/encoder.md){.internal-link target=_blank}.
+
+## Метадані OpenAPI - Документація { #openapi-metadata-docs }
+
+Щоб додати метадані до вашої схеми OpenAPI, зокрема ліцензію, версію, контактні дані тощо, прочитайте документацію [Навчальний посібник - Метадані та URL документації](../tutorial/metadata.md){.internal-link target=_blank}.
+
+## Власний URL OpenAPI { #openapi-custom-url }
+
+Щоб налаштувати URL OpenAPI (або прибрати його), прочитайте документацію [Навчальний посібник - Метадані та URL документації](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}.
+
+## URL документації OpenAPI { #openapi-docs-urls }
+
+Щоб оновити URL, які використовуються для автоматично згенерованих інтерфейсів користувача документації, прочитайте документацію [Навчальний посібник - Метадані та URL документації](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}.
diff --git a/docs/uk/docs/how-to/graphql.md b/docs/uk/docs/how-to/graphql.md
new file mode 100644
index 000000000..2d0e355ea
--- /dev/null
+++ b/docs/uk/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+Оскільки FastAPI базується на стандарті ASGI, дуже просто інтегрувати будь-яку бібліотеку GraphQL, сумісну з ASGI.
+
+Ви можете поєднувати звичайні *операції шляху* FastAPI з GraphQL в одному застосунку.
+
+/// tip | Порада
+
+GraphQL розв’язує деякі дуже специфічні сценарії використання.
+
+Порівняно зі звичайними веб-API він має переваги та недоліки.
+
+Переконайтеся, що переваги для вашого випадку використання переважають недоліки. 🤓
+
+///
+
+## Бібліотеки GraphQL { #graphql-libraries }
+
+Ось деякі бібліотеки GraphQL з підтримкою ASGI. Ви можете використовувати їх із FastAPI:
+
+* Strawberry 🍓
+ * З документацією для FastAPI
+* Ariadne
+ * З документацією для FastAPI
+* Tartiflette
+ * З Tartiflette ASGI для інтеграції з ASGI
+* Graphene
+ * З starlette-graphene3
+
+## GraphQL зі Strawberry { #graphql-with-strawberry }
+
+Якщо вам потрібен або ви хочете використовувати GraphQL, Strawberry - рекомендована бібліотека, адже її дизайн найближчий до дизайну FastAPI; усе базується на анотаціях типів.
+
+Залежно від вашого сценарію використання ви можете надати перевагу іншій бібліотеці, але якби ви запитали мене, я, ймовірно, порадив би спробувати Strawberry.
+
+Ось невеликий приклад того, як інтегрувати Strawberry з FastAPI:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+Більше про Strawberry ви можете дізнатися в документації Strawberry.
+
+І також документацію про Strawberry з FastAPI.
+
+## Застарілий `GraphQLApp` зі Starlette { #older-graphqlapp-from-starlette }
+
+Попередні версії Starlette містили клас `GraphQLApp` для інтеграції з Graphene.
+
+Його вилучено з Starlette як застарілий, але якщо у вас є код, що його використовував, ви можете легко мігрувати на starlette-graphene3, який покриває той самий сценарій використання та має майже ідентичний інтерфейс.
+
+/// tip | Порада
+
+Якщо вам потрібен GraphQL, я все ж рекомендую звернути увагу на Strawberry, адже він базується на анотаціях типів, а не на власних класах і типах.
+
+///
+
+## Дізнайтеся більше { #learn-more }
+
+Ви можете дізнатися більше про GraphQL в офіційній документації GraphQL.
+
+Також ви можете почитати більше про кожну з цих бібліотек за наведеними посиланнями.
diff --git a/docs/uk/docs/how-to/index.md b/docs/uk/docs/how-to/index.md
new file mode 100644
index 000000000..ac2dd16eb
--- /dev/null
+++ b/docs/uk/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# Як зробити - Рецепти { #how-to-recipes }
+
+Тут ви побачите різні рецепти або керівництва «як зробити» з **різних тем**.
+
+Більшість із цих ідей є більш-менш **незалежними**, і в більшості випадків вам слід вивчати їх лише тоді, коли вони безпосередньо стосуються **вашого проєкту**.
+
+Якщо щось здається цікавим і корисним для вашого проєкту, сміливо перевірте це, інакше, ймовірно, просто пропустіть.
+
+/// tip | Порада
+
+Якщо ви хочете **вивчити FastAPI** у структурований спосіб (рекомендується), натомість прочитайте [Навчальний посібник - Посібник користувача](../tutorial/index.md){.internal-link target=_blank} розділ за розділом.
+
+///
diff --git a/docs/uk/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/uk/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 000000000..0f5d1c924
--- /dev/null
+++ b/docs/uk/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Перехід з Pydantic v1 на Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+Якщо у вас стара програма FastAPI, можливо, ви використовуєте Pydantic версії 1.
+
+FastAPI версії 0.100.0 підтримував як Pydantic v1, так і v2. Використовувалася та версія, яку ви встановили.
+
+FastAPI версії 0.119.0 запровадив часткову підтримку Pydantic v1 всередині Pydantic v2 (як `pydantic.v1`), щоб спростити перехід на v2.
+
+FastAPI 0.126.0 припинив підтримку Pydantic v1, водночас ще певний час підтримував `pydantic.v1`.
+
+/// warning | Попередження
+
+Команда Pydantic припинила підтримку Pydantic v1 для останніх версій Python, починаючи з Python 3.14.
+
+Це стосується і `pydantic.v1`, який більше не підтримується в Python 3.14 і новіших.
+
+Якщо ви хочете використовувати найновіші можливості Python, вам потрібно переконатися, що ви використовуєте Pydantic v2.
+
+///
+
+Якщо у вас стара програма FastAPI з Pydantic v1, нижче я покажу, як мігрувати на Pydantic v2, а також можливості FastAPI 0.119.0, які допоможуть з поступовою міграцією.
+
+## Офіційний посібник { #official-guide }
+
+У Pydantic є офіційний Посібник з міграції з v1 на v2.
+
+Там описано, що змінилося, як перевірки тепер стали коректнішими та суворішими, можливі застереження тощо.
+
+Прочитайте його, щоб краще зрозуміти зміни.
+
+## Тести { #tests }
+
+Переконайтеся, що у вашій програмі є [тести](../tutorial/testing.md){.internal-link target=_blank} і що ви запускаєте їх у системі безперервної інтеграції (CI).
+
+Так ви зможете виконати оновлення і впевнитися, що все працює як очікується.
+
+## `bump-pydantic` { #bump-pydantic }
+
+У багатьох випадках, якщо ви використовуєте звичайні моделі Pydantic без налаштувань, більшу частину процесу міграції з Pydantic v1 на Pydantic v2 можна автоматизувати.
+
+Ви можете скористатися `bump-pydantic` від тієї ж команди Pydantic.
+
+Цей інструмент допоможе автоматично змінити більшість коду, який потрібно змінити.
+
+Після цього запустіть тести й перевірте, чи все працює. Якщо так - ви все завершили. 😎
+
+## Pydantic v1 у v2 { #pydantic-v1-in-v2 }
+
+Pydantic v2 містить усе з Pydantic v1 як підмодуль `pydantic.v1`. Але це більше не підтримується у версіях Python вище 3.13.
+
+Це означає, що ви можете встановити останню версію Pydantic v2 та імпортувати і використовувати старі компоненти Pydantic v1 з цього підмодуля, ніби у вас встановлено старий Pydantic v1.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### Підтримка FastAPI для Pydantic v1 у v2 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+Починаючи з FastAPI 0.119.0, також є часткова підтримка Pydantic v1 всередині Pydantic v2, щоб спростити перехід на v2.
+
+Тож ви можете оновити Pydantic до останньої версії 2 і змінити імпорти на використання підмодуля `pydantic.v1`, і в багатьох випадках усе просто запрацює.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | Попередження
+
+Майте на увазі, що оскільки команда Pydantic більше не підтримує Pydantic v1 у нових версіях Python, починаючи з Python 3.14, використання `pydantic.v1` також не підтримується в Python 3.14 і новіших.
+
+///
+
+### Pydantic v1 і v2 в одній програмі { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic не підтримує ситуацію, коли модель Pydantic v2 має власні поля, визначені як моделі Pydantic v1, або навпаки.
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...але в одній програмі ви можете мати окремі моделі на Pydantic v1 і v2.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+У деяких випадках можна навіть використовувати моделі і Pydantic v1, і v2 в одній операції шляху у вашій програмі FastAPI:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+У наведеному вище прикладі вхідна модель - це модель Pydantic v1, а вихідна модель (визначена як `response_model=ItemV2`) - модель Pydantic v2.
+
+### Параметри Pydantic v1 { #pydantic-v1-parameters }
+
+Якщо вам потрібно використовувати деякі специфічні для FastAPI інструменти для параметрів, як-от `Body`, `Query`, `Form` тощо, з моделями Pydantic v1, ви можете імпортувати їх з `fastapi.temp_pydantic_v1_params`, поки завершуєте міграцію на Pydantic v2:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### Покрокова міграція { #migrate-in-steps }
+
+/// tip | Порада
+
+Спершу спробуйте `bump-pydantic`: якщо ваші тести проходять і все працює - ви впоралися однією командою. ✨
+
+///
+
+Якщо `bump-pydantic` не підходить для вашого випадку, скористайтеся підтримкою одночасно Pydantic v1 і v2 в одній програмі, щоб виконати поступову міграцію на Pydantic v2.
+
+Спочатку ви можете оновити Pydantic до останньої версії 2 і змінити імпорти на `pydantic.v1` для всіх ваших моделей.
+
+Потім починайте переносити моделі з Pydantic v1 на v2 групами, поступовими кроками. 🚶
diff --git a/docs/uk/docs/how-to/separate-openapi-schemas.md b/docs/uk/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 000000000..7e6fcbf5f
--- /dev/null
+++ b/docs/uk/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,101 @@
+# Окремі схеми OpenAPI для введення та виведення, чи ні { #separate-openapi-schemas-for-input-and-output-or-not }
+
+Відколи вийшов **Pydantic v2**, згенерований OpenAPI став трохи точнішим і більш коректним, ніж раніше. 😎
+
+Насправді подекуди буде навіть **дві схеми JSON** в OpenAPI для тієї самої моделі Pydantic: для введення та для виведення - залежно від наявності значень за замовчуванням.
+
+Розгляньмо, як це працює, і як це змінити за потреби.
+
+## Моделі Pydantic для введення та виведення { #pydantic-models-for-input-and-output }
+
+Припустімо, у вас є модель Pydantic зі значеннями за замовчуванням, наприклад:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### Модель для введення { #model-for-input }
+
+Якщо ви використовуєте цю модель як введення, як тут:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+…тоді поле `description` не буде обов'язковим, адже воно має значення за замовчуванням `None`.
+
+### Модель для введення в документації { #input-model-in-docs }
+
+У документації ви побачите, що поле `description` не має **червоної зірочки** - воно не позначене як обов'язкове:
+
+
+
+
+
+
+
+
+Та сама структура файлів з коментарями:
+
+```bash
+.
+├── app # «app» - це пакет Python
+│ ├── __init__.py # цей файл робить «app» «пакетом Python»
+│ ├── main.py # модуль «main», напр. import app.main
+│ ├── dependencies.py # модуль «dependencies», напр. import app.dependencies
+│ └── routers # «routers» - це «підпакет Python»
+│ │ ├── __init__.py # робить «routers» «підпакетом Python»
+│ │ ├── items.py # підмодуль «items», напр. import app.routers.items
+│ │ └── users.py # підмодуль «users», напр. import app.routers.users
+│ └── internal # «internal» - це «підпакет Python»
+│ ├── __init__.py # робить «internal» «підпакетом Python»
+│ └── admin.py # підмодуль «admin», напр. import app.internal.admin
+```
+
+## `APIRouter` { #apirouter }
+
+Припустімо, файл, присвячений обробці лише користувачів, - це підмодуль у `/app/routers/users.py`.
+
+Ви хочете мати *операції шляху*, пов'язані з користувачами, відокремлено від решти коду, щоб зберегти порядок.
+
+Але це все одно частина того самого застосунку/веб-API **FastAPI** (це частина того самого «пакета Python»).
+
+Ви можете створювати *операції шляху* для цього модуля, використовуючи `APIRouter`.
+
+### Імпортуйте `APIRouter` { #import-apirouter }
+
+Імпортуйте його та створіть «екземпляр» так само, як ви б робили з класом `FastAPI`:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+
+### *Операції шляху* з `APIRouter` { #path-operations-with-apirouter }
+
+Потім використовуйте його для оголошення *операцій шляху*.
+
+Використовуйте його так само, як і клас `FastAPI`:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+
+Можете думати про `APIRouter` як про «міні `FastAPI`».
+
+Підтримуються ті самі опції.
+
+Ті самі `parameters`, `responses`, `dependencies`, `tags` тощо.
+
+/// tip | Порада
+
+У цьому прикладі змінна називається `router`, але ви можете назвати її як завгодно.
+
+///
+
+Ми включимо цей `APIRouter` у основний застосунок `FastAPI`, але спочатку розгляньмо залежності та інший `APIRouter`.
+
+## Залежності { #dependencies }
+
+Бачимо, що нам знадобляться кілька залежностей, які використовуються в різних місцях застосунку.
+
+Тож помістимо їх у власний модуль `dependencies` (`app/dependencies.py`).
+
+Тепер використаємо просту залежність для читання користувацького заголовка `X-Token`:
+
+{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+
+/// tip | Порада
+
+Ми використовуємо вигаданий заголовок, щоб спростити приклад.
+
+Але в реальних випадках ви отримаєте кращі результати, використовуючи інтегровані [засоби безпеки](security/index.md){.internal-link target=_blank}.
+
+///
+
+## Інший модуль з `APIRouter` { #another-module-with-apirouter }
+
+Припустімо, у вас також є кінцеві точки для обробки «items» у модулі `app/routers/items.py`.
+
+У вас є *операції шляху* для:
+
+* `/items/`
+* `/items/{item_id}`
+
+Структура така сама, як у `app/routers/users.py`.
+
+Але ми хочемо бути розумнішими й трохи спростити код.
+
+Ми знаємо, що всі *операції шляху* в цьому модулі мають однакові:
+
+* Префікс шляху `prefix`: `/items`.
+* `tags`: (лише одна мітка: `items`).
+* Додаткові `responses`.
+* `dependencies`: усім потрібна залежність `X-Token`, яку ми створили.
+
+Тож замість додавання цього до кожної *операції шляху*, ми можемо додати це до `APIRouter`.
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+
+Оскільки шлях кожної *операції шляху* має починатися з `/`, як у:
+
+```Python hl_lines="1"
+@router.get("/{item_id}")
+async def read_item(item_id: str):
+ ...
+```
+
+...префікс не має містити кінцевий `/`.
+
+Отже, у цьому випадку префікс - це `/items`.
+
+Ми також можемо додати список `tags` та додаткові `responses`, які застосовуватимуться до всіх *операцій шляху*, включених у цей router.
+
+І ми можемо додати список `dependencies`, які буде додано до всіх *операцій шляху* у router і які виконуватимуться/вирішуватимуться для кожного запиту до них.
+
+/// tip | Порада
+
+Зверніть увагу, що так само як і для [залежностей у декораторах *операцій шляху*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, жодне значення не буде передано вашій *функції операції шляху*.
+
+///
+
+У підсумку шляхи предметів тепер:
+
+* `/items/`
+* `/items/{item_id}`
+
+...як ми і планували.
+
+* Вони будуть позначені списком міток, що містить один рядок `"items"`.
+ * Ці «мітки» особливо корисні для автоматичної інтерактивної документації (за допомогою OpenAPI).
+* Усі вони включатимуть наперед визначені `responses`.
+* Для всіх цих *операцій шляху* список `dependencies` буде оцінений/виконаний перед ними.
+ * Якщо ви також оголосите залежності в конкретній *операції шляху*, **вони також будуть виконані**.
+ * Спочатку виконуються залежності router'а, потім [`dependencies` у декораторі](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, а потім звичайні параметричні залежності.
+ * Ви також можете додати [`Security` залежності з `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.
+
+/// tip | Порада
+
+Наявність `dependencies` у `APIRouter` можна використати, наприклад, щоб вимагати автентифікацію для всієї групи *операцій шляху*. Навіть якщо залежності не додані до кожної з них окремо.
+
+///
+
+/// check | Перевірте
+
+Параметри `prefix`, `tags`, `responses` і `dependencies` - це (як і в багатьох інших випадках) просто можливість **FastAPI**, яка допомагає уникати дублювання коду.
+
+///
+
+### Імпортуйте залежності { #import-the-dependencies }
+
+Цей код живе в модулі `app.routers.items`, у файлі `app/routers/items.py`.
+
+І нам потрібно отримати функцію залежності з модуля `app.dependencies`, файлу `app/dependencies.py`.
+
+Тож ми використовуємо відносний імпорт з `..` для залежностей:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}
+
+#### Як працюють відносні імпорти { #how-relative-imports-work }
+
+/// tip | Порада
+
+Якщо ви досконало знаєте, як працюють імпорти, перейдіть до наступного розділу нижче.
+
+///
+
+Одна крапка `.`, як у:
+
+```Python
+from .dependencies import get_token_header
+```
+
+означає:
+
+* Починаючи в тому самому пакеті, де знаходиться цей модуль (файл `app/routers/items.py`) (каталог `app/routers/`)...
+* знайти модуль `dependencies` (уявний файл `app/routers/dependencies.py`)...
+* і з нього імпортувати функцію `get_token_header`.
+
+Але такого файлу не існує, наші залежності у файлі `app/dependencies.py`.
+
+Згадайте, як виглядає структура нашого застосунку/файлів:
+
+
+
+---
+
+Дві крапки `..`, як у:
+
+```Python
+from ..dependencies import get_token_header
+```
+
+означають:
+
+* Починаючи в тому самому пакеті, де знаходиться цей модуль (файл `app/routers/items.py`) (каталог `app/routers/`)...
+* перейти до батьківського пакета (каталог `app/`)...
+* і там знайти модуль `dependencies` (файл `app/dependencies.py`)...
+* і з нього імпортувати функцію `get_token_header`.
+
+Це працює правильно! 🎉
+
+---
+
+Так само, якби ми використали три крапки `...`, як у:
+
+```Python
+from ...dependencies import get_token_header
+```
+
+це б означало:
+
+* Починаючи в тому самому пакеті, де знаходиться цей модуль (файл `app/routers/items.py`) (каталог `app/routers/`)...
+* перейти до батьківського пакета (каталог `app/`)...
+* потім перейти до батьківського пакета від того (немає батьківського пакета, `app` - верхній рівень 😱)...
+* і там знайти модуль `dependencies` (файл `app/dependencies.py`)...
+* і з нього імпортувати функцію `get_token_header`.
+
+Це б посилалося на якийсь пакет вище за `app/` з власним файлом `__init__.py` тощо. Але в нас такого немає. Тож у нашому прикладі це спричинить помилку. 🚨
+
+Але тепер ви знаєте, як це працює, тож можете використовувати відносні імпорти у власних застосунках, незалежно від їхньої складності. 🤓
+
+### Додайте користувацькі `tags`, `responses` і `dependencies` { #add-some-custom-tags-responses-and-dependencies }
+
+Ми не додаємо префікс `/items` ані `tags=["items"]` до кожної *операції шляху*, бо додали їх до `APIRouter`.
+
+Але ми все ще можемо додати _ще_ `tags`, які будуть застосовані до конкретної *операції шляху*, а також додаткові `responses`, специфічні для цієї *операції шляху*:
+
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+
+/// tip | Порада
+
+Остання операція шляху матиме комбінацію міток: `["items", "custom"]`.
+
+І вона також матиме в документації обидві відповіді: одну для `404` і одну для `403`.
+
+///
+
+## Основний `FastAPI` { #the-main-fastapi }
+
+Тепер розгляньмо модуль `app/main.py`.
+
+Тут ви імпортуєте і використовуєте клас `FastAPI`.
+
+Це буде головний файл вашого застосунку, який усе поєднує.
+
+І оскільки більшість вашої логіки тепер житиме у власних модулях, головний файл буде досить простим.
+
+### Імпортуйте `FastAPI` { #import-fastapi }
+
+Імпортуйте та створіть клас `FastAPI`, як зазвичай.
+
+І ми навіть можемо оголосити [глобальні залежності](dependencies/global-dependencies.md){.internal-link target=_blank}, які будуть поєднані із залежностями кожного `APIRouter`:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
+
+### Імпортуйте `APIRouter` { #import-the-apirouter }
+
+Тепер імпортуємо інші підмодулі, що мають `APIRouter`:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}
+
+Оскільки файли `app/routers/users.py` та `app/routers/items.py` - це підмодулі, що є частиною того самого пакета Python `app`, ми можемо використати одну крапку `.` для «відносних імпортів».
+
+### Як працює імпорт { #how-the-importing-works }
+
+Розділ:
+
+```Python
+from .routers import items, users
+```
+
+означає:
+
+* Починаючи в тому самому пакеті, де знаходиться цей модуль (файл `app/main.py`) (каталог `app/`)...
+* знайти підпакет `routers` (каталог `app/routers/`)...
+* і з нього імпортувати підмодулі `items` (файл `app/routers/items.py`) і `users` (файл `app/routers/users.py`)...
+
+Модуль `items` матиме змінну `router` (`items.router`). Це та сама, що ми створили у файлі `app/routers/items.py`, це об’єкт `APIRouter`.
+
+Потім ми робимо те саме для модуля `users`.
+
+Ми також могли б імпортувати їх так:
+
+```Python
+from app.routers import items, users
+```
+
+/// info | Інформація
+
+Перша версія - «відносний імпорт»:
+
+```Python
+from .routers import items, users
+```
+
+Друга версія - «абсолютний імпорт»:
+
+```Python
+from app.routers import items, users
+```
+
+Щоб дізнатися більше про пакети й модулі Python, прочитайте офіційну документацію Python про модулі.
+
+///
+
+### Уникайте колізій імен { #avoid-name-collisions }
+
+Ми імпортуємо підмодуль `items` напряму, замість імпорту лише його змінної `router`.
+
+Це тому, що в підмодулі `users` також є змінна з назвою `router`.
+
+Якби ми імпортували один за одним, як:
+
+```Python
+from .routers.items import router
+from .routers.users import router
+```
+
+`router` з `users` перезаписав би той, що з `items`, і ми не змогли б використовувати їх одночасно.
+
+Щоб мати змогу використовувати обидва в одному файлі, ми імпортуємо підмодулі напряму:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}
+
+### Додайте `APIRouter` для `users` і `items` { #include-the-apirouters-for-users-and-items }
+
+Тепер додаймо `router` з підмодулів `users` і `items`:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}
+
+/// info | Інформація
+
+`users.router` містить `APIRouter` у файлі `app/routers/users.py`.
+
+А `items.router` містить `APIRouter` у файлі `app/routers/items.py`.
+
+///
+
+За допомогою `app.include_router()` ми можемо додати кожен `APIRouter` до основного застосунку `FastAPI`.
+
+Це включить усі маршрути з цього router'а як частину застосунку.
+
+/// note | Технічні деталі
+
+Фактично, всередині для кожної *операції шляху*, оголошеної в `APIRouter`, буде створена окрема *операція шляху*.
+
+Тобто за лаштунками все працюватиме так, ніби це один і той самий застосунок.
+
+///
+
+/// check | Перевірте
+
+Вам не потрібно перейматися продуктивністю під час включення router'ів.
+
+Це займе мікросекунди і відбуватиметься лише під час запуску.
+
+Тож це не вплине на продуктивність. ⚡
+
+///
+
+### Додайте `APIRouter` з власними `prefix`, `tags`, `responses` і `dependencies` { #include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies }
+
+Уявімо, що ваша організація надала вам файл `app/internal/admin.py`.
+
+Він містить `APIRouter` з кількома адміністративними *операціями шляху*, які організація спільно використовує між кількома проєктами.
+
+Для цього прикладу він буде дуже простим. Але припустімо, що оскільки його спільно використовують з іншими проєктами організації, ми не можемо модифікувати його та додавати `prefix`, `dependencies`, `tags` тощо прямо до `APIRouter`:
+
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+
+Але ми все одно хочемо встановити користувацький `prefix` під час включення `APIRouter`, щоб усі його *операції шляху* починалися з `/admin`, хочемо захистити його за допомогою `dependencies`, які вже є в цьому проєкті, і хочемо додати `tags` та `responses`.
+
+Ми можемо оголосити все це, не змінюючи оригінальний `APIRouter`, передавши ці параметри до `app.include_router()`:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}
+
+Таким чином, вихідний `APIRouter` залишиться без змін, тож ми все ще зможемо спільно використовувати той самий файл `app/internal/admin.py` з іншими проєктами в організації.
+
+У результаті в нашому застосунку кожна з *операцій шляху* з модуля `admin` матиме:
+
+* Префікс `/admin`.
+* Мітку `admin`.
+* Залежність `get_token_header`.
+* Відповідь `418`. 🍵
+
+Але це вплине лише на цей `APIRouter` у нашому застосунку, а не на будь-який інший код, який його використовує.
+
+Наприклад, інші проєкти можуть використовувати той самий `APIRouter` з іншим методом автентифікації.
+
+### Додайте *операцію шляху* { #include-a-path-operation }
+
+Ми також можемо додавати *операції шляху* безпосередньо до застосунку `FastAPI`.
+
+Тут ми це робимо... просто щоб показати, що так можна 🤷:
+
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}
+
+і це працюватиме коректно разом з усіма іншими *операціями шляху*, доданими через `app.include_router()`.
+
+/// info | Дуже технічні деталі
+
+Примітка: це дуже технічна деталь, яку ви, ймовірно, можете просто пропустити.
+
+---
+
+`APIRouter` не «монтуються», вони не ізольовані від решти застосунку.
+
+Це тому, що ми хочемо включати їхні *операції шляху* в схему OpenAPI та інтерфейси користувача.
+
+Оскільки ми не можемо просто ізолювати їх і «змонтувати» незалежно від решти, *операції шляху* «клонуються» (створюються заново), а не включаються безпосередньо.
+
+///
+
+## Перевірте автоматичну документацію API { #check-the-automatic-api-docs }
+
+Тепер запустіть ваш застосунок:
+
+
+
+## Включайте той самий router кілька разів з різними `prefix` { #include-the-same-router-multiple-times-with-different-prefix }
+
+Ви також можете використовувати `.include_router()` кілька разів з одним і тим самим router'ом, але з різними префіксами.
+
+Це може бути корисно, наприклад, щоб публікувати той самий API під різними префіксами, наприклад `/api/v1` і `/api/latest`.
+
+Це просунуте використання, яке вам може й не знадобитися, але воно є на випадок, якщо потрібно.
+
+## Включіть один `APIRouter` до іншого { #include-an-apirouter-in-another }
+
+Так само як ви можете включити `APIRouter` у застосунок `FastAPI`, ви можете включити `APIRouter` в інший `APIRouter`, використовуючи:
+
+```Python
+router.include_router(other_router)
+```
+
+Переконайтеся, що ви робите це до включення `router` в застосунок `FastAPI`, щоб *операції шляху* з `other_router` також були включені.
diff --git a/docs/uk/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/uk/docs/tutorial/dependencies/classes-as-dependencies.md
new file mode 100644
index 000000000..e64f90ae2
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,288 @@
+# Класи як залежності { #classes-as-dependencies }
+
+Перш ніж заглибитися у систему **впровадження залежностей**, оновімо попередній приклад.
+
+## `dict` з попереднього прикладу { #a-dict-from-the-previous-example }
+
+У попередньому прикладі ми повертали `dict` із нашого «залежного»:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}
+
+Але тоді ми отримуємо `dict` у параметрі `commons` функції операції шляху.
+
+І ми знаємо, що редактори не можуть надати багато підтримки (наприклад, автодоповнення) для `dict`, адже вони не знають їхніх ключів і типів значень.
+
+Можна зробити краще…
+
+## Що робить об’єкт залежністю { #what-makes-a-dependency }
+
+Дотепер ви бачили залежності, оголошені як функції.
+
+Але це не єдиний спосіб оголошувати залежності (хоча, ймовірно, найпоширеніший).
+
+Ключовий момент у тому, що залежність має бути «викликаємим».
+
+«Викликаємий» у Python - це будь-що, що Python може «викликати», як функцію.
+
+Отже, якщо у вас є об’єкт `something` (який може й не бути функцією) і ви можете «викликати» його (виконати) так:
+
+```Python
+something()
+```
+
+або
+
+```Python
+something(some_argument, some_keyword_argument="foo")
+```
+
+тоді це «викликаємий».
+
+## Класи як залежності { #classes-as-dependencies_1 }
+
+Ви могли помітити, що для створення екземпляра класу Python ви використовуєте той самий синтаксис.
+
+Наприклад:
+
+```Python
+class Cat:
+ def __init__(self, name: str):
+ self.name = name
+
+
+fluffy = Cat(name="Mr Fluffy")
+```
+
+У цьому випадку `fluffy` - екземпляр класу `Cat`.
+
+А для створення `fluffy` ви «викликаєте» `Cat`.
+
+Отже, клас Python також є **викликаємим**.
+
+Тож у **FastAPI** ви можете використовувати клас Python як залежність.
+
+Насправді **FastAPI** перевіряє, що це «викликаємий» об’єкт (функція, клас чи щось інше) і які параметри в нього оголошені.
+
+Якщо ви передаєте «викликаємий» як залежність у **FastAPI**, він проаналізує параметри цього об’єкта і обробить їх так само, як параметри для функції операції шляху. Включно з підзалежностями.
+
+Це також стосується викликаємих без жодних параметрів. Так само, як і для функцій операцій шляху без параметрів.
+
+Тоді ми можемо змінити залежність `common_parameters` вище на клас `CommonQueryParams`:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}
+
+Зверніть увагу на метод `__init__`, який використовують для створення екземпляра класу:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}
+
+…він має ті самі параметри, що й наш попередній `common_parameters`:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}
+
+Саме ці параметри **FastAPI** використає, щоб «розв’язати» залежність.
+
+В обох випадках буде:
+
+- Необов’язковий параметр запиту `q`, який є `str`.
+- Параметр запиту `skip`, який є `int`, зі значенням за замовчуванням `0`.
+- Параметр запиту `limit`, який є `int`, зі значенням за замовчуванням `100`.
+
+В обох випадках дані будуть перетворені, перевірені й задокументовані в схемі OpenAPI тощо.
+
+## Використання { #use-it }
+
+Тепер ви можете оголосити залежність, використовуючи цей клас.
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}
+
+**FastAPI** викликає клас `CommonQueryParams`. Це створює «екземпляр» цього класу, і цей екземпляр буде передано як параметр `commons` у вашу функцію.
+
+## Анотація типів проти `Depends` { #type-annotation-vs-depends }
+
+Зверніть увагу, що вище ми двічі пишемо `CommonQueryParams`:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+Останній `CommonQueryParams` у:
+
+```Python
+... Depends(CommonQueryParams)
+```
+
+ - це те, що **FastAPI** фактично використає, щоб дізнатися, яка залежність.
+
+Саме з нього **FastAPI** витягне оголошені параметри і саме його **FastAPI** буде викликати.
+
+---
+
+У цьому випадку перший `CommonQueryParams` у:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
+
+…не має жодного особливого значення для **FastAPI**. FastAPI не використовуватиме його для перетворення даних, перевірки тощо (адже для цього використовується `Depends(CommonQueryParams)`).
+
+Насправді ви могли б написати просто:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
+
+…як у:
+
+{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}
+
+Але оголошувати тип рекомендується - так ваш редактор знатиме, що буде передано в параметр `commons`, і зможе допомагати з автодоповненням, перевірками типів тощо:
+
+
+
+## Скорочення { #shortcut }
+
+Але ви бачите, що тут маємо деяке дублювання коду - `CommonQueryParams` пишемо двічі:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+**FastAPI** надає скорочення для таких випадків, коли залежність - це саме клас, який **FastAPI** «викличе», щоб створити екземпляр цього класу.
+
+Для таких випадків ви можете зробити так:
+
+Замість того щоб писати:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+…напишіть:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+Ви оголошуєте залежність як тип параметра і використовуєте `Depends()` без параметрів, замість того щоб вдруге писати повний клас усередині `Depends(CommonQueryParams)`.
+
+Той самий приклад виглядатиме так:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+…і **FastAPI** знатиме, що робити.
+
+/// tip | Порада
+
+Якщо це здається заплутанішим, ніж корисним, просто не використовуйте це - воно не є обов’язковим.
+
+Це лише скорочення. Адже **FastAPI** дбає про мінімізацію дублювання коду.
+
+///
diff --git a/docs/uk/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/uk/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 000000000..4614c626c
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# Залежності в декораторах операцій шляху { #dependencies-in-path-operation-decorators }
+
+Іноді вам насправді не потрібне значення, яке повертає залежність, у вашій *функції операції шляху*.
+
+Або залежність узагалі не повертає значення.
+
+Але її все одно потрібно виконати/опрацювати.
+
+Для таких випадків, замість оголошення параметра *функції операції шляху* з `Depends`, ви можете додати `list` `dependencies` до *декоратора операції шляху*.
+
+## Додайте `dependencies` до *декоратора операції шляху* { #add-dependencies-to-the-path-operation-decorator }
+
+*Декоратор операції шляху* приймає необов'язковий аргумент `dependencies`.
+
+Це має бути `list` з `Depends()`:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+Ці залежності будуть виконані/оброблені так само, як звичайні залежності. Але їхні значення (якщо щось повертають) не передаватимуться у вашу *функцію операції шляху*.
+
+/// tip | Порада
+
+Деякі редактори перевіряють невикористані параметри функцій і показують їх як помилки.
+
+Використовуючи ці `dependencies` у *декораторі операції шляху*, ви можете гарантувати їх виконання та водночас уникнути помилок редактора/інструментів.
+
+Це також може допомогти уникнути плутанини для нових розробників, які бачать невикористаний параметр у вашому коді й можуть вирішити, що він зайвий.
+
+///
+
+/// info | Інформація
+
+У цьому прикладі ми використовуємо вигадані власні заголовки `X-Key` і `X-Token`.
+
+Але в реальних випадках, під час впровадження безпеки, ви отримаєте більше користі, використовуючи вбудовані [Інструменти безпеки (наступний розділ)](../security/index.md){.internal-link target=_blank}.
+
+///
+
+## Помилки залежностей і значення, що повертаються { #dependencies-errors-and-return-values }
+
+Ви можете використовувати ті самі *функції* залежностей, що й зазвичай.
+
+### Вимоги залежностей { #dependency-requirements }
+
+Вони можуть оголошувати вимоги до запиту (наприклад, заголовки) або інші підзалежності:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### Підіймати винятки { #raise-exceptions }
+
+Ці залежності можуть `raise` винятки, так само як і звичайні залежності:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### Значення, що повертаються { #return-values }
+
+Вони можуть повертати значення або ні - ці значення не використовуватимуться.
+
+Отже, ви можете перевикористати звичайну залежність (яка повертає значення), яку вже застосовуєте деінде, і навіть якщо значення не буде використано, залежність буде виконана:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## Залежності для групи операцій шляху { #dependencies-for-a-group-of-path-operations }
+
+Далі, читаючи про структурування великих застосунків ([Більші застосунки - декілька файлів](../../tutorial/bigger-applications.md){.internal-link target=_blank}), можливо з кількома файлами, ви дізнаєтеся, як оголосити один параметр `dependencies` для групи *операцій шляху*.
+
+## Глобальні залежності { #global-dependencies }
+
+Далі ми побачимо, як додати залежності до всього застосунку `FastAPI`, щоб вони застосовувалися до кожної *операції шляху*.
diff --git a/docs/uk/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/uk/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 000000000..70d4210a1
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,289 @@
+# Залежності з yield { #dependencies-with-yield }
+
+FastAPI підтримує залежності, які виконують деякі додаткові кроки після завершення.
+
+Щоб це зробити, використовуйте `yield` замість `return` і напишіть додаткові кроки (код) після нього.
+
+/// tip | Порада
+
+Переконайтесь, що ви використовуєте `yield` лише один раз на залежність.
+
+///
+
+/// note | Технічні деталі
+
+Будь-яка функція, яку можна використовувати з:
+
+* `@contextlib.contextmanager` або
+* `@contextlib.asynccontextmanager`
+
+буде придатною як залежність у **FastAPI**.
+
+Насправді FastAPI використовує ці два декоратори внутрішньо.
+
+///
+
+## Залежність бази даних з `yield` { #a-database-dependency-with-yield }
+
+Наприклад, ви можете використати це, щоб створити сесію бази даних і закрити її після завершення.
+
+Перед створенням відповіді виконується лише код до і включно з оператором `yield`:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+Значення, передане `yield`, впроваджується в *операції шляху* та інші залежності:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+Код після оператора `yield` виконується після відповіді:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip | Порада
+
+Можете використовувати як `async`, так і звичайні функції.
+
+**FastAPI** зробить усе правильно з кожною з них, так само як і зі звичайними залежностями.
+
+///
+
+## Залежність з `yield` та `try` { #a-dependency-with-yield-and-try }
+
+Якщо ви використовуєте блок `try` в залежності з `yield`, ви отримаєте будь-який виняток, який був згенерований під час використання залежності.
+
+Наприклад, якщо якийсь код десь посередині, в іншій залежності або в *операції шляху*, зробив «rollback» транзакції бази даних або створив будь-який інший виняток, ви отримаєте цей виняток у своїй залежності.
+
+Тож ви можете обробити цей конкретний виняток усередині залежності за допомогою `except SomeException`.
+
+Так само ви можете використовувати `finally`, щоб гарантувати виконання завершальних кроків незалежно від того, був виняток чи ні.
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## Підзалежності з `yield` { #sub-dependencies-with-yield }
+
+Ви можете мати підзалежності та «дерева» підзалежностей будь-якого розміру і форми, і будь-яка або всі з них можуть використовувати `yield`.
+
+**FastAPI** гарантує, що «exit code» у кожній залежності з `yield` буде виконано в правильному порядку.
+
+Наприклад, `dependency_c` може залежати від `dependency_b`, а `dependency_b` - від `dependency_a`:
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+І всі вони можуть використовувати `yield`.
+
+У цьому випадку `dependency_c`, щоб виконати свій завершальний код, потребує, щоб значення з `dependency_b` (тут `dep_b`) все ще було доступним.
+
+І, у свою чергу, `dependency_b` потребує, щоб значення з `dependency_a` (тут `dep_a`) було доступним для свого завершального коду.
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+Так само ви можете мати деякі залежності з `yield`, а інші - з `return`, і частина з них може залежати від інших.
+
+І ви можете мати одну залежність, яка вимагає кілька інших залежностей з `yield` тощо.
+
+Ви можете мати будь-які комбінації залежностей, які вам потрібні.
+
+**FastAPI** подбає, щоб усе виконувалося в правильному порядку.
+
+/// note | Технічні деталі
+
+Це працює завдяки Менеджерам контексту Python.
+
+**FastAPI** використовує їх внутрішньо, щоб досягти цього.
+
+///
+
+## Залежності з `yield` та `HTTPException` { #dependencies-with-yield-and-httpexception }
+
+Ви бачили, що можна використовувати залежності з `yield` і мати блоки `try`, які намагаються виконати деякий код, а потім запускають завершальний код після `finally`.
+
+Також можна використовувати `except`, щоб перехопити згенерований виняток і щось із ним зробити.
+
+Наприклад, ви можете підняти інший виняток, як-от `HTTPException`.
+
+/// tip | Порада
+
+Це доволі просунута техніка, і в більшості випадків вона вам не знадобиться, адже ви можете піднімати винятки (включно з `HTTPException`) всередині іншого коду вашого застосунку, наприклад, у *функції операції шляху*.
+
+Але вона є, якщо вам це потрібно. 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+Якщо ви хочете перехоплювати винятки та створювати на їх основі користувацьку відповідь, створіть [Користувацький обробник винятків](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
+
+## Залежності з `yield` та `except` { #dependencies-with-yield-and-except }
+
+Якщо ви перехоплюєте виняток за допомогою `except` у залежності з `yield` і не піднімаєте його знову (або не піднімаєте новий виняток), FastAPI не зможе помітити, що стався виняток, так само як це було б у звичайному Python:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+У цьому випадку клієнт побачить відповідь *HTTP 500 Internal Server Error*, як і має бути, з огляду на те, що ми не піднімаємо `HTTPException` або подібний виняток, але на сервері **не буде жодних логів** чи інших ознак того, що це була за помилка. 😱
+
+### Завжди використовуйте `raise` у залежностях з `yield` та `except` { #always-raise-in-dependencies-with-yield-and-except }
+
+Якщо ви перехоплюєте виняток у залежності з `yield`, якщо тільки ви не піднімаєте інший `HTTPException` або подібний, **вам слід повторно підняти початковий виняток**.
+
+Ви можете повторно підняти той самий виняток, використовуючи `raise`:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+Тепер клієнт отримає ту саму відповідь *HTTP 500 Internal Server Error*, але сервер матиме наш користувацький `InternalError` у логах. 😎
+
+## Виконання залежностей з `yield` { #execution-of-dependencies-with-yield }
+
+Послідовність виконання приблизно така, як на цій діаграмі. Час тече зверху вниз. І кожна колонка - це одна з частин, що взаємодіють або виконують код.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant handler as Exception handler
+participant dep as Dep with yield
+participant operation as Path Operation
+participant tasks as Background tasks
+
+ Note over client,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ end
+
+ operation ->> client: Return response to client
+ Note over client,operation: Response is already sent, can't change it anymore
+ opt Tasks
+ operation -->> tasks: Send background tasks
+ end
+ opt Raise other exception
+ tasks -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info | Інформація
+
+Лише **одна відповідь** буде надіслана клієнту. Це може бути одна з помилкових відповідей або відповідь від *операції шляху*.
+
+Після відправлення однієї з цих відповідей іншу відправити не можна.
+
+///
+
+/// tip | Порада
+
+Якщо ви піднімаєте будь-який виняток у коді з *функції операції шляху*, він буде переданий у залежності з `yield`, включно з `HTTPException`. У більшості випадків ви захочете повторно підняти той самий виняток або новий із залежності з `yield`, щоб переконатися, що його коректно оброблено.
+
+///
+
+## Ранній вихід і `scope` { #early-exit-and-scope }
+
+Зазвичай завершальний код залежностей з `yield` виконується **після того**, як відповідь надіслано клієнту.
+
+Але якщо ви знаєте, що вам не потрібно використовувати залежність після повернення з *функції операції шляху*, ви можете використати `Depends(scope="function")`, щоб сказати FastAPI, що слід закрити залежність після повернення з *функції операції шляху*, але **до** надсилання **відповіді**.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` приймає параметр `scope`, який може бути:
+
+* `"function"`: запустити залежність перед *функцією операції шляху*, що обробляє запит, завершити залежність після завершення *функції операції шляху*, але **до** того, як відповідь буде відправлена клієнту. Тобто функція залежності буде виконуватися **навколо** *функції операції **шляху***.
+* `"request"`: запустити залежність перед *функцією операції шляху*, що обробляє запит (подібно до `"function"`), але завершити **після** того, як відповідь буде відправлена клієнту. Тобто функція залежності буде виконуватися **навколо** циклу **запиту** та відповіді.
+
+Якщо не вказано, і залежність має `yield`, за замовчуванням `scope` дорівнює `"request"`.
+
+### `scope` для підзалежностей { #scope-for-sub-dependencies }
+
+Коли ви оголошуєте залежність із `scope="request"` (за замовчуванням), будь-яка підзалежність також має мати `scope` рівний `"request"`.
+
+Але залежність з `scope` рівним `"function"` може мати залежності з `scope` `"function"` і `scope` `"request"`.
+
+Це тому, що будь-яка залежність має бути здатною виконати свій завершальний код раніше за підзалежності, оскільки вона може все ще потребувати їх під час свого завершального коду.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## Залежності з `yield`, `HTTPException`, `except` і фоновими задачами { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+Залежності з `yield` еволюціонували з часом, щоб покрити різні сценарії та виправити деякі проблеми.
+
+Якщо ви хочете дізнатися, що змінювалося в різних версіях FastAPI, прочитайте про це в просунутому посібнику користувача: [Розширені залежності - Залежності з `yield`, `HTTPException`, `except` і фоновими задачами](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks){.internal-link target=_blank}.
+## Менеджери контексту { #context-managers }
+
+### Що таке «Менеджери контексту» { #what-are-context-managers }
+
+«Менеджери контексту» - це будь-які Python-об'єкти, які можна використовувати в операторі `with`.
+
+Наприклад, можна використати `with`, щоб прочитати файл:
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+Під капотом `open("./somefile.txt")` створює об'єкт, який називається «Менеджер контексту».
+
+Коли блок `with` завершується, він гарантує закриття файлу, навіть якщо були винятки.
+
+Коли ви створюєте залежність з `yield`, **FastAPI** внутрішньо створить для неї менеджер контексту й поєднає його з іншими пов'язаними інструментами.
+
+### Використання менеджерів контексту в залежностях з `yield` { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | Попередження
+
+Це, загалом, «просунута» ідея.
+
+Якщо ви тільки починаєте з **FastAPI**, можливо, варто наразі пропустити це.
+
+///
+
+У Python ви можете створювати Менеджери контексту, створивши клас із двома методами: `__enter__()` і `__exit__()`.
+
+Ви також можете використовувати їх усередині залежностей **FastAPI** з `yield`, використовуючи
+`with` або `async with` у середині функції залежності:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip | Порада
+
+Інший спосіб створити менеджер контексту:
+
+* `@contextlib.contextmanager` або
+* `@contextlib.asynccontextmanager`
+
+використовуючи їх для декорування функції з одним `yield`.
+
+Саме це **FastAPI** використовує внутрішньо для залежностей з `yield`.
+
+Але вам не потрібно використовувати ці декоратори для залежностей FastAPI (і не варто).
+
+FastAPI зробить це за вас внутрішньо.
+
+///
diff --git a/docs/uk/docs/tutorial/dependencies/global-dependencies.md b/docs/uk/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 000000000..3cffa1752
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,15 @@
+# Глобальні залежності { #global-dependencies }
+
+Для деяких типів застосунків ви можете захотіти додати залежності до всього застосунку.
+
+Подібно до того, як ви можете [додавати `dependencies` до *декораторів операцій шляху*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, ви можете додати їх до застосунку `FastAPI`.
+
+У такому разі вони будуть застосовані до всіх *операцій шляху* в застосунку:
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+Усі ідеї з розділу про [додавання `dependencies` до *декораторів операцій шляху*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} так само застосовні, але в цьому випадку - до всіх *операцій шляху* в застосунку.
+
+## Залежності для груп *операцій шляху* { #dependencies-for-groups-of-path-operations }
+
+Пізніше, читаючи про структуру більших застосунків ([Більші застосунки - кілька файлів](../../tutorial/bigger-applications.md){.internal-link target=_blank}), можливо з кількома файлами, ви дізнаєтеся, як оголосити єдиний параметр `dependencies` для групи *операцій шляху*.
diff --git a/docs/uk/docs/tutorial/dependencies/index.md b/docs/uk/docs/tutorial/dependencies/index.md
new file mode 100644
index 000000000..cbcf69307
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/index.md
@@ -0,0 +1,250 @@
+# Залежності { #dependencies }
+
+**FastAPI** має дуже потужну, але інтуїтивну систему **Впровадження залежностей**.
+
+Вона створена так, щоб бути дуже простою у використанні та щоб полегшити будь-якому розробнику інтеграцію інших компонентів з **FastAPI**.
+
+## Що таке «Впровадження залежностей» { #what-is-dependency-injection }
+
+У програмуванні **«Впровадження залежностей»** означає, що існує спосіб для вашого коду (у цьому випадку ваших *функцій операцій шляху*) задекларувати речі, які йому потрібні для роботи: «залежності».
+
+А потім ця система (у цьому випадку **FastAPI**) подбає про все необхідне, щоб надати вашому коду ці потрібні залежності («інжектувати» залежності).
+
+Це дуже корисно, коли вам потрібно:
+
+* Мати спільну логіку (одна й та сама логіка знову і знову).
+* Ділитися з’єднаннями з базою даних.
+* Примусово застосовувати безпеку, автентифікацію, вимоги до ролей тощо.
+* І багато іншого...
+
+Все це з мінімізацією дублювання коду.
+
+## Перші кроки { #first-steps }
+
+Розгляньмо дуже простий приклад. Він буде таким простим, що поки що не дуже корисним.
+
+Але так ми зможемо зосередитися на тому, як працює система **Впровадження залежностей**.
+
+### Створіть залежність або «залежний» { #create-a-dependency-or-dependable }
+
+Спочатку зосередьмося на залежності.
+
+Це просто функція, яка може приймати ті самі параметри, що й *функція операції шляху*:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+Ось і все.
+
+**2 рядки**.
+
+І вона має ту саму форму та структуру, що й усі ваші *функції операцій шляху*.
+
+Можете думати про неї як про *функцію операції шляху* без «декоратора» (без `@app.get("/some-path")`).
+
+І вона може повертати будь-що.
+
+У цьому випадку ця залежність очікує:
+
+* Необов’язковий параметр запиту `q` типу `str`.
+* Необов’язковий параметр запиту `skip` типу `int`, за замовчуванням `0`.
+* Необов’язковий параметр запиту `limit` типу `int`, за замовчуванням `100`.
+
+Потім вона просто повертає `dict`, що містить ці значення.
+
+/// info | Інформація
+
+FastAPI додав підтримку `Annotated` (і почав її рекомендувати) у версії 0.95.0.
+
+Якщо у вас старіша версія, ви отримаєте помилки при спробі використати `Annotated`.
+
+Переконайтеся, що ви [Оновіть версію FastAPI](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} щонайменше до 0.95.1 перед використанням `Annotated`.
+
+///
+
+### Імпортуйте `Depends` { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### Оголосіть залежність у «залежному» { #declare-the-dependency-in-the-dependant }
+
+Так само, як ви використовуєте `Body`, `Query` тощо з параметрами вашої *функції операції шляху*, використовуйте `Depends` з новим параметром:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+Хоча ви використовуєте `Depends` у параметрах вашої функції так само, як `Body`, `Query` тощо, `Depends` працює трохи інакше.
+
+Ви передаєте в `Depends` лише один параметр.
+
+Цей параметр має бути чимось на кшталт функції.
+
+Ви її не викликаєте безпосередньо (не додавайте дужки в кінці), ви просто передаєте її як параметр у `Depends()`.
+
+І ця функція приймає параметри так само, як і *функції операцій шляху*.
+
+/// tip | Порада
+
+У наступному розділі ви побачите, які ще «речі», окрім функцій, можна використовувати як залежності.
+
+///
+
+Щоразу, коли надходить новий запит, **FastAPI** подбає про:
+
+* Виклик вашої функції-залежності («залежного») з правильними параметрами.
+* Отримання результату з вашої функції.
+* Присвоєння цього результату параметру у вашій *функції операції шляху*.
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+Таким чином ви пишете спільний код один раз, а **FastAPI** подбає про його виклик для ваших *операцій шляху*.
+
+/// check | Перевірте
+
+Зверніть увагу, що вам не потрібно створювати спеціальний клас і передавати його кудись у **FastAPI**, щоб «зареєструвати» його чи щось подібне.
+
+Ви просто передаєте його в `Depends`, і **FastAPI** знає, що робити далі.
+
+///
+
+## Спільне використання залежностей `Annotated` { #share-annotated-dependencies }
+
+У наведених вище прикладах видно невелике **дублювання коду**.
+
+Коли вам потрібно використати залежність `common_parameters()`, доводиться писати весь параметр з анотацією типу та `Depends()`:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+Але оскільки ми використовуємо `Annotated`, ми можемо зберегти це значення `Annotated` у змінній і використовувати його в кількох місцях:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | Порада
+
+Це просто стандартний Python, це називається «псевдонім типу» і насправді не є специфічним для **FastAPI**.
+
+Але оскільки **FastAPI** базується на стандартах Python, включно з `Annotated`, ви можете використати цей трюк у своєму коді. 😎
+
+///
+
+Залежності продовжать працювати як очікується, і **найкраще** те, що **інформація про типи буде збережена**, а це означає, що ваш редактор зможе й надалі надавати **автозаповнення**, **помилки в рядку** тощо. Те саме і для інших інструментів, як-от `mypy`.
+
+Це буде особливо корисно у **великій кодовій базі**, де ви використовуєте **одні й ті самі залежності** знову і знову в **багатьох *операціях шляху***.
+
+## Бути `async` чи не бути `async` { #to-async-or-not-to-async }
+
+Оскільки залежності також викликатимуться **FastAPI** (так само, як і ваші *функції операцій шляху*), під час визначення ваших функцій діють ті самі правила.
+
+Ви можете використовувати `async def` або звичайний `def`.
+
+І ви можете оголошувати залежності з `async def` всередині звичайних *функцій операцій шляху* з `def`, або залежності з `def` всередині *функцій операцій шляху* з `async def` тощо.
+
+Це не має значення. **FastAPI** знатиме, що робити.
+
+/// note | Примітка
+
+Якщо ви не впевнені, перегляньте розділ [Async: *"In a hurry?"*](../../async.md#in-a-hurry){.internal-link target=_blank} про `async` і `await` у документації.
+
+///
+
+## Інтегровано з OpenAPI { #integrated-with-openapi }
+
+Усі декларації запитів, перевірки та вимоги ваших залежностей (і субзалежностей) будуть інтегровані в ту саму схему OpenAPI.
+
+Тож інтерактивна документація також міститиме всю інформацію з цих залежностей:
+
+
+
+## Просте використання { #simple-usage }
+
+Якщо придивитися, *функції операцій шляху* оголошуються для використання щоразу, коли збігаються *шлях* та *операція*, а потім **FastAPI** подбає про виклик функції з правильними параметрами, витягуючи дані із запиту.
+
+Насправді всі (або більшість) вебфреймворків працюють так само.
+
+Ви ніколи не викликаєте ці функції безпосередньо. Їх викликає ваш фреймворк (у цьому випадку **FastAPI**).
+
+За допомогою системи впровадження залежностей ви також можете вказати **FastAPI**, що ваша *функція операції шляху* також «залежить» від чогось, що має бути виконано до вашої *функції операції шляху*, і **FastAPI** подбає про виконання цього та «інжектування» результатів.
+
+Інші поширені терміни для цієї самої ідеї «впровадження залежностей»:
+
+* ресурси
+* провайдери
+* сервіси
+* інжектовані об’єкти
+* компоненти
+
+## Плагіни **FastAPI** { #fastapi-plug-ins }
+
+Інтеграції та «плагіни» можна будувати за допомогою системи **Впровадження залежностей**. Але насправді **немає потреби створювати «плагіни»**, оскільки, використовуючи залежності, можна оголосити безмежну кількість інтеграцій та взаємодій, які стають доступними для ваших *функцій операцій шляху*.
+
+І залежності можна створювати дуже просто та інтуїтивно, що дозволяє вам просто імпортувати потрібні пакунки Python і інтегрувати їх з вашими функціями API за кілька рядків коду, буквально.
+
+Ви побачите приклади цього в наступних розділах, про реляційні та NoSQL бази даних, безпеку тощо.
+
+## Сумісність **FastAPI** { #fastapi-compatibility }
+
+Простота системи впровадження залежностей робить **FastAPI** сумісним з:
+
+* усіма реляційними базами даних
+* NoSQL базами даних
+* зовнішніми пакунками
+* зовнішніми API
+* системами автентифікації та авторизації
+* системами моніторингу використання API
+* системами інжекції даних у відповідь
+* тощо.
+
+## Просто і потужно { #simple-and-powerful }
+
+Хоча ієрархічна система впровадження залежностей дуже проста у визначенні та використанні, вона все ще дуже потужна.
+
+Ви можете визначати залежності, які своєю чергою можуть визначати власні залежності.
+
+Зрештою будується ієрархічне дерево залежностей, і система **Впровадження залежностей** подбає про розв’язання всіх цих залежностей (і їхніх субзалежностей) та надання (інжектування) результатів на кожному кроці.
+
+Наприклад, припустімо, у вас є 4 кінцеві точки API (*операції шляху*):
+
+* `/items/public/`
+* `/items/private/`
+* `/users/{user_id}/activate`
+* `/items/pro/`
+
+тоді ви могли б додати різні вимоги до дозволів для кожної з них лише за допомогою залежностей і субзалежностей:
+
+```mermaid
+graph TB
+
+current_user(["current_user"])
+active_user(["active_user"])
+admin_user(["admin_user"])
+paying_user(["paying_user"])
+
+public["/items/public/"]
+private["/items/private/"]
+activate_user["/users/{user_id}/activate"]
+pro_items["/items/pro/"]
+
+current_user --> active_user
+active_user --> admin_user
+active_user --> paying_user
+
+current_user --> public
+active_user --> private
+admin_user --> activate_user
+paying_user --> pro_items
+```
+
+## Інтегровано з **OpenAPI** { #integrated-with-openapi_1 }
+
+Усі ці залежності, декларуючи свої вимоги, також додають параметри, перевірки тощо до ваших *операцій шляху*.
+
+**FastAPI** подбає про додавання всього цього до схеми OpenAPI, щоб це відображалося в інтерактивних системах документації.
diff --git a/docs/uk/docs/tutorial/dependencies/sub-dependencies.md b/docs/uk/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 000000000..4e7488086
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# Підзалежності { #sub-dependencies }
+
+Ви можете створювати залежності, які мають підзалежності.
+
+Вони можуть бути настільки глибокими, наскільки потрібно.
+
+FastAPI подбає про їх розв'язання.
+
+## Перша залежність «dependable» { #first-dependency-dependable }
+
+Можна створити першу залежність («dependable») так:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+Вона оголошує необов'язковий параметр запиту `q` типу `str`, а потім просто повертає його.
+
+Це досить просто (не дуже корисно), але допоможе зосередитися на тому, як працюють підзалежності.
+
+## Друга залежність, «dependable» і «dependant» { #second-dependency-dependable-and-dependant }
+
+Далі ви можете створити іншу функцію залежності («dependable»), яка водночас оголошує власну залежність (тож вона також є «dependant»):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+Зосередьмося на оголошених параметрах:
+
+- Хоча ця функція сама є залежністю («dependable»), вона також оголошує іншу залежність (вона «залежить» від чогось).
+ - Вона залежить від `query_extractor` і присвоює значення, яке він повертає, параметру `q`.
+- Вона також оголошує необов'язкове кукі `last_query` типу `str`.
+ - Якщо користувач не надав параметр запиту `q`, ми використовуємо останній запит, який зберегли раніше в кукі.
+
+## Використання залежності { #use-the-dependency }
+
+Потім ми можемо використати залежність так:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info | Інформація
+
+Зверніть увагу, що ми оголошуємо лише одну залежність у функції операції шляху — `query_or_cookie_extractor`.
+
+Але FastAPI знатиме, що спочатку треба розв'язати `query_extractor`, щоб передати його результат у `query_or_cookie_extractor` під час виклику.
+
+///
+
+```mermaid
+graph TB
+
+query_extractor(["query_extractor"])
+query_or_cookie_extractor(["query_or_cookie_extractor"])
+
+read_query["/items/"]
+
+query_extractor --> query_or_cookie_extractor --> read_query
+```
+
+## Використання тієї ж залежності кілька разів { #using-the-same-dependency-multiple-times }
+
+Якщо одна з ваших залежностей оголошена кілька разів для однієї операції шляху, наприклад, кілька залежностей мають спільну підзалежність, FastAPI знатиме, що цю підзалежність потрібно викликати лише один раз на запит.
+
+І він збереже повернуте значення у «кеш» і передасть його всім «dependants», яким воно потрібне в цьому конкретному запиті, замість того щоб викликати залежність кілька разів для одного й того ж запиту.
+
+У просунутому сценарії, коли ви знаєте, що залежність має викликатися на кожному кроці (можливо, кілька разів) у межах того самого запиту замість використання «кешованого» значення, ви можете встановити параметр `use_cache=False` при використанні `Depends`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу версії з `Annotated`, якщо це можливо.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## Підсумок { #recap }
+
+Попри всі модні терміни, система впровадження залежностей досить проста.
+
+Це просто функції, які виглядають так само, як функції операцій шляху.
+
+Втім вона дуже потужна і дозволяє оголошувати довільно глибоко вкладені «графи» залежностей (дерева).
+
+/// tip | Порада
+
+Усе це може здаватися не надто корисним на простих прикладах.
+
+Але ви побачите, наскільки це корисно, у розділах про **безпеку**.
+
+І також побачите, скільки коду це вам заощадить.
+
+///
diff --git a/docs/uk/docs/tutorial/extra-models.md b/docs/uk/docs/tutorial/extra-models.md
new file mode 100644
index 000000000..25930b8c0
--- /dev/null
+++ b/docs/uk/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# Додаткові моделі { #extra-models }
+
+Продовжуючи попередній приклад, часто потрібно мати більше ніж одну пов’язану модель.
+
+Особливо це стосується моделей користувача, тому що:
+
+* **вхідна модель** повинна мати пароль.
+* **вихідна модель** не повинна містити пароль.
+* **модель бази даних**, ймовірно, повинна містити хеш пароля.
+
+/// danger | Обережно
+
+Ніколи не зберігайте паролі користувачів у відкритому вигляді. Завжди зберігайте «безпечний хеш», який потім можна перевірити.
+
+Якщо ви ще не знаєте, що таке «хеш пароля», ви дізнаєтесь у [розділах про безпеку](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+
+///
+
+## Кілька моделей { #multiple-models }
+
+Ось загальна ідея того, як можуть виглядати моделі з їхніми полями пароля та місцями використання:
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### Про `**user_in.model_dump()` { #about-user-in-model-dump }
+
+#### `.model_dump()` у Pydantic { #pydantics-model-dump }
+
+`user_in` - це модель Pydantic класу `UserIn`.
+
+Моделі Pydantic мають метод `.model_dump()`, який повертає `dict` з даними моделі.
+
+Отже, якщо ми створимо об’єкт Pydantic `user_in` так:
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+і викличемо:
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+тепер ми маємо `dict` з даними у змінній `user_dict` (це `dict`, а не об’єкт моделі Pydantic).
+
+А якщо викликати:
+
+```Python
+print(user_dict)
+```
+
+ми отримаємо Python `dict` з:
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### Розпакування `dict` { #unpacking-a-dict }
+
+Якщо взяти `dict`, наприклад `user_dict`, і передати його у функцію (або клас) як `**user_dict`, Python «розпакує» його. Ключі та значення `user_dict` будуть передані безпосередньо як іменовані аргументи.
+
+Отже, продовжуючи з `user_dict` вище, запис:
+
+```Python
+UserInDB(**user_dict)
+```
+
+дасть еквівалентний результат:
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ full_name=None,
+)
+```
+
+А точніше, використовуючи безпосередньо `user_dict`, з будь-яким його вмістом у майбутньому:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+)
+```
+
+#### Модель Pydantic зі вмісту іншої { #a-pydantic-model-from-the-contents-of-another }
+
+Як у прикладі вище ми отримали `user_dict` з `user_in.model_dump()`, цей код:
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+буде еквівалентним:
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+...тому що `user_in.model_dump()` повертає `dict`, а ми змушуємо Python «розпакувати» його, передаючи в `UserInDB` з префіксом `**`.
+
+Тож ми отримуємо модель Pydantic з даних іншої моделі Pydantic.
+
+#### Розпакування `dict` і додаткові ключові аргументи { #unpacking-a-dict-and-extra-keywords }
+
+Додаючи додатковий іменований аргумент `hashed_password=hashed_password`, як тут:
+
+```Python
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
+```
+
+...у підсумку це дорівнює:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ hashed_password = hashed_password,
+)
+```
+
+/// warning | Попередження
+
+Додаткові допоміжні функції `fake_password_hasher` і `fake_save_user` лише демонструють можливий потік даних і, звісно, не забезпечують реальної безпеки.
+
+///
+
+## Зменшення дублювання { #reduce-duplication }
+
+Зменшення дублювання коду - одна з ключових ідей у **FastAPI**.
+
+Адже дублювання коду підвищує ймовірність помилок, проблем безпеки, розсинхронізації коду (коли ви оновлюєте в одному місці, але не в інших) тощо.
+
+І ці моделі спільно використовують багато даних та дублюють назви і типи атрибутів.
+
+Можна зробити краще.
+
+Можна оголосити модель `UserBase`, яка буде базовою для інших моделей. Потім створити підкласи цієї моделі, що наслідуватимуть її атрибути (оголошення типів, валідацію тощо).
+
+Уся конвертація даних, валідація, документація тощо працюватимуть як зазвичай.
+
+Таким чином, ми оголошуємо лише відмінності між моделями (з відкритим `password`, з `hashed_password` і без пароля):
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` або `anyOf` { #union-or-anyof }
+
+Ви можете оголосити відповідь як `Union` двох або більше типів - це означає, що відповідь може бути будь-якого з них.
+
+В OpenAPI це буде визначено як `anyOf`.
+
+Для цього використайте стандартну підказку типу Python `typing.Union`:
+
+/// note | Примітка
+
+Під час визначення `Union` спочатку вказуйте найконкретніший тип, а потім менш конкретний. У прикладі нижче більш конкретний `PlaneItem` стоїть перед `CarItem` у `Union[PlaneItem, CarItem]`.
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### `Union` у Python 3.10 { #union-in-python-3-10 }
+
+У цьому прикладі ми передаємо `Union[PlaneItem, CarItem]` як значення аргументу `response_model`.
+
+Оскільки ми передаємо його як значення аргументу, а не в анотації типу, потрібно використовувати `Union` навіть у Python 3.10.
+
+Якби це була анотація типу, можна було б використати вертикальну риску, наприклад:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+Але якщо записати це як присвоєння `response_model=PlaneItem | CarItem`, отримаємо помилку, тому що Python спробує виконати невалідну операцію між `PlaneItem` і `CarItem`, замість того щоб трактувати це як анотацію типу.
+
+## Список моделей { #list-of-models }
+
+Аналогічно можна оголошувати відповіді як списки об’єктів.
+
+Для цього використайте стандартний Python `list`:
+
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
+
+## Відповідь з довільним `dict` { #response-with-arbitrary-dict }
+
+Також можна оголосити відповідь, використовуючи звичайний довільний `dict`, вказавши лише типи ключів і значень, без моделі Pydantic.
+
+Це корисно, якщо ви заздалегідь не знаєте допустимі назви полів/атрибутів (які були б потрібні для моделі Pydantic).
+
+У такому разі можна використати `dict`:
+
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
+
+## Підсумок { #recap }
+
+Використовуйте кілька моделей Pydantic і вільно наслідуйте для кожного випадку.
+
+Не обов’язково мати одну модель даних на сутність, якщо ця сутність може мати різні «стани». Як у випадку сутності користувача зі станами: з `password`, з `password_hash` і без пароля.
diff --git a/docs/uk/docs/tutorial/path-operation-configuration.md b/docs/uk/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 000000000..91b58b24e
--- /dev/null
+++ b/docs/uk/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# Налаштування операції шляху { #path-operation-configuration }
+
+Є кілька параметрів, які ви можете передати вашому «декоратору операції шляху» для налаштування.
+
+/// warning | Попередження
+
+Зверніть увагу, що ці параметри передаються безпосередньо «декоратору операції шляху», а не вашій «функції операції шляху».
+
+///
+
+## Код статусу відповіді { #response-status-code }
+
+Ви можете визначити (HTTP) `status_code`, який буде використано у відповіді вашої «операції шляху».
+
+Можна передати безпосередньо цілий код, наприклад `404`.
+
+Якщо ви не пам'ятаєте призначення числових кодів, скористайтеся скороченими константами в `status`:
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+Цей код статусу буде використано у відповіді та додано до схеми OpenAPI.
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette import status`.
+
+FastAPI надає той самий `starlette.status` як `fastapi.status` для вашої зручності як розробника. Але він походить безпосередньо зі Starlette.
+
+///
+
+## Мітки { #tags }
+
+Ви можете додати мітки до вашої «операції шляху», передайте параметр `tags` зі `list` із `str` (зазвичай лише один `str`):
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+Вони будуть додані до схеми OpenAPI та використані інтерфейсами автоматичної документації:
+
+
+
+### Мітки з переліками { #tags-with-enums }
+
+У великому застосунку ви можете накопичити багато міток і захочете переконатися, що завжди використовуєте ту саму мітку для пов'язаних «операцій шляху».
+
+У таких випадках має сенс зберігати мітки в `Enum`.
+
+FastAPI підтримує це так само, як і зі звичайними строками:
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
+
+## Короткий опис і опис { #summary-and-description }
+
+Ви можете додати `summary` і `description`:
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## Опис зі строки документації { #description-from-docstring }
+
+Оскільки описи зазвичай довгі та займають кілька рядків, ви можете оголосити опис «операції шляху» у строці документації функції, і FastAPI прочитає його звідти.
+
+Ви можете писати Markdown у строці документації, його буде інтерпретовано та показано коректно (з урахуванням відступів у строці документації).
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+Його буде використано в інтерактивній документації:
+
+
+
+## Опис відповіді { #response-description }
+
+Ви можете вказати опис відповіді параметром `response_description`:
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info | Інформація
+
+Зверніть увагу, що `response_description` стосується саме відповіді, а `description` стосується «операції шляху» загалом.
+
+///
+
+/// check | Перевірте
+
+OpenAPI визначає, що кожна «операція шляху» потребує опису відповіді.
+
+Тому, якщо ви його не надасте, FastAPI автоматично згенерує «Successful response».
+
+///
+
+
+
+## Позначити операцію шляху як застарілу { #deprecate-a-path-operation }
+
+Якщо потрібно позначити «операцію шляху» як застарілу, але не видаляючи її, передайте параметр `deprecated`:
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
+
+У інтерактивній документації вона буде чітко позначена як застаріла:
+
+
+
+Подивіться, як виглядають застарілі та незастарілі «операції шляху»:
+
+
+
+## Підсумок { #recap }
+
+Ви можете легко налаштовувати та додавати метадані до ваших «операцій шляху», передаючи параметри «декораторам операцій шляху».
diff --git a/docs/uk/docs/tutorial/security/first-steps.md b/docs/uk/docs/tutorial/security/first-steps.md
new file mode 100644
index 000000000..491328d86
--- /dev/null
+++ b/docs/uk/docs/tutorial/security/first-steps.md
@@ -0,0 +1,203 @@
+# Безпека - перші кроки { #security-first-steps }
+
+Уявімо, що ваш **backend** API працює на певному домені.
+
+А **frontend** - на іншому домені або в іншому шляху того ж домену (або у мобільному застосунку).
+
+І ви хочете, щоб frontend міг автентифікуватися в backend, використовуючи ім'я користувача та пароль.
+
+Ми можемо використати **OAuth2**, щоб збудувати це з **FastAPI**.
+
+Але заощадимо вам час на читання всієї довгої специфікації, щоб знайти лише потрібні дрібниці.
+
+Скористаймося інструментами, які надає **FastAPI**, щоб обробляти безпеку.
+
+## Як це виглядає { #how-it-looks }
+
+Спочатку просто запустімо код і подивімося, як він працює, а потім повернемося, щоб розібратися, що відбувається.
+
+## Створіть `main.py` { #create-main-py }
+
+Скопіюйте приклад у файл `main.py`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## Запустіть { #run-it }
+
+/// info | Інформація
+
+Пакет `python-multipart` автоматично встановлюється з **FastAPI**, коли ви виконуєте команду `pip install "fastapi[standard]"`.
+
+Однак, якщо ви використовуєте команду `pip install fastapi`, пакет `python-multipart` за замовчуванням не включено.
+
+Щоб встановити його вручну, переконайтеся, що ви створили [віртуальне оточення](../../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили:
+
+```console
+$ pip install python-multipart
+```
+
+Це тому, що **OAuth2** використовує «form data» для надсилання `username` та `password`.
+
+///
+
+Запустіть приклад:
+
+
+
+/// check | Кнопка Authorize!
+
+У вас уже є нова блискуча кнопка «Authorize».
+
+А ваша *операція шляху* має маленький замок у правому верхньому куті, на який можна натиснути.
+
+///
+
+Якщо натиснути її, з’явиться маленька форма авторизації, щоб ввести `username` і `password` (та інші необов’язкові поля):
+
+
+
+/// note | Примітка
+
+Неважливо, що ви введете у форму, поки що це не спрацює. Але ми скоро це доробимо.
+
+///
+
+Звісно, це не frontend для кінцевих користувачів, але це чудовий інструмент для інтерактивної документації всього вашого API.
+
+Ним може користуватися команда frontend (якою можете бути і ви самі).
+
+Ним можуть користуватися сторонні застосунки та системи.
+
+І ним також можете користуватися ви самі, щоб налагоджувати, перевіряти та тестувати той самий застосунок.
+
+## Потік паролю { #the-password-flow }
+
+Тепер повернімося трохи назад і розберімося, що це все таке.
+
+`password` «flow» - це один зі способів («flows»), визначених в OAuth2, для обробки безпеки та автентифікації.
+
+OAuth2 був спроєктований так, щоб backend або API могли бути незалежними від сервера, який автентифікує користувача.
+
+Але в нашому випадку той самий застосунок **FastAPI** оброблятиме і API, і автентифікацію.
+
+Тож розгляньмо це у спрощеному вигляді:
+
+- Користувач вводить `username` і `password` у frontend і натискає `Enter`.
+- Frontend (у браузері користувача) надсилає ці `username` і `password` на специфічну URL-адресу нашого API (оголошену як `tokenUrl="token"`).
+- API перевіряє ці `username` і `password` та повертає «токен» (ми ще нічого з цього не реалізували).
+ - «Токен» - це просто строка з деяким вмістом, який ми можемо пізніше використати, щоб перевірити цього користувача.
+ - Зазвичай токен налаштований на завершення строку дії через певний час.
+ - Тож користувачу доведеться знову увійти пізніше.
+ - І якщо токен викрадуть, ризик менший. Це не як постійний ключ, який працюватиме завжди (у більшості випадків).
+- Frontend тимчасово зберігає цей токен десь.
+- Користувач клікає у frontend, щоб перейти до іншого розділу вебзастосунку.
+- Frontend має отримати ще дані з API.
+ - Але для того конкретного кінцевого пункту потрібна автентифікація.
+ - Тож, щоб автентифікуватися в нашому API, він надсилає заголовок `Authorization` зі значенням `Bearer ` плюс токен.
+ - Якщо токен містить `foobar`, вміст заголовка `Authorization` буде: `Bearer foobar`.
+
+## `OAuth2PasswordBearer` у **FastAPI** { #fastapis-oauth2passwordbearer }
+
+**FastAPI** надає кілька інструментів на різних рівнях абстракції, щоб реалізувати ці функції безпеки.
+
+У цьому прикладі ми використаємо **OAuth2** з потоком **Password**, використовуючи токен **Bearer**. Це робиться за допомогою класу `OAuth2PasswordBearer`.
+
+/// info | Інформація
+
+«Bearer»-токен - не єдиний варіант.
+
+Але це найкращий для нашого сценарію.
+
+І, можливо, найкращий для більшості сценаріїв, якщо ви не експерт з OAuth2 і точно не знаєте, чому інша опція краще відповідає вашим потребам.
+
+У такому разі **FastAPI** теж надає інструменти, щоб це збудувати.
+
+///
+
+Коли ми створюємо екземпляр класу `OAuth2PasswordBearer`, ми передаємо параметр `tokenUrl`. Цей параметр містить URL, який клієнт (frontend у браузері користувача) використовуватиме, щоб надіслати `username` і `password` для отримання токена.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip | Порада
+
+Тут `tokenUrl="token"` відноситься до відносної URL-адреси `token`, яку ми ще не створили. Оскільки це відносна URL-адреса, вона еквівалентна `./token`.
+
+Тому, якщо ваш API розміщений на `https://example.com/`, це буде `https://example.com/token`. А якщо на `https://example.com/api/v1/`, тоді це буде `https://example.com/api/v1/token`.
+
+Використання відносної URL-адреси важливе, щоб ваша програма продовжувала працювати навіть у просунутому сценарії, як-от [Behind a Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+
+///
+
+Цей параметр не створює той endpoint / *операцію шляху*, а декларує, що URL `/token` буде тим, який клієнт має використовувати, щоб отримати токен. Ця інформація використовується в OpenAPI, а потім - у системах інтерактивної документації API.
+
+Незабаром ми також створимо фактичну операцію шляху.
+
+/// info | Інформація
+
+Якщо ви дуже строгий «Pythonista», вам може не подобатися стиль імені параметра `tokenUrl` замість `token_url`.
+
+Це тому, що використано ту саму назву, що і в специфікації OpenAPI. Тож якщо вам потрібно буде дослідити ці схеми безпеки глибше, ви зможете просто скопіювати та вставити її, щоб знайти більше інформації.
+
+///
+
+Змінна `oauth2_scheme` - це екземпляр `OAuth2PasswordBearer`, але це також і «викликаємий» об’єкт.
+
+Його можна викликати так:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+Тож його можна використовувати з `Depends`.
+
+### Використання { #use-it }
+
+Тепер ви можете передати `oauth2_scheme` як залежність через `Depends`.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Ця залежність надасть `str`, який буде присвоєний параметру `token` *функції операції шляху*.
+
+**FastAPI** знатиме, що може використати цю залежність, щоб визначити «схему безпеки» в схемі OpenAPI (і в автоматичній документації API).
+
+/// info | Технічні деталі
+
+**FastAPI** знатиме, що може використати клас `OAuth2PasswordBearer` (оголошений у залежності), щоб визначити схему безпеки в OpenAPI, тому що він наслідує `fastapi.security.oauth2.OAuth2`, який своєю чергою наслідує `fastapi.security.base.SecurityBase`.
+
+Усі утиліти безпеки, які інтегруються з OpenAPI (і автоматичною документацією API), наслідують `SecurityBase`. Так **FastAPI** розуміє, як інтегрувати їх в OpenAPI.
+
+///
+
+## Що відбувається { #what-it-does }
+
+Вона шукатиме в запиті заголовок `Authorization`, перевірить, чи його значення - це `Bearer ` плюс деякий токен, і поверне токен як `str`.
+
+Якщо заголовка `Authorization` немає або значення не містить токена `Bearer `, вона одразу відповість помилкою зі статус-кодом 401 (`UNAUTHORIZED`).
+
+Вам навіть не потрібно перевіряти, чи існує токен, щоб повернути помилку. Ви можете бути певні: якщо ваша функція виконується, у параметрі токена буде `str`.
+
+Ви вже можете спробувати це в інтерактивній документації:
+
+
+
+Ми ще не перевіряємо дійсність токена, але це вже початок.
+
+## Підсумок { #recap }
+
+Отже, лише 3-4 додатковими рядками ви вже маєте деяку примітивну форму безпеки.
diff --git a/docs/uk/docs/tutorial/security/get-current-user.md b/docs/uk/docs/tutorial/security/get-current-user.md
new file mode 100644
index 000000000..2371ad9fc
--- /dev/null
+++ b/docs/uk/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# Отримати поточного користувача { #get-current-user }
+
+У попередньому розділі система безпеки (яка базується на системі впровадження залежностей) передавала функції операції шляху `token` як `str`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Але це ще не дуже корисно.
+
+Зробімо так, щоб вона повертала поточного користувача.
+
+## Створити модель користувача { #create-a-user-model }
+
+Спочатку створімо модель користувача в Pydantic.
+
+Так само, як ми використовуємо Pydantic для оголошення тіл, ми можемо використовувати його будь-де:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## Створити залежність `get_current_user` { #create-a-get-current-user-dependency }
+
+Створімо залежність `get_current_user`.
+
+Пам'ятаєте, що залежності можуть мати підзалежності?
+
+`get_current_user` матиме залежність із тим самим `oauth2_scheme`, який ми створили раніше.
+
+Так само, як ми робили раніше безпосередньо в операції шляху, наша нова залежність `get_current_user` отримає `token` як `str` від підзалежності `oauth2_scheme`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## Отримати користувача { #get-the-user }
+
+`get_current_user` використає (фальшиву) утилітну функцію, яку ми створили, що приймає `token` як `str` і повертає нашу Pydantic-модель `User`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## Впровадити поточного користувача { #inject-the-current-user }
+
+Тепер ми можемо використати той самий `Depends` з нашим `get_current_user` в операції шляху:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+Зверніть увагу, що ми оголошуємо тип `current_user` як Pydantic-модель `User`.
+
+Це допоможе всередині функції з автодоповненням і перевірками типів.
+
+/// tip | Порада
+
+Можливо, ви пам'ятаєте, що тіла запиту також оголошуються моделями Pydantic.
+
+Тут **FastAPI** не заплутається, тому що ви використовуєте `Depends`.
+
+///
+
+/// check | Перевірте
+
+Те, як спроєктована ця система залежностей, дозволяє мати різні залежності (різні «залежні»), які всі повертають модель `User`.
+
+Ми не обмежені наявністю лише однієї залежності, що може повертати такі дані.
+
+///
+
+## Інші моделі { #other-models }
+
+Тепер ви можете отримувати поточного користувача безпосередньо у функціях операцій шляху та працювати з механізмами безпеки на рівні **впровадження залежностей**, використовуючи `Depends`.
+
+І ви можете використовувати будь-яку модель або дані для вимог безпеки (у цьому випадку Pydantic-модель `User`).
+
+Але ви не обмежені використанням якоїсь конкретної модели даних, класу чи типу.
+
+Хочете мати id та email і не мати жодного username у вашій моделі? Без проблем. Ви можете використовувати ті самі інструменти.
+
+Хочете мати просто `str`? Або лише `dict`? Або безпосередньо екземпляр класу моделі бази даних? Усе працює так само.
+
+У вашій програмі насправді входять не користувачі, а роботи, боти чи інші системи, що мають лише токен доступу? Знову ж, усе працює так само.
+
+Просто використовуйте будь-який тип моделі, будь-який клас, будь-яку базу даних, які потрібні вашій програмі. **FastAPI** подбає про це завдяки системі впровадження залежностей.
+
+## Розмір коду { #code-size }
+
+Цей приклад може здаватися багатослівним. Майте на увазі, що ми змішуємо безпеку, моделі даних, утилітні функції та операції шляху в одному файлі.
+
+Але ось ключовий момент.
+
+Речі, пов'язані з безпекою та впровадженням залежностей, пишуться один раз.
+
+І ви можете зробити це настільки складним, наскільки потрібно. І все одно мати це написаним лише один раз, в одному місці. З усією гнучкістю.
+
+Зате ви можете мати тисячі кінцевих точок (операцій шляху), що використовують одну й ту саму систему безпеки.
+
+І всі вони (або будь-яка їхня частина, яку ви захочете) можуть скористатися повторним використанням цих залежностей або будь-яких інших, які ви створите.
+
+І всі ці тисячі операцій шляху можуть бути всього у 3 рядки:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## Підсумок { #recap }
+
+Тепер ви можете отримувати поточного користувача безпосередньо у вашій функції операції шляху.
+
+Ми вже на півдорозі.
+
+Потрібно лише додати операцію шляху, щоб користувач/клієнт міг фактично надіслати `username` і `password`.
+
+Далі саме це.
diff --git a/docs/uk/docs/tutorial/security/oauth2-jwt.md b/docs/uk/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 000000000..f94abb897
--- /dev/null
+++ b/docs/uk/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# OAuth2 з паролем (і хешуванням), Bearer з токенами JWT { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+Тепер, коли ми маємо весь потік безпеки, зробімо застосунок справді захищеним, використовуючи токени JWT і безпечне хешування паролів.
+
+Цей код ви можете реально використовувати у своєму застосунку, зберігати хеші паролів у своїй базі даних тощо.
+
+Ми почнемо з того місця, де зупинилися в попередньому розділі, і розширимо його.
+
+## Про JWT { #about-jwt }
+
+JWT означає «JSON Web Tokens».
+
+Це стандарт кодування об'єкта JSON у довгий щільний рядок без пробілів. Він виглядає так:
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+Він не зашифрований, тому кожен може відновити інформацію з вмісту.
+
+Але він підписаний. Тож коли ви отримуєте токен, який ви видали, ви можете перевірити, що справді його видали ви.
+
+Таким чином, ви можете створити токен із терміном дії, наприклад, 1 тиждень. І коли користувач повернеться наступного дня з токеном, ви знатимете, що користувач досі увійшов у вашу систему.
+
+Через тиждень токен завершить термін дії, і користувач не буде авторизований та має знову увійти, щоб отримати новий токен. І якщо користувач (або третя сторона) намагатиметься змінити токен, щоб змінити термін дії, ви це виявите, бо підписи не співпадатимуть.
+
+Якщо хочете «погратися» з токенами JWT і побачити, як вони працюють, перегляньте https://jwt.io.
+
+## Встановіть `PyJWT` { #install-pyjwt }
+
+Нам потрібно встановити `PyJWT`, щоб створювати та перевіряти токени JWT у Python.
+
+Переконайтеся, що ви створили [віртуальне оточення](../../virtual-environments.md){.internal-link target=_blank}, активували його і тоді встановіть `pyjwt`:
+
+
+
+Авторизуйте застосунок так само, як раніше.
+
+Використайте облікові дані:
+
+Username: `johndoe`
+Password: `secret`
+
+/// check | Перевірте
+
+Зверніть увагу, що ніде в коді немає відкритого пароля "`secret`", ми маємо лише хешовану версію.
+
+///
+
+
+
+Викличте кінцеву точку `/users/me/`, ви отримаєте відповідь:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+Якщо відкриєте інструменти розробника, ви побачите, що у відправлених даних є лише токен, пароль надсилається тільки в першому запиті для автентифікації користувача та отримання токена доступу, але не надсилається далі:
+
+
+
+/// note | Примітка
+
+Зверніть увагу на заголовок `Authorization` зі значенням, що починається з `Bearer `.
+
+///
+
+## Просунуте використання зі `scopes` { #advanced-usage-with-scopes }
+
+OAuth2 має поняття «scopes».
+
+Ви можете використовувати їх, щоб додати конкретний набір дозволів до токена JWT.
+
+Потім ви можете видати цей токен користувачу напряму або третій стороні для взаємодії з вашою API із набором обмежень.
+
+Ви можете дізнатися, як їх використовувати і як вони інтегровані з **FastAPI** пізніше у **просунутому посібнику користувача**.
+
+## Підсумок { #recap }
+
+Маючи все, що ви бачили досі, ви можете налаштувати захищений застосунок **FastAPI**, використовуючи стандарти на кшталт OAuth2 і JWT.
+
+Майже в будь-якому фреймворку опрацювання безпеки дуже швидко стає досить складною темою.
+
+Багато пакетів, що сильно це спрощують, змушені йти на численні компроміси з моделлю даних, базою даних і доступними можливостями. Дехто з цих пакетів, які надто все спрощують, насправді мають приховані вади безпеки.
+
+---
+
+**FastAPI** не йде на жодні компроміси з будь-якою базою даних, моделлю даних чи інструментом.
+
+Він дає вам усю гнучкість, щоб обрати ті, які найкраще підходять вашому проєкту.
+
+І ви можете напряму використовувати добре підтримувані та широко застосовувані пакети на кшталт `pwdlib` і `PyJWT`, адже **FastAPI** не вимагає жодних складних механізмів для інтеграції зовнішніх пакетів.
+
+Водночас він надає інструменти, щоб максимально спростити процес без компромісів у гнучкості, надійності чи безпеці.
+
+І ви можете використовувати та впроваджувати безпечні стандартні протоколи, як-от OAuth2, відносно простим способом.
+
+У **просунутому посібнику користувача** ви можете дізнатися більше про те, як використовувати «scopes» в OAuth2 для більш детальної системи дозволів, дотримуючись тих самих стандартів. OAuth2 зі scopes - це механізм, який використовують багато великих провайдерів автентифікації, як-от Facebook, Google, GitHub, Microsoft, X (Twitter) тощо, щоб авторизувати сторонні застосунки на взаємодію з їхніми API від імені користувачів.
diff --git a/docs/uk/docs/tutorial/security/simple-oauth2.md b/docs/uk/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 000000000..05f949738
--- /dev/null
+++ b/docs/uk/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# Простий OAuth2 з паролем і Bearer { #simple-oauth2-with-password-and-bearer }
+
+Тепер продовжимо з попереднього розділу і додамо відсутні частини, щоб отримати повний потік безпеки.
+
+## Отримайте `username` і `password` { #get-the-username-and-password }
+
+Ми використаємо утиліти безпеки **FastAPI**, щоб отримати `username` і `password`.
+
+OAuth2 визначає, що під час використання «потоку паролю» (який ми використовуємо) клієнт/користувач має надіслати поля `username` і `password` як дані форми.
+
+І специфікація каже, що поля мають називатися саме так. Тому `user-name` або `email` не підійдуть.
+
+Але не хвилюйтеся, у фронтенді ви можете відображати це так, як забажаєте, для кінцевих користувачів.
+
+І ваші моделі бази даних можуть використовувати будь-які інші назви.
+
+Але для *операції шляху* входу ми маємо використовувати саме ці назви, щоб бути сумісними зі специфікацією (і мати змогу, наприклад, користуватися вбудованою системою документації API).
+
+Специфікація також вказує, що `username` і `password` мають надсилатися як дані форми (тобто без JSON).
+
+### `scope` { #scope }
+
+Специфікація також каже, що клієнт може надіслати інше поле форми «`scope`».
+
+Назва поля форми — `scope` (в однині), але насправді це довга строка зі «scopes», розділеними пробілами.
+
+Кожен «scope» — це просто строка (без пробілів).
+
+Їх зазвичай використовують для оголошення конкретних прав доступу, наприклад:
+
+- `users:read` або `users:write` — поширені приклади.
+- `instagram_basic` використовується Facebook / Instagram.
+- `https://www.googleapis.com/auth/drive` використовується Google.
+
+/// info | Інформація
+
+У OAuth2 «scope» — це просто строка, що оголошує конкретний потрібний дозвіл.
+
+Не має значення, чи містить вона інші символи на кшталт `:` або чи це URL.
+
+Ці деталі залежать від реалізації.
+
+Для OAuth2 це просто строки.
+
+///
+
+## Код для отримання `username` і `password` { #code-to-get-the-username-and-password }
+
+Тепер скористаймося утилітами, наданими **FastAPI**, щоб обробити це.
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+Спочатку імпортуйте `OAuth2PasswordRequestForm` і використайте його як залежність із `Depends` в *операції шляху* для `/token`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` — це клас залежності, що оголошує тіло форми з:
+
+- `username`.
+- `password`.
+- Необов'язковим полем `scope` як великою строкою, складеною зі строк, розділених пробілами.
+- Необов'язковим `grant_type`.
+
+/// tip | Порада
+
+Специфікація OAuth2 насправді вимагає поле `grant_type` із фіксованим значенням `password`, але `OAuth2PasswordRequestForm` цього не примушує.
+
+Якщо вам потрібно це примусити, використовуйте `OAuth2PasswordRequestFormStrict` замість `OAuth2PasswordRequestForm`.
+
+///
+
+- Необов'язковим `client_id` (для нашого прикладу не потрібно).
+- Необов'язковим `client_secret` (для нашого прикладу не потрібно).
+
+/// info | Інформація
+
+`OAuth2PasswordRequestForm` — не спеціальний клас для **FastAPI**, як `OAuth2PasswordBearer`.
+
+`OAuth2PasswordBearer` робить так, що **FastAPI** знає, що це схема безпеки. Тому її додають таким чином до OpenAPI.
+
+Але `OAuth2PasswordRequestForm` — це просто клас залежності, який ви могли б написати самі, або ви могли б напряму оголосити параметри `Form`.
+
+Оскільки це типова задача, **FastAPI** надає його безпосередньо, щоб спростити роботу.
+
+///
+
+### Використовуйте дані форми { #use-the-form-data }
+
+/// tip | Порада
+
+Екземпляр класу залежності `OAuth2PasswordRequestForm` не матиме атрибута `scope` з довгою строкою, розділеною пробілами, натомість він матиме атрибут `scopes` зі справжнім списком строк для кожного надісланого scope.
+
+У цьому прикладі ми не використовуємо `scopes`, але ця можливість є, якщо знадобиться.
+
+///
+
+Тепер отримайте дані користувача з (фальшивої) бази даних, використовуючи `username` з поля форми.
+
+Якщо такого користувача немає, повертаємо помилку «Incorrect username or password».
+
+Для помилки використовуємо виняток `HTTPException`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### Перевірте пароль { #check-the-password }
+
+На цьому етапі ми маємо дані користувача з нашої бази даних, але ще не перевірили пароль.
+
+Спершу розмістимо ці дані в Pydantic-моделі `UserInDB`.
+
+Ви ніколи не повинні зберігати паролі у відкритому вигляді, тож ми використаємо (фальшиву) систему хешування паролів.
+
+Якщо паролі не збігаються, повертаємо ту саму помилку.
+
+#### Хешування паролів { #password-hashing }
+
+«Хешування» означає: перетворення деякого вмісту (у цьому випадку пароля) у послідовність байтів (просто строку), яка виглядає як нісенітниця.
+
+Кожного разу, коли ви передаєте точно той самий вміст (точно той самий пароль), ви отримуєте точно ту саму «нісенітницю».
+
+Але ви не можете перетворити цю «нісенітницю» назад у пароль.
+
+##### Навіщо використовувати хешування паролів { #why-use-password-hashing }
+
+Якщо вашу базу даних вкрадуть, зловмисник не матиме паролів користувачів у відкритому вигляді, лише хеші.
+
+Тож зловмисник не зможе спробувати використати ті самі паролі в іншій системі (оскільки багато користувачів використовують той самий пароль всюди, це було б небезпечно).
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### Про `**user_dict` { #about-user-dict }
+
+`UserInDB(**user_dict)` означає:
+
+Передати ключі та значення з `user_dict` безпосередньо як аргументи ключ-значення, еквівалентно до:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info | Інформація
+
+Для повнішого пояснення `**user_dict` перегляньте [документацію для **Додаткових моделей**](../extra-models.md#about-user-in-dict){.internal-link target=_blank}.
+
+///
+
+## Поверніть токен { #return-the-token }
+
+Відповідь точки входу `token` має бути об'єктом JSON.
+
+Вона повинна містити `token_type`. У нашому випадку, оскільки ми використовуємо токени «Bearer», тип токена має бути «`bearer`».
+
+Також має бути `access_token` зі строкою, що містить наш токен доступу.
+
+Для цього простого прикладу ми зробимо повністю небезпечно і повернемо той самий `username` як токен.
+
+/// tip | Порада
+
+У наступному розділі ви побачите справді безпечну реалізацію з хешуванням паролів і токенами JWT.
+
+А поки зосередьмося на конкретних деталях, які нам потрібні.
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | Порада
+
+Згідно зі специфікацією, ви маєте повертати JSON з `access_token` і `token_type`, як у цьому прикладі.
+
+Це те, що ви маєте зробити самостійно у своєму коді, і переконатися, що використовуєте саме ці ключі JSON.
+
+Це майже єдине, що ви маєте зробити правильно самі, щоб відповідати специфікації.
+
+Решту **FastAPI** зробить за вас.
+
+///
+
+## Оновіть залежності { #update-the-dependencies }
+
+Тепер оновимо наші залежності.
+
+Ми хочемо отримати `current_user` лише якщо цей користувач активний.
+
+Тому створимо додаткову залежність `get_current_active_user`, яка своєю чергою використовує як залежність `get_current_user`.
+
+Обидві ці залежності просто повернуть HTTP-помилку, якщо користувача не існує або він неактивний.
+
+Отже, у нашій кінцевій точці ми отримаємо користувача лише якщо він існує, був правильно автентифікований і є активним:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | Інформація
+
+Додатковий заголовок `WWW-Authenticate` зі значенням `Bearer`, який ми тут повертаємо, також є частиною специфікації.
+
+Будь-який HTTP (помилка) зі статус-кодом 401 «UNAUTHORIZED» також має повертати заголовок `WWW-Authenticate`.
+
+У випадку токенів носія (наш випадок) значенням цього заголовка має бути `Bearer`.
+
+Фактично ви можете пропустити цей додатковий заголовок, і все одно працюватиме.
+
+Але він наданий тут, щоб відповідати специфікаціям.
+
+Також можуть існувати інструменти, які очікують і використовують його (зараз або в майбутньому), і це може бути корисно вам або вашим користувачам, зараз або в майбутньому.
+
+У цьому користь стандартів...
+
+///
+
+## Подивіться в дії { #see-it-in-action }
+
+Відкрийте інтерактивну документацію: http://127.0.0.1:8000/docs.
+
+### Автентифікація { #authenticate }
+
+Натисніть кнопку «Authorize».
+
+Використайте облікові дані:
+
+Користувач: `johndoe`
+
+Пароль: `secret`
+
+
+
+Після автентифікації в системі ви побачите таке:
+
+
+
+### Отримайте власні дані користувача { #get-your-own-user-data }
+
+Тепер використайте операцію `GET` зі шляхом `/users/me`.
+
+Ви отримаєте дані свого користувача, наприклад:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+Якщо натиснути значок замка й вийти з системи, а потім знову спробувати ту саму операцію, ви отримаєте помилку HTTP 401 такого вигляду:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### Неактивний користувач { #inactive-user }
+
+Тепер спробуйте з неактивним користувачем, автентифікуйтеся з:
+
+Користувач: `alice`
+
+Пароль: `secret2`
+
+І спробуйте використати операцію `GET` зі шляхом `/users/me`.
+
+Ви отримаєте помилку «Inactive user», наприклад:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## Підсумок { #recap }
+
+Тепер у вас є інструменти для реалізації повної системи безпеки на основі `username` і `password` для вашого API.
+
+Використовуючи ці інструменти, ви можете зробити систему безпеки сумісною з будь-якою базою даних і з будь-якою моделлю користувача чи даних.
+
+Єдина відсутня деталь у тому, що наразі це ще не «безпечна» реалізація.
+
+У наступному розділі ви побачите, як використовувати безпечну бібліотеку для хешування паролів і токени JWT.
diff --git a/docs/uk/docs/tutorial/sql-databases.md b/docs/uk/docs/tutorial/sql-databases.md
new file mode 100644
index 000000000..991d1e33a
--- /dev/null
+++ b/docs/uk/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# SQL (реляційні) бази даних { #sql-relational-databases }
+
+**FastAPI** не вимагає від вас використовувати SQL (реляційну) базу даних. Але ви можете скористатися будь-якою базою даних, яку забажаєте.
+
+Тут ми розглянемо приклад з SQLModel.
+
+**SQLModel** побудовано поверх SQLAlchemy та Pydantic. Її створив той самий автор, що і **FastAPI**, як ідеальну пару для застосунків FastAPI, яким потрібні **SQL бази даних**.
+
+/// tip | Порада
+
+Ви можете використовувати будь-яку іншу бібліотеку для SQL або NoSQL баз (інколи їх називають "ORMs"), FastAPI нічого не нав’язує. 😎
+
+///
+
+Оскільки SQLModel базується на SQLAlchemy, ви можете легко використовувати будь-яку базу даних, яку підтримує SQLAlchemy (а отже й SQLModel), наприклад:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server тощо
+
+У цьому прикладі ми використаємо **SQLite**, оскільки вона зберігається в одному файлі, а Python має вбудовану підтримку. Тож ви можете скопіювати цей приклад і запустити «як є».
+
+Пізніше, для вашого продакшн-застосунку, ви можете перейти на сервер бази даних, наприклад **PostgreSQL**.
+
+/// tip | Порада
+
+Існує офіційний генератор проєкту з **FastAPI** та **PostgreSQL**, включно з фронтендом та іншими інструментами: https://github.com/fastapi/full-stack-fastapi-template
+
+///
+
+Це дуже простий і короткий навчальний посібник. Якщо ви хочете вивчити бази даних загалом, SQL або більш просунуті можливості, зверніться до документації SQLModel.
+
+## Встановіть `SQLModel` { #install-sqlmodel }
+
+Спочатку переконайтеся, що ви створили [віртуальне оточення](../virtual-environments.md){.internal-link target=_blank}, активували його та встановили `sqlmodel`:
+
+
+
+harry v1]
+ style harry-1 fill:#ccc,stroke-dasharray: 5 5
+ harry-3[harry v3]
+ end
+ subgraph stone-project[philosophers-stone project]
+ stone(philosophers-stone) -.-x|⛔️| harry-1
+ end
+ subgraph azkaban-project[prisoner-of-azkaban project]
+ azkaban(prisoner-of-azkaban) --> |requires| harry-3
+ end
+```
+
+/// tip | Порада
+
+У пакетах Python дуже поширена практика намагатися якнайкраще уникати несумісних змін у нових версіях, але краще підстрахуватися та встановлювати новіші версії свідомо і тоді, коли ви можете запустити тести, щоб перевірити, що все працює коректно.
+
+///
+
+Тепер уявіть те саме з багатьма іншими пакетами, від яких залежать усі ваші проєкти. Це дуже складно керувати. І ви, імовірно, запускатимете деякі проєкти з деякими несумісними версіями пакетів і не розумітимете, чому щось не працює.
+
+Також, залежно від вашої операційної системи (напр., Linux, Windows, macOS), у ній може бути вже встановлений Python. І в такому разі, імовірно, уже будуть попередньо встановлені деякі пакети з певними версіями, потрібними вашій системі. Якщо ви встановлюєте пакети в глобальне середовище Python, ви можете зламати деякі програми, що постачаються з вашою операційною системою.
+
+## Де встановлюються пакети { #where-are-packages-installed }
+
+Коли ви встановлюєте Python, він створює на вашому комп'ютері кілька каталогів із деякими файлами.
+
+Деякі з цих каталогів відповідають за зберігання всіх пакетів, які ви встановлюєте.
+
+Коли ви запускаєте:
+
+
-그리고 WebSockets가 포함된 **FastAPI** 응용 프로그램이 응답을 돌려줄 것입니다:
+그리고 WebSockets가 포함된 **FastAPI** 애플리케이션이 응답을 돌려줄 것입니다:
@@ -121,7 +121,7 @@ WebSocket이기 때문에 `HTTPException`을 발생시키는 것은 적절하지
### 종속성을 가진 WebSockets 시도해보기 { #try-the-websockets-with-dependencies }
-파일 이름이 `main.py`라고 가정하고 다음으로 응용 프로그램을 실행합니다:
+파일 이름이 `main.py`라고 가정하고 다음으로 애플리케이션을 실행합니다:
+
httpx - `TestClient`를 사용하려면 필요.
* jinja2 - 기본 템플릿 설정을 사용하려면 필요.
-* python-multipart - `request.form()`과 함께 form "parsing" 지원을 원하면 필요.
+* python-multipart - `request.form()`과 함께 form "파싱" 지원을 원하면 필요.
FastAPI가 사용하는:
diff --git a/docs/ko/docs/project-generation.md b/docs/ko/docs/project-generation.md
index 73ea67d3e..e3120e6f8 100644
--- a/docs/ko/docs/project-generation.md
+++ b/docs/ko/docs/project-generation.md
@@ -2,7 +2,7 @@
템플릿은 일반적으로 특정 설정과 함께 제공되지만, 유연하고 커스터마이징이 가능하게 디자인 되었습니다. 이 특성들은 여러분이 프로젝트의 요구사항에 맞춰 수정, 적용을 할 수 있게 해주고, 템플릿이 완벽한 시작점이 되게 해줍니다. 🏁
-많은 초기 설정, 보안, 데이터베이스 및 일부 API 엔드포인트가 이미 준비되어 있으므로, 여러분은 이 템플릿을 (프로젝트를) 시작하는 데 사용할 수 있습니다.
+많은 초기 설정, 보안, 데이터베이스 및 일부 API 엔드포인트가 이미 준비되어 있으므로, 여러분은 이 템플릿을 시작하는 데 사용할 수 있습니다.
GitHub 저장소: Full Stack FastAPI 템플릿
diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md
index dc264df80..d7d9021ed 100644
--- a/docs/ko/docs/python-types.md
+++ b/docs/ko/docs/python-types.md
@@ -2,7 +2,7 @@
파이썬은 선택적으로 "타입 힌트(type hints)"(“type annotations”라고도 함)를 지원합니다.
-이러한 **"타입 힌트"** 또는 애너테이션은 변수의 타입을 선언할 수 있게 해주는 특수한 구문입니다.
+이러한 **"타입 힌트"** 또는 애너테이션은 변수의 타입을 선언할 수 있게 해주는 특수한 구문입니다.
변수의 타입을 선언하면 에디터와 도구가 더 나은 지원을 제공할 수 있습니다.
@@ -22,7 +22,7 @@
간단한 예제로 시작해봅시다:
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
이 프로그램을 호출하면 다음이 출력됩니다:
@@ -34,9 +34,9 @@ John Doe
* `first_name`과 `last_name`를 받습니다.
* `title()`로 각각의 첫 글자를 대문자로 변환합니다.
-* 가운데에 공백을 두고 연결합니다.
+* 가운데에 공백을 두고 연결합니다.
-{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
### 수정하기 { #edit-it }
@@ -80,7 +80,7 @@ John Doe
이것들이 "타입 힌트"입니다:
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
이것은 다음처럼 기본값을 선언하는 것과는 다릅니다:
@@ -108,7 +108,7 @@ John Doe
이 함수를 확인해보세요. 이미 타입 힌트가 있습니다:
-{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
에디터가 변수의 타입을 알고 있기 때문에, 자동완성만 되는 게 아니라 오류 검사도 할 수 있습니다:
@@ -116,7 +116,7 @@ John Doe
이제 고쳐야 한다는 것을 알고, `age`를 `str(age)`로 문자열로 바꿉니다:
-{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
## 타입 선언 { #declaring-types }
@@ -135,29 +135,32 @@ John Doe
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### 타입 매개변수가 있는 Generic(제네릭) 타입 { #generic-types-with-type-parameters }
+### `typing` 모듈 { #typing-module }
-`dict`, `list`, `set`, `tuple`처럼 다른 값을 담을 수 있는 데이터 구조가 있습니다. 그리고 내부 값에도 각자의 타입이 있을 수 있습니다.
+몇 가지 추가적인 사용 사례에서는 표준 라이브러리의 `typing` 모듈에서 무언가를 import해야 할 수 있습니다. 예를 들어 어떤 값이 "아무 타입"일 수 있다고 선언하려면, `typing`의 `Any`를 사용할 수 있습니다:
-이렇게 내부 타입을 가지는 타입을 "**generic**" 타입이라고 부릅니다. 그리고 내부 타입까지 포함해 선언할 수도 있습니다.
+```python
+from typing import Any
-이런 타입과 내부 타입을 선언하려면 표준 파이썬 모듈 `typing`을 사용할 수 있습니다. 이 모듈은 이러한 타입 힌트를 지원하기 위해 존재합니다.
-#### 더 최신 버전의 Python { #newer-versions-of-python }
+def some_function(data: Any):
+ print(data)
+```
-`typing`을 사용하는 문법은 Python 3.6부터 최신 버전까지, Python 3.9, Python 3.10 등을 포함한 모든 버전과 **호환**됩니다.
+### Generic(제네릭) 타입 { #generic-types }
-파이썬이 발전함에 따라 **더 최신 버전**에서는 이러한 타입 애너테이션 지원이 개선되며, 많은 경우 타입 애너테이션을 선언하기 위해 `typing` 모듈을 import해서 사용할 필요조차 없게 됩니다.
+일부 타입은 대괄호 안에 "타입 매개변수"를 받아 내부 타입을 정의할 수 있습니다. 예를 들어 "문자열의 리스트"는 `list[str]`로 선언합니다.
-프로젝트에서 더 최신 버전의 파이썬을 선택할 수 있다면, 그 추가적인 단순함을 활용할 수 있습니다.
+이렇게 타입 매개변수를 받을 수 있는 타입을 **Generic types** 또는 **Generics**라고 부릅니다.
-이 문서 전체에는 각 파이썬 버전과 호환되는 예제가 있습니다(차이가 있을 때).
+대괄호와 내부 타입을 사용해 동일한 내장 타입들을 제네릭으로 사용할 수 있습니다:
-예를 들어 "**Python 3.6+**"는 Python 3.6 이상(3.7, 3.8, 3.9, 3.10 등 포함)과 호환된다는 뜻입니다. 그리고 "**Python 3.9+**"는 Python 3.9 이상(3.10 등 포함)과 호환된다는 뜻입니다.
-
-**최신 버전의 Python**을 사용할 수 있다면, 최신 버전용 예제를 사용하세요. 예를 들어 "**Python 3.10+**"처럼, 가장 **좋고 가장 단순한 문법**을 갖게 됩니다.
+* `list`
+* `tuple`
+* `set`
+* `dict`
#### List { #list }
@@ -169,7 +172,7 @@ John Doe
`list`는 내부 타입을 포함하는 타입이므로, 그 타입들을 대괄호 안에 넣습니다:
-{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
/// info | 정보
@@ -195,7 +198,7 @@ John Doe
`tuple`과 `set`도 동일하게 선언할 수 있습니다:
-{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
이는 다음을 의미합니다:
@@ -210,7 +213,7 @@ John Doe
두 번째 타입 매개변수는 `dict`의 값을 위한 것입니다:
-{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
이는 다음을 의미합니다:
@@ -222,44 +225,20 @@ John Doe
변수가 **여러 타입 중 어떤 것이든** 될 수 있다고 선언할 수 있습니다. 예를 들어 `int` 또는 `str`입니다.
-Python 3.6 이상(3.10 포함)에서는 `typing`의 `Union` 타입을 사용하고, 대괄호 안에 허용할 수 있는 타입들을 넣을 수 있습니다.
+이를 정의하려면 두 타입을 세로 막대(`|`)로 구분해 사용합니다.
-Python 3.10에는 가능한 타입들을 세로 막대(`|`)로 구분해 넣을 수 있는 **새 문법**도 있습니다.
-
-//// tab | Python 3.10+
+이는 두 타입 집합의 합집합(union) 안의 어느 것이든 될 수 있다는 뜻이므로 "유니온"이라고 부릅니다.
```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-////
-
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b_py39.py!}
-```
-
-////
-
-두 경우 모두 이는 `item`이 `int` 또는 `str`일 수 있다는 뜻입니다.
+이는 `item`이 `int` 또는 `str`일 수 있다는 뜻입니다.
#### `None`일 수도 있음 { #possibly-none }
값이 `str` 같은 타입일 수도 있지만, `None`일 수도 있다고 선언할 수 있습니다.
-Python 3.6 이상(3.10 포함)에서는 `typing` 모듈에서 `Optional`을 import해서 사용하여 선언할 수 있습니다.
-
-```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-그냥 `str` 대신 `Optional[str]`을 사용하면, 값이 항상 `str`이라고 가정하고 있지만 실제로는 `None`일 수도 있는 상황에서 에디터가 오류를 감지하도록 도와줍니다.
-
-`Optional[Something]`은 사실 `Union[Something, None]`의 축약이며, 서로 동등합니다.
-
-또한 이는 Python 3.10에서 `Something | None`을 사용할 수 있다는 의미이기도 합니다:
-
//// tab | Python 3.10+
```Python hl_lines="1"
@@ -268,96 +247,7 @@ Python 3.6 이상(3.10 포함)에서는 `typing` 모듈에서 `Optional`을 impo
////
-//// tab | Python 3.9+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009_py39.py!}
-```
-
-////
-
-//// tab | Python 3.9+ alternative
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b_py39.py!}
-```
-
-////
-
-#### `Union` 또는 `Optional` 사용하기 { #using-union-or-optional }
-
-Python 3.10 미만 버전을 사용한다면, 아주 **주관적인** 관점에서의 팁입니다:
-
-* 🚨 `Optional[SomeType]` 사용을 피하세요
-* 대신 ✨ **`Union[SomeType, None]`을 사용하세요** ✨.
-
-둘은 동등하고 내부적으로는 같은 것이지만, `Optional`이라는 단어가 값이 선택 사항인 것처럼 보일 수 있기 때문에 `Optional` 대신 `Union`을 권장합니다. 실제 의미는 값이 선택 사항이라는 뜻이 아니라, "값이 `None`일 수 있다"는 뜻이기 때문입니다. 선택 사항이 아니고 여전히 필수인 경우에도요.
-
-`Union[SomeType, None]`이 의미를 더 명확하게 드러낸다고 생각합니다.
-
-이건 단지 단어와 이름의 문제입니다. 하지만 그런 단어들이 여러분과 팀원이 코드에 대해 생각하는 방식에 영향을 줄 수 있습니다.
-
-예로, 이 함수를 봅시다:
-
-{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
-
-매개변수 `name`은 `Optional[str]`로 정의되어 있지만, **선택 사항이 아닙니다**. 매개변수 없이 함수를 호출할 수 없습니다:
-
-```Python
-say_hi() # Oh, no, this throws an error! 😱
-```
-
-기본값이 없기 때문에 `name` 매개변수는 **여전히 필수입니다**(*optional*이 아님). 그럼에도 `name`은 값으로 `None`을 허용합니다:
-
-```Python
-say_hi(name=None) # This works, None is valid 🎉
-```
-
-좋은 소식은 Python 3.10을 사용하면, 타입의 유니온을 정의하기 위해 간단히 `|`를 사용할 수 있어서 이런 걱정을 할 필요가 없다는 점입니다:
-
-{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
-
-그러면 `Optional`이나 `Union` 같은 이름에 대해 걱정할 필요도 없습니다. 😎
-
-#### Generic(제네릭) 타입 { #generic-types }
-
-대괄호 안에 타입 매개변수를 받는 이러한 타입들은 **Generic types** 또는 **Generics**라고 부릅니다. 예를 들면:
-
-//// tab | Python 3.10+
-
-대괄호와 내부 타입을 사용해, 동일한 내장 타입들을 제네릭으로 사용할 수 있습니다:
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-그리고 이전 파이썬 버전과 마찬가지로 `typing` 모듈의 다음도 사용할 수 있습니다:
-
-* `Union`
-* `Optional`
-* ...그 밖의 것들.
-
-Python 3.10에서는 제네릭 `Union`과 `Optional`을 사용하는 대안으로, 타입 유니온을 선언하기 위해 세로 막대(`|`)를 사용할 수 있는데, 훨씬 더 좋고 단순합니다.
-
-////
-
-//// tab | Python 3.9+
-
-대괄호와 내부 타입을 사용해, 동일한 내장 타입들을 제네릭으로 사용할 수 있습니다:
-
-* `list`
-* `tuple`
-* `set`
-* `dict`
-
-그리고 `typing` 모듈의 제네릭들:
-
-* `Union`
-* `Optional`
-* ...그 밖의 것들.
-
-////
+그냥 `str` 대신 `str | None`을 사용하면, 값이 항상 `str`이라고 가정하고 있지만 실제로는 `None`일 수도 있는 상황에서 에디터가 오류를 감지하도록 도와줍니다.
### 타입으로서의 클래스 { #classes-as-types }
@@ -365,11 +255,11 @@ Python 3.10에서는 제네릭 `Union`과 `Optional`을 사용하는 대안으
이름을 가진 `Person` 클래스가 있다고 해봅시다:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
그러면 `Person` 타입의 변수를 선언할 수 있습니다:
-{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
그리고 다시, 에디터의 모든 지원을 받을 수 있습니다:
@@ -405,19 +295,13 @@ Pydantic 공식 문서의 예시:
이 모든 것은 [자습서 - 사용자 안내서](tutorial/index.md){.internal-link target=_blank}에서 실제로 많이 보게 될 것입니다.
-/// tip | 팁
-
-Pydantic은 기본값 없이 `Optional` 또는 `Union[Something, None]`을 사용할 때 특별한 동작이 있습니다. 이에 대해서는 Pydantic 문서의 Required Optional fields에서 더 읽을 수 있습니다.
-
-///
-
## 메타데이터 애너테이션이 있는 타입 힌트 { #type-hints-with-metadata-annotations }
-파이썬에는 `Annotated`를 사용해 이러한 타입 힌트에 **추가 메타데이터**를 넣을 수 있는 기능도 있습니다.
+파이썬에는 `Annotated`를 사용해 이러한 타입 힌트에 **추가 메타데이터**를 넣을 수 있는 기능도 있습니다.
-Python 3.9부터 `Annotated`는 표준 라이브러리의 일부이므로, `typing`에서 import할 수 있습니다.
+`Annotated`는 `typing`에서 import할 수 있습니다.
-{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
파이썬 자체는 이 `Annotated`로 아무것도 하지 않습니다. 그리고 에디터와 다른 도구들에게는 타입이 여전히 `str`입니다.
diff --git a/docs/ko/docs/resources/index.md b/docs/ko/docs/resources/index.md
index 477b93a58..f8ec8dddd 100644
--- a/docs/ko/docs/resources/index.md
+++ b/docs/ko/docs/resources/index.md
@@ -1,3 +1,3 @@
# 리소스 { #resources }
-추가 리소스, 외부 링크 등. ✈️
+추가 리소스, 외부 링크, 그리고 더 많은 자료. ✈️
diff --git a/docs/ko/docs/translation-banner.md b/docs/ko/docs/translation-banner.md
new file mode 100644
index 000000000..7bcd907d5
--- /dev/null
+++ b/docs/ko/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 AI와 사람이 함께한 번역
+
+이 번역은 사람의 안내를 받아 AI가 만들었습니다. 🤝
+
+원문의 의미를 오해하거나 부자연스러워 보이는 등 오류가 있을 수 있습니다. 🤖
+
+[AI LLM을 더 잘 안내하는 데 도움을 주세요](https://fastapi.tiangolo.com/ko/contributing/#translations).
+
+[영문 버전](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md
index 9e868f2fa..f23902e11 100644
--- a/docs/ko/docs/tutorial/background-tasks.md
+++ b/docs/ko/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@ FastAPI에서는 응답을 반환한 *후에* 실행할 백그라운드 작업
먼저 `BackgroundTasks`를 임포트하고, `BackgroundTasks` 타입 선언으로 *경로 처리 함수*에 매개변수를 정의합니다:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI**가 `BackgroundTasks` 타입의 객체를 생성하고 해당 매개변수로 전달합니다.
@@ -31,13 +31,13 @@ FastAPI에서는 응답을 반환한 *후에* 실행할 백그라운드 작업
그리고 쓰기 작업은 `async`와 `await`를 사용하지 않으므로, 일반 `def`로 함수를 정의합니다:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
## 백그라운드 작업 추가 { #add-the-background-task }
*경로 처리 함수* 내부에서 `.add_task()` 메서드로 작업 함수를 *백그라운드 작업* 객체에 전달합니다:
-{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()`는 다음 인자를 받습니다:
diff --git a/docs/ko/docs/tutorial/bigger-applications.md b/docs/ko/docs/tutorial/bigger-applications.md
index cfc3900d4..1b9d17e49 100644
--- a/docs/ko/docs/tutorial/bigger-applications.md
+++ b/docs/ko/docs/tutorial/bigger-applications.md
@@ -58,17 +58,17 @@ from app.routers import items
```bash
.
-├── app # "app" is a Python package
-│ ├── __init__.py # this file makes "app" a "Python package"
-│ ├── main.py # "main" module, e.g. import app.main
-│ ├── dependencies.py # "dependencies" module, e.g. import app.dependencies
-│ └── routers # "routers" is a "Python subpackage"
-│ │ ├── __init__.py # makes "routers" a "Python subpackage"
-│ │ ├── items.py # "items" submodule, e.g. import app.routers.items
-│ │ └── users.py # "users" submodule, e.g. import app.routers.users
-│ └── internal # "internal" is a "Python subpackage"
-│ ├── __init__.py # makes "internal" a "Python subpackage"
-│ └── admin.py # "admin" submodule, e.g. import app.internal.admin
+├── app # 'app'은 Python 패키지입니다
+│ ├── __init__.py # 이 파일로 'app'이 'Python 패키지'가 됩니다
+│ ├── main.py # 'main' 모듈, 예: import app.main
+│ ├── dependencies.py # 'dependencies' 모듈, 예: import app.dependencies
+│ └── routers # 'routers'는 'Python 하위 패키지'입니다
+│ │ ├── __init__.py # 이 파일로 'routers'가 'Python 하위 패키지'가 됩니다
+│ │ ├── items.py # 'items' 서브모듈, 예: import app.routers.items
+│ │ └── users.py # 'users' 서브모듈, 예: import app.routers.users
+│ └── internal # 'internal'은 'Python 하위 패키지'입니다
+│ ├── __init__.py # 이 파일로 'internal'이 'Python 하위 패키지'가 됩니다
+│ └── admin.py # 'admin' 서브모듈, 예: import app.internal.admin
```
## `APIRouter` { #apirouter }
@@ -85,7 +85,7 @@ from app.routers import items
`FastAPI` 클래스와 동일한 방식으로 import하고 "instance"를 생성합니다:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
### `APIRouter`로 *path operations* 만들기 { #path-operations-with-apirouter }
@@ -93,7 +93,7 @@ from app.routers import items
`FastAPI` 클래스를 사용할 때와 동일한 방식으로 사용합니다:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}
`APIRouter`는 "미니 `FastAPI`" 클래스라고 생각할 수 있습니다.
@@ -117,7 +117,7 @@ from app.routers import items
이제 간단한 dependency를 사용해 커스텀 `X-Token` 헤더를 읽어 보겠습니다:
-{* ../../docs_src/bigger_applications/app_an_py39/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}
/// tip | 팁
@@ -149,7 +149,7 @@ from app.routers import items
따라서 각 *path operation*마다 매번 모두 추가하는 대신, `APIRouter`에 한 번에 추가할 수 있습니다.
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}
각 *path operation*의 경로는 다음처럼 `/`로 시작해야 하므로:
@@ -208,7 +208,7 @@ async def read_item(item_id: str):
그래서 dependencies에 대해 `..`를 사용하는 상대 import를 사용합니다:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[3] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}
#### 상대 import가 동작하는 방식 { #how-relative-imports-work }
@@ -279,7 +279,7 @@ from ...dependencies import get_token_header
하지만 특정 *path operation*에만 적용될 _추가_ `tags`를 더할 수도 있고, 그 *path operation* 전용의 추가 `responses`도 넣을 수 있습니다:
-{* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[30:31] title["app/routers/items.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}
/// tip | 팁
@@ -305,13 +305,13 @@ from ...dependencies import get_token_header
또한 각 `APIRouter`의 dependencies와 결합될 [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank}도 선언할 수 있습니다:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[1,3,7] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}
### `APIRouter` import하기 { #import-the-apirouter }
이제 `APIRouter`가 있는 다른 submodule들을 import합니다:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[4:5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}
`app/routers/users.py`와 `app/routers/items.py` 파일은 같은 Python package `app`에 속한 submodule들이므로, 점 하나 `.`를 사용해 "상대 import"로 가져올 수 있습니다.
@@ -374,13 +374,13 @@ from .routers.users import router
따라서 같은 파일에서 둘 다 사용할 수 있도록 submodule들을 직접 import합니다:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[5] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}
### `users`와 `items`용 `APIRouter` 포함하기 { #include-the-apirouters-for-users-and-items }
이제 submodule `users`와 `items`의 `router`를 포함해 봅시다:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[10:11] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}
/// info | 정보
@@ -394,7 +394,7 @@ from .routers.users import router
그 router의 모든 route가 애플리케이션의 일부로 포함됩니다.
-/// note Technical Details | 기술 세부사항
+/// note | 기술 세부사항
내부적으로는 `APIRouter`에 선언된 각 *path operation*마다 *path operation*을 실제로 생성합니다.
@@ -420,13 +420,13 @@ router를 포함(include)할 때 성능을 걱정할 필요는 없습니다.
이 예시에서는 매우 단순하게 만들겠습니다. 하지만 조직 내 다른 프로젝트와 공유되기 때문에, 이를 수정할 수 없어 `prefix`, `dependencies`, `tags` 등을 `APIRouter`에 직접 추가할 수 없다고 해봅시다:
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
하지만 `APIRouter`를 포함할 때 커스텀 `prefix`를 지정해 모든 *path operations*가 `/admin`으로 시작하게 하고, 이 프로젝트에서 이미 가진 `dependencies`로 보호하고, `tags`와 `responses`도 포함하고 싶습니다.
원래 `APIRouter`를 수정하지 않고도 `app.include_router()`에 파라미터를 전달해서 이를 선언할 수 있습니다:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[14:17] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}
이렇게 하면 원래 `APIRouter`는 수정되지 않으므로, 조직 내 다른 프로젝트에서도 동일한 `app/internal/admin.py` 파일을 계속 공유할 수 있습니다.
@@ -447,11 +447,11 @@ router를 포함(include)할 때 성능을 걱정할 필요는 없습니다.
여기서는 가능하다는 것을 보여주기 위해... 그냥 해봅니다 🤷:
-{* ../../docs_src/bigger_applications/app_an_py39/main.py hl[21:23] title["app/main.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}
그리고 `app.include_router()`로 추가한 다른 모든 *path operations*와 함께 올바르게 동작합니다.
-/// info | 정보
+/// info | 매우 기술적인 세부사항
**참고**: 이는 매우 기술적인 세부사항이라 아마 **그냥 건너뛰어도 됩니다**.
diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md
index c98734ab3..0774dc441 100644
--- a/docs/ko/docs/tutorial/body-fields.md
+++ b/docs/ko/docs/tutorial/body-fields.md
@@ -48,8 +48,8 @@
/// warning | 경고
-별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다.
-이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다.
+별도 키가 전달된 `Field` 또한 여러분의 애플리케이션의 OpenAPI 스키마에 나타날 것입니다.
+이런 키가 OpenAPI 명세서의 일부가 아닐 수도 있으므로, [OpenAPI validator](https://validator.swagger.io/) 같은 몇몇 OpenAPI 도구들은 여러분이 생성한 스키마와 호환되지 않을 수 있습니다.
///
diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md
index bebdffed8..3db614d72 100644
--- a/docs/ko/docs/tutorial/body-multiple-params.md
+++ b/docs/ko/docs/tutorial/body-multiple-params.md
@@ -106,13 +106,6 @@
q: str | None = None
```
-또는 Python 3.9에서는:
-
-```Python
-q: Union[str, None] = None
-```
-
-
예를 들어:
{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md
index 4a8c1afc1..33f0f71e9 100644
--- a/docs/ko/docs/tutorial/body-nested-models.md
+++ b/docs/ko/docs/tutorial/body-nested-models.md
@@ -164,7 +164,7 @@ images: list[Image]
이를 아래처럼:
-{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
## 어디서나 편집기 지원 { #editor-support-everywhere }
@@ -194,7 +194,7 @@ Pydantic 모델 대신 `dict`로 직접 작업한다면 이런 종류의 편집
이 경우, `int` 키와 `float` 값을 가진 한 어떤 `dict`든 받아들입니다:
-{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
/// tip | 팁
diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md
index 1e66c60c2..b282d1cc9 100644
--- a/docs/ko/docs/tutorial/body.md
+++ b/docs/ko/docs/tutorial/body.md
@@ -74,7 +74,7 @@
* 매개변수 `item`에 포함된 수신 데이터를 제공합니다.
* 함수 내에서 매개변수를 `Item` 타입으로 선언했기 때문에, 모든 어트리뷰트와 그에 대한 타입에 대한 편집기 지원(완성 등)을 또한 받을 수 있습니다.
* 여러분의 모델을 위한 JSON Schema 정의를 생성합니다. 여러분의 프로젝트에 적합하다면 여러분이 사용하고 싶은 곳 어디에서나 사용할 수 있습니다.
-* 이러한 스키마는, 생성된 OpenAPI 스키마 일부가 될 것이며, 자동 문서화 UIs에 사용됩니다.
+* 이러한 스키마는, 생성된 OpenAPI 스키마 일부가 될 것이며, 자동 문서화 UIs에 사용됩니다.
## 자동 문서화 { #automatic-docs }
@@ -141,7 +141,7 @@
**본문**, **경로** 그리고 **쿼리** 매개변수 모두 동시에 선언할 수도 있습니다.
-**FastAPI**는 각각을 인지하고 데이터를 옳바른 위치에 가져올 것입니다.
+**FastAPI**는 각각을 인지하고 데이터를 올바른 위치에 가져올 것입니다.
{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
@@ -153,9 +153,9 @@
/// note | 참고
-FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다.
+FastAPI는 `q`의 값이 필요없음을 기본 값 `= None` 때문에 알게 됩니다.
-Python 3.10+의 `str | None` 또는 Python 3.9+의 `Union[str, None]`에 있는 `Union`은 FastAPI가 `q` 값이 필수가 아님을 판단하기 위해 사용하지 않습니다. 기본 값이 `= None`이기 때문에 필수가 아님을 알게 됩니다.
+`str | None`은 FastAPI가 값이 필수인지 아닌지를 판단하기 위해 사용하지 않습니다. 기본 값이 `= None`이므로 필수가 아님을 알게 됩니다.
하지만 타입 어노테이션을 추가하면 편집기가 더 나은 지원을 제공하고 오류를 감지할 수 있습니다.
diff --git a/docs/ko/docs/tutorial/cookie-param-models.md b/docs/ko/docs/tutorial/cookie-param-models.md
index 00238d1b7..70b76e09c 100644
--- a/docs/ko/docs/tutorial/cookie-param-models.md
+++ b/docs/ko/docs/tutorial/cookie-param-models.md
@@ -46,7 +46,7 @@
일부 특별한 사용 사례(흔하지는 않겠지만)에서는 수신하려는 쿠키를 **제한**할 수 있습니다.
-이제 API는 자신의 cookie consent를 제어할 수 있는 권한을 갖게 되었습니다. 🤪🍪
+이제 API는 자신의 쿠키 동의를 제어할 수 있는 권한을 갖게 되었습니다. 🤪🍪
Pydantic의 모델 구성을 사용하여 추가(`extra`) 필드를 금지(`forbid`)할 수 있습니다:
@@ -54,9 +54,9 @@ Pydantic의 모델 구성을 사용하여 추가(`extra`) 필드를 금지(`forb
클라이언트가 **추가 쿠키**를 보내려고 시도하면, **오류** 응답을 받게 됩니다.
-동의를 얻기 위해 애쓰는 불쌍한 쿠키 배너(팝업)들, API가 거부하는데도. 🍪
+동의를 얻기 위해 애쓰는 불쌍한 쿠키 배너(팝업)들, API가 거부하는데도. 🍪
-예를 들어, 클라이언트가 `good-list-please` 값으로 `santa_tracker` 쿠키를 보내려고 하면 클라이언트는 `santa_tracker` 쿠키가 허용되지 않는다는 **오류** 응답을 받게 됩니다:
+예를 들어, 클라이언트가 `good-list-please` 값으로 `santa_tracker` 쿠키를 보내려고 하면 클라이언트는 `santa_tracker` 쿠키가 허용되지 않는다는 **오류** 응답을 받게 됩니다:
```json
{
@@ -73,4 +73,4 @@ Pydantic의 모델 구성을 사용하여 추가(`extra`) 필드를 금지(`forb
## 요약 { #summary }
-**Pydantic 모델**을 사용하여 **FastAPI**에서 **쿠키**를 선언할 수 있습니다. 😎
+**Pydantic 모델**을 사용하여 **FastAPI**에서 **쿠키**를 선언할 수 있습니다. 😎
diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md
index 0591a5e96..6ea09101c 100644
--- a/docs/ko/docs/tutorial/cookie-params.md
+++ b/docs/ko/docs/tutorial/cookie-params.md
@@ -24,13 +24,13 @@
///
-/// info | 정보
+/// info
쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다.
///
-/// info | 정보
+/// info
**브라우저는 쿠키를** 내부적으로 특별한 방식으로 처리하기 때문에, **JavaScript**가 쉽게 쿠키를 다루도록 허용하지 않는다는 점을 염두에 두세요.
diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md
index 0f3948a3d..f78e1c070 100644
--- a/docs/ko/docs/tutorial/cors.md
+++ b/docs/ko/docs/tutorial/cors.md
@@ -46,7 +46,7 @@
* 특정 HTTP 메서드(`POST`, `PUT`) 또는 와일드카드 `"*"`를 사용한 모든 메서드.
* 특정 HTTP 헤더 또는 와일드카드 `"*"`를 사용한 모든 헤더.
-{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *}
`CORSMiddleware` 구현에서 사용하는 기본 매개변수는 기본적으로 제한적이므로, 브라우저가 Cross-Domain 컨텍스트에서 특정 출처, 메서드 또는 헤더를 사용할 수 있도록 하려면 이를 명시적으로 활성화해야 합니다.
@@ -78,7 +78,7 @@
## 더 많은 정보 { #more-info }
-CORS에 대한 더 많은 정보는 Mozilla CORS 문서를 참고하세요.
+CORS에 대한 더 많은 정보는 Mozilla CORS 문서를 참고하세요.
/// note | 기술 세부사항
diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md
index ca20acff6..c27b68bc1 100644
--- a/docs/ko/docs/tutorial/debugging.md
+++ b/docs/ko/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@
FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다:
-{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *}
### `__name__ == "__main__"` 에 대하여 { #about-name-main }
diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md
index 68bba669a..83749f7b0 100644
--- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -101,7 +101,7 @@ FastAPI가 실제로 확인하는 것은 그것이 "호출 가능(callable)"(함
위 코드에서 `CommonQueryParams`를 두 번 작성하는 방식에 주목하세요:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ Annotated 미사용
/// tip | 팁
@@ -137,7 +137,7 @@ FastAPI는 여기에서 선언된 매개변수들을 추출하고, 실제로 이
이 경우 첫 번째 `CommonQueryParams`는 다음에서:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ Annotated 미사용
/// tip | 팁
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
실제로는 이렇게만 작성해도 됩니다:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ Annotated 미사용
/// tip | 팁
@@ -197,7 +197,7 @@ commons = Depends(CommonQueryParams)
하지만 `CommonQueryParams`를 두 번 작성하는 코드 반복이 있다는 것을 볼 수 있습니다:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ Annotated 미사용
/// tip | 팁
@@ -225,7 +225,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
다음처럼 작성하는 대신:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ Annotated 미사용
/// tip | 팁
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
...이렇게 작성합니다:
-//// tab | Python 3.9+
+//// tab | Python 3.10+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.9+ non-Annotated
+//// tab | Python 3.10+ Annotated 미사용
/// tip | 팁
diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 39c78c078..d269e7e77 100644
--- a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -1,28 +1,28 @@
-# 경로 작동 데코레이터에서의 의존성 { #dependencies-in-path-operation-decorators }
+# 경로 처리 데코레이터에서의 의존성 { #dependencies-in-path-operation-decorators }
-몇몇 경우에는, *경로 작동 함수* 안에서 의존성의 반환 값이 필요하지 않습니다.
+몇몇 경우에는, *경로 처리 함수* 안에서 의존성의 반환 값이 필요하지 않습니다.
또는 의존성이 값을 반환하지 않습니다.
그러나 여전히 실행/해결될 필요가 있습니다.
-그런 경우에, `Depends`를 사용하여 *경로 작동 함수*의 매개변수로 선언하는 것보다 *경로 작동 데코레이터*에 `dependencies`의 `list`를 추가할 수 있습니다.
+그런 경우에, `Depends`를 사용하여 *경로 처리 함수*의 매개변수로 선언하는 대신 *경로 처리 데코레이터*에 `dependencies`의 `list`를 추가할 수 있습니다.
-## *경로 작동 데코레이터*에 `dependencies` 추가하기 { #add-dependencies-to-the-path-operation-decorator }
+## *경로 처리 데코레이터*에 `dependencies` 추가하기 { #add-dependencies-to-the-path-operation-decorator }
-*경로 작동 데코레이터*는 `dependencies`라는 선택적인 인자를 받습니다.
+*경로 처리 데코레이터*는 선택적인 인자 `dependencies`를 받습니다.
-`Depends()`로 된 `list`이어야합니다:
+`Depends()`로 된 `list`이어야 합니다:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
-이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다.
+이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 처리 함수*에 제공되지 않습니다.
/// tip | 팁
일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다.
-*경로 작동 데코레이터*에서 이러한 `dependencies`를 사용하면 편집기/도구 오류를 피하면서도 실행되도록 할 수 있습니다.
+*경로 처리 데코레이터*에서 이러한 `dependencies`를 사용하면 편집기/도구 오류를 피하면서도 실행되도록 할 수 있습니다.
또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다.
@@ -44,13 +44,13 @@
(헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
### 오류 발생시키기 { #raise-exceptions }
다음 의존성은 기존 의존성과 동일하게 예외를 `raise`할 수 있습니다:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
### 값 반환하기 { #return-values }
@@ -58,12 +58,12 @@
그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다:
-{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *}
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
-## *경로 작동* 모음에 대한 의존성 { #dependencies-for-a-group-of-path-operations }
+## *경로 처리* 모음에 대한 의존성 { #dependencies-for-a-group-of-path-operations }
-나중에 여러 파일을 가지고 있을 수 있는 더 큰 애플리케이션을 구조화하는 법([더 큰 애플리케이션 - 여러 파일들](../../tutorial/bigger-applications.md){.internal-link target=_blank})을 읽을 때, *경로 작동* 모음에 대한 단일 `dependencies` 매개변수를 선언하는 법에 대해서 배우게 될 것입니다.
+나중에 여러 파일을 가지고 있을 수 있는 더 큰 애플리케이션을 구조화하는 법([더 큰 애플리케이션 - 여러 파일들](../../tutorial/bigger-applications.md){.internal-link target=_blank})을 읽을 때, *경로 처리* 모음에 대한 단일 `dependencies` 매개변수를 선언하는 법에 대해서 배우게 될 것입니다.
## 전역 의존성 { #global-dependencies }
-다음으로 각 *경로 작동*에 적용되도록 `FastAPI` 애플리케이션 전체에 의존성을 추가하는 법을 볼 것입니다.
+다음으로 각 *경로 처리*에 적용되도록 `FastAPI` 애플리케이션 전체에 의존성을 추가하는 법을 볼 것입니다.
diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md
index 9bf6c0693..7b50fd438 100644
--- a/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,6 +1,6 @@
# `yield`를 사용하는 의존성 { #dependencies-with-yield }
-FastAPI는 작업 완료 후 추가 단계를 수행하는 의존성을 지원합니다.
+FastAPI는 작업 완료 후 추가 단계를 수행하는 의존성을 지원합니다.
이를 구현하려면 `return` 대신 `yield`를 사용하고, 추가로 실행할 단계 (코드)를 그 뒤에 작성하세요.
@@ -29,15 +29,15 @@ FastAPI는 CORS를 처리하는 방법을 보게 될 것입니다.
+다음 섹션에서 미들웨어로 CORS를 처리하는 방법을 보게 될 것입니다.
diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md
index baef3fb40..0d6a0d422 100644
--- a/docs/ko/docs/tutorial/path-operation-configuration.md
+++ b/docs/ko/docs/tutorial/path-operation-configuration.md
@@ -46,7 +46,7 @@
**FastAPI**는 일반 문자열과 동일한 방식으로 이를 지원합니다:
-{* ../../docs_src/path_operation_configuration/tutorial002b_py39.py hl[1,8:10,13,18] *}
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
## 요약과 설명 { #summary-and-description }
@@ -56,7 +56,7 @@
## 독스트링으로 만든 설명 { #description-from-docstring }
-설명은 보통 길어지고 여러 줄에 걸쳐있기 때문에, *경로 처리* 설명을 함수 docstring에 선언할 수 있으며, **FastAPI**는 그곳에서 이를 읽습니다.
+설명은 보통 길어지고 여러 줄에 걸쳐있기 때문에, *경로 처리* 설명을 함수 독스트링에 선언할 수 있으며, **FastAPI**는 그곳에서 이를 읽습니다.
독스트링에는 Markdown을 작성할 수 있으며, (독스트링의 들여쓰기를 고려하여) 올바르게 해석되고 표시됩니다.
@@ -90,9 +90,9 @@ OpenAPI는 각 *경로 처리*가 응답에 관한 설명을 요구할 것을
## *경로 처리* 지원중단하기 { #deprecate-a-path-operation }
-*경로 처리*를 제거하지 않고 deprecated로 표시해야 한다면, `deprecated` 매개변수를 전달하면 됩니다:
+*경로 처리*를 제거하지 않고 지원중단으로 표시해야 한다면, `deprecated` 매개변수를 전달하면 됩니다:
-{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
대화형 문서에서 지원중단으로 명확하게 표시됩니다:
diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md
index f2c52d4aa..51f9fe2c1 100644
--- a/docs/ko/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md
@@ -54,11 +54,11 @@ FastAPI는 0.95.0 버전에서 `Annotated` 지원을 추가했고(그리고 이
따라서 함수를 다음과 같이 선언할 수 있습니다:
-{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
하지만 `Annotated`를 사용하면 이 문제가 없다는 점을 기억하세요. `Query()`나 `Path()`에 함수 매개변수 기본값을 사용하지 않기 때문에, 순서는 중요하지 않습니다.
-{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
## 필요한 대로 매개변수 정렬하기, 트릭 { #order-the-parameters-as-you-need-tricks }
@@ -83,13 +83,13 @@ FastAPI는 0.95.0 버전에서 `Annotated` 지원을 추가했고(그리고 이
파이썬은 `*`으로 아무것도 하지 않지만, 뒤따르는 모든 매개변수는 키워드 인자(키-값 쌍)로 호출되어야 함을 알게 됩니다. 이는 kwargs로도 알려져 있습니다. 기본값이 없더라도 마찬가지입니다.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
### `Annotated`를 쓰면 더 좋습니다 { #better-with-annotated }
`Annotated`를 사용하면 함수 매개변수 기본값을 사용하지 않기 때문에 이 문제가 발생하지 않으며, 아마 `*`도 사용할 필요가 없다는 점을 기억하세요.
-{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
## 숫자 검증: 크거나 같음 { #number-validations-greater-than-or-equal }
@@ -97,7 +97,7 @@ FastAPI는 0.95.0 버전에서 `Annotated` 지원을 추가했고(그리고 이
여기서 `ge=1`인 경우, `item_id`는 `1`보다 "`g`reater than or `e`qual"(크거나 같은) 정수형 숫자여야 합니다.
-{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
## 숫자 검증: 크거나 및 작거나 같음 { #number-validations-greater-than-and-less-than-or-equal }
@@ -106,7 +106,7 @@ FastAPI는 0.95.0 버전에서 `Annotated` 지원을 추가했고(그리고 이
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
## 숫자 검증: 부동소수, 크거나 및 작거나 { #number-validations-floats-greater-than-and-less-than }
@@ -118,7 +118,7 @@ FastAPI는 0.95.0 버전에서 `Annotated` 지원을 추가했고(그리고 이
lt 역시 마찬가지입니다.
-{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
## 요약 { #recap }
diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md
index ea5170ecc..c6e973709 100644
--- a/docs/ko/docs/tutorial/path-params.md
+++ b/docs/ko/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다:
-{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
경로 매개변수 `item_id`의 값은 함수의 `item_id` 인자로 전달됩니다.
@@ -16,7 +16,7 @@
파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다:
-{* ../../docs_src/path_params/tutorial002_py39.py hl[7] *}
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
위의 예시에서, `item_id`는 `int`로 선언되었습니다.
@@ -26,7 +26,7 @@
///
-## 데이터 변환 { #data-conversion }
+## 데이터 변환 { #data-conversion }
이 예제를 실행하고 http://127.0.0.1:8000/items/3을 열면, 다음 응답을 볼 수 있습니다:
@@ -38,7 +38,7 @@
함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
-즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
+즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
///
@@ -116,21 +116,21 @@
사용자 ID를 이용해 특정 사용자의 정보를 가져오는 경로 `/users/{user_id}`도 있습니다.
-*경로 처리*는 순차적으로 평가되기 때문에 `/users/{user_id}` 이전에 `/users/me`에 대한 경로가 먼저 선언되었는지 확인해야 합니다:
+*경로 처리*는 순차적으로 평가되기 때문에 `/users/me`에 대한 경로가 `/users/{user_id}` 이전에 먼저 선언되었는지 확인해야 합니다:
-{* ../../docs_src/path_params/tutorial003_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
그렇지 않으면 `/users/{user_id}`에 대한 경로가 `/users/me`에도 매칭되어, 매개변수 `user_id`에 `"me"` 값이 들어왔다고 "생각하게" 됩니다.
마찬가지로, 경로 처리를 재정의할 수는 없습니다:
-{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
경로가 먼저 매칭되기 때문에 첫 번째 것이 항상 사용됩니다.
## 사전정의 값 { #predefined-values }
-만약 *경로 매개변수*를 받는 *경로 처리*가 있지만, 가능한 유효한 *경로 매개변수* 값들을 미리 정의하고 싶다면 파이썬 표준 `Enum`을 사용할 수 있습니다.
+만약 *경로 매개변수*를 받는 *경로 처리*가 있지만, 가능한 유효한 *경로 매개변수* 값들을 미리 정의하고 싶다면 파이썬 표준 `Enum`을 사용할 수 있습니다.
### `Enum` 클래스 생성 { #create-an-enum-class }
@@ -140,11 +140,11 @@
가능한 값들에 해당하는 고정된 값의 클래스 어트리뷰트들을 만듭니다:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
/// tip | 팁
-혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 머신 러닝 모델들의 이름입니다.
+혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 머신 러닝 모델들의 이름입니다.
///
@@ -152,7 +152,7 @@
생성한 열거형 클래스(`ModelName`)를 사용하는 타입 어노테이션으로 *경로 매개변수*를 만듭니다:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
### 문서 확인 { #check-the-docs }
@@ -168,13 +168,13 @@
생성한 열거형 `ModelName`의 *열거형 멤버*와 비교할 수 있습니다:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[17] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
#### *열거형 값* 가져오기 { #get-the-enumeration-value }
`model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제 값(위 예시의 경우 `str`)을 가져올 수 있습니다:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[20] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
/// tip | 팁
@@ -188,7 +188,7 @@
클라이언트에 반환하기 전에 해당 값(이 경우 문자열)으로 변환됩니다:
-{* ../../docs_src/path_params/tutorial005_py39.py hl[18,21,23] *}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
클라이언트는 아래와 같은 JSON 응답을 얻게 됩니다:
@@ -227,7 +227,7 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으
따라서 다음과 같이 사용할 수 있습니다:
-{* ../../docs_src/path_params/tutorial004_py39.py hl[6] *}
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
/// tip | 팁
@@ -242,7 +242,7 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으
**FastAPI**를 이용하면 짧고 직관적인 표준 파이썬 타입 선언을 사용하여 다음을 얻을 수 있습니다:
* 편집기 지원: 오류 검사, 자동완성 등
-* 데이터 "parsing"
+* 데이터 "파싱"
* 데이터 검증
* API 주석(Annotation)과 자동 문서
diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md
index 68824932e..2b608fd1d 100644
--- a/docs/ko/docs/tutorial/query-params-str-validations.md
+++ b/docs/ko/docs/tutorial/query-params-str-validations.md
@@ -2,7 +2,7 @@
**FastAPI**를 사용하면 매개변수에 대한 추가 정보 및 검증을 선언할 수 있습니다.
-이 응용 프로그램을 예로 들어보겠습니다:
+이 애플리케이션을 예로 들어보겠습니다:
{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *}
@@ -41,46 +41,22 @@ FastAPI는 0.95.0 버전에서 `Annotated` 지원을 추가했고(그리고 이
## `q` 매개변수의 타입에 `Annotated` 사용하기 { #use-annotated-in-the-type-for-the-q-parameter }
-이전에 [Python Types Intro](../python-types.md#type-hints-with-metadata-annotations){.internal-link target=_blank}에서 `Annotated`를 사용해 매개변수에 메타데이터를 추가할 수 있다고 말씀드린 것을 기억하시나요?
+이전에 [Python 타입 소개](../python-types.md#type-hints-with-metadata-annotations){.internal-link target=_blank}에서 `Annotated`를 사용해 매개변수에 메타데이터를 추가할 수 있다고 말씀드린 것을 기억하시나요?
이제 FastAPI에서 사용할 차례입니다. 🚀
다음과 같은 타입 어노테이션이 있었습니다:
-//// tab | Python 3.10+
-
```Python
q: str | None = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Union[str, None] = None
-```
-
-////
-
여기서 `Annotated`로 감싸서 다음과 같이 만듭니다:
-//// tab | Python 3.10+
-
```Python
q: Annotated[str | None] = None
```
-////
-
-//// tab | Python 3.9+
-
-```Python
-q: Annotated[Union[str, None]] = None
-```
-
-////
-
두 버전 모두 같은 의미로, `q`는 `str` 또는 `None`이 될 수 있는 매개변수이며 기본값은 `None`입니다.
이제 재미있는 부분으로 넘어가 봅시다. 🎉
@@ -109,7 +85,7 @@ q: Annotated[Union[str, None]] = None
## 대안(이전 방식): 기본값으로 `Query` 사용 { #alternative-old-query-as-the-default-value }
-이전 FastAPI 버전(0.95.0 이전)에서는 `Annotated`에 넣는 대신, 매개변수의 기본값으로 `Query`를 사용해야 했습니다. 주변에서 이 방식을 사용하는 코드를 볼 가능성이 높기 때문에 설명해 드리겠습니다.
+이전 FastAPI 버전(0.95.0 이전)에서는 `Annotated`에 넣는 대신, 매개변수의 기본값으로 `Query`를 사용해야 했습니다. 주변에서 이 방식을 사용하는 코드를 볼 가능성이 높기 때문에 설명해 드리겠습니다.
/// tip | 팁
@@ -192,7 +168,7 @@ FastAPI 없이도 **다른 곳에서** 같은 함수를 **호출**할 수 있고
## 정규식 추가 { #add-regular-expressions }
-매개변수와 일치해야 하는 정규 표현식 `pattern`을 정의할 수 있습니다:
+매개변수와 일치해야 하는 정규 표현식 `pattern`을 정의할 수 있습니다:
{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
@@ -212,7 +188,7 @@ FastAPI 없이도 **다른 곳에서** 같은 함수를 **호출**할 수 있고
`q` 쿼리 매개변수에 `min_length`를 `3`으로 설정하고, 기본값을 `"fixedquery"`로 선언하고 싶다고 해봅시다:
-{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial005_an_py310.py hl[9] *}
/// note | 참고
@@ -242,7 +218,7 @@ q: Annotated[str | None, Query(min_length=3)] = None
따라서 `Query`를 사용하면서 값을 필수로 선언해야 할 때는, 기본값을 선언하지 않으면 됩니다:
-{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial006_an_py310.py hl[9] *}
### 필수지만 `None` 가능 { #required-can-be-none }
@@ -293,7 +269,7 @@ http://localhost:8000/items/?q=foo&q=bar
제공된 값이 없으면 기본 `list` 값을 정의할 수도 있습니다:
-{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
다음으로 이동하면:
@@ -316,7 +292,7 @@ http://localhost:8000/items/
`list[str]` 대신 `list`를 직접 사용할 수도 있습니다:
-{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
/// note | 참고
@@ -372,7 +348,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
이제는 더 이상 이 매개변수를 마음에 들어하지 않는다고 가정해 봅시다.
-이 매개변수를 사용하는 클라이언트가 있기 때문에 한동안은 남겨둬야 하지만, 문서에서 deprecated로 명확하게 보여주고 싶습니다.
+이 매개변수를 사용하는 클라이언트가 있기 때문에 한동안은 남겨둬야 하지만, 문서에서 사용 중단됨으로 명확하게 보여주고 싶습니다.
그렇다면 `deprecated=True` 매개변수를 `Query`로 전달합니다:
@@ -402,7 +378,7 @@ Pydantic에는 ISBN 도서 번호의 경우 아이템 ID가 `isbn-`으로 시작하고, IMDB 영화 URL ID의 경우 `imdb-`로 시작하는지 확인합니다:
+예를 들어, 이 커스텀 validator는 ISBN 도서 번호의 경우 아이템 ID가 `isbn-`으로 시작하고, IMDB 영화 URL ID의 경우 `imdb-`로 시작하는지 확인합니다:
{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
@@ -436,9 +412,9 @@ Pydantic에는 iterable object를 얻습니다.
+`data.items()`를 사용하면 각 딕셔너리 항목의 키와 값을 담은 튜플로 구성된 이터러블 객체를 얻습니다.
-이 iterable object를 `list(data.items())`로 적절한 `list`로 변환합니다.
+이 이터러블 객체를 `list(data.items())`로 적절한 `list`로 변환합니다.
그 다음 `random.choice()`로 리스트에서 **무작위 값**을 얻어 `(id, name)` 형태의 튜플을 얻습니다. 예를 들어 `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")` 같은 값이 될 것입니다.
diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md
index 5124f73bf..0a6b1f922 100644
--- a/docs/ko/docs/tutorial/query-params.md
+++ b/docs/ko/docs/tutorial/query-params.md
@@ -2,7 +2,7 @@
경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언하면 "쿼리" 매개변수로 자동 해석합니다.
-{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
쿼리는 URL에서 `?` 후에 나오고 `&`으로 구분되는 키-값 쌍의 집합입니다.
@@ -24,7 +24,7 @@ URL의 일부이므로 "자연스럽게" 문자열입니다.
경로 매개변수에 적용된 동일한 프로세스가 쿼리 매개변수에도 적용됩니다:
* (당연히) 편집기 지원
-* 데이터 "파싱"
+* 데이터 "파싱"
* 데이터 검증
* 자동 문서화
@@ -128,7 +128,7 @@ http://127.0.0.1:8000/items/foo?short=yes
그러나 쿼리 매개변수를 필수로 만들려면 단순히 기본값을 선언하지 않으면 됩니다:
-{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
여기 쿼리 매개변수 `needy`는 `str`형인 필수 쿼리 매개변수입니다.
diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md
index cc0000921..3ee0fa74c 100644
--- a/docs/ko/docs/tutorial/request-files.md
+++ b/docs/ko/docs/tutorial/request-files.md
@@ -20,13 +20,13 @@ $ pip install python-multipart
`fastapi` 에서 `File` 과 `UploadFile` 을 임포트 합니다:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
## `File` 매개변수 정의 { #define-file-parameters }
`Body` 및 `Form` 과 동일한 방식으로 파일의 매개변수를 생성합니다:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
/// info | 정보
@@ -54,7 +54,7 @@ File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본
`File` 매개변수를 `UploadFile` 타입으로 정의합니다:
-{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *}
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
`UploadFile` 을 사용하는 것은 `bytes` 과 비교해 다음과 같은 장점이 있습니다:
@@ -121,7 +121,7 @@ HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은
하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다.
-인코딩과 폼 필드에 대해 더 알고싶다면, MDN web docs for POST를 참고하기 바랍니다.
+인코딩과 폼 필드에 대해 더 알고싶다면, MDN web docs for POST를 참고하기 바랍니다.
///
@@ -143,7 +143,7 @@ HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은
추가 메타데이터를 설정하기 위해 예를 들어 `UploadFile`과 함께 `File()`을 사용할 수도 있습니다:
-{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
## 다중 파일 업로드 { #multiple-file-uploads }
@@ -153,7 +153,7 @@ HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은
이 기능을 사용하기 위해 , `bytes` 의 `List` 또는 `UploadFile` 를 선언하기 바랍니다:
-{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다.
@@ -169,7 +169,7 @@ HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은
이전과 같은 방식으로 `UploadFile`에 대해서도 `File()`을 사용해 추가 매개변수를 설정할 수 있습니다:
-{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
## 요약 { #recap }
diff --git a/docs/ko/docs/tutorial/request-form-models.md b/docs/ko/docs/tutorial/request-form-models.md
index b37186dfb..20a2e9597 100644
--- a/docs/ko/docs/tutorial/request-form-models.md
+++ b/docs/ko/docs/tutorial/request-form-models.md
@@ -24,7 +24,7 @@ $ pip install python-multipart
**폼 필드**로 받고 싶은 필드를 **Pydantic 모델**로 선언한 다음, 매개변수를 `Form`으로 선언하면 됩니다:
-{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
**FastAPI**는 요청에서 받은 **폼 데이터**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다.
@@ -48,7 +48,7 @@ $ pip install python-multipart
Pydantic의 모델 구성을 사용하여 `extra` 필드를 `forbid`할 수 있습니다:
-{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *}
+{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *}
클라이언트가 추가 데이터를 보내려고 하면 **오류** 응답을 받게 됩니다.
diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md
index a5309b5c0..4c2d12bc0 100644
--- a/docs/ko/docs/tutorial/request-forms-and-files.md
+++ b/docs/ko/docs/tutorial/request-forms-and-files.md
@@ -16,13 +16,13 @@ $ pip install python-multipart
## `File` 및 `Form` 임포트 { #import-file-and-form }
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[3] *}
## `File` 및 `Form` 매개변수 정의 { #define-file-and-form-parameters }
`Body` 및 `Query`와 동일한 방식으로 파일과 폼의 매개변수를 생성합니다:
-{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *}
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[10:12] *}
파일과 폼 필드는 폼 데이터로 업로드되며, 파일과 폼 필드를 받게 됩니다.
diff --git a/docs/ko/docs/tutorial/request-forms.md b/docs/ko/docs/tutorial/request-forms.md
index 584cbba35..a830bc5f8 100644
--- a/docs/ko/docs/tutorial/request-forms.md
+++ b/docs/ko/docs/tutorial/request-forms.md
@@ -18,17 +18,17 @@ $ pip install python-multipart
`fastapi`에서 `Form`을 임포트합니다:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[3] *}
## `Form` 매개변수 정의하기 { #define-form-parameters }
`Body` 또는 `Query`와 동일한 방식으로 폼 매개변수를 만듭니다:
-{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *}
+{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[9] *}
예를 들어, OAuth2 사양을 사용할 수 있는 방법 중 하나("패스워드 플로우"라고 함)로 `username`과 `password`를 폼 필드로 보내야 합니다.
-spec에서는 필드 이름이 `username` 및 `password`로 정확하게 명명되어야 하고, JSON이 아닌 폼 필드로 전송해야 합니다.
+사양에서는 필드 이름이 `username` 및 `password`로 정확하게 명명되어야 하고, JSON이 아닌 폼 필드로 전송해야 합니다.
`Form`을 사용하면 유효성 검사, 예제, 별칭(예: `username` 대신 `user-name`) 등을 포함하여 `Body`(및 `Query`, `Path`, `Cookie`)와 동일한 구성을 선언할 수 있습니다.
@@ -56,7 +56,7 @@ HTML 폼(``)이 데이터를 서버로 보내는 방식은 일반
그러나 폼에 파일이 포함된 경우, `multipart/form-data`로 인코딩합니다. 다음 장에서 파일 처리에 대해 읽을 겁니다.
-이러한 인코딩 및 폼 필드에 대해 더 읽고 싶다면, POST에 대한 MDN 웹 문서를 참조하세요.
+이러한 인코딩 및 폼 필드에 대해 더 읽고 싶다면, MDN 웹 문서를 참조하세요 POST에 대한.
///
diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md
index 6246ed9ad..942901e7c 100644
--- a/docs/ko/docs/tutorial/response-model.md
+++ b/docs/ko/docs/tutorial/response-model.md
@@ -183,7 +183,7 @@ FastAPI는 Pydantic을 내부적으로 여러 방식으로 사용하여, 클래
가장 흔한 경우는 [고급 문서에서 나중에 설명하는 대로 Response를 직접 반환하는 것](../advanced/response-directly.md){.internal-link target=_blank}입니다.
-{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
이 간단한 경우는 반환 타입 어노테이션이 `Response` 클래스(또는 그 서브클래스)이기 때문에 FastAPI에서 자동으로 처리됩니다.
@@ -193,7 +193,7 @@ FastAPI는 Pydantic을 내부적으로 여러 방식으로 사용하여, 클래
타입 어노테이션에 `Response`의 서브클래스를 사용할 수도 있습니다:
-{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
이는 `RedirectResponse`가 `Response`의 서브클래스이기 때문에 동작하며, FastAPI가 이 간단한 경우를 자동으로 처리합니다.
@@ -201,7 +201,7 @@ FastAPI는 Pydantic을 내부적으로 여러 방식으로 사용하여, 클래
하지만 유효한 Pydantic 타입이 아닌 다른 임의의 객체(예: 데이터베이스 객체)를 반환하고, 함수에서 그렇게 어노테이션하면, FastAPI는 그 타입 어노테이션으로부터 Pydantic 응답 모델을 만들려고 시도하다가 실패합니다.
-또한, 유효한 Pydantic 타입이 아닌 타입이 하나 이상 포함된 여러 타입 간의 union이 있는 경우에도 동일합니다. 예를 들어, 아래는 실패합니다 💥:
+또한, 유효한 Pydantic 타입이 아닌 타입이 하나 이상 포함된 여러 타입 간의 union이 있는 경우에도 동일합니다. 예를 들어, 아래는 실패합니다 💥:
{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md
index 257f6a8d6..c81132dfb 100644
--- a/docs/ko/docs/tutorial/response-status-code.md
+++ b/docs/ko/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@
* `@app.delete()`
* 등
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
/// note | 참고
@@ -43,7 +43,7 @@ FastAPI는 이를 알고 있으며, 응답 본문이 없다고 명시하는 Open
/// note | 참고
-만약 HTTP 상태 코드가 무엇인지 이미 알고 있다면, 다음 섹션으로 넘어가세요.
+만약 HTTP 상태 코드가 무엇인지 이미 알고 있다면, 다음 섡션으로 넘어가세요.
///
@@ -66,7 +66,7 @@ HTTP에서는 응답의 일부로 3자리 숫자 상태 코드를 보냅니다.
/// tip | 팁
-각 상태 코드와 어떤 코드가 어떤 용도인지 더 알고 싶다면 MDN의 HTTP 상태 코드에 관한 문서를 확인하세요.
+각 상태 코드와 어떤 코드가 어떤 용도인지 더 알고 싶다면 MDN의 HTTP 상태 코드에 관한 문서를 확인하세요.
///
@@ -74,7 +74,7 @@ HTTP에서는 응답의 일부로 3자리 숫자 상태 코드를 보냅니다.
이전 예시를 다시 확인해보겠습니다:
-{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201` 은 "생성됨"을 위한 상태 코드입니다.
@@ -82,7 +82,7 @@ HTTP에서는 응답의 일부로 3자리 숫자 상태 코드를 보냅니다.
`fastapi.status` 의 편의 변수를 사용할 수 있습니다.
-{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
이것들은 단지 편의를 위한 것으로, 동일한 숫자를 갖고 있지만, 이를 통해 편집기의 자동완성 기능으로 찾을 수 있습니다:
diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md
index b2b54836a..a1d0c8468 100644
--- a/docs/ko/docs/tutorial/schema-extra-example.md
+++ b/docs/ko/docs/tutorial/schema-extra-example.md
@@ -74,7 +74,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를
이와 같이 하면 예제들은 그 본문 데이터의 내부 **JSON 스키마**의 일부가 될 것입니다.
-그럼에도 불구하고, 지금 이 문서를 작성하는 시간에, 문서 UI를 보여주는 역할을 맡은 Swagger UI는 **JSON 스키마** 속 데이터를 위한 여러 예제의 표현을 지원하지 않습니다. 하지만 해결 방안을 밑에서 읽어보세요.
+그럼에도 불구하고, 지금 이 문서를 작성하는 시간에, 문서 UI를 보여주는 역할을 맡은 Swagger UI는 **JSON 스키마** 속 데이터를 위한 여러 예제의 표현을 지원하지 않습니다. 하지만 해결 방안을 밑에서 읽어보세요.
### OpenAPI-특화 `examples` { #openapi-specific-examples }
diff --git a/docs/ko/docs/tutorial/security/first-steps.md b/docs/ko/docs/tutorial/security/first-steps.md
index 4c9181b31..57b336d52 100644
--- a/docs/ko/docs/tutorial/security/first-steps.md
+++ b/docs/ko/docs/tutorial/security/first-steps.md
@@ -20,7 +20,7 @@
예제를 파일 `main.py`에 복사하세요:
-{* ../../docs_src/security/tutorial001_an_py39.py *}
+{* ../../docs_src/security/tutorial001_an_py310.py *}
## 실행하기 { #run-it }
@@ -132,7 +132,7 @@ OAuth2는 backend 또는 API가 사용자를 인증하는 서버와 독립적일
`OAuth2PasswordBearer` 클래스의 인스턴스를 만들 때 `tokenUrl` 파라미터를 전달합니다. 이 파라미터에는 클라이언트(사용자의 브라우저에서 실행되는 frontend)가 token을 받기 위해 `username`과 `password`를 보낼 URL이 들어 있습니다.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
/// tip | 팁
@@ -170,7 +170,7 @@ oauth2_scheme(some, parameters)
이제 `Depends`로 `oauth2_scheme`를 의존성에 전달할 수 있습니다.
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
이 의존성은 `str`을 제공하고, 그 값은 *경로 처리 함수*의 파라미터 `token`에 할당됩니다.
diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md
index f21a22b7a..eab599e27 100644
--- a/docs/ko/docs/tutorial/security/get-current-user.md
+++ b/docs/ko/docs/tutorial/security/get-current-user.md
@@ -2,7 +2,7 @@
이전 장에서 (의존성 주입 시스템을 기반으로 한) 보안 시스템은 *경로 처리 함수*에 `str`로 `token`을 제공했습니다:
-{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
하지만 이는 여전히 그다지 유용하지 않습니다.
diff --git a/docs/ko/docs/tutorial/security/oauth2-jwt.md b/docs/ko/docs/tutorial/security/oauth2-jwt.md
index 907795ca4..f9c4cc2ff 100644
--- a/docs/ko/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/ko/docs/tutorial/security/oauth2-jwt.md
@@ -1,6 +1,6 @@
# 패스워드(해싱 포함)를 사용하는 OAuth2, JWT 토큰을 사용하는 Bearer { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
-모든 보안 흐름을 구성했으므로, 이제 JWT 토큰과 안전한 패스워드 해싱을 사용해 애플리케이션을 실제로 안전하게 만들겠습니다.
+모든 보안 흐름을 구성했으므로, 이제 JWT 토큰과 안전한 패스워드 해싱을 사용해 애플리케이션을 실제로 안전하게 만들겠습니다.
이 코드는 실제로 애플리케이션에서 사용할 수 있으며, 패스워드 해시를 데이터베이스에 저장하는 등의 작업에 활용할 수 있습니다.
@@ -42,7 +42,7 @@ $ pip install pyjwt
-/// note
+/// note | 참고
`Bearer `로 시작하는 값을 가진 `Authorization` 헤더에 주목하십시오.
diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md
index 189dd89f2..918c94b25 100644
--- a/docs/ko/docs/tutorial/security/simple-oauth2.md
+++ b/docs/ko/docs/tutorial/security/simple-oauth2.md
@@ -162,7 +162,7 @@ UserInDB(
/// tip | 팁
-다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다.
+다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다.
하지만 지금은 필요한 세부 정보에 집중하겠습니다.
@@ -286,4 +286,4 @@ UserInDB(
유일한 오점은 아직 실제로 "안전"하지 않다는 것입니다.
-다음 장에서는 안전한 패스워드 해싱 라이브러리와 JWT 토큰을 사용하는 방법을 살펴보겠습니다.
+다음 장에서는 안전한 패스워드 해싱 라이브러리와 JWT 토큰을 사용하는 방법을 살펴보겠습니다.
diff --git a/docs/ko/docs/tutorial/sql-databases.md b/docs/ko/docs/tutorial/sql-databases.md
index 3d64cf627..20c136716 100644
--- a/docs/ko/docs/tutorial/sql-databases.md
+++ b/docs/ko/docs/tutorial/sql-databases.md
@@ -8,7 +8,7 @@
/// tip | 팁
-다른 SQL 또는 NoSQL 데이터베이스 라이브러리를 사용할 수도 있습니다 (일부는 "ORMs"이라고도 불립니다), FastAPI는 특정 라이브러리의 사용을 강요하지 않습니다. 😎
+다른 SQL 또는 NoSQL 데이터베이스 라이브러리를 사용할 수도 있습니다 (일부는 "ORMs"이라고도 불립니다), FastAPI는 특정 라이브러리의 사용을 강요하지 않습니다. 😎
///
diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md
index aa4c57179..0235d83c7 100644
--- a/docs/ko/docs/tutorial/static-files.md
+++ b/docs/ko/docs/tutorial/static-files.md
@@ -7,7 +7,7 @@
* `StaticFiles`를 임포트합니다.
* 특정 경로에 `StaticFiles()` 인스턴스를 "마운트"합니다.
-{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py310.py hl[2,6] *}
/// note | 기술 세부사항
diff --git a/docs/ko/docs/tutorial/testing.md b/docs/ko/docs/tutorial/testing.md
index db7fb17ea..57ab81151 100644
--- a/docs/ko/docs/tutorial/testing.md
+++ b/docs/ko/docs/tutorial/testing.md
@@ -2,7 +2,7 @@
Starlette 덕분에 **FastAPI** 애플리케이션을 테스트하는 일은 쉽고 즐거운 일이 되었습니다.
-Starlette는 HTTPX를 기반으로 하며, 이는 Requests를 기반으로 설계되었기 때문에 매우 친숙하고 직관적입니다.
+이는 HTTPX를 기반으로 하며, 이는 Requests를 기반으로 설계되었기 때문에 매우 친숙하고 직관적입니다.
이를 사용하면 **FastAPI**에서 pytest를 직접 사용할 수 있습니다.
@@ -30,7 +30,7 @@ $ pip install httpx
표준적인 파이썬 표현식으로 확인이 필요한 곳에 간단한 `assert` 문장을 작성하세요(역시 표준적인 `pytest` 관례입니다).
-{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py310.py hl[2,12,15:18] *}
/// tip | 팁
@@ -42,7 +42,7 @@ $ pip install httpx
///
-/// note Technical Details | 기술 세부사항
+/// note | 기술 세부사항
`from starlette.testclient import TestClient` 역시 사용할 수 있습니다.
@@ -76,7 +76,7 @@ FastAPI 애플리케이션에 요청을 보내는 것 외에도 테스트에서
`main.py` 파일 안에 **FastAPI** app 을 만들었습니다:
-{* ../../docs_src/app_testing/app_a_py39/main.py *}
+{* ../../docs_src/app_testing/app_a_py310/main.py *}
### 테스트 파일 { #testing-file }
@@ -92,7 +92,7 @@ FastAPI 애플리케이션에 요청을 보내는 것 외에도 테스트에서
파일들이 동일한 패키지에 위치해 있으므로, 상대 임포트를 사용하여 `main` 모듈(`main.py`)에서 `app` 객체를 임포트 해올 수 있습니다.
-{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py310/test_main.py hl[3] *}
...그리고 이전에 작성했던 것과 같은 테스트 코드를 작성할 수 있습니다.
@@ -115,7 +115,7 @@ FastAPI 애플리케이션에 요청을 보내는 것 외에도 테스트에서
이제 **FastAPI** 앱이 있는 `main.py` 파일에 몇 가지 다른 **경로 처리**가 추가된 경우를 생각해봅시다.
-단일 오류를 반환할 수 있는 `GET` 작업이 있습니다.
+오류를 반환할 수 있는 `GET` 작업이 있습니다.
여러 다른 오류를 반환할 수 있는 `POST` 작업이 있습니다.
diff --git a/docs/ko/docs/virtual-environments.md b/docs/ko/docs/virtual-environments.md
index b639f8a3e..e6baef73b 100644
--- a/docs/ko/docs/virtual-environments.md
+++ b/docs/ko/docs/virtual-environments.md
@@ -37,15 +37,15 @@ Python 설치까지 포함해 **모든 것을 관리해주는 도구**를 도입
Look ma! HTML!
-
-
- """
diff --git a/docs_src/custom_response/tutorial003_py39.py b/docs_src/custom_response/tutorial003_py39.py
deleted file mode 100644
index 51ad3c146..000000000
--- a/docs_src/custom_response/tutorial003_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items():
- html_content = """
-
-
- Look ma! HTML!
-
-
- """
- return HTMLResponse(content=html_content, status_code=200)
diff --git a/docs_src/custom_response/tutorial004_py39.py b/docs_src/custom_response/tutorial004_py39.py
deleted file mode 100644
index 0e90f2012..000000000
--- a/docs_src/custom_response/tutorial004_py39.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-
-def generate_html_response():
- html_content = """
-
-
- Look ma! HTML!
-
-
- """
- return HTMLResponse(content=html_content, status_code=200)
-
-
-@app.get("/items/", response_class=HTMLResponse)
-async def read_items():
- return generate_html_response()
diff --git a/docs_src/custom_response/tutorial005_py39.py b/docs_src/custom_response/tutorial005_py39.py
deleted file mode 100644
index 3d58f57fb..000000000
--- a/docs_src/custom_response/tutorial005_py39.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import PlainTextResponse
-
-app = FastAPI()
-
-
-@app.get("/", response_class=PlainTextResponse)
-async def main():
- return "Hello World"
diff --git a/docs_src/custom_response/tutorial006_py39.py b/docs_src/custom_response/tutorial006_py39.py
deleted file mode 100644
index 332f8f87f..000000000
--- a/docs_src/custom_response/tutorial006_py39.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import RedirectResponse
-
-app = FastAPI()
-
-
-@app.get("/typer")
-async def redirect_typer():
- return RedirectResponse("https://typer.tiangolo.com")
diff --git a/docs_src/custom_response/tutorial006b_py39.py b/docs_src/custom_response/tutorial006b_py39.py
deleted file mode 100644
index 03a7be399..000000000
--- a/docs_src/custom_response/tutorial006b_py39.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import RedirectResponse
-
-app = FastAPI()
-
-
-@app.get("/fastapi", response_class=RedirectResponse)
-async def redirect_fastapi():
- return "https://fastapi.tiangolo.com"
diff --git a/docs_src/custom_response/tutorial006c_py39.py b/docs_src/custom_response/tutorial006c_py39.py
deleted file mode 100644
index 87c720364..000000000
--- a/docs_src/custom_response/tutorial006c_py39.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import RedirectResponse
-
-app = FastAPI()
-
-
-@app.get("/pydantic", response_class=RedirectResponse, status_code=302)
-async def redirect_pydantic():
- return "https://docs.pydantic.dev/"
diff --git a/docs_src/custom_response/tutorial007_py39.py b/docs_src/custom_response/tutorial007_py39.py
deleted file mode 100644
index e2a53a211..000000000
--- a/docs_src/custom_response/tutorial007_py39.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import StreamingResponse
-
-app = FastAPI()
-
-
-async def fake_video_streamer():
- for i in range(10):
- yield b"some fake video bytes"
-
-
-@app.get("/")
-async def main():
- return StreamingResponse(fake_video_streamer())
diff --git a/docs_src/custom_response/tutorial008_py39.py b/docs_src/custom_response/tutorial008_py39.py
deleted file mode 100644
index fc071cbee..000000000
--- a/docs_src/custom_response/tutorial008_py39.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import StreamingResponse
-
-some_file_path = "large-video-file.mp4"
-app = FastAPI()
-
-
-@app.get("/")
-def main():
- def iterfile(): # (1)
- with open(some_file_path, mode="rb") as file_like: # (2)
- yield from file_like # (3)
-
- return StreamingResponse(iterfile(), media_type="video/mp4")
diff --git a/docs_src/custom_response/tutorial009_py39.py b/docs_src/custom_response/tutorial009_py39.py
deleted file mode 100644
index 71cf50cc1..000000000
--- a/docs_src/custom_response/tutorial009_py39.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import FileResponse
-
-some_file_path = "large-video-file.mp4"
-app = FastAPI()
-
-
-@app.get("/")
-async def main():
- return FileResponse(some_file_path)
diff --git a/docs_src/custom_response/tutorial009b_py39.py b/docs_src/custom_response/tutorial009b_py39.py
deleted file mode 100644
index 27200ee4b..000000000
--- a/docs_src/custom_response/tutorial009b_py39.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import FileResponse
-
-some_file_path = "large-video-file.mp4"
-app = FastAPI()
-
-
-@app.get("/", response_class=FileResponse)
-async def main():
- return some_file_path
diff --git a/docs_src/custom_response/tutorial009c_py39.py b/docs_src/custom_response/tutorial009c_py39.py
deleted file mode 100644
index de6b6688e..000000000
--- a/docs_src/custom_response/tutorial009c_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Any
-
-import orjson
-from fastapi import FastAPI, Response
-
-app = FastAPI()
-
-
-class CustomORJSONResponse(Response):
- media_type = "application/json"
-
- def render(self, content: Any) -> bytes:
- assert orjson is not None, "orjson must be installed"
- return orjson.dumps(content, option=orjson.OPT_INDENT_2)
-
-
-@app.get("/", response_class=CustomORJSONResponse)
-async def main():
- return {"message": "Hello World"}
diff --git a/docs_src/custom_response/tutorial010_py39.py b/docs_src/custom_response/tutorial010_py39.py
deleted file mode 100644
index 57cb06260..000000000
--- a/docs_src/custom_response/tutorial010_py39.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import ORJSONResponse
-
-app = FastAPI(default_response_class=ORJSONResponse)
-
-
-@app.get("/items/")
-async def read_items():
- return [{"item_id": "Foo"}]
diff --git a/docs_src/debugging/tutorial001_py39.py b/docs_src/debugging/tutorial001_py39.py
deleted file mode 100644
index 3de21d2a8..000000000
--- a/docs_src/debugging/tutorial001_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-import uvicorn
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/")
-def root():
- a = "a"
- b = "b" + a
- return {"hello world": b}
-
-
-if __name__ == "__main__":
- uvicorn.run(app, host="0.0.0.0", port=8000)
diff --git a/docs_src/dependencies/tutorial006_an_py39.py b/docs_src/dependencies/tutorial006_an_py39.py
deleted file mode 100644
index 11976ed6a..000000000
--- a/docs_src/dependencies/tutorial006_an_py39.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Annotated
-
-from fastapi import Depends, FastAPI, Header, HTTPException
-
-app = FastAPI()
-
-
-async def verify_token(x_token: Annotated[str, Header()]):
- if x_token != "fake-super-secret-token":
- raise HTTPException(status_code=400, detail="X-Token header invalid")
-
-
-async def verify_key(x_key: Annotated[str, Header()]):
- if x_key != "fake-super-secret-key":
- raise HTTPException(status_code=400, detail="X-Key header invalid")
- return x_key
-
-
-@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
-async def read_items():
- return [{"item": "Foo"}, {"item": "Bar"}]
diff --git a/docs_src/dependencies/tutorial006_py39.py b/docs_src/dependencies/tutorial006_py39.py
deleted file mode 100644
index 9aff4154f..000000000
--- a/docs_src/dependencies/tutorial006_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from fastapi import Depends, FastAPI, Header, HTTPException
-
-app = FastAPI()
-
-
-async def verify_token(x_token: str = Header()):
- if x_token != "fake-super-secret-token":
- raise HTTPException(status_code=400, detail="X-Token header invalid")
-
-
-async def verify_key(x_key: str = Header()):
- if x_key != "fake-super-secret-key":
- raise HTTPException(status_code=400, detail="X-Key header invalid")
- return x_key
-
-
-@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
-async def read_items():
- return [{"item": "Foo"}, {"item": "Bar"}]
diff --git a/docs_src/dependencies/tutorial007_py39.py b/docs_src/dependencies/tutorial007_py39.py
deleted file mode 100644
index 2e4ab4777..000000000
--- a/docs_src/dependencies/tutorial007_py39.py
+++ /dev/null
@@ -1,6 +0,0 @@
-async def get_db():
- db = DBSession()
- try:
- yield db
- finally:
- db.close()
diff --git a/docs_src/dependencies/tutorial008_an_py39.py b/docs_src/dependencies/tutorial008_an_py39.py
deleted file mode 100644
index acc804c32..000000000
--- a/docs_src/dependencies/tutorial008_an_py39.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from typing import Annotated
-
-from fastapi import Depends
-
-
-async def dependency_a():
- dep_a = generate_dep_a()
- try:
- yield dep_a
- finally:
- dep_a.close()
-
-
-async def dependency_b(dep_a: Annotated[DepA, Depends(dependency_a)]):
- dep_b = generate_dep_b()
- try:
- yield dep_b
- finally:
- dep_b.close(dep_a)
-
-
-async def dependency_c(dep_b: Annotated[DepB, Depends(dependency_b)]):
- dep_c = generate_dep_c()
- try:
- yield dep_c
- finally:
- dep_c.close(dep_b)
diff --git a/docs_src/dependencies/tutorial008_py39.py b/docs_src/dependencies/tutorial008_py39.py
deleted file mode 100644
index 8472f642d..000000000
--- a/docs_src/dependencies/tutorial008_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from fastapi import Depends
-
-
-async def dependency_a():
- dep_a = generate_dep_a()
- try:
- yield dep_a
- finally:
- dep_a.close()
-
-
-async def dependency_b(dep_a=Depends(dependency_a)):
- dep_b = generate_dep_b()
- try:
- yield dep_b
- finally:
- dep_b.close(dep_a)
-
-
-async def dependency_c(dep_b=Depends(dependency_b)):
- dep_c = generate_dep_c()
- try:
- yield dep_c
- finally:
- dep_c.close(dep_b)
diff --git a/docs_src/dependencies/tutorial008b_an_py39.py b/docs_src/dependencies/tutorial008b_an_py39.py
deleted file mode 100644
index 3b8434c81..000000000
--- a/docs_src/dependencies/tutorial008b_an_py39.py
+++ /dev/null
@@ -1,32 +0,0 @@
-from typing import Annotated
-
-from fastapi import Depends, FastAPI, HTTPException
-
-app = FastAPI()
-
-
-data = {
- "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
- "portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
-}
-
-
-class OwnerError(Exception):
- pass
-
-
-def get_username():
- try:
- yield "Rick"
- except OwnerError as e:
- raise HTTPException(status_code=400, detail=f"Owner error: {e}")
-
-
-@app.get("/items/{item_id}")
-def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
- if item_id not in data:
- raise HTTPException(status_code=404, detail="Item not found")
- item = data[item_id]
- if item["owner"] != username:
- raise OwnerError(username)
- return item
diff --git a/docs_src/dependencies/tutorial008b_py39.py b/docs_src/dependencies/tutorial008b_py39.py
deleted file mode 100644
index 163e96600..000000000
--- a/docs_src/dependencies/tutorial008b_py39.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from fastapi import Depends, FastAPI, HTTPException
-
-app = FastAPI()
-
-
-data = {
- "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
- "portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
-}
-
-
-class OwnerError(Exception):
- pass
-
-
-def get_username():
- try:
- yield "Rick"
- except OwnerError as e:
- raise HTTPException(status_code=400, detail=f"Owner error: {e}")
-
-
-@app.get("/items/{item_id}")
-def get_item(item_id: str, username: str = Depends(get_username)):
- if item_id not in data:
- raise HTTPException(status_code=404, detail="Item not found")
- item = data[item_id]
- if item["owner"] != username:
- raise OwnerError(username)
- return item
diff --git a/docs_src/dependencies/tutorial008c_an_py39.py b/docs_src/dependencies/tutorial008c_an_py39.py
deleted file mode 100644
index da92efa9c..000000000
--- a/docs_src/dependencies/tutorial008c_an_py39.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from typing import Annotated
-
-from fastapi import Depends, FastAPI, HTTPException
-
-app = FastAPI()
-
-
-class InternalError(Exception):
- pass
-
-
-def get_username():
- try:
- yield "Rick"
- except InternalError:
- print("Oops, we didn't raise again, Britney 😱")
-
-
-@app.get("/items/{item_id}")
-def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
- if item_id == "portal-gun":
- raise InternalError(
- f"The portal gun is too dangerous to be owned by {username}"
- )
- if item_id != "plumbus":
- raise HTTPException(
- status_code=404, detail="Item not found, there's only a plumbus here"
- )
- return item_id
diff --git a/docs_src/dependencies/tutorial008c_py39.py b/docs_src/dependencies/tutorial008c_py39.py
deleted file mode 100644
index 4b99a5a31..000000000
--- a/docs_src/dependencies/tutorial008c_py39.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from fastapi import Depends, FastAPI, HTTPException
-
-app = FastAPI()
-
-
-class InternalError(Exception):
- pass
-
-
-def get_username():
- try:
- yield "Rick"
- except InternalError:
- print("Oops, we didn't raise again, Britney 😱")
-
-
-@app.get("/items/{item_id}")
-def get_item(item_id: str, username: str = Depends(get_username)):
- if item_id == "portal-gun":
- raise InternalError(
- f"The portal gun is too dangerous to be owned by {username}"
- )
- if item_id != "plumbus":
- raise HTTPException(
- status_code=404, detail="Item not found, there's only a plumbus here"
- )
- return item_id
diff --git a/docs_src/dependencies/tutorial008d_an_py39.py b/docs_src/dependencies/tutorial008d_an_py39.py
deleted file mode 100644
index 99bd5cb91..000000000
--- a/docs_src/dependencies/tutorial008d_an_py39.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from typing import Annotated
-
-from fastapi import Depends, FastAPI, HTTPException
-
-app = FastAPI()
-
-
-class InternalError(Exception):
- pass
-
-
-def get_username():
- try:
- yield "Rick"
- except InternalError:
- print("We don't swallow the internal error here, we raise again 😎")
- raise
-
-
-@app.get("/items/{item_id}")
-def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
- if item_id == "portal-gun":
- raise InternalError(
- f"The portal gun is too dangerous to be owned by {username}"
- )
- if item_id != "plumbus":
- raise HTTPException(
- status_code=404, detail="Item not found, there's only a plumbus here"
- )
- return item_id
diff --git a/docs_src/dependencies/tutorial008d_py39.py b/docs_src/dependencies/tutorial008d_py39.py
deleted file mode 100644
index 93039343d..000000000
--- a/docs_src/dependencies/tutorial008d_py39.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from fastapi import Depends, FastAPI, HTTPException
-
-app = FastAPI()
-
-
-class InternalError(Exception):
- pass
-
-
-def get_username():
- try:
- yield "Rick"
- except InternalError:
- print("We don't swallow the internal error here, we raise again 😎")
- raise
-
-
-@app.get("/items/{item_id}")
-def get_item(item_id: str, username: str = Depends(get_username)):
- if item_id == "portal-gun":
- raise InternalError(
- f"The portal gun is too dangerous to be owned by {username}"
- )
- if item_id != "plumbus":
- raise HTTPException(
- status_code=404, detail="Item not found, there's only a plumbus here"
- )
- return item_id
diff --git a/docs_src/dependencies/tutorial008e_an_py39.py b/docs_src/dependencies/tutorial008e_an_py39.py
deleted file mode 100644
index 80a44c7e2..000000000
--- a/docs_src/dependencies/tutorial008e_an_py39.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import Annotated
-
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-def get_username():
- try:
- yield "Rick"
- finally:
- print("Cleanup up before response is sent")
-
-
-@app.get("/users/me")
-def get_user_me(username: Annotated[str, Depends(get_username, scope="function")]):
- return username
diff --git a/docs_src/dependencies/tutorial008e_py39.py b/docs_src/dependencies/tutorial008e_py39.py
deleted file mode 100644
index 1ed056e91..000000000
--- a/docs_src/dependencies/tutorial008e_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-def get_username():
- try:
- yield "Rick"
- finally:
- print("Cleanup up before response is sent")
-
-
-@app.get("/users/me")
-def get_user_me(username: str = Depends(get_username, scope="function")):
- return username
diff --git a/docs_src/dependencies/tutorial010_py39.py b/docs_src/dependencies/tutorial010_py39.py
deleted file mode 100644
index c27f1b170..000000000
--- a/docs_src/dependencies/tutorial010_py39.py
+++ /dev/null
@@ -1,14 +0,0 @@
-class MySuperContextManager:
- def __init__(self):
- self.db = DBSession()
-
- def __enter__(self):
- return self.db
-
- def __exit__(self, exc_type, exc_value, traceback):
- self.db.close()
-
-
-async def get_db():
- with MySuperContextManager() as db:
- yield db
diff --git a/docs_src/dependencies/tutorial011_an_py39.py b/docs_src/dependencies/tutorial011_an_py39.py
deleted file mode 100644
index 68b7434ec..000000000
--- a/docs_src/dependencies/tutorial011_an_py39.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from typing import Annotated
-
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-class FixedContentQueryChecker:
- def __init__(self, fixed_content: str):
- self.fixed_content = fixed_content
-
- def __call__(self, q: str = ""):
- if q:
- return self.fixed_content in q
- return False
-
-
-checker = FixedContentQueryChecker("bar")
-
-
-@app.get("/query-checker/")
-async def read_query_check(fixed_content_included: Annotated[bool, Depends(checker)]):
- return {"fixed_content_in_query": fixed_content_included}
diff --git a/docs_src/dependencies/tutorial011_py39.py b/docs_src/dependencies/tutorial011_py39.py
deleted file mode 100644
index 5d22f6823..000000000
--- a/docs_src/dependencies/tutorial011_py39.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from fastapi import Depends, FastAPI
-
-app = FastAPI()
-
-
-class FixedContentQueryChecker:
- def __init__(self, fixed_content: str):
- self.fixed_content = fixed_content
-
- def __call__(self, q: str = ""):
- if q:
- return self.fixed_content in q
- return False
-
-
-checker = FixedContentQueryChecker("bar")
-
-
-@app.get("/query-checker/")
-async def read_query_check(fixed_content_included: bool = Depends(checker)):
- return {"fixed_content_in_query": fixed_content_included}
diff --git a/docs_src/dependencies/tutorial012_an_py39.py b/docs_src/dependencies/tutorial012_an_py39.py
deleted file mode 100644
index 6503591fc..000000000
--- a/docs_src/dependencies/tutorial012_an_py39.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from typing import Annotated
-
-from fastapi import Depends, FastAPI, Header, HTTPException
-
-
-async def verify_token(x_token: Annotated[str, Header()]):
- if x_token != "fake-super-secret-token":
- raise HTTPException(status_code=400, detail="X-Token header invalid")
-
-
-async def verify_key(x_key: Annotated[str, Header()]):
- if x_key != "fake-super-secret-key":
- raise HTTPException(status_code=400, detail="X-Key header invalid")
- return x_key
-
-
-app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
-
-
-@app.get("/items/")
-async def read_items():
- return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
-
-
-@app.get("/users/")
-async def read_users():
- return [{"username": "Rick"}, {"username": "Morty"}]
diff --git a/docs_src/dependencies/tutorial012_py39.py b/docs_src/dependencies/tutorial012_py39.py
deleted file mode 100644
index 36ce6c711..000000000
--- a/docs_src/dependencies/tutorial012_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from fastapi import Depends, FastAPI, Header, HTTPException
-
-
-async def verify_token(x_token: str = Header()):
- if x_token != "fake-super-secret-token":
- raise HTTPException(status_code=400, detail="X-Token header invalid")
-
-
-async def verify_key(x_key: str = Header()):
- if x_key != "fake-super-secret-key":
- raise HTTPException(status_code=400, detail="X-Key header invalid")
- return x_key
-
-
-app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
-
-
-@app.get("/items/")
-async def read_items():
- return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
-
-
-@app.get("/users/")
-async def read_users():
- return [{"username": "Rick"}, {"username": "Morty"}]
diff --git a/docs_src/events/tutorial001_py39.py b/docs_src/events/tutorial001_py39.py
deleted file mode 100644
index 128004c9f..000000000
--- a/docs_src/events/tutorial001_py39.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-items = {}
-
-
-@app.on_event("startup")
-async def startup_event():
- items["foo"] = {"name": "Fighters"}
- items["bar"] = {"name": "Tenders"}
-
-
-@app.get("/items/{item_id}")
-async def read_items(item_id: str):
- return items[item_id]
diff --git a/docs_src/events/tutorial002_py39.py b/docs_src/events/tutorial002_py39.py
deleted file mode 100644
index a71fea802..000000000
--- a/docs_src/events/tutorial002_py39.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.on_event("shutdown")
-def shutdown_event():
- with open("log.txt", mode="a") as log:
- log.write("Application shutdown")
-
-
-@app.get("/items/")
-async def read_items():
- return [{"name": "Foo"}]
diff --git a/docs_src/events/tutorial003_py39.py b/docs_src/events/tutorial003_py39.py
deleted file mode 100644
index 2b650590b..000000000
--- a/docs_src/events/tutorial003_py39.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from contextlib import asynccontextmanager
-
-from fastapi import FastAPI
-
-
-def fake_answer_to_everything_ml_model(x: float):
- return x * 42
-
-
-ml_models = {}
-
-
-@asynccontextmanager
-async def lifespan(app: FastAPI):
- # Load the ML model
- ml_models["answer_to_everything"] = fake_answer_to_everything_ml_model
- yield
- # Clean up the ML models and release the resources
- ml_models.clear()
-
-
-app = FastAPI(lifespan=lifespan)
-
-
-@app.get("/predict")
-async def predict(x: float):
- result = ml_models["answer_to_everything"](x)
- return {"result": result}
diff --git a/docs_src/extending_openapi/tutorial001_py39.py b/docs_src/extending_openapi/tutorial001_py39.py
deleted file mode 100644
index 35e31c0e0..000000000
--- a/docs_src/extending_openapi/tutorial001_py39.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from fastapi import FastAPI
-from fastapi.openapi.utils import get_openapi
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items():
- return [{"name": "Foo"}]
-
-
-def custom_openapi():
- if app.openapi_schema:
- return app.openapi_schema
- openapi_schema = get_openapi(
- title="Custom title",
- version="2.5.0",
- summary="This is a very custom OpenAPI schema",
- description="Here's a longer description of the custom **OpenAPI** schema",
- routes=app.routes,
- )
- openapi_schema["info"]["x-logo"] = {
- "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png"
- }
- app.openapi_schema = openapi_schema
- return app.openapi_schema
-
-
-app.openapi = custom_openapi
diff --git a/docs_src/extra_models/tutorial004_py39.py b/docs_src/extra_models/tutorial004_py39.py
deleted file mode 100644
index 28cacde4d..000000000
--- a/docs_src/extra_models/tutorial004_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: str
-
-
-items = [
- {"name": "Foo", "description": "There comes my hero"},
- {"name": "Red", "description": "It's my aeroplane"},
-]
-
-
-@app.get("/items/", response_model=list[Item])
-async def read_items():
- return items
diff --git a/docs_src/extra_models/tutorial005_py39.py b/docs_src/extra_models/tutorial005_py39.py
deleted file mode 100644
index 9da2a0a0f..000000000
--- a/docs_src/extra_models/tutorial005_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/keyword-weights/", response_model=dict[str, float])
-async def read_keyword_weights():
- return {"foo": 2.3, "bar": 3.4}
diff --git a/docs_src/first_steps/tutorial001_py39.py b/docs_src/first_steps/tutorial001_py39.py
deleted file mode 100644
index ee60be1f9..000000000
--- a/docs_src/first_steps/tutorial001_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/")
-async def root():
- return {"message": "Hello World"}
diff --git a/docs_src/first_steps/tutorial003_py39.py b/docs_src/first_steps/tutorial003_py39.py
deleted file mode 100644
index e30b827ea..000000000
--- a/docs_src/first_steps/tutorial003_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/")
-def root():
- return {"message": "Hello World"}
diff --git a/docs_src/generate_clients/tutorial001_py39.py b/docs_src/generate_clients/tutorial001_py39.py
deleted file mode 100644
index 6a5ae2320..000000000
--- a/docs_src/generate_clients/tutorial001_py39.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- price: float
-
-
-class ResponseMessage(BaseModel):
- message: str
-
-
-@app.post("/items/", response_model=ResponseMessage)
-async def create_item(item: Item):
- return {"message": "item received"}
-
-
-@app.get("/items/", response_model=list[Item])
-async def get_items():
- return [
- {"name": "Plumbus", "price": 3},
- {"name": "Portal Gun", "price": 9001},
- ]
diff --git a/docs_src/generate_clients/tutorial002_py39.py b/docs_src/generate_clients/tutorial002_py39.py
deleted file mode 100644
index 83309760b..000000000
--- a/docs_src/generate_clients/tutorial002_py39.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- price: float
-
-
-class ResponseMessage(BaseModel):
- message: str
-
-
-class User(BaseModel):
- username: str
- email: str
-
-
-@app.post("/items/", response_model=ResponseMessage, tags=["items"])
-async def create_item(item: Item):
- return {"message": "Item received"}
-
-
-@app.get("/items/", response_model=list[Item], tags=["items"])
-async def get_items():
- return [
- {"name": "Plumbus", "price": 3},
- {"name": "Portal Gun", "price": 9001},
- ]
-
-
-@app.post("/users/", response_model=ResponseMessage, tags=["users"])
-async def create_user(user: User):
- return {"message": "User received"}
diff --git a/docs_src/generate_clients/tutorial003_py39.py b/docs_src/generate_clients/tutorial003_py39.py
deleted file mode 100644
index 40722cf10..000000000
--- a/docs_src/generate_clients/tutorial003_py39.py
+++ /dev/null
@@ -1,42 +0,0 @@
-from fastapi import FastAPI
-from fastapi.routing import APIRoute
-from pydantic import BaseModel
-
-
-def custom_generate_unique_id(route: APIRoute):
- return f"{route.tags[0]}-{route.name}"
-
-
-app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
-
-
-class Item(BaseModel):
- name: str
- price: float
-
-
-class ResponseMessage(BaseModel):
- message: str
-
-
-class User(BaseModel):
- username: str
- email: str
-
-
-@app.post("/items/", response_model=ResponseMessage, tags=["items"])
-async def create_item(item: Item):
- return {"message": "Item received"}
-
-
-@app.get("/items/", response_model=list[Item], tags=["items"])
-async def get_items():
- return [
- {"name": "Plumbus", "price": 3},
- {"name": "Portal Gun", "price": 9001},
- ]
-
-
-@app.post("/users/", response_model=ResponseMessage, tags=["users"])
-async def create_user(user: User):
- return {"message": "User received"}
diff --git a/docs_src/generate_clients/tutorial004_py39.py b/docs_src/generate_clients/tutorial004_py39.py
deleted file mode 100644
index 894dc7f8d..000000000
--- a/docs_src/generate_clients/tutorial004_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-import json
-from pathlib import Path
-
-file_path = Path("./openapi.json")
-openapi_content = json.loads(file_path.read_text())
-
-for path_data in openapi_content["paths"].values():
- for operation in path_data.values():
- tag = operation["tags"][0]
- operation_id = operation["operationId"]
- to_remove = f"{tag}-"
- new_operation_id = operation_id[len(to_remove) :]
- operation["operationId"] = new_operation_id
-
-file_path.write_text(json.dumps(openapi_content))
diff --git a/docs_src/graphql_/tutorial001_py39.py b/docs_src/graphql_/tutorial001_py39.py
deleted file mode 100644
index e92b2d71c..000000000
--- a/docs_src/graphql_/tutorial001_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import strawberry
-from fastapi import FastAPI
-from strawberry.fastapi import GraphQLRouter
-
-
-@strawberry.type
-class User:
- name: str
- age: int
-
-
-@strawberry.type
-class Query:
- @strawberry.field
- def user(self) -> User:
- return User(name="Patrick", age=100)
-
-
-schema = strawberry.Schema(query=Query)
-
-
-graphql_app = GraphQLRouter(schema)
-
-app = FastAPI()
-app.include_router(graphql_app, prefix="/graphql")
diff --git a/docs_src/handling_errors/tutorial001_py39.py b/docs_src/handling_errors/tutorial001_py39.py
deleted file mode 100644
index e5f32aac2..000000000
--- a/docs_src/handling_errors/tutorial001_py39.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from fastapi import FastAPI, HTTPException
-
-app = FastAPI()
-
-items = {"foo": "The Foo Wrestlers"}
-
-
-@app.get("/items/{item_id}")
-async def read_item(item_id: str):
- if item_id not in items:
- raise HTTPException(status_code=404, detail="Item not found")
- return {"item": items[item_id]}
diff --git a/docs_src/handling_errors/tutorial002_py39.py b/docs_src/handling_errors/tutorial002_py39.py
deleted file mode 100644
index e48c295c9..000000000
--- a/docs_src/handling_errors/tutorial002_py39.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from fastapi import FastAPI, HTTPException
-
-app = FastAPI()
-
-items = {"foo": "The Foo Wrestlers"}
-
-
-@app.get("/items-header/{item_id}")
-async def read_item_header(item_id: str):
- if item_id not in items:
- raise HTTPException(
- status_code=404,
- detail="Item not found",
- headers={"X-Error": "There goes my error"},
- )
- return {"item": items[item_id]}
diff --git a/docs_src/handling_errors/tutorial003_py39.py b/docs_src/handling_errors/tutorial003_py39.py
deleted file mode 100644
index 791cd6838..000000000
--- a/docs_src/handling_errors/tutorial003_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from fastapi import FastAPI, Request
-from fastapi.responses import JSONResponse
-
-
-class UnicornException(Exception):
- def __init__(self, name: str):
- self.name = name
-
-
-app = FastAPI()
-
-
-@app.exception_handler(UnicornException)
-async def unicorn_exception_handler(request: Request, exc: UnicornException):
- return JSONResponse(
- status_code=418,
- content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
- )
-
-
-@app.get("/unicorns/{name}")
-async def read_unicorn(name: str):
- if name == "yolo":
- raise UnicornException(name=name)
- return {"unicorn_name": name}
diff --git a/docs_src/handling_errors/tutorial004_py39.py b/docs_src/handling_errors/tutorial004_py39.py
deleted file mode 100644
index ae50807e9..000000000
--- a/docs_src/handling_errors/tutorial004_py39.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from fastapi import FastAPI, HTTPException
-from fastapi.exceptions import RequestValidationError
-from fastapi.responses import PlainTextResponse
-from starlette.exceptions import HTTPException as StarletteHTTPException
-
-app = FastAPI()
-
-
-@app.exception_handler(StarletteHTTPException)
-async def http_exception_handler(request, exc):
- return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
-
-
-@app.exception_handler(RequestValidationError)
-async def validation_exception_handler(request, exc: RequestValidationError):
- message = "Validation errors:"
- for error in exc.errors():
- message += f"\nField: {error['loc']}, Error: {error['msg']}"
- return PlainTextResponse(message, status_code=400)
-
-
-@app.get("/items/{item_id}")
-async def read_item(item_id: int):
- if item_id == 3:
- raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
- return {"item_id": item_id}
diff --git a/docs_src/handling_errors/tutorial005_py39.py b/docs_src/handling_errors/tutorial005_py39.py
deleted file mode 100644
index 0e04fa086..000000000
--- a/docs_src/handling_errors/tutorial005_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from fastapi import FastAPI, Request
-from fastapi.encoders import jsonable_encoder
-from fastapi.exceptions import RequestValidationError
-from fastapi.responses import JSONResponse
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-@app.exception_handler(RequestValidationError)
-async def validation_exception_handler(request: Request, exc: RequestValidationError):
- return JSONResponse(
- status_code=422,
- content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
- )
-
-
-class Item(BaseModel):
- title: str
- size: int
-
-
-@app.post("/items/")
-async def create_item(item: Item):
- return item
diff --git a/docs_src/handling_errors/tutorial006_py39.py b/docs_src/handling_errors/tutorial006_py39.py
deleted file mode 100644
index e05160d7e..000000000
--- a/docs_src/handling_errors/tutorial006_py39.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from fastapi import FastAPI, HTTPException
-from fastapi.exception_handlers import (
- http_exception_handler,
- request_validation_exception_handler,
-)
-from fastapi.exceptions import RequestValidationError
-from starlette.exceptions import HTTPException as StarletteHTTPException
-
-app = FastAPI()
-
-
-@app.exception_handler(StarletteHTTPException)
-async def custom_http_exception_handler(request, exc):
- print(f"OMG! An HTTP error!: {repr(exc)}")
- return await http_exception_handler(request, exc)
-
-
-@app.exception_handler(RequestValidationError)
-async def validation_exception_handler(request, exc):
- print(f"OMG! The client sent invalid data!: {exc}")
- return await request_validation_exception_handler(request, exc)
-
-
-@app.get("/items/{item_id}")
-async def read_item(item_id: int):
- if item_id == 3:
- raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
- return {"item_id": item_id}
diff --git a/docs_src/metadata/tutorial001_1_py39.py b/docs_src/metadata/tutorial001_1_py39.py
deleted file mode 100644
index 419232d86..000000000
--- a/docs_src/metadata/tutorial001_1_py39.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from fastapi import FastAPI
-
-description = """
-ChimichangApp API helps you do awesome stuff. 🚀
-
-## Items
-
-You can **read items**.
-
-## Users
-
-You will be able to:
-
-* **Create users** (_not implemented_).
-* **Read users** (_not implemented_).
-"""
-
-app = FastAPI(
- title="ChimichangApp",
- description=description,
- summary="Deadpool's favorite app. Nuff said.",
- version="0.0.1",
- terms_of_service="http://example.com/terms/",
- contact={
- "name": "Deadpoolio the Amazing",
- "url": "http://x-force.example.com/contact/",
- "email": "dp@x-force.example.com",
- },
- license_info={
- "name": "Apache 2.0",
- "identifier": "Apache-2.0",
- },
-)
-
-
-@app.get("/items/")
-async def read_items():
- return [{"name": "Katana"}]
diff --git a/docs_src/metadata/tutorial001_py39.py b/docs_src/metadata/tutorial001_py39.py
deleted file mode 100644
index 76656e81b..000000000
--- a/docs_src/metadata/tutorial001_py39.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from fastapi import FastAPI
-
-description = """
-ChimichangApp API helps you do awesome stuff. 🚀
-
-## Items
-
-You can **read items**.
-
-## Users
-
-You will be able to:
-
-* **Create users** (_not implemented_).
-* **Read users** (_not implemented_).
-"""
-
-app = FastAPI(
- title="ChimichangApp",
- description=description,
- summary="Deadpool's favorite app. Nuff said.",
- version="0.0.1",
- terms_of_service="http://example.com/terms/",
- contact={
- "name": "Deadpoolio the Amazing",
- "url": "http://x-force.example.com/contact/",
- "email": "dp@x-force.example.com",
- },
- license_info={
- "name": "Apache 2.0",
- "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
- },
-)
-
-
-@app.get("/items/")
-async def read_items():
- return [{"name": "Katana"}]
diff --git a/docs_src/metadata/tutorial002_py39.py b/docs_src/metadata/tutorial002_py39.py
deleted file mode 100644
index cf9ed7087..000000000
--- a/docs_src/metadata/tutorial002_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI(openapi_url="/api/v1/openapi.json")
-
-
-@app.get("/items/")
-async def read_items():
- return [{"name": "Foo"}]
diff --git a/docs_src/metadata/tutorial003_py39.py b/docs_src/metadata/tutorial003_py39.py
deleted file mode 100644
index ee09c7f37..000000000
--- a/docs_src/metadata/tutorial003_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI(docs_url="/documentation", redoc_url=None)
-
-
-@app.get("/items/")
-async def read_items():
- return [{"name": "Foo"}]
diff --git a/docs_src/metadata/tutorial004_py39.py b/docs_src/metadata/tutorial004_py39.py
deleted file mode 100644
index 465bd659d..000000000
--- a/docs_src/metadata/tutorial004_py39.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from fastapi import FastAPI
-
-tags_metadata = [
- {
- "name": "users",
- "description": "Operations with users. The **login** logic is also here.",
- },
- {
- "name": "items",
- "description": "Manage items. So _fancy_ they have their own docs.",
- "externalDocs": {
- "description": "Items external docs",
- "url": "https://fastapi.tiangolo.com/",
- },
- },
-]
-
-app = FastAPI(openapi_tags=tags_metadata)
-
-
-@app.get("/users/", tags=["users"])
-async def get_users():
- return [{"name": "Harry"}, {"name": "Ron"}]
-
-
-@app.get("/items/", tags=["items"])
-async def get_items():
- return [{"name": "wand"}, {"name": "flying broom"}]
diff --git a/docs_src/middleware/tutorial001_py39.py b/docs_src/middleware/tutorial001_py39.py
deleted file mode 100644
index e65a7dade..000000000
--- a/docs_src/middleware/tutorial001_py39.py
+++ /dev/null
@@ -1,14 +0,0 @@
-import time
-
-from fastapi import FastAPI, Request
-
-app = FastAPI()
-
-
-@app.middleware("http")
-async def add_process_time_header(request: Request, call_next):
- start_time = time.perf_counter()
- response = await call_next(request)
- process_time = time.perf_counter() - start_time
- response.headers["X-Process-Time"] = str(process_time)
- return response
diff --git a/docs_src/openapi_webhooks/tutorial001_py39.py b/docs_src/openapi_webhooks/tutorial001_py39.py
deleted file mode 100644
index 55822bb48..000000000
--- a/docs_src/openapi_webhooks/tutorial001_py39.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from datetime import datetime
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Subscription(BaseModel):
- username: str
- monthly_fee: float
- start_date: datetime
-
-
-@app.webhooks.post("new-subscription")
-def new_subscription(body: Subscription):
- """
- When a new user subscribes to your service we'll send you a POST request with this
- data to the URL that you register for the event `new-subscription` in the dashboard.
- """
-
-
-@app.get("/users/")
-def read_users():
- return ["Rick", "Morty"]
diff --git a/docs_src/path_operation_advanced_configuration/tutorial001_py39.py b/docs_src/path_operation_advanced_configuration/tutorial001_py39.py
deleted file mode 100644
index fafa8ffb8..000000000
--- a/docs_src/path_operation_advanced_configuration/tutorial001_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/", operation_id="some_specific_id_you_define")
-async def read_items():
- return [{"item_id": "Foo"}]
diff --git a/docs_src/path_operation_advanced_configuration/tutorial002_py39.py b/docs_src/path_operation_advanced_configuration/tutorial002_py39.py
deleted file mode 100644
index 3aaae9b37..000000000
--- a/docs_src/path_operation_advanced_configuration/tutorial002_py39.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from fastapi import FastAPI
-from fastapi.routing import APIRoute
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items():
- return [{"item_id": "Foo"}]
-
-
-def use_route_names_as_operation_ids(app: FastAPI) -> None:
- """
- Simplify operation IDs so that generated API clients have simpler function
- names.
-
- Should be called only after all routes have been added.
- """
- for route in app.routes:
- if isinstance(route, APIRoute):
- route.operation_id = route.name # in this case, 'read_items'
-
-
-use_route_names_as_operation_ids(app)
diff --git a/docs_src/path_operation_advanced_configuration/tutorial003_py39.py b/docs_src/path_operation_advanced_configuration/tutorial003_py39.py
deleted file mode 100644
index dcc358e32..000000000
--- a/docs_src/path_operation_advanced_configuration/tutorial003_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/", include_in_schema=False)
-async def read_items():
- return [{"item_id": "Foo"}]
diff --git a/docs_src/path_operation_advanced_configuration/tutorial005_py39.py b/docs_src/path_operation_advanced_configuration/tutorial005_py39.py
deleted file mode 100644
index 5837ad835..000000000
--- a/docs_src/path_operation_advanced_configuration/tutorial005_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/", openapi_extra={"x-aperture-labs-portal": "blue"})
-async def read_items():
- return [{"item_id": "portal-gun"}]
diff --git a/docs_src/path_operation_advanced_configuration/tutorial006_py39.py b/docs_src/path_operation_advanced_configuration/tutorial006_py39.py
deleted file mode 100644
index 403c3ee3f..000000000
--- a/docs_src/path_operation_advanced_configuration/tutorial006_py39.py
+++ /dev/null
@@ -1,41 +0,0 @@
-from fastapi import FastAPI, Request
-
-app = FastAPI()
-
-
-def magic_data_reader(raw_body: bytes):
- return {
- "size": len(raw_body),
- "content": {
- "name": "Maaaagic",
- "price": 42,
- "description": "Just kiddin', no magic here. ✨",
- },
- }
-
-
-@app.post(
- "/items/",
- openapi_extra={
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "required": ["name", "price"],
- "type": "object",
- "properties": {
- "name": {"type": "string"},
- "price": {"type": "number"},
- "description": {"type": "string"},
- },
- }
- }
- },
- "required": True,
- },
- },
-)
-async def create_item(request: Request):
- raw_body = await request.body()
- data = magic_data_reader(raw_body)
- return data
diff --git a/docs_src/path_operation_advanced_configuration/tutorial007_py39.py b/docs_src/path_operation_advanced_configuration/tutorial007_py39.py
deleted file mode 100644
index ff64ef792..000000000
--- a/docs_src/path_operation_advanced_configuration/tutorial007_py39.py
+++ /dev/null
@@ -1,32 +0,0 @@
-import yaml
-from fastapi import FastAPI, HTTPException, Request
-from pydantic import BaseModel, ValidationError
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- tags: list[str]
-
-
-@app.post(
- "/items/",
- openapi_extra={
- "requestBody": {
- "content": {"application/x-yaml": {"schema": Item.model_json_schema()}},
- "required": True,
- },
- },
-)
-async def create_item(request: Request):
- raw_body = await request.body()
- try:
- data = yaml.safe_load(raw_body)
- except yaml.YAMLError:
- raise HTTPException(status_code=422, detail="Invalid YAML")
- try:
- item = Item.model_validate(data)
- except ValidationError as e:
- raise HTTPException(status_code=422, detail=e.errors(include_url=False))
- return item
diff --git a/docs_src/path_operation_configuration/tutorial002b_py39.py b/docs_src/path_operation_configuration/tutorial002b_py39.py
deleted file mode 100644
index d53b4d817..000000000
--- a/docs_src/path_operation_configuration/tutorial002b_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from enum import Enum
-
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-class Tags(Enum):
- items = "items"
- users = "users"
-
-
-@app.get("/items/", tags=[Tags.items])
-async def get_items():
- return ["Portal gun", "Plumbus"]
-
-
-@app.get("/users/", tags=[Tags.users])
-async def read_users():
- return ["Rick", "Morty"]
diff --git a/docs_src/path_operation_configuration/tutorial006_py39.py b/docs_src/path_operation_configuration/tutorial006_py39.py
deleted file mode 100644
index 7c1aa9b20..000000000
--- a/docs_src/path_operation_configuration/tutorial006_py39.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/", tags=["items"])
-async def read_items():
- return [{"name": "Foo", "price": 42}]
-
-
-@app.get("/users/", tags=["users"])
-async def read_users():
- return [{"username": "johndoe"}]
-
-
-@app.get("/elements/", tags=["items"], deprecated=True)
-async def read_elements():
- return [{"item_id": "Foo"}]
diff --git a/docs_src/path_params/tutorial001_py39.py b/docs_src/path_params/tutorial001_py39.py
deleted file mode 100644
index 7bbf70e6c..000000000
--- a/docs_src/path_params/tutorial001_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_item(item_id):
- return {"item_id": item_id}
diff --git a/docs_src/path_params/tutorial002_py39.py b/docs_src/path_params/tutorial002_py39.py
deleted file mode 100644
index 8272ad70d..000000000
--- a/docs_src/path_params/tutorial002_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_item(item_id: int):
- return {"item_id": item_id}
diff --git a/docs_src/path_params/tutorial003_py39.py b/docs_src/path_params/tutorial003_py39.py
deleted file mode 100644
index 5f0aa0923..000000000
--- a/docs_src/path_params/tutorial003_py39.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/users/me")
-async def read_user_me():
- return {"user_id": "the current user"}
-
-
-@app.get("/users/{user_id}")
-async def read_user(user_id: str):
- return {"user_id": user_id}
diff --git a/docs_src/path_params/tutorial003b_py39.py b/docs_src/path_params/tutorial003b_py39.py
deleted file mode 100644
index 822d37369..000000000
--- a/docs_src/path_params/tutorial003b_py39.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/users")
-async def read_users():
- return ["Rick", "Morty"]
-
-
-@app.get("/users")
-async def read_users2():
- return ["Bean", "Elfo"]
diff --git a/docs_src/path_params/tutorial004_py39.py b/docs_src/path_params/tutorial004_py39.py
deleted file mode 100644
index 2961e6178..000000000
--- a/docs_src/path_params/tutorial004_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/files/{file_path:path}")
-async def read_file(file_path: str):
- return {"file_path": file_path}
diff --git a/docs_src/path_params/tutorial005_py39.py b/docs_src/path_params/tutorial005_py39.py
deleted file mode 100644
index 9a24a4963..000000000
--- a/docs_src/path_params/tutorial005_py39.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from enum import Enum
-
-from fastapi import FastAPI
-
-
-class ModelName(str, Enum):
- alexnet = "alexnet"
- resnet = "resnet"
- lenet = "lenet"
-
-
-app = FastAPI()
-
-
-@app.get("/models/{model_name}")
-async def get_model(model_name: ModelName):
- if model_name is ModelName.alexnet:
- return {"model_name": model_name, "message": "Deep Learning FTW!"}
-
- if model_name.value == "lenet":
- return {"model_name": model_name, "message": "LeCNN all the images"}
-
- return {"model_name": model_name, "message": "Have some residuals"}
diff --git a/docs_src/path_params_numeric_validations/tutorial002_an_py39.py b/docs_src/path_params_numeric_validations/tutorial002_an_py39.py
deleted file mode 100644
index cd882abb2..000000000
--- a/docs_src/path_params_numeric_validations/tutorial002_an_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Path
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial002_py39.py b/docs_src/path_params_numeric_validations/tutorial002_py39.py
deleted file mode 100644
index 63ac691a8..000000000
--- a/docs_src/path_params_numeric_validations/tutorial002_py39.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from fastapi import FastAPI, Path
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(q: str, item_id: int = Path(title="The ID of the item to get")):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial003_an_py39.py b/docs_src/path_params_numeric_validations/tutorial003_an_py39.py
deleted file mode 100644
index 1588556e7..000000000
--- a/docs_src/path_params_numeric_validations/tutorial003_an_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Path
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial003_py39.py b/docs_src/path_params_numeric_validations/tutorial003_py39.py
deleted file mode 100644
index 8df0ffc62..000000000
--- a/docs_src/path_params_numeric_validations/tutorial003_py39.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from fastapi import FastAPI, Path
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial004_an_py39.py b/docs_src/path_params_numeric_validations/tutorial004_an_py39.py
deleted file mode 100644
index f67f6450e..000000000
--- a/docs_src/path_params_numeric_validations/tutorial004_an_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Path
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial004_py39.py b/docs_src/path_params_numeric_validations/tutorial004_py39.py
deleted file mode 100644
index 86651d47c..000000000
--- a/docs_src/path_params_numeric_validations/tutorial004_py39.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from fastapi import FastAPI, Path
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- *, item_id: int = Path(title="The ID of the item to get", ge=1), q: str
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial005_an_py39.py b/docs_src/path_params_numeric_validations/tutorial005_an_py39.py
deleted file mode 100644
index 571dd583c..000000000
--- a/docs_src/path_params_numeric_validations/tutorial005_an_py39.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Path
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- item_id: Annotated[int, Path(title="The ID of the item to get", gt=0, le=1000)],
- q: str,
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial005_py39.py b/docs_src/path_params_numeric_validations/tutorial005_py39.py
deleted file mode 100644
index 8f12f2da0..000000000
--- a/docs_src/path_params_numeric_validations/tutorial005_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from fastapi import FastAPI, Path
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- *,
- item_id: int = Path(title="The ID of the item to get", gt=0, le=1000),
- q: str,
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py
deleted file mode 100644
index 426ec3776..000000000
--- a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Path, Query
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- *,
- item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
- q: str,
- size: Annotated[float, Query(gt=0, lt=10.5)],
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- if size:
- results.update({"size": size})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial006_py39.py b/docs_src/path_params_numeric_validations/tutorial006_py39.py
deleted file mode 100644
index f07629aa0..000000000
--- a/docs_src/path_params_numeric_validations/tutorial006_py39.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from fastapi import FastAPI, Path, Query
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- *,
- item_id: int = Path(title="The ID of the item to get", ge=0, le=1000),
- q: str,
- size: float = Query(gt=0, lt=10.5),
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- if size:
- results.update({"size": size})
- return results
diff --git a/docs_src/python_types/tutorial001_py39.py b/docs_src/python_types/tutorial001_py39.py
deleted file mode 100644
index 09039435f..000000000
--- a/docs_src/python_types/tutorial001_py39.py
+++ /dev/null
@@ -1,6 +0,0 @@
-def get_full_name(first_name, last_name):
- full_name = first_name.title() + " " + last_name.title()
- return full_name
-
-
-print(get_full_name("john", "doe"))
diff --git a/docs_src/python_types/tutorial002_py39.py b/docs_src/python_types/tutorial002_py39.py
deleted file mode 100644
index c0857a116..000000000
--- a/docs_src/python_types/tutorial002_py39.py
+++ /dev/null
@@ -1,6 +0,0 @@
-def get_full_name(first_name: str, last_name: str):
- full_name = first_name.title() + " " + last_name.title()
- return full_name
-
-
-print(get_full_name("john", "doe"))
diff --git a/docs_src/python_types/tutorial003_py39.py b/docs_src/python_types/tutorial003_py39.py
deleted file mode 100644
index d021d8211..000000000
--- a/docs_src/python_types/tutorial003_py39.py
+++ /dev/null
@@ -1,3 +0,0 @@
-def get_name_with_age(name: str, age: int):
- name_with_age = name + " is this old: " + age
- return name_with_age
diff --git a/docs_src/python_types/tutorial004_py39.py b/docs_src/python_types/tutorial004_py39.py
deleted file mode 100644
index 9400269e2..000000000
--- a/docs_src/python_types/tutorial004_py39.py
+++ /dev/null
@@ -1,3 +0,0 @@
-def get_name_with_age(name: str, age: int):
- name_with_age = name + " is this old: " + str(age)
- return name_with_age
diff --git a/docs_src/python_types/tutorial006_py39.py b/docs_src/python_types/tutorial006_py39.py
deleted file mode 100644
index 486b67caf..000000000
--- a/docs_src/python_types/tutorial006_py39.py
+++ /dev/null
@@ -1,3 +0,0 @@
-def process_items(items: list[str]):
- for item in items:
- print(item)
diff --git a/docs_src/python_types/tutorial007_py39.py b/docs_src/python_types/tutorial007_py39.py
deleted file mode 100644
index ea96c7964..000000000
--- a/docs_src/python_types/tutorial007_py39.py
+++ /dev/null
@@ -1,2 +0,0 @@
-def process_items(items_t: tuple[int, int, str], items_s: set[bytes]):
- return items_t, items_s
diff --git a/docs_src/python_types/tutorial008_py39.py b/docs_src/python_types/tutorial008_py39.py
deleted file mode 100644
index a393385b0..000000000
--- a/docs_src/python_types/tutorial008_py39.py
+++ /dev/null
@@ -1,4 +0,0 @@
-def process_items(prices: dict[str, float]):
- for item_name, item_price in prices.items():
- print(item_name)
- print(item_price)
diff --git a/docs_src/python_types/tutorial008b_py39.py b/docs_src/python_types/tutorial008b_py39.py
deleted file mode 100644
index e52539ead..000000000
--- a/docs_src/python_types/tutorial008b_py39.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from typing import Union
-
-
-def process_item(item: Union[int, str]):
- print(item)
diff --git a/docs_src/python_types/tutorial009_py39.py b/docs_src/python_types/tutorial009_py39.py
deleted file mode 100644
index 6328a1495..000000000
--- a/docs_src/python_types/tutorial009_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from typing import Optional
-
-
-def say_hi(name: Optional[str] = None):
- if name is not None:
- print(f"Hey {name}!")
- else:
- print("Hello World")
diff --git a/docs_src/python_types/tutorial009b_py39.py b/docs_src/python_types/tutorial009b_py39.py
deleted file mode 100644
index 9f1a05bc0..000000000
--- a/docs_src/python_types/tutorial009b_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from typing import Union
-
-
-def say_hi(name: Union[str, None] = None):
- if name is not None:
- print(f"Hey {name}!")
- else:
- print("Hello World")
diff --git a/docs_src/python_types/tutorial009c_py310.py b/docs_src/python_types/tutorial009c_py310.py
deleted file mode 100644
index 96b1220fc..000000000
--- a/docs_src/python_types/tutorial009c_py310.py
+++ /dev/null
@@ -1,2 +0,0 @@
-def say_hi(name: str | None):
- print(f"Hey {name}!")
diff --git a/docs_src/python_types/tutorial009c_py39.py b/docs_src/python_types/tutorial009c_py39.py
deleted file mode 100644
index 2f539a34b..000000000
--- a/docs_src/python_types/tutorial009c_py39.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from typing import Optional
-
-
-def say_hi(name: Optional[str]):
- print(f"Hey {name}!")
diff --git a/docs_src/python_types/tutorial010_py39.py b/docs_src/python_types/tutorial010_py39.py
deleted file mode 100644
index 468cffc2d..000000000
--- a/docs_src/python_types/tutorial010_py39.py
+++ /dev/null
@@ -1,7 +0,0 @@
-class Person:
- def __init__(self, name: str):
- self.name = name
-
-
-def get_person_name(one_person: Person):
- return one_person.name
diff --git a/docs_src/python_types/tutorial013_py39.py b/docs_src/python_types/tutorial013_py39.py
deleted file mode 100644
index 65a0eaa93..000000000
--- a/docs_src/python_types/tutorial013_py39.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from typing import Annotated
-
-
-def say_hello(name: Annotated[str, "this is just metadata"]) -> str:
- return f"Hello {name}"
diff --git a/docs_src/query_params/tutorial001_py39.py b/docs_src/query_params/tutorial001_py39.py
deleted file mode 100644
index 74e1a1760..000000000
--- a/docs_src/query_params/tutorial001_py39.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
-
-
-@app.get("/items/")
-async def read_item(skip: int = 0, limit: int = 10):
- return fake_items_db[skip : skip + limit]
diff --git a/docs_src/query_params/tutorial005_py39.py b/docs_src/query_params/tutorial005_py39.py
deleted file mode 100644
index e16a40574..000000000
--- a/docs_src/query_params/tutorial005_py39.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_user_item(item_id: str, needy: str):
- item = {"item_id": item_id, "needy": needy}
- return item
diff --git a/docs_src/query_params_str_validations/tutorial005_an_py39.py b/docs_src/query_params_str_validations/tutorial005_an_py39.py
deleted file mode 100644
index b1f6046b5..000000000
--- a/docs_src/query_params_str_validations/tutorial005_an_py39.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[str, Query(min_length=3)] = "fixedquery"):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial005_py39.py b/docs_src/query_params_str_validations/tutorial005_py39.py
deleted file mode 100644
index 8ab42869e..000000000
--- a/docs_src/query_params_str_validations/tutorial005_py39.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: str = Query(default="fixedquery", min_length=3)):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial006_an_py39.py b/docs_src/query_params_str_validations/tutorial006_an_py39.py
deleted file mode 100644
index 3b4a676d2..000000000
--- a/docs_src/query_params_str_validations/tutorial006_an_py39.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[str, Query(min_length=3)]):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial006_py39.py b/docs_src/query_params_str_validations/tutorial006_py39.py
deleted file mode 100644
index 9a90eb64e..000000000
--- a/docs_src/query_params_str_validations/tutorial006_py39.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: str = Query(min_length=3)):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial012_an_py39.py b/docs_src/query_params_str_validations/tutorial012_an_py39.py
deleted file mode 100644
index 9b5a9c2fb..000000000
--- a/docs_src/query_params_str_validations/tutorial012_an_py39.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[list[str], Query()] = ["foo", "bar"]):
- query_items = {"q": q}
- return query_items
diff --git a/docs_src/query_params_str_validations/tutorial012_py39.py b/docs_src/query_params_str_validations/tutorial012_py39.py
deleted file mode 100644
index 070d0b04b..000000000
--- a/docs_src/query_params_str_validations/tutorial012_py39.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: list[str] = Query(default=["foo", "bar"])):
- query_items = {"q": q}
- return query_items
diff --git a/docs_src/query_params_str_validations/tutorial013_an_py39.py b/docs_src/query_params_str_validations/tutorial013_an_py39.py
deleted file mode 100644
index 602734145..000000000
--- a/docs_src/query_params_str_validations/tutorial013_an_py39.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[list, Query()] = []):
- query_items = {"q": q}
- return query_items
diff --git a/docs_src/query_params_str_validations/tutorial013_py39.py b/docs_src/query_params_str_validations/tutorial013_py39.py
deleted file mode 100644
index 0b0f44869..000000000
--- a/docs_src/query_params_str_validations/tutorial013_py39.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: list = Query(default=[])):
- query_items = {"q": q}
- return query_items
diff --git a/docs_src/request_files/tutorial001_03_an_py39.py b/docs_src/request_files/tutorial001_03_an_py39.py
deleted file mode 100644
index 93098a677..000000000
--- a/docs_src/request_files/tutorial001_03_an_py39.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, File, UploadFile
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(file: Annotated[bytes, File(description="A file read as bytes")]):
- return {"file_size": len(file)}
-
-
-@app.post("/uploadfile/")
-async def create_upload_file(
- file: Annotated[UploadFile, File(description="A file read as UploadFile")],
-):
- return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial001_03_py39.py b/docs_src/request_files/tutorial001_03_py39.py
deleted file mode 100644
index d8005cc7d..000000000
--- a/docs_src/request_files/tutorial001_03_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from fastapi import FastAPI, File, UploadFile
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(file: bytes = File(description="A file read as bytes")):
- return {"file_size": len(file)}
-
-
-@app.post("/uploadfile/")
-async def create_upload_file(
- file: UploadFile = File(description="A file read as UploadFile"),
-):
- return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial001_an_py39.py b/docs_src/request_files/tutorial001_an_py39.py
deleted file mode 100644
index 26a767221..000000000
--- a/docs_src/request_files/tutorial001_an_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, File, UploadFile
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(file: Annotated[bytes, File()]):
- return {"file_size": len(file)}
-
-
-@app.post("/uploadfile/")
-async def create_upload_file(file: UploadFile):
- return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial001_py39.py b/docs_src/request_files/tutorial001_py39.py
deleted file mode 100644
index 2e0ea6391..000000000
--- a/docs_src/request_files/tutorial001_py39.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from fastapi import FastAPI, File, UploadFile
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(file: bytes = File()):
- return {"file_size": len(file)}
-
-
-@app.post("/uploadfile/")
-async def create_upload_file(file: UploadFile):
- return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial002_an_py39.py b/docs_src/request_files/tutorial002_an_py39.py
deleted file mode 100644
index db524ceab..000000000
--- a/docs_src/request_files/tutorial002_an_py39.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, File, UploadFile
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_files(files: Annotated[list[bytes], File()]):
- return {"file_sizes": [len(file) for file in files]}
-
-
-@app.post("/uploadfiles/")
-async def create_upload_files(files: list[UploadFile]):
- return {"filenames": [file.filename for file in files]}
-
-
-@app.get("/")
-async def main():
- content = """
-
-
-
-
- """
- return HTMLResponse(content=content)
diff --git a/docs_src/request_files/tutorial002_py39.py b/docs_src/request_files/tutorial002_py39.py
deleted file mode 100644
index b64cf5598..000000000
--- a/docs_src/request_files/tutorial002_py39.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from fastapi import FastAPI, File, UploadFile
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_files(files: list[bytes] = File()):
- return {"file_sizes": [len(file) for file in files]}
-
-
-@app.post("/uploadfiles/")
-async def create_upload_files(files: list[UploadFile]):
- return {"filenames": [file.filename for file in files]}
-
-
-@app.get("/")
-async def main():
- content = """
-
-
-
-
- """
- return HTMLResponse(content=content)
diff --git a/docs_src/request_files/tutorial003_an_py39.py b/docs_src/request_files/tutorial003_an_py39.py
deleted file mode 100644
index 5a8c5dab5..000000000
--- a/docs_src/request_files/tutorial003_an_py39.py
+++ /dev/null
@@ -1,39 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, File, UploadFile
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_files(
- files: Annotated[list[bytes], File(description="Multiple files as bytes")],
-):
- return {"file_sizes": [len(file) for file in files]}
-
-
-@app.post("/uploadfiles/")
-async def create_upload_files(
- files: Annotated[
- list[UploadFile], File(description="Multiple files as UploadFile")
- ],
-):
- return {"filenames": [file.filename for file in files]}
-
-
-@app.get("/")
-async def main():
- content = """
-
-
-
-
- """
- return HTMLResponse(content=content)
diff --git a/docs_src/request_files/tutorial003_py39.py b/docs_src/request_files/tutorial003_py39.py
deleted file mode 100644
index 96f5e8742..000000000
--- a/docs_src/request_files/tutorial003_py39.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from fastapi import FastAPI, File, UploadFile
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_files(
- files: list[bytes] = File(description="Multiple files as bytes"),
-):
- return {"file_sizes": [len(file) for file in files]}
-
-
-@app.post("/uploadfiles/")
-async def create_upload_files(
- files: list[UploadFile] = File(description="Multiple files as UploadFile"),
-):
- return {"filenames": [file.filename for file in files]}
-
-
-@app.get("/")
-async def main():
- content = """
-
-
-
-
- """
- return HTMLResponse(content=content)
diff --git a/docs_src/request_form_models/tutorial001_an_py39.py b/docs_src/request_form_models/tutorial001_an_py39.py
deleted file mode 100644
index 7cc81aae9..000000000
--- a/docs_src/request_form_models/tutorial001_an_py39.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Form
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class FormData(BaseModel):
- username: str
- password: str
-
-
-@app.post("/login/")
-async def login(data: Annotated[FormData, Form()]):
- return data
diff --git a/docs_src/request_form_models/tutorial001_py39.py b/docs_src/request_form_models/tutorial001_py39.py
deleted file mode 100644
index 98feff0b9..000000000
--- a/docs_src/request_form_models/tutorial001_py39.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from fastapi import FastAPI, Form
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class FormData(BaseModel):
- username: str
- password: str
-
-
-@app.post("/login/")
-async def login(data: FormData = Form()):
- return data
diff --git a/docs_src/request_form_models/tutorial002_an_py39.py b/docs_src/request_form_models/tutorial002_an_py39.py
deleted file mode 100644
index 3004e0852..000000000
--- a/docs_src/request_form_models/tutorial002_an_py39.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Form
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class FormData(BaseModel):
- username: str
- password: str
- model_config = {"extra": "forbid"}
-
-
-@app.post("/login/")
-async def login(data: Annotated[FormData, Form()]):
- return data
diff --git a/docs_src/request_form_models/tutorial002_py39.py b/docs_src/request_form_models/tutorial002_py39.py
deleted file mode 100644
index 59b329e8d..000000000
--- a/docs_src/request_form_models/tutorial002_py39.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from fastapi import FastAPI, Form
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class FormData(BaseModel):
- username: str
- password: str
- model_config = {"extra": "forbid"}
-
-
-@app.post("/login/")
-async def login(data: FormData = Form()):
- return data
diff --git a/docs_src/request_forms/tutorial001_an_py39.py b/docs_src/request_forms/tutorial001_an_py39.py
deleted file mode 100644
index 8e9d2ea53..000000000
--- a/docs_src/request_forms/tutorial001_an_py39.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Form
-
-app = FastAPI()
-
-
-@app.post("/login/")
-async def login(username: Annotated[str, Form()], password: Annotated[str, Form()]):
- return {"username": username}
diff --git a/docs_src/request_forms/tutorial001_py39.py b/docs_src/request_forms/tutorial001_py39.py
deleted file mode 100644
index a53770001..000000000
--- a/docs_src/request_forms/tutorial001_py39.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI, Form
-
-app = FastAPI()
-
-
-@app.post("/login/")
-async def login(username: str = Form(), password: str = Form()):
- return {"username": username}
diff --git a/docs_src/request_forms_and_files/tutorial001_an_py39.py b/docs_src/request_forms_and_files/tutorial001_an_py39.py
deleted file mode 100644
index 12cc43e50..000000000
--- a/docs_src/request_forms_and_files/tutorial001_an_py39.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, File, Form, UploadFile
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(
- file: Annotated[bytes, File()],
- fileb: Annotated[UploadFile, File()],
- token: Annotated[str, Form()],
-):
- return {
- "file_size": len(file),
- "token": token,
- "fileb_content_type": fileb.content_type,
- }
diff --git a/docs_src/request_forms_and_files/tutorial001_py39.py b/docs_src/request_forms_and_files/tutorial001_py39.py
deleted file mode 100644
index 7b5224ce5..000000000
--- a/docs_src/request_forms_and_files/tutorial001_py39.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from fastapi import FastAPI, File, Form, UploadFile
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(
- file: bytes = File(), fileb: UploadFile = File(), token: str = Form()
-):
- return {
- "file_size": len(file),
- "token": token,
- "fileb_content_type": fileb.content_type,
- }
diff --git a/docs_src/response_change_status_code/tutorial001_py39.py b/docs_src/response_change_status_code/tutorial001_py39.py
deleted file mode 100644
index 197decbfb..000000000
--- a/docs_src/response_change_status_code/tutorial001_py39.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from fastapi import FastAPI, Response, status
-
-app = FastAPI()
-
-tasks = {"foo": "Listen to the Bar Fighters"}
-
-
-@app.put("/get-or-create-task/{task_id}", status_code=200)
-def get_or_create_task(task_id: str, response: Response):
- if task_id not in tasks:
- tasks[task_id] = "This didn't exist before"
- response.status_code = status.HTTP_201_CREATED
- return tasks[task_id]
diff --git a/docs_src/response_cookies/tutorial001_py39.py b/docs_src/response_cookies/tutorial001_py39.py
deleted file mode 100644
index 33f8e8f6e..000000000
--- a/docs_src/response_cookies/tutorial001_py39.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from fastapi import FastAPI
-from fastapi.responses import JSONResponse
-
-app = FastAPI()
-
-
-@app.post("/cookie/")
-def create_cookie():
- content = {"message": "Come to the dark side, we have cookies"}
- response = JSONResponse(content=content)
- response.set_cookie(key="fakesession", value="fake-cookie-session-value")
- return response
diff --git a/docs_src/response_cookies/tutorial002_py39.py b/docs_src/response_cookies/tutorial002_py39.py
deleted file mode 100644
index 76c06fdb9..000000000
--- a/docs_src/response_cookies/tutorial002_py39.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from fastapi import FastAPI, Response
-
-app = FastAPI()
-
-
-@app.post("/cookie-and-object/")
-def create_cookie(response: Response):
- response.set_cookie(key="fakesession", value="fake-cookie-session-value")
- return {"message": "Come to the dark side, we have cookies"}
diff --git a/docs_src/response_directly/tutorial002_py39.py b/docs_src/response_directly/tutorial002_py39.py
deleted file mode 100644
index 6643da6e6..000000000
--- a/docs_src/response_directly/tutorial002_py39.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from fastapi import FastAPI, Response
-
-app = FastAPI()
-
-
-@app.get("/legacy/")
-def get_legacy_data():
- data = """
- WebSocket Chat
-
-
-
-
-
-
-"""
-
-
-@app.get("/")
-async def get():
- return HTMLResponse(html)
-
-
-@app.websocket("/ws")
-async def websocket_endpoint(websocket: WebSocket):
- await websocket.accept()
- while True:
- data = await websocket.receive_text()
- await websocket.send_text(f"Message text was: {data}")
diff --git a/docs_src/websockets/tutorial003_py39.py b/docs_src/websockets/tutorial003_py39.py
deleted file mode 100644
index 316218088..000000000
--- a/docs_src/websockets/tutorial003_py39.py
+++ /dev/null
@@ -1,81 +0,0 @@
-from fastapi import FastAPI, WebSocket, WebSocketDisconnect
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-html = """
-
-
-
- WebSocket Chat
- Your ID:
-
-
-
-
-
-
-"""
-
-
-class ConnectionManager:
- def __init__(self):
- self.active_connections: list[WebSocket] = []
-
- async def connect(self, websocket: WebSocket):
- await websocket.accept()
- self.active_connections.append(websocket)
-
- def disconnect(self, websocket: WebSocket):
- self.active_connections.remove(websocket)
-
- async def send_personal_message(self, message: str, websocket: WebSocket):
- await websocket.send_text(message)
-
- async def broadcast(self, message: str):
- for connection in self.active_connections:
- await connection.send_text(message)
-
-
-manager = ConnectionManager()
-
-
-@app.get("/")
-async def get():
- return HTMLResponse(html)
-
-
-@app.websocket("/ws/{client_id}")
-async def websocket_endpoint(websocket: WebSocket, client_id: int):
- await manager.connect(websocket)
- try:
- while True:
- data = await websocket.receive_text()
- await manager.send_personal_message(f"You wrote: {data}", websocket)
- await manager.broadcast(f"Client #{client_id} says: {data}")
- except WebSocketDisconnect:
- manager.disconnect(websocket)
- await manager.broadcast(f"Client #{client_id} left the chat")
diff --git a/docs_src/wsgi/tutorial001_py39.py b/docs_src/wsgi/tutorial001_py39.py
deleted file mode 100644
index 8eeceb829..000000000
--- a/docs_src/wsgi/tutorial001_py39.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from a2wsgi import WSGIMiddleware
-from fastapi import FastAPI
-from flask import Flask, request
-from markupsafe import escape
-
-flask_app = Flask(__name__)
-
-
-@flask_app.route("/")
-def flask_main():
- name = request.args.get("name", "World")
- return f"Hello, {escape(name)} from Flask!"
-
-
-app = FastAPI()
-
-
-@app.get("/v2")
-def read_main():
- return {"message": "Hello World"}
-
-
-app.mount("/v1", WSGIMiddleware(flask_app))
diff --git a/scripts/tests/test_translation_fixer/test_code_includes/data/en_doc.md b/scripts/tests/test_translation_fixer/test_code_includes/data/en_doc.md
index 593da0b32..0e021dade 100644
--- a/scripts/tests/test_translation_fixer/test_code_includes/data/en_doc.md
+++ b/scripts/tests/test_translation_fixer/test_code_includes/data/en_doc.md
@@ -4,7 +4,7 @@
Some text
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
Some more text
diff --git a/scripts/tests/test_translation_fixer/test_code_includes/data/translated_doc_number_gt.md b/scripts/tests/test_translation_fixer/test_code_includes/data/translated_doc_number_gt.md
index c1ad94d27..aca1464ff 100644
--- a/scripts/tests/test_translation_fixer/test_code_includes/data/translated_doc_number_gt.md
+++ b/scripts/tests/test_translation_fixer/test_code_includes/data/translated_doc_number_gt.md
@@ -4,7 +4,7 @@
Some text
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
Some more text
@@ -12,4 +12,4 @@ Some more text
And even more text
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
diff --git a/scripts/tests/test_translation_fixer/test_code_includes/data/translated_doc_number_lt.md b/scripts/tests/test_translation_fixer/test_code_includes/data/translated_doc_number_lt.md
index 07eaf2c23..12573aa19 100644
--- a/scripts/tests/test_translation_fixer/test_code_includes/data/translated_doc_number_lt.md
+++ b/scripts/tests/test_translation_fixer/test_code_includes/data/translated_doc_number_lt.md
@@ -4,7 +4,7 @@
Some text
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
Some more text
diff --git a/scripts/tests/test_translation_fixer/test_complex_doc/data/en_doc.md b/scripts/tests/test_translation_fixer/test_complex_doc/data/en_doc.md
index 69cd3f3fd..d6c1e3d2f 100644
--- a/scripts/tests/test_translation_fixer/test_complex_doc/data/en_doc.md
+++ b/scripts/tests/test_translation_fixer/test_complex_doc/data/en_doc.md
@@ -141,16 +141,16 @@ def hello_world():
## Simple code includes { #simple-code-includes }
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
-{* ../../docs_src/python_types/tutorial002_py39.py *}
+{* ../../docs_src/python_types/tutorial002_py310.py *}
## Code includes with highlighting { #code-includes-with-highlighting }
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
-{* ../../docs_src/python_types/tutorial006_py39.py hl[10] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[10] *}
## Code includes with line ranges { #code-includes-with-line-ranges }
@@ -169,19 +169,19 @@ def hello_world():
## Code includes qith title { #code-includes-with-title }
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
## Code includes with unknown attributes { #code-includes-with-unknown-attributes }
-{* ../../docs_src/python_types/tutorial001_py39.py unknown[123] *}
+{* ../../docs_src/python_types/tutorial001_py310.py unknown[123] *}
## Some more code includes to test fixing { #some-more-code-includes-to-test-fixing }
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
diff --git a/scripts/tests/test_translation_fixer/test_complex_doc/data/translated_doc.md b/scripts/tests/test_translation_fixer/test_complex_doc/data/translated_doc.md
index c922d7b13..b27eef202 100644
--- a/scripts/tests/test_translation_fixer/test_complex_doc/data/translated_doc.md
+++ b/scripts/tests/test_translation_fixer/test_complex_doc/data/translated_doc.md
@@ -139,16 +139,16 @@ def hello_world():
## Простые включения кода { #simple-code-includes }
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
-{* ../../docs_src/python_types/tutorial002_py39.py *}
+{* ../../docs_src/python_types/tutorial002_py310.py *}
## Включения кода с подсветкой { #code-includes-with-highlighting }
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
-{* ../../docs_src/python_types/tutorial006_py39.py hl[10] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[10] *}
## Включения кода с диапазонами строк { #code-includes-with-line-ranges }
@@ -167,19 +167,19 @@ def hello_world():
## Включения кода с заголовком { #code-includes-with-title }
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
## Включения кода с неизвестными атрибутами { #code-includes-with-unknown-attributes }
-{* ../../docs_src/python_types/tutorial001_py39.py unknown[123] *}
+{* ../../docs_src/python_types/tutorial001_py310.py unknown[123] *}
## Ещё включения кода для тестирования исправления { #some-more-code-includes-to-test-fixing }
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19 : 21] *}
-{* ../../docs_src/bigger_applications/app_an_py39/wrong.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/wrong.py hl[3] title["app/internal/admin.py"] *}
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[1:30] hl[1:10] *}
diff --git a/scripts/tests/test_translation_fixer/test_complex_doc/data/translated_doc_expected.md b/scripts/tests/test_translation_fixer/test_complex_doc/data/translated_doc_expected.md
index b33f36e77..8e2394f14 100644
--- a/scripts/tests/test_translation_fixer/test_complex_doc/data/translated_doc_expected.md
+++ b/scripts/tests/test_translation_fixer/test_complex_doc/data/translated_doc_expected.md
@@ -139,16 +139,16 @@ def hello_world():
## Простые включения кода { #simple-code-includes }
-{* ../../docs_src/python_types/tutorial001_py39.py *}
+{* ../../docs_src/python_types/tutorial001_py310.py *}
-{* ../../docs_src/python_types/tutorial002_py39.py *}
+{* ../../docs_src/python_types/tutorial002_py310.py *}
## Включения кода с подсветкой { #code-includes-with-highlighting }
-{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
-{* ../../docs_src/python_types/tutorial006_py39.py hl[10] *}
+{* ../../docs_src/python_types/tutorial006_py310.py hl[10] *}
## Включения кода с диапазонами строк { #code-includes-with-line-ranges }
@@ -167,19 +167,19 @@ def hello_world():
## Включения кода с заголовком { #code-includes-with-title }
-{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
## Включения кода с неизвестными атрибутами { #code-includes-with-unknown-attributes }
-{* ../../docs_src/python_types/tutorial001_py39.py unknown[123] *}
+{* ../../docs_src/python_types/tutorial001_py310.py unknown[123] *}
## Ещё включения кода для тестирования исправления { #some-more-code-includes-to-test-fixing }
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
-{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
+{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
diff --git a/tests/test_tutorial/test_python_types/test_tutorial009c.py b/tests/test_tutorial/test_python_types/test_tutorial009c.py
deleted file mode 100644
index 17c4b9e0c..000000000
--- a/tests/test_tutorial/test_python_types/test_tutorial009c.py
+++ /dev/null
@@ -1,33 +0,0 @@
-import importlib
-import re
-from types import ModuleType
-from unittest.mock import patch
-
-import pytest
-
-from ...utils import needs_py310
-
-
-@pytest.fixture(
- name="module",
- params=[
- pytest.param("tutorial009c_py310"),
- pytest.param("tutorial009c_py310", marks=needs_py310),
- ],
-)
-def get_module(request: pytest.FixtureRequest):
- mod = importlib.import_module(f"docs_src.python_types.{request.param}")
- return mod
-
-
-def test_say_hi(module: ModuleType):
- with patch("builtins.print") as mock_print:
- module.say_hi("FastAPI")
-
- mock_print.assert_called_once_with("Hey FastAPI!")
-
- with pytest.raises(
- TypeError,
- match=re.escape("say_hi() missing 1 required positional argument: 'name'"),
- ):
- module.say_hi()
From 6e5680c7ea3edbb092518832f16b5203c618c557 Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
+g
zYFy6l1LSwD+2VP&^_Sa@^2e1l`{DOHHHN)I?t8yMR>PHzcHQ6WGRdVqrAlRKD@nbS
z{$UBBD-r!u)H~u1-)A?$1Fi`cJf2;t#PR-_b=+>@jeigx`l>Tid-#E)s!b7rO=}pcuv$BQP`ku=nP
OBYOzMu2ayi`3Ug+Ii6kTr9ob3G!X)Nj{`KWBHf4Q*s
zB9un|j<2v?vDiDI5`t_y+Gib^dtq>M^2h`kssCi`;iX$rd zc0