mirror of
https://github.com/fastapi/fastapi.git
synced 2026-01-22 12:58:11 -05:00
Compare commits
2 Commits
Update-emb
...
translate-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
490dc7d92d | ||
|
|
27e7d13ce2 |
@@ -1,3 +1,3 @@
|
||||
# 關於 FastAPI
|
||||
# 關於 { #about }
|
||||
|
||||
關於 FastAPI、其設計、靈感來源等更多資訊。 🤓
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# 基準測試
|
||||
# 基準測試 { #benchmarks }
|
||||
|
||||
由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">最快的 Python 可用框架之一</a>,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。
|
||||
|
||||
但是在查看基準得分和對比時,請注意以下幾點。
|
||||
|
||||
## 基準測試和速度
|
||||
## 基準測試與速度 { #benchmarks-and-speed }
|
||||
|
||||
當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
* 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。
|
||||
* **FastAPI**:
|
||||
* 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。
|
||||
* FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。
|
||||
* FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。並且使用它時,你可以免費獲得自動文件(自動文件甚至不會增加運行中應用程式的開銷,它是在啟動時產生的)。
|
||||
* 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。
|
||||
* 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。
|
||||
* 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。
|
||||
* 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且你很可能會獲得與不使用它時相同的效能(或更好)(因為那樣你必須在程式碼中實現所有功能)。
|
||||
* 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等。具備整合式自動資料驗證、序列化和文件的框架。
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
# 在雲端部署 FastAPI
|
||||
# 在雲端供應商上部署 FastAPI { #deploy-fastapi-on-cloud-providers }
|
||||
|
||||
你幾乎可以使用**任何雲端供應商**來部署你的 FastAPI 應用程式。
|
||||
|
||||
在大多數情況下,主要的雲端供應商都有部署 FastAPI 的指南。
|
||||
在大多數情況下,主要的雲端供應商都有使用其服務部署 FastAPI 的指南。
|
||||
|
||||
## 雲端供應商 - 贊助商
|
||||
## FastAPI Cloud { #fastapi-cloud }
|
||||
|
||||
一些雲端供應商 ✨ [**贊助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,這確保了 FastAPI 及其**生態系統**持續健康地**發展**。
|
||||
**<a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>** 由打造 **FastAPI** 的同一位作者與團隊所建置。
|
||||
|
||||
這也展現了他們對 FastAPI 和其**社群**(包括你)的真正承諾,他們不僅希望為你提供**優質的服務**,還希望確保你擁有一個**良好且健康的框架**:FastAPI。🙇
|
||||
它以最少的精力,簡化 **建置**、**部署** 與**存取** API 的流程。
|
||||
|
||||
你可能會想嘗試他們的服務,以下有他們的指南.
|
||||
它將使用 FastAPI 建置應用程式時的相同**開發者體驗**帶到將它們**部署**到雲端的過程。🎉
|
||||
|
||||
FastAPI Cloud 是 *FastAPI and friends* 開源專案的主要贊助商與資金提供者。✨
|
||||
|
||||
## 雲端供應商 - 贊助商 { #cloud-providers-sponsors }
|
||||
|
||||
一些其他雲端供應商也 ✨ [**贊助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨。🙇
|
||||
|
||||
你也可以考慮他們,跟著他們的指南並嘗試他們的服務:
|
||||
|
||||
* <a href="https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi" class="external-link" target="_blank">Render</a>
|
||||
* <a href="https://docs.railway.com/guides/fastapi?utm_medium=integration&utm_source=docs&utm_campaign=fastapi" class="external-link" target="_blank">Railway</a>
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
# 部署
|
||||
# 部署 { #deployment }
|
||||
|
||||
部署 **FastAPI** 應用程式相對容易。
|
||||
|
||||
## 部署是什麼意思
|
||||
## 部署是什麼意思 { #what-does-deployment-mean }
|
||||
|
||||
**部署**應用程式指的是執行一系列必要的步驟,使其能夠**讓使用者存取和使用**。
|
||||
**部署**應用程式指的是執行必要的步驟,使其能夠**讓使用者存取和使用**。
|
||||
|
||||
對於一個 **Web API**,部署通常涉及將其放置在**遠端伺服器**上,並使用性能優良且穩定的**伺服器程式**,確保使用者能夠高效、無中斷地存取應用程式,且不會遇到問題。
|
||||
對於 **Web API**,部署通常涉及將其放置在**遠端機器**上,並搭配具備良好效能、穩定性等的**伺服器程式**,讓你的**使用者**能夠高效且不中斷或不遇到問題地**存取**應用程式。
|
||||
|
||||
這與**開發**階段形成鮮明對比,在**開發**階段,你會不斷更改程式碼、破壞程式碼、修復程式碼,然後停止和重新啟動伺服器等。
|
||||
這與**開發**階段形成對比:在**開發**階段,你會不斷更改程式碼、破壞程式碼並修復它,停止並重新啟動開發伺服器等。
|
||||
|
||||
## 部署策略
|
||||
## 部署策略 { #deployment-strategies }
|
||||
|
||||
根據你的使用場景和使用工具,有多種方法可以實現此目的。
|
||||
根據你的特定使用場景與所使用的工具,有多種方法可以做到。
|
||||
|
||||
你可以使用一些工具自行**部署伺服器**,你也可以使用能為你完成部分工作的**雲端服務**,或其他可能的選項。
|
||||
你可以自行使用一組工具來**部署伺服器**;也可以使用替你完成部分工作的**雲端服務**,或其他可能的選項。
|
||||
|
||||
例如,我們(FastAPI 背後的團隊)打造了 <a href="https://fastapicloud.com" class="external-link" target="_blank">**FastAPI Cloud**</a>,讓將 FastAPI apps 部署到雲端的流程盡可能順暢,同時保有使用 FastAPI 開發時的相同開發者體驗。
|
||||
|
||||
我將向你展示在部署 **FastAPI** 應用程式時你可能應該記住的一些主要概念(儘管其中大部分適用於任何其他類型的 Web 應用程式)。
|
||||
|
||||
在接下來的部分中,你將看到更多需要記住的細節以及一些技巧。 ✨
|
||||
在接下來的部分中,你將看到更多需要記住的細節以及一些實作技巧。 ✨
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# 環境變數
|
||||
# 環境變數 { #environment-variables }
|
||||
|
||||
/// tip
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
環境變數對於處理應用程式**設定**(作為 Python **安裝**的一部分等方面)非常有用。
|
||||
|
||||
## 建立和使用環境變數
|
||||
## 建立和使用 env var { #create-and-use-env-vars }
|
||||
|
||||
你在 **shell(終端機)**中就可以**建立**和使用環境變數,並不需要用到 Python:
|
||||
|
||||
@@ -50,7 +50,7 @@ Hello Wade Wilson
|
||||
|
||||
////
|
||||
|
||||
## 在 Python 中讀取環境變數
|
||||
## 在 Python 中讀取 env var { #read-env-vars-in-python }
|
||||
|
||||
你也可以在 Python **之外**的終端機中建立環境變數(或使用其他方法),然後在 Python 中**讀取**它們。
|
||||
|
||||
@@ -65,9 +65,9 @@ print(f"Hello {name} from Python")
|
||||
|
||||
/// tip
|
||||
|
||||
第二個參數是 <a href="https://docs.python.org/zh-tw/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> 的預設回傳值。
|
||||
<a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> 的第二個參數是預設要回傳的值。
|
||||
|
||||
如果沒有提供,預設值為 `None`,這裡我們提供 `"World"` 作為預設值。
|
||||
如果未提供,預設值為 `None`,這裡我們提供 `"World"` 作為要使用的預設值。
|
||||
|
||||
///
|
||||
|
||||
@@ -78,10 +78,10 @@ print(f"Hello {name} from Python")
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// 這裡我們還沒有設定環境變數
|
||||
// 這裡我們還沒有設定 env var
|
||||
$ python main.py
|
||||
|
||||
// 因為我們沒有設定環境變數,所以我們得到的是預設值
|
||||
// 因為我們沒有設定 env var,所以我們得到的是預設值
|
||||
|
||||
Hello World from Python
|
||||
|
||||
@@ -105,10 +105,10 @@ Hello Wade Wilson from Python
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// 這裡我們還沒有設定環境變數
|
||||
// 這裡我們還沒有設定 env var
|
||||
$ python main.py
|
||||
|
||||
// 因為我們沒有設定環境變數,所以我們得到的是預設值
|
||||
// 因為我們沒有設定 env var,所以我們得到的是預設值
|
||||
|
||||
Hello World from Python
|
||||
|
||||
@@ -136,14 +136,14 @@ Hello Wade Wilson from Python
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// 在這個程式呼叫的同一行中建立一個名為 MY_NAME 的環境變數
|
||||
// 在這個程式呼叫的同一行中建立一個名為 MY_NAME 的 env var
|
||||
$ MY_NAME="Wade Wilson" python main.py
|
||||
|
||||
// 現在就可以讀取到環境變數了
|
||||
|
||||
Hello Wade Wilson from Python
|
||||
|
||||
// 在此之後這個環境變數將不再存在
|
||||
// 在此之後這個 env var 將不再存在
|
||||
$ python main.py
|
||||
|
||||
Hello World from Python
|
||||
@@ -153,19 +153,19 @@ Hello World from Python
|
||||
|
||||
/// tip
|
||||
|
||||
你可以在 <a href="https://12factor.net/zh_cn/config" class="external-link" target="_blank">The Twelve-Factor App: 配置</a>中了解更多資訊。
|
||||
你可以在 <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a> 中了解更多資訊。
|
||||
|
||||
///
|
||||
|
||||
## 型別和驗證
|
||||
## 型別和驗證 { #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)用它來查找要執行的程式。
|
||||
|
||||
@@ -181,11 +181,11 @@ Hello World from Python
|
||||
|
||||
這意味著系統應該在以下目錄中查找程式:
|
||||
|
||||
- `/usr/local/bin`
|
||||
- `/usr/bin`
|
||||
- `/bin`
|
||||
- `/usr/sbin`
|
||||
- `/sbin`
|
||||
* `/usr/local/bin`
|
||||
* `/usr/bin`
|
||||
* `/bin`
|
||||
* `/usr/sbin`
|
||||
* `/sbin`
|
||||
|
||||
////
|
||||
|
||||
@@ -197,9 +197,9 @@ C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System3
|
||||
|
||||
這意味著系統應該在以下目錄中查找程式:
|
||||
|
||||
- `C:\Program Files\Python312\Scripts`
|
||||
- `C:\Program Files\Python312`
|
||||
- `C:\Windows\System32`
|
||||
* `C:\Program Files\Python312\Scripts`
|
||||
* `C:\Program Files\Python312`
|
||||
* `C:\Windows\System32`
|
||||
|
||||
////
|
||||
|
||||
@@ -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 中使用它們有了基本的了解。
|
||||
|
||||
你也可以在<a href="https://zh.wikipedia.org/wiki/%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F" class="external-link" target="_blank">環境變數 - 維基百科</a> (<a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">Wikipedia for Environment Variable</a>) 中了解更多關於它們的資訊。
|
||||
你也可以在<a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">Wikipedia for Environment Variable</a>中了解更多關於它們的資訊。
|
||||
|
||||
在許多情況下,環境變數的用途和適用性可能不會立刻顯現。但是在開發過程中,它們會在許多不同的場景中出現,因此瞭解它們是非常必要的。
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# 使用指南 - 範例集
|
||||
# 使用指南 - 範例集 { #how-to-recipes }
|
||||
|
||||
在這裡,你將會看到**不同主題**的範例或「如何使用」的指南。
|
||||
在這裡,你將會看到不同的範例集或「如何使用」指南,涵蓋**多個主題**。
|
||||
|
||||
大多數這些想法都是**獨立**的,在大多數情況下,你只需要研究那些直接適用於**你的專案**的東西。
|
||||
這些想法大多或多或少是**獨立**的,在大多數情況下,你應該只需要在它們直接適用於**你的專案**時才研究它們。
|
||||
|
||||
如果有些東西看起來很有趣且對你的專案很有用的話再去讀它,否則你可能可以跳過它們。
|
||||
如果某些內容看起來很有趣且對你的專案很有用,那就去看看;否則,你大概可以直接跳過它們。
|
||||
|
||||
/// tip
|
||||
|
||||
如果你想要以結構化的方式**學習 FastAPI**(推薦),請前往[教學 - 使用者指南](../tutorial/index.md){.internal-link target=_blank}逐章閱讀。
|
||||
如果你想要以結構化的方式**學習 FastAPI**(推薦),請改為前往並逐章閱讀[教學 - 使用者指南](../tutorial/index.md){.internal-link target=_blank}。
|
||||
|
||||
///
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
# FastAPI { #fastapi }
|
||||
|
||||
<style>
|
||||
.md-content .md-typeset h1 { display: none; }
|
||||
</style>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a>
|
||||
<a href="https://fastapi.tiangolo.com/zh-hant"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<em>FastAPI 框架,高效能,易於學習,快速開發,適用於生產環境</em>
|
||||
@@ -21,59 +27,65 @@
|
||||
|
||||
---
|
||||
|
||||
**文件**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
|
||||
**文件**: <a href="https://fastapi.tiangolo.com/zh-hant" target="_blank">https://fastapi.tiangolo.com</a>
|
||||
|
||||
**程式碼**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a>
|
||||
**原始碼**: <a href="https://github.com/fastapi/fastapi" target="_blank">https://github.com/fastapi/fastapi</a>
|
||||
|
||||
---
|
||||
|
||||
FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 並採用標準 Python 型別提示。
|
||||
FastAPI 是一個現代、快速(高效能)的 Web 框架,用於以 Python(基於標準 Python 型別提示)建構 API。
|
||||
|
||||
主要特點包含:
|
||||
|
||||
- **快速**: 非常高的效能,可與 **NodeJS** 和 **Go** 效能相當 (歸功於 Starlette and Pydantic)。 [FastAPI 是最快的 Python web 框架之一](#performance)。
|
||||
- **極速開發**: 提高開發功能的速度約 200% 至 300%。 \*
|
||||
- **更少的 Bug**: 減少約 40% 的人為(開發者)導致的錯誤。 \*
|
||||
- **直覺**: 具有出色的編輯器支援,處處都有<abbr title="也被稱為自動完成、IntelliSense">自動補全</abbr>以減少偵錯時間。
|
||||
- **簡單**: 設計上易於使用和學習,大幅減少閱讀文件的時間。
|
||||
- **簡潔**: 最小化程式碼重複性。可以通過不同的參數聲明來實現更豐富的功能,和更少的錯誤。
|
||||
- **穩健**: 立即獲得生產級可用的程式碼,還有自動生成互動式文件。
|
||||
- **標準化**: 基於 (且完全相容於) OpenAPIs 的相關標準:<a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a>(之前被稱為 Swagger)和<a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>。
|
||||
* **快速**: 非常高的效能,可與 **NodeJS** 和 **Go** 效能相當(歸功於 Starlette 和 Pydantic)。[可用的最快 Python 框架之一](#performance)。
|
||||
* **快速撰寫程式碼**: 提高開發功能的速度約 200% 至 300%。 *
|
||||
* **更少的 Bug**: 減少約 40% 的人為(開發者)導致的錯誤。 *
|
||||
* **直覺**: 具有出色的編輯器支援。處處都有<abbr title="也被稱為自動完成、自動補全、IntelliSense">Completion</abbr>。更少的除錯時間。
|
||||
* **簡單**: 設計上易於使用和學習。更少的閱讀文件時間。
|
||||
* **簡潔**: 最小化程式碼重複性。每個參數宣告即可獲得多項功能。更少的 Bug。
|
||||
* **穩健**: 立即獲得可用於生產環境的程式碼,並有自動生成的互動式文件。
|
||||
* **基於標準**: 基於(且完全相容於)API 的開放標準:<a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a>(之前被稱為 Swagger)與 <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>。
|
||||
|
||||
<small>\* 基於內部開發團隊在建立生產應用程式時的測試預估。</small>
|
||||
<small>* 基於內部開發團隊在建立生產應用程式時所做測試的估算。</small>
|
||||
|
||||
## 贊助
|
||||
## 贊助 { #sponsors }
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
{% if sponsors %}
|
||||
### Keystone 贊助商 { #keystone-sponsor }
|
||||
|
||||
{% for sponsor in sponsors.keystone -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
|
||||
{% endfor -%}
|
||||
|
||||
### 金級與銀級贊助商 { #gold-and-silver-sponsors }
|
||||
|
||||
{% for sponsor in sponsors.gold -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
|
||||
{% endfor -%}
|
||||
{%- for sponsor in sponsors.silver -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
<a href="https://fastapi.tiangolo.com/fastapi-people/#sponsors" class="external-link" target="_blank">其他贊助商</a>
|
||||
<a href="https://fastapi.tiangolo.com/zh-hant/fastapi-people/#sponsors" class="external-link" target="_blank">其他贊助商</a>
|
||||
|
||||
## 評價
|
||||
## 評價 { #opinions }
|
||||
|
||||
"_[...] 近期大量的使用 **FastAPI**。 [...] 目前正在計畫在**微軟**團隊的**機器學習**服務中導入。其中一些正在整合到核心的 **Windows** 產品和一些 **Office** 產品。_"
|
||||
"_[...] 近期大量使用 **FastAPI**。[...] 我其實正計畫把它用在我們團隊在 **Microsoft 的所有 ML 服務**中。其中一些正在整合到核心的 **Windows** 產品和一些 **Office** 產品。_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_我們使用 **FastAPI** 來建立產生**預測**結果的 **REST** 伺服器。 [for Ludwig]_"
|
||||
"_我們採用 **FastAPI** 函式庫來啟動一個可被查詢以取得**預測**的 **REST** 伺服器。[for Ludwig]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_**Netflix** 很榮幸地宣布開源**危機管理**協調框架: **Dispatch**! [是使用 **FastAPI** 建構]_"
|
||||
"_**Netflix** 很榮幸宣布開源我們的**危機管理**協調框架:**Dispatch**![使用 **FastAPI** 建構]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Kevin Glisson, Marc Vilanova, Forest Monsen - <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
@@ -85,70 +97,68 @@ FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python
|
||||
|
||||
---
|
||||
|
||||
"_老實說,你建造的東西看起來非常堅固和精緻。在很多方面,這就是我想要的,看到有人建造它真的很鼓舞人心。_"
|
||||
"_老實說,你建造的東西看起來非常堅固且精緻。在很多方面,這就是我希望 **Hug** 成為的樣子——看到有人建造出來真的很鼓舞人心。_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong><a href="https://github.com/hugapi/hug" target="_blank">Hug</a> creator</strong> <a href="https://news.ycombinator.com/item?id=19455465" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_如果您想學習一種用於構建 REST API 的**現代框架**,不能錯過 **FastAPI** [...] 它非常快速、且易於使用和學習 [...]_"
|
||||
"_如果你想學一個用來建構 REST API 的**現代框架**,看看 **FastAPI** [...] 它很快、易於使用且易於學習 [...]_"
|
||||
|
||||
"_我們的 **APIs** 已經改用 **FastAPI** [...] 我想你會喜歡它 [...]_"
|
||||
"_我們的 **API** 已經改用 **FastAPI** [...] 我想你會喜歡它 [...]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong><a href="https://explosion.ai" target="_blank">Explosion AI</a> 創辦人 - <a href="https://spacy.io" target="_blank">spaCy</a> creators</strong> <a href="https://x.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(ref)</small></a> - <a href="https://x.com/honnibal/status/1144031421859655680" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_如果有人想要建立一個生產環境的 Python API,我強烈推薦 **FastAPI**,它**設計精美**,**使用簡單**且**高度可擴充**,它已成為我們 API 優先開發策略中的**關鍵組件**,並且驅動了許多自動化服務,例如我們的 Virtual TAC Engineer。_"
|
||||
"_如果有人想要建立一個生產環境的 Python API,我強烈推薦 **FastAPI**。它**設計精美**、**使用簡單**且**高度可擴充**,已成為我們 API 優先開發策略中的**關鍵組件**,並且驅動了許多自動化與服務,例如我們的 Virtual TAC Engineer。_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Deon Pillsbury - <strong>Cisco</strong> <a href="https://www.linkedin.com/posts/deonpillsbury_cisco-cx-python-activity-6963242628536487936-trAp/" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
## **Typer**,命令列中的 FastAPI
|
||||
## FastAPI 迷你紀錄片 { #fastapi-mini-documentary }
|
||||
|
||||
在 2025 年底發布了一部 <a href="https://www.youtube.com/watch?v=mpR8ngthqiE" class="external-link" target="_blank">FastAPI 迷你紀錄片</a>,你可以線上觀看:
|
||||
|
||||
<a href="https://www.youtube.com/watch?v=mpR8ngthqiE" target="_blank"><img src="https://fastapi.tiangolo.com/img/fastapi-documentary.jpg" alt="FastAPI Mini Documentary"></a>
|
||||
|
||||
## **Typer**,CLI 的 FastAPI { #typer-the-fastapi-of-clis }
|
||||
|
||||
<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>
|
||||
|
||||
如果你不是在開發網頁 API,而是正在開發一個在終端機中運行的<abbr title="Command Line Interface">命令列</abbr>應用程式,不妨嘗試 <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>。
|
||||
如果你不是在開發 Web API,而是在開發一個要在終端機中使用的 <abbr title="Command Line Interface">CLI</abbr> 應用程式,不妨試試 <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>。
|
||||
|
||||
**Typer** 是 FastAPI 的小兄弟。他立志成為命令列的 **FastAPI**。 ⌨️ 🚀
|
||||
**Typer** 是 FastAPI 的小兄弟,並且旨在成為 **CLI 的 FastAPI**。 ⌨️ 🚀
|
||||
|
||||
## 安裝需求
|
||||
## 安裝需求 { #requirements }
|
||||
|
||||
FastAPI 是站在以下巨人的肩膀上:
|
||||
|
||||
- <a href="https://www.starlette.dev/" class="external-link" target="_blank">Starlette</a> 負責網頁的部分
|
||||
- <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 負責資料的部分
|
||||
* <a href="https://www.starlette.dev/" class="external-link" target="_blank">Starlette</a> 負責 Web 的部分。
|
||||
* <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 負責資料的部分。
|
||||
|
||||
## 安裝
|
||||
## 安裝 { #installation }
|
||||
|
||||
建立並啟用一個 <a href="https://fastapi.tiangolo.com/zh-hant/virtual-environments/" class="external-link" target="_blank">虛擬環境</a>,然後安裝 FastAPI:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install fastapi
|
||||
$ pip install "fastapi[standard]"
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
你同時也會需要 ASGI 伺服器用於生產環境,像是 <a href="https://www.uvicorn.dev" class="external-link" target="_blank">Uvicorn</a> 或 <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>。
|
||||
**注意**:請確認你把 `"fastapi[standard]"` 放在引號中,以確保它能在所有終端機中正常運作。
|
||||
|
||||
<div class="termy">
|
||||
## 範例 { #example }
|
||||
|
||||
```console
|
||||
$ pip install "uvicorn[standard]"
|
||||
### 建立 { #create-it }
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## 範例
|
||||
|
||||
### 建立
|
||||
|
||||
- 建立一個 python 檔案 `main.py`,並寫入以下程式碼:
|
||||
建立一個檔案 `main.py`,內容如下:
|
||||
|
||||
```Python
|
||||
from typing import Union
|
||||
@@ -169,7 +179,7 @@ def read_item(item_id: int, q: Union[str, None] = None):
|
||||
```
|
||||
|
||||
<details markdown="1">
|
||||
<summary>或可以使用 <code>async def</code>...</summary>
|
||||
<summary>或使用 <code>async def</code>...</summary>
|
||||
|
||||
如果你的程式使用 `async` / `await`,請使用 `async def`:
|
||||
|
||||
@@ -193,22 +203,35 @@ async def read_item(item_id: int, q: Union[str, None] = None):
|
||||
|
||||
**注意**:
|
||||
|
||||
如果你不知道是否會用到,可以查看 _"In a hurry?"_ 章節中,關於 <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">`async` 和 `await` 的部分</a>。
|
||||
如果你不確定,請查看文件中 _"In a hurry?"_ 章節關於 <a href="https://fastapi.tiangolo.com/zh-hant/async/#in-a-hurry" target="_blank">`async` 和 `await`</a> 的說明。
|
||||
|
||||
</details>
|
||||
|
||||
### 運行
|
||||
### 運行 { #run-it }
|
||||
|
||||
使用以下指令運行伺服器:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --reload
|
||||
$ fastapi dev main.py
|
||||
|
||||
╭────────── FastAPI CLI - Development mode ───────────╮
|
||||
│ │
|
||||
│ Serving at: http://127.0.0.1:8000 │
|
||||
│ │
|
||||
│ API docs: http://127.0.0.1:8000/docs │
|
||||
│ │
|
||||
│ Running in development mode, for production use: │
|
||||
│ │
|
||||
│ fastapi run │
|
||||
│ │
|
||||
╰─────────────────────────────────────────────────────╯
|
||||
|
||||
INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
|
||||
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
INFO: Started reloader process [28720]
|
||||
INFO: Started server process [28722]
|
||||
INFO: Started reloader process [2248755] using WatchFiles
|
||||
INFO: Started server process [2248757]
|
||||
INFO: Waiting for application startup.
|
||||
INFO: Application startup complete.
|
||||
```
|
||||
@@ -216,21 +239,21 @@ INFO: Application startup complete.
|
||||
</div>
|
||||
|
||||
<details markdown="1">
|
||||
<summary>關於指令 <code>uvicorn main:app --reload</code>...</summary>
|
||||
<summary>關於指令 <code>fastapi dev main.py</code>...</summary>
|
||||
|
||||
該指令 `uvicorn main:app` 指的是:
|
||||
指令 `fastapi dev` 會讀取你的 `main.py` 檔案,偵測其中的 **FastAPI** app,並使用 <a href="https://www.uvicorn.dev" class="external-link" target="_blank">Uvicorn</a> 啟動伺服器。
|
||||
|
||||
- `main`:`main.py` 檔案(一個 python 的 "模組")。
|
||||
- `app`:在 `main.py` 檔案中,使用 `app = FastAPI()` 建立的物件。
|
||||
- `--reload`:程式碼更改後會自動重新啟動,請僅在開發時使用此參數。
|
||||
預設情況下,`fastapi dev` 會啟用自動重新載入,方便本機開發。
|
||||
|
||||
你可以在 <a href="https://fastapi.tiangolo.com/zh-hant/fastapi-cli/" target="_blank">FastAPI CLI 文件</a> 了解更多。
|
||||
|
||||
</details>
|
||||
|
||||
### 檢查
|
||||
### 檢查 { #check-it }
|
||||
|
||||
使用瀏覽器開啟 <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>。
|
||||
|
||||
你將會看到以下的 JSON 回應:
|
||||
你將會看到以下 JSON 回應:
|
||||
|
||||
```JSON
|
||||
{"item_id": 5, "q": "somequery"}
|
||||
@@ -238,32 +261,32 @@ INFO: Application startup complete.
|
||||
|
||||
你已經建立了一個具有以下功能的 API:
|
||||
|
||||
- 透過路徑 `/` 和 `/items/{item_id}` 接受 HTTP 請求。
|
||||
- 以上路經都接受 `GET` <em>請求</em>(也被稱為 HTTP _方法_)。
|
||||
- 路徑 `/items/{item_id}` 有一個 `int` 型別的 `item_id` 參數。
|
||||
- 路徑 `/items/{item_id}` 有一個 `str` 型別的查詢參數 `q`。
|
||||
* 在 _路徑_ `/` 與 `/items/{item_id}` 接收 HTTP 請求。
|
||||
* 兩個 _路徑_ 都使用 `GET` <em>操作</em>(也稱為 HTTP _方法_)。
|
||||
* _路徑_ `/items/{item_id}` 有一個 _路徑參數_ `item_id`,其型別應為 `int`。
|
||||
* _路徑_ `/items/{item_id}` 有一個選填的 `str` _查詢參數_ `q`。
|
||||
|
||||
### 互動式 API 文件
|
||||
### 互動式 API 文件 { #interactive-api-docs }
|
||||
|
||||
使用瀏覽器開啟 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>。
|
||||
現在前往 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>。
|
||||
|
||||
你會看到自動生成的互動式 API 文件(由 <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> 生成):
|
||||
你會看到自動生成的互動式 API 文件(由 <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> 提供):
|
||||
|
||||

|
||||
|
||||
### ReDoc API 文件
|
||||
### 替代 API 文件 { #alternative-api-docs }
|
||||
|
||||
使用瀏覽器開啟 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>。
|
||||
接著前往 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>。
|
||||
|
||||
你將看到 ReDoc 文件 (由 <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> 生成):
|
||||
你會看到替代的自動文件(由 <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> 提供):
|
||||
|
||||

|
||||
|
||||
## 範例升級
|
||||
## 範例升級 { #example-upgrade }
|
||||
|
||||
現在繼續修改 `main.py` 檔案,來接收一個帶有 body 的 `PUT` 請求。
|
||||
現在修改 `main.py` 檔案來接收 `PUT` 請求的 body。
|
||||
|
||||
我們使用 Pydantic 來使用標準的 Python 型別聲明請求。
|
||||
藉由 Pydantic,你可以使用標準 Python 型別來宣告 body。
|
||||
|
||||
```Python hl_lines="4 9-12 25-27"
|
||||
from typing import Union
|
||||
@@ -295,174 +318,248 @@ def update_item(item_id: int, item: Item):
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
```
|
||||
|
||||
伺服器將自動重新載入(因為在上一步中,你向 `uvicorn` 指令添加了 `--reload` 的選項)。
|
||||
`fastapi dev` 伺服器應該會自動重新載入。
|
||||
|
||||
### 互動式 API 文件升級
|
||||
### 互動式 API 文件升級 { #interactive-api-docs-upgrade }
|
||||
|
||||
使用瀏覽器開啟 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>。
|
||||
現在前往 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>。
|
||||
|
||||
- 互動式 API 文件會自動更新,並加入新的 body 請求:
|
||||
* 互動式 API 文件會自動更新,並包含新的 body:
|
||||
|
||||

|
||||
|
||||
- 點擊 "Try it out" 按鈕, 你可以填寫參數並直接與 API 互動:
|
||||
* 點擊 "Try it out" 按鈕,你可以填寫參數並直接與 API 互動:
|
||||
|
||||

|
||||
|
||||
- 然後點擊 "Execute" 按鈕,使用者介面將會向 API 發送請求,並將結果顯示在螢幕上:
|
||||
* 然後點擊 "Execute" 按鈕,使用者介面會與你的 API 溝通,送出參數、取得結果並顯示在畫面上:
|
||||
|
||||

|
||||
|
||||
### ReDoc API 文件升級
|
||||
### 替代 API 文件升級 { #alternative-api-docs-upgrade }
|
||||
|
||||
使用瀏覽器開啟 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>。
|
||||
接著前往 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>。
|
||||
|
||||
- ReDoc API 文件會自動更新,並加入新的參數和 body 請求:
|
||||
* 替代文件也會反映新的查詢參數與 body:
|
||||
|
||||

|
||||
|
||||
### 總結
|
||||
### 總結 { #recap }
|
||||
|
||||
總結來說, 你就像宣告函式的參數型別一樣,只宣告了一次請求參數和請求主體參數等型別。
|
||||
總結來說,你只需要**一次**像函式參數一樣,宣告參數、body 等的型別。
|
||||
|
||||
你使用 Python 標準型別來完成聲明。
|
||||
你使用的是標準、現代的 Python 型別。
|
||||
|
||||
你不需要學習新的語法、類別、方法或函式庫等等。
|
||||
你不需要學習新的語法、特定函式庫的方法或類別等。
|
||||
|
||||
只需要使用 **Python 以上的版本**。
|
||||
只要標準的 **Python**。
|
||||
|
||||
舉個範例,比如宣告 int 的型別:
|
||||
例如,一個 `int`:
|
||||
|
||||
```Python
|
||||
item_id: int
|
||||
```
|
||||
|
||||
或是一個更複雜的 `Item` 模型:
|
||||
或一個更複雜的 `Item` model:
|
||||
|
||||
```Python
|
||||
item: Item
|
||||
```
|
||||
|
||||
在進行一次宣告後,你將獲得:
|
||||
...透過這一次宣告,你將獲得:
|
||||
|
||||
- 編輯器支援:
|
||||
- 自動補全
|
||||
- 型別檢查
|
||||
- 資料驗證:
|
||||
- 驗證失敗時自動生成清楚的錯誤訊息
|
||||
- 可驗證多層巢狀的 JSON 物件
|
||||
- <abbr title="也被稱為: 序列化或解析">轉換</abbr>輸入的資料: 轉換來自網路請求到 Python 資料型別。包含以下數據:
|
||||
- JSON
|
||||
- 路徑參數
|
||||
- 查詢參數
|
||||
- Cookies
|
||||
- 請求標頭
|
||||
- 表單
|
||||
- 文件
|
||||
- <abbr title="也被稱為: 序列化或解析">轉換</abbr>輸出的資料: 轉換 Python 資料型別到網路傳輸的 JSON:
|
||||
- 轉換 Python 型別 (`str`、 `int`、 `float`、 `bool`、 `list` 等)
|
||||
- `datetime` 物件
|
||||
- `UUID` 物件
|
||||
- 數據模型
|
||||
- ...還有其他更多
|
||||
- 自動生成的 API 文件,包含 2 種不同的使用介面:
|
||||
- Swagger UI
|
||||
- ReDoc
|
||||
* 編輯器支援,包含:
|
||||
* 自動補全。
|
||||
* 型別檢查。
|
||||
* 資料驗證:
|
||||
* 當資料無效時,自動且清楚地回報錯誤。
|
||||
* 即使是深層巢狀的 JSON 物件也能驗證。
|
||||
* <abbr title="也被稱為: 序列化、解析、封送處理">Conversion</abbr>輸入資料:將來自網路的資料轉換為 Python 資料與型別。可從以下讀取:
|
||||
* JSON。
|
||||
* 路徑參數。
|
||||
* 查詢參數。
|
||||
* Cookies。
|
||||
* Headers。
|
||||
* Forms。
|
||||
* Files。
|
||||
* <abbr title="也被稱為: 序列化、解析、封送處理">Conversion</abbr>輸出資料:將 Python 資料與型別轉換為網路資料(JSON):
|
||||
* 轉換 Python 型別(`str`、`int`、`float`、`bool`、`list` 等)。
|
||||
* `datetime` 物件。
|
||||
* `UUID` 物件。
|
||||
* 資料庫 models。
|
||||
* ...以及更多。
|
||||
* 自動生成的互動式 API 文件,包含 2 種替代的使用者介面:
|
||||
* Swagger UI。
|
||||
* ReDoc。
|
||||
|
||||
---
|
||||
|
||||
回到前面的的程式碼範例,**FastAPI** 還會:
|
||||
回到前面的程式碼範例,**FastAPI** 還會:
|
||||
|
||||
- 驗證 `GET` 和 `PUT` 請求路徑中是否包含 `item_id`。
|
||||
- 驗證 `GET` 和 `PUT` 請求中的 `item_id` 是否是 `int` 型別。
|
||||
- 如果驗證失敗,將會返回清楚有用的錯誤訊息。
|
||||
- 查看 `GET` 請求中是否有命名為 `q` 的查詢參數 (例如 `http://127.0.0.1:8000/items/foo?q=somequery`)。
|
||||
- 因為 `q` 參數被宣告為 `= None`,所以是選填的。
|
||||
- 如果沒有宣告 `None`,則此參數將會是必填 (例如 `PUT` 範例的請求 body)。
|
||||
- 對於 `PUT` 的請求 `/items/{item_id}`,將會讀取 body 為 JSON:
|
||||
- 驗證是否有必填屬性 `name` 且型別是 `str`。
|
||||
- 驗證是否有必填屬性 `price` 且型別是 `float`。
|
||||
- 驗證是否有選填屬性 `is_offer` 且型別是 `bool`。
|
||||
- 以上驗證都適用於多層次巢狀 JSON 物件。
|
||||
- 自動轉換 JSON 格式。
|
||||
- 透過 OpenAPI 文件來記錄所有內容,可以被用於:
|
||||
- 互動式文件系統。
|
||||
- 自動為多種程式語言生成用戶端的程式碼。
|
||||
- 提供兩種交互式文件介面。
|
||||
* 驗證 `GET` 與 `PUT` 請求的路徑中是否包含 `item_id`。
|
||||
* 驗證 `GET` 與 `PUT` 請求的 `item_id` 是否為 `int` 型別。
|
||||
* 如果不是,用戶端會看到有用且清楚的錯誤。
|
||||
* 檢查 `GET` 請求是否有名為 `q` 的選填查詢參數(例如 `http://127.0.0.1:8000/items/foo?q=somequery`)。
|
||||
* 因為 `q` 參數宣告為 `= None`,所以它是選填的。
|
||||
* 若沒有 `None`,它就會是必填(就像 `PUT` 的 body 一樣)。
|
||||
* 對 `PUT` 請求 `/items/{item_id}`,將 body 讀取為 JSON:
|
||||
* 檢查是否有必填屬性 `name` 且其型別應為 `str`。
|
||||
* 檢查是否有必填屬性 `price` 且其型別必須為 `float`。
|
||||
* 檢查是否有選填屬性 `is_offer`,若存在其型別應為 `bool`。
|
||||
* 以上也適用於深層巢狀的 JSON 物件。
|
||||
* 自動在 JSON 之間做轉換(進出)。
|
||||
* 使用 OpenAPI 記錄所有內容,可用於:
|
||||
* 互動式文件系統。
|
||||
* 支援多種語言的自動用戶端程式碼生成系統。
|
||||
* 直接提供 2 種互動式文件 Web 介面。
|
||||
|
||||
---
|
||||
|
||||
雖然我們只敘述了表面的功能,但其實你已經理解了它是如何執行。
|
||||
雖然我們只觸及表面,但你已經理解它是如何運作的。
|
||||
|
||||
試著修改以下程式碼:
|
||||
試著修改這一行:
|
||||
|
||||
```Python
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
```
|
||||
|
||||
從:
|
||||
...從:
|
||||
|
||||
```Python
|
||||
... "item_name": item.name ...
|
||||
```
|
||||
|
||||
修改為:
|
||||
...改成:
|
||||
|
||||
```Python
|
||||
... "item_price": item.price ...
|
||||
```
|
||||
|
||||
然後觀察你的編輯器,會自動補全並且還知道他們的型別:
|
||||
...然後看看你的編輯器如何自動補全屬性,並知道它們的型別:
|
||||
|
||||

|
||||
|
||||
有關更多功能的完整範例,可以參考 <a href="https://fastapi.tiangolo.com/tutorial/">教學 - 使用者指南</a>。
|
||||
要看包含更多功能的完整範例,請參考 <a href="https://fastapi.tiangolo.com/zh-hant/tutorial/">教學 - 使用者指南</a>。
|
||||
|
||||
**劇透警告**: 教學 - 使用者指南內容有:
|
||||
**劇透警告**:教學 - 使用者指南包含:
|
||||
|
||||
- 對來自不同地方的**參數**進行宣告:像是 **headers**, **cookies**, **form 表單**以及**上傳檔案**。
|
||||
- 如何設定 **驗證限制** 像是 `maximum_length` or `regex`。
|
||||
- 簡單且非常容易使用的 **<abbr title="也被稱為元件、資源、提供者、服務或是注入">依賴注入</abbr>** 系統。
|
||||
- 安全性和身份驗證,包含提供支援 **OAuth2**、**JWT tokens** 和 **HTTP Basic** 驗證。
|
||||
- 更進階 (但同樣簡單) 的宣告 **多層次的巢狀 JSON 格式** (感謝 Pydantic)。
|
||||
- **GraphQL** 與 <a href="https://strawberry.rocks" class="external-link" target="_blank">Strawberry</a> 以及其他的相關函式庫進行整合。
|
||||
- 更多其他的功能 (感謝 Starlette) 像是:
|
||||
- **WebSockets**
|
||||
- 於 HTTPX 和 `pytest` 的非常簡單測試
|
||||
- **CORS**
|
||||
- **Cookie Sessions**
|
||||
- ...以及更多
|
||||
* 從不同位置宣告**參數**,例如:**headers**、**cookies**、**form 欄位**和**檔案**。
|
||||
* 如何設定 **驗證限制**,例如 `maximum_length` 或 `regex`。
|
||||
* 強大且易用的 **<abbr title="也被稱為元件、資源、提供者、服務或是可注入物">Dependency Injection</abbr>** 系統。
|
||||
* 安全性與身份驗證,包含支援 **OAuth2**、**JWT tokens** 與 **HTTP Basic** 驗證。
|
||||
* 更進階(但同樣簡單)的技巧,用於宣告**深層巢狀的 JSON models**(歸功於 Pydantic)。
|
||||
* 與 <a href="https://strawberry.rocks" class="external-link" target="_blank">Strawberry</a> 及其他函式庫的 **GraphQL** 整合。
|
||||
* 許多額外功能(歸功於 Starlette),例如:
|
||||
* **WebSockets**
|
||||
* 基於 HTTPX 與 `pytest` 的極其簡單測試
|
||||
* **CORS**
|
||||
* **Cookie Sessions**
|
||||
* ...以及更多。
|
||||
|
||||
## 效能
|
||||
### 部署你的 app(可選) { #deploy-your-app-optional }
|
||||
|
||||
來自獨立機構 TechEmpower 的測試結果,顯示在 Uvicorn 執行下的 **FastAPI** 是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">最快的 Python 框架之一</a>, 僅次於 Starlette 和 Uvicorn 本身 (兩者是 FastAPI 的底層)。 (\*)
|
||||
你也可以選擇將 FastAPI app 部署到 <a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>;如果你還沒加入候補名單,可以前往加入。 🚀
|
||||
|
||||
想了解更多訊息,可以參考 <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">測試結果</a>。
|
||||
如果你已經有 **FastAPI Cloud** 帳號(我們已從候補名單邀請你 😉),你可以用一個指令部署你的應用程式。
|
||||
|
||||
## 可選的依賴套件
|
||||
部署前,請確保你已登入:
|
||||
|
||||
用於 Pydantic:
|
||||
<div class="termy">
|
||||
|
||||
- <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - 用於電子郵件驗證。
|
||||
- <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - 用於設定管理。
|
||||
- <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - 用於與 Pydantic 一起使用的額外型別。
|
||||
```console
|
||||
$ fastapi login
|
||||
|
||||
用於 Starlette:
|
||||
You are logged in to FastAPI Cloud 🚀
|
||||
```
|
||||
|
||||
- <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - 使用 `TestClient`時必須安裝。
|
||||
- <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - 使用預設的模板配置時必須安裝。
|
||||
- <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - 需要使用 `request.form()` 對表單進行<abbr title="轉換來自表單的 HTTP 請求到 Python 資料型別"> "解析" </abbr>時安裝。
|
||||
- <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - 需要使用 `SessionMiddleware` 支援時安裝。
|
||||
- <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - 用於支援 Starlette 的 `SchemaGenerator` (如果你使用 FastAPI,可能不需要它)。
|
||||
</div>
|
||||
|
||||
用於 FastAPI / Starlette:
|
||||
接著部署你的 app:
|
||||
|
||||
- <a href="https://www.uvicorn.dev" target="_blank"><code>uvicorn</code></a> - 用於加載和運行應用程式的服務器。
|
||||
- <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - 使用 `ORJSONResponse`時必須安裝。
|
||||
- <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - 使用 `UJSONResponse` 時必須安裝。
|
||||
<div class="termy">
|
||||
|
||||
你可以使用 `pip install "fastapi[all]"` 來安裝這些所有依賴套件。
|
||||
```console
|
||||
$ fastapi deploy
|
||||
|
||||
## 授權
|
||||
Deploying to FastAPI Cloud...
|
||||
|
||||
該項目遵循 MIT 許可協議。
|
||||
✅ Deployment successful!
|
||||
|
||||
🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
就這樣!現在你可以透過該 URL 存取你的 app。 ✨
|
||||
|
||||
#### 關於 FastAPI Cloud { #about-fastapi-cloud }
|
||||
|
||||
**<a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>** 是由 **FastAPI** 背後的同一位作者與團隊打造。
|
||||
|
||||
它以最少的投入,大幅簡化 **建構**、**部署** 與 **存取** API 的流程。
|
||||
|
||||
它把使用 FastAPI 建構 app 的相同 **developer experience**,也帶到了把它們**部署**到雲端的過程。 🎉
|
||||
|
||||
FastAPI Cloud 是 *FastAPI and friends* 開源專案的主要贊助商與資金提供者。 ✨
|
||||
|
||||
#### 部署到其他雲端供應商 { #deploy-to-other-cloud-providers }
|
||||
|
||||
FastAPI 是開源並基於標準的。你可以將 FastAPI app 部署到任何你選擇的雲端供應商。
|
||||
|
||||
請依照你的雲端供應商指南來部署 FastAPI app。 🤓
|
||||
|
||||
## 效能 { #performance }
|
||||
|
||||
來自獨立機構 TechEmpower 的測試顯示,在 Uvicorn 下執行的 **FastAPI** 應用程式是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">可用的最快 Python 框架之一</a>,僅次於 Starlette 和 Uvicorn 本身(FastAPI 內部使用)。(*)
|
||||
|
||||
想了解更多,請參考 <a href="https://fastapi.tiangolo.com/zh-hant/benchmarks/" class="internal-link" target="_blank">測試結果</a>。
|
||||
|
||||
## 依賴 { #dependencies }
|
||||
|
||||
FastAPI 依賴 Pydantic 與 Starlette。
|
||||
|
||||
### `standard` 依賴 { #standard-dependencies }
|
||||
|
||||
當你使用 `pip install "fastapi[standard]"` 安裝 FastAPI 時,它會包含 `standard` 這組選填依賴:
|
||||
|
||||
由 Pydantic 使用:
|
||||
|
||||
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email-validator</code></a> - 用於電子郵件驗證。
|
||||
|
||||
由 Starlette 使用:
|
||||
|
||||
* <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - 若你想使用 `TestClient`,則必須安裝。
|
||||
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - 若你想使用預設的 template 設定,則必須安裝。
|
||||
* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - 若你想透過 `request.form()` 支援表單 <abbr title="將來自 HTTP 請求的字串轉換為 Python 資料">"parsing"</abbr>,則必須安裝。
|
||||
|
||||
由 FastAPI 使用:
|
||||
|
||||
* <a href="https://www.uvicorn.dev" target="_blank"><code>uvicorn</code></a> - 用於載入與提供應用程式的伺服器。這包含 `uvicorn[standard]`,其內含一些用於高效能服務所需的依賴(例如 `uvloop`)。
|
||||
* `fastapi-cli[standard]` - 用於提供 `fastapi` 指令。
|
||||
* 其中包含 `fastapi-cloud-cli`,可讓你將 FastAPI 應用程式部署到 <a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>。
|
||||
|
||||
### 不含 `standard` 依賴 { #without-standard-dependencies }
|
||||
|
||||
如果你不想包含 `standard` 選填依賴,你可以使用 `pip install fastapi`(而不是 `pip install "fastapi[standard]"`)來安裝。
|
||||
|
||||
### 不含 `fastapi-cloud-cli` { #without-fastapi-cloud-cli }
|
||||
|
||||
如果你想安裝含標準依賴但不含 `fastapi-cloud-cli` 的 FastAPI,你可以使用 `pip install "fastapi[standard-no-fastapi-cloud-cli]"` 安裝。
|
||||
|
||||
### 額外的選填依賴 { #additional-optional-dependencies }
|
||||
|
||||
你可能還會想安裝一些額外的依賴。
|
||||
|
||||
Pydantic 額外選填依賴:
|
||||
|
||||
* <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - 用於設定管理。
|
||||
* <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - 用於與 Pydantic 一起使用的額外型別。
|
||||
|
||||
FastAPI 額外選填依賴:
|
||||
|
||||
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - 若你想使用 `ORJSONResponse`,則必須安裝。
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - 若你想使用 `UJSONResponse`,則必須安裝。
|
||||
|
||||
## 授權 { #license }
|
||||
|
||||
此專案以 MIT 授權條款授權。
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# 學習
|
||||
# 學習 { #learn }
|
||||
|
||||
以下是學習 FastAPI 的入門介紹和教學。
|
||||
以下是學習 **FastAPI** 的入門章節與教學。
|
||||
|
||||
你可以將其視為一本**書籍**或一門**課程**,這是**官方**認可並推薦的 FastAPI 學習方式。 😎
|
||||
你可以把它當作一本**書**、一門**課程**,這是學習 FastAPI 的**官方**且推薦的方式。 😎
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
# 資源
|
||||
# 資源 { #resources }
|
||||
|
||||
額外的資源、外部連結、文章等。 ✈️
|
||||
額外的資源、外部連結,以及更多內容。 ✈️
|
||||
|
||||
@@ -1,57 +1,49 @@
|
||||
# 第一步
|
||||
# 第一步 { #first-steps }
|
||||
|
||||
最簡單的 FastAPI 檔案可能看起來像這樣:
|
||||
|
||||
{* ../../docs_src/first_steps/tutorial001.py *}
|
||||
{* ../../docs_src/first_steps/tutorial001_py39.py *}
|
||||
|
||||
將其複製到一個名為 `main.py` 的文件中。
|
||||
將其複製到一個名為 `main.py` 的檔案中。
|
||||
|
||||
執行即時重新載入伺服器(live server):
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u>
|
||||
<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files
|
||||
<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
|
||||
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:solid">main.py</u>
|
||||
|
||||
╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮
|
||||
│ │
|
||||
│ 🐍 main.py │
|
||||
│ │
|
||||
╰──────────────────────╯
|
||||
<span style="background-color:#009485"><font color="#D3D7CF"> FastAPI </font></span> Starting development server 🚀
|
||||
|
||||
<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font>
|
||||
<font color="#3465A4">INFO </font> Found importable FastAPI app
|
||||
Searching for package file structure from directories
|
||||
with <font color="#3465A4">__init__.py</font> files
|
||||
Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
|
||||
|
||||
╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮
|
||||
│ │
|
||||
│ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │
|
||||
│ │
|
||||
╰──────────────────────────╯
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> module </font></span> 🐍 main.py
|
||||
|
||||
<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font>
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> code </font></span> Importing the FastAPI app object from the module with
|
||||
the following code:
|
||||
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span>
|
||||
<u style="text-decoration-style:solid">from </u><u style="text-decoration-style:solid"><b>main</b></u><u style="text-decoration-style:solid"> import </u><u style="text-decoration-style:solid"><b>app</b></u>
|
||||
|
||||
<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
|
||||
<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit)
|
||||
<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font>
|
||||
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>]
|
||||
<font color="#4E9A06">INFO</font>: Waiting for application startup.
|
||||
<font color="#4E9A06">INFO</font>: Application startup complete.
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> app </font></span> Using import string: <font color="#3465A4">main:app</font>
|
||||
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> server </font></span> Server started at <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000</u></font>
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> server </font></span> Documentation at <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000/docs</u></font>
|
||||
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> tip </font></span> Running in development mode, for production use:
|
||||
<b>fastapi run</b>
|
||||
|
||||
Logs:
|
||||
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Will watch for changes in these directories:
|
||||
<b>[</b><font color="#4E9A06">'/home/user/code/awesomeapp'</font><b>]</b>
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Uvicorn running on <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000</u></font> <b>(</b>Press CTRL+C
|
||||
to quit<b>)</b>
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Started reloader process <b>[</b><font color="#34E2E2"><b>383138</b></font><b>]</b> using WatchFiles
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Started server process <b>[</b><font color="#34E2E2"><b>383153</b></font><b>]</b>
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Waiting for application startup.
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Application startup complete.
|
||||
```
|
||||
|
||||
</div>
|
||||
@@ -62,11 +54,11 @@ $ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:singl
|
||||
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
|
||||
那列顯示了你的應用程式正在本地端機器上運行的 URL。
|
||||
那列顯示了你的應用程式在本機上提供服務的 URL。
|
||||
|
||||
### 查看它
|
||||
### 查看它 { #check-it }
|
||||
|
||||
在瀏覽器中打開 <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000</a>.
|
||||
在瀏覽器中打開 <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000</a>。
|
||||
|
||||
你將看到如下的 JSON 回應:
|
||||
|
||||
@@ -74,53 +66,53 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
{"message": "Hello World"}
|
||||
```
|
||||
|
||||
### 互動式 API 文件
|
||||
### 互動式 API 文件 { #interactive-api-docs }
|
||||
|
||||
現在,前往 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
現在,前往 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>。
|
||||
|
||||
你將看到自動的互動式 API 文件(由 <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> 提供):
|
||||
|
||||

|
||||
|
||||
### 替代 API 文件
|
||||
### 替代 API 文件 { #alternative-api-docs }
|
||||
|
||||
現在,前往 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||
現在,前往 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>。
|
||||
|
||||
你將看到另一種自動文件(由 <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> 提供):
|
||||
|
||||

|
||||
|
||||
### OpenAPI
|
||||
### OpenAPI { #openapi }
|
||||
|
||||
**FastAPI** 使用定義 API 的 **OpenAPI** 標準來生成一個 「schema」 與你的所有 API。
|
||||
**FastAPI** 使用定義 API 的 **OpenAPI** 標準來生成一個「schema」,包含你的所有 API。
|
||||
|
||||
#### 「Schema」
|
||||
#### 「Schema」 { #schema }
|
||||
|
||||
「schema」是對某個事物的定義或描述。它並不是實作它的程式碼,而僅僅是一個抽象的描述。
|
||||
「schema」是對某個事物的定義或描述。它不是實作它的程式碼,而僅僅是一個抽象的描述。
|
||||
|
||||
#### API 「schema」
|
||||
#### API「schema」 { #api-schema }
|
||||
|
||||
在這種情況下,<a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> 是一個規範,它規定了如何定義 API 的 schema。
|
||||
|
||||
這個 schema 定義包含了你的 API 路徑、可能接收的參數等內容。
|
||||
這個 schema 定義包含了你的 API 路徑、它們可能接收的參數等內容。
|
||||
|
||||
#### 資料 「schema」
|
||||
#### 資料「schema」 { #data-schema }
|
||||
|
||||
「schema」這個術語也可能指某些資料的結構,比如 JSON 內容的結構。
|
||||
「schema」這個術語也可能指某些資料的結構,例如 JSON 內容。
|
||||
|
||||
在這種情況下,它指的是 JSON 的屬性、資料型別等。
|
||||
在這種情況下,它指的是 JSON 的屬性、以及它們的資料型別等。
|
||||
|
||||
#### OpenAPI 和 JSON Schema
|
||||
#### OpenAPI 和 JSON Schema { #openapi-and-json-schema }
|
||||
|
||||
OpenAPI 定義了 API 的 schema。這個 schema 包含了使用 **JSON Schema** 定義的資料,這是 JSON 資料 schema 的標準。
|
||||
OpenAPI 為你的 API 定義了一個 API schema。而該 schema 使用 **JSON Schema**(JSON 資料 schema 的標準)包含你的 API 傳送與接收的資料定義(或「schemas」)。
|
||||
|
||||
#### 檢查 `openapi.json`
|
||||
#### 檢查 `openapi.json` { #check-the-openapi-json }
|
||||
|
||||
如果你好奇原始的 OpenAPI schema 長什麼樣子,FastAPI 會自動生成一個包含所有 API 描述的 JSON (schema)。
|
||||
如果你對原始的 OpenAPI schema 長什麼樣子感到好奇,FastAPI 會自動生成一個 JSON(schema),其中包含你的所有 API 的描述。
|
||||
|
||||
你可以直接在 <a href="http://127.0.0.1:8000/openapi.json" class="external-link" target="_blank">http://127.0.0.1:8000/openapi.json</a> 查看它。
|
||||
你可以直接在:<a href="http://127.0.0.1:8000/openapi.json" class="external-link" target="_blank">http://127.0.0.1:8000/openapi.json</a> 查看它。
|
||||
|
||||
它會顯示一個 JSON,類似於:
|
||||
它會顯示一個開頭類似於以下內容的 JSON:
|
||||
|
||||
```JSON
|
||||
{
|
||||
@@ -143,21 +135,57 @@ OpenAPI 定義了 API 的 schema。這個 schema 包含了使用 **JSON Schema**
|
||||
...
|
||||
```
|
||||
|
||||
#### OpenAPI 的用途
|
||||
#### OpenAPI 的用途 { #what-is-openapi-for }
|
||||
|
||||
OpenAPI schema 驅動了兩個互動式文件系統。
|
||||
OpenAPI schema 驅動了內建的兩個互動式文件系統。
|
||||
|
||||
而且有許多替代方案,所有這些都是基於 OpenAPI。你可以輕鬆地將任何這些替代方案添加到使用 **FastAPI** 建置的應用程式中。
|
||||
而且有許多替代方案,全部都基於 OpenAPI。你可以輕鬆地將任何這些替代方案添加到使用 **FastAPI** 建置的應用程式中。
|
||||
|
||||
你也可以用它自動生成程式碼,讓前端、手機應用程式或物聯網設備等與你的 API 進行通訊。
|
||||
你也可以用它自動生成程式碼,讓與你的 API 通訊的 client 使用。例如,前端、行動或 IoT 應用程式。
|
||||
|
||||
## 逐步回顧
|
||||
### 部署你的應用程式(可選) { #deploy-your-app-optional }
|
||||
|
||||
### 第一步:引入 `FastAPI`
|
||||
你也可以選擇把你的 FastAPI 應用程式部署到 <a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>;如果你還沒加入候補名單,就去加入吧。 🚀
|
||||
|
||||
{* ../../docs_src/first_steps/tutorial001.py h1[1] *}
|
||||
如果你已經有 **FastAPI Cloud** 帳號(我們從候補名單邀請了你 😉),你可以用一個指令部署你的應用程式。
|
||||
|
||||
`FastAPI` 是一個 Python 類別,提供所有 API 的全部功能。
|
||||
在部署之前,請確認你已登入:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ fastapi login
|
||||
|
||||
You are logged in to FastAPI Cloud 🚀
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
接著部署你的應用程式:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ fastapi deploy
|
||||
|
||||
Deploying to FastAPI Cloud...
|
||||
|
||||
✅ Deployment successful!
|
||||
|
||||
🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
就這樣!現在你可以透過那個 URL 存取你的應用程式。 ✨
|
||||
|
||||
## 逐步回顧 { #recap-step-by-step }
|
||||
|
||||
### 第一步:引入 `FastAPI` { #step-1-import-fastapi }
|
||||
|
||||
{* ../../docs_src/first_steps/tutorial001_py39.py hl[1] *}
|
||||
|
||||
`FastAPI` 是一個 Python 類別,提供你的 API 所有功能。
|
||||
|
||||
/// note | Technical Details
|
||||
|
||||
@@ -167,19 +195,19 @@ OpenAPI schema 驅動了兩個互動式文件系統。
|
||||
|
||||
///
|
||||
|
||||
### 第二步:建立一個 `FastAPI` 「實例」
|
||||
### 第二步:建立一個 `FastAPI`「實例」 { #step-2-create-a-fastapi-instance }
|
||||
|
||||
{* ../../docs_src/first_steps/tutorial001.py h1[3] *}
|
||||
{* ../../docs_src/first_steps/tutorial001_py39.py hl[3] *}
|
||||
|
||||
這裡的 `app` 變數將會是 `FastAPI` 類別的「實例」。
|
||||
這裡的 `app` 變數將會是 `FastAPI` 類別的一個「實例」。
|
||||
|
||||
這將是你建立所有 API 的主要互動點。
|
||||
這將是你用來建立所有 API 的主要互動點。
|
||||
|
||||
### 第三步:建立一個 *路徑操作*
|
||||
### 第三步:建立一個 *路徑操作* { #step-3-create-a-path-operation }
|
||||
|
||||
#### 路徑
|
||||
#### 路徑 { #path }
|
||||
|
||||
這裡的「路徑」指的是 URL 中自第一個 `/` 以後的部分。
|
||||
這裡的「路徑」指的是 URL 中自第一個 `/` 開始的最後一段部分。
|
||||
|
||||
例如,在 URL 中:
|
||||
|
||||
@@ -187,7 +215,7 @@ OpenAPI schema 驅動了兩個互動式文件系統。
|
||||
https://example.com/items/foo
|
||||
```
|
||||
|
||||
……的路徑將會是:
|
||||
...路徑將會是:
|
||||
|
||||
```
|
||||
/items/foo
|
||||
@@ -201,7 +229,7 @@ https://example.com/items/foo
|
||||
|
||||
在建置 API 時,「路徑」是分離「關注點」和「資源」的主要方式。
|
||||
|
||||
#### 操作
|
||||
#### 操作 { #operation }
|
||||
|
||||
這裡的「操作」指的是 HTTP 的「方法」之一。
|
||||
|
||||
@@ -212,14 +240,14 @@ https://example.com/items/foo
|
||||
* `PUT`
|
||||
* `DELETE`
|
||||
|
||||
……以及更少見的:
|
||||
...以及更少見的:
|
||||
|
||||
* `OPTIONS`
|
||||
* `HEAD`
|
||||
* `PATCH`
|
||||
* `TRACE`
|
||||
|
||||
在 HTTP 協定中,你可以使用這些「方法」之一(或更多)與每個路徑進行通信。
|
||||
在 HTTP 協定中,你可以使用這些「方法」之一(或更多)與每個路徑進行通訊。
|
||||
|
||||
---
|
||||
|
||||
@@ -234,16 +262,16 @@ https://example.com/items/foo
|
||||
|
||||
所以,在 OpenAPI 中,每個 HTTP 方法都被稱為「操作」。
|
||||
|
||||
我們將會稱它們為「**操作**」。
|
||||
我們也將稱它們為「**操作**」。
|
||||
|
||||
#### 定義一個 *路徑操作裝飾器*
|
||||
#### 定義一個 *路徑操作裝飾器* { #define-a-path-operation-decorator }
|
||||
|
||||
{* ../../docs_src/first_steps/tutorial001.py h1[6] *}
|
||||
{* ../../docs_src/first_steps/tutorial001_py39.py hl[6] *}
|
||||
|
||||
`@app.get("/")` 告訴 **FastAPI** 那個函式負責處理請求:
|
||||
`@app.get("/")` 告訴 **FastAPI**,下面那個函式負責處理前往以下位置的請求:
|
||||
|
||||
* 路徑 `/`
|
||||
* 使用 <abbr title="HTTP GET 方法"><code>get</code>操作</abbr>
|
||||
* 使用 <abbr title="an HTTP GET method"><code>get</code> operation</abbr>
|
||||
|
||||
/// info | `@decorator` Info
|
||||
|
||||
@@ -253,7 +281,7 @@ Python 中的 `@something` 語法被稱為「裝飾器」。
|
||||
|
||||
一個「裝飾器」會對下面的函式做一些事情。
|
||||
|
||||
在這種情況下,這個裝飾器告訴 **FastAPI** 那個函式對應於 **路徑** `/` 和 **操作** `get`.
|
||||
在這種情況下,這個裝飾器告訴 **FastAPI**,下面的函式對應於 **路徑** `/` 和 **操作** `get`。
|
||||
|
||||
這就是「**路徑操作裝飾器**」。
|
||||
|
||||
@@ -274,58 +302,79 @@ Python 中的 `@something` 語法被稱為「裝飾器」。
|
||||
|
||||
/// tip
|
||||
|
||||
你可以自由地使用每個操作(HTTP 方法)。
|
||||
你可以依照你的需求自由使用每個操作(HTTP 方法)。
|
||||
|
||||
**FastAPI** 不強制任何特定的意義。
|
||||
**FastAPI** 不強制任何特定意義。
|
||||
|
||||
這裡的資訊作為一個指南,而不是要求。
|
||||
這裡的資訊是作為指南,而不是要求。
|
||||
|
||||
例如,當使用 GraphQL 時,你通常只使用 `POST` 操作。
|
||||
例如,當使用 GraphQL 時,你通常只使用 `POST` 操作來執行所有動作。
|
||||
|
||||
///
|
||||
|
||||
### 第四步:定義 **路徑操作函式**
|
||||
### 第四步:定義 **路徑操作函式** { #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** 收到一個前往 URL "`/`" 並使用 `GET` 操作的請求時,它就會被呼叫。
|
||||
|
||||
在這種情況下,它是一個 `async` 函式。
|
||||
|
||||
---
|
||||
|
||||
你可以將它定義為一個正常的函式,而不是 `async def`:
|
||||
你也可以將它定義為一個一般函式,而不是 `async def`:
|
||||
|
||||
{* ../../docs_src/first_steps/tutorial003.py h1[7] *}
|
||||
{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
|
||||
|
||||
/// note
|
||||
|
||||
如果你不知道差別,請查看 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
|
||||
如果你不知道差別,請查看 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}。
|
||||
|
||||
///
|
||||
|
||||
### 第五步:回傳內容
|
||||
### 第五步:回傳內容 { #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` 等。
|
||||
你可以回傳一個 `dict`、`list`、`str`、`int` 等單一值。
|
||||
|
||||
你也可以返回 Pydantic 模型(稍後你會看到更多關於這方面的內容)。
|
||||
你也可以回傳 Pydantic 模型(稍後你會看到更多關於這方面的內容)。
|
||||
|
||||
有很多其他物件和模型會自動轉換為 JSON(包括 ORMs,等等)。試用你最喜歡的,很有可能它們已經有支援。
|
||||
有很多其他物件和模型會自動轉換為 JSON(包括 ORMs 等)。試用你最喜歡的,很有可能它們已經有支援。
|
||||
|
||||
## 回顧
|
||||
### 第六步:部署它 { #step-6-deploy-it }
|
||||
|
||||
* 引入 `FastAPI`.
|
||||
用一個指令將你的應用程式部署到 **<a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>**:`fastapi deploy`。 🎉
|
||||
|
||||
#### 關於 FastAPI Cloud { #about-fastapi-cloud }
|
||||
|
||||
**<a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>** 是由 **FastAPI** 背後的同一位作者與團隊打造。
|
||||
|
||||
它簡化了以最少力氣進行 **建置**、**部署** 與**存取** API 的流程。
|
||||
|
||||
它把用 FastAPI 建置應用程式的同樣 **developer experience**,帶到把它們 **部署** 到雲端的流程中。 🎉
|
||||
|
||||
FastAPI Cloud 是 *FastAPI and friends* 開源專案的主要贊助者與資金提供者。 ✨
|
||||
|
||||
#### 部署到其他雲端供應商 { #deploy-to-other-cloud-providers }
|
||||
|
||||
FastAPI 是開源且基於標準。你可以把 FastAPI 應用程式部署到你選擇的任何雲端供應商。
|
||||
|
||||
請依照你的雲端供應商指南來部署 FastAPI 應用程式。 🤓
|
||||
|
||||
## 回顧 { #recap }
|
||||
|
||||
* 引入 `FastAPI`。
|
||||
* 建立一個 `app` 實例。
|
||||
* 寫一個 **路徑操作裝飾器** 使用裝飾器像 `@app.get("/")`。
|
||||
* 定義一個 **路徑操作函式**;例如,`def root(): ...`。
|
||||
* 使用像 `@app.get("/")` 這樣的裝飾器來撰寫 **路徑操作裝飾器**。
|
||||
* 定義一個 **路徑操作函式**;例如 `def root(): ...`。
|
||||
* 使用命令 `fastapi dev` 執行開發伺服器。
|
||||
* (可選)使用 `fastapi deploy` 部署你的應用程式。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# 教學 - 使用者指南
|
||||
# 教學 - 使用者指南 { #tutorial-user-guide }
|
||||
|
||||
本教學將一步一步展示如何使用 **FastAPI** 及其大多數功能。
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
它也被設計成可作為未來的參考,讓你隨時回來查看所需的內容。
|
||||
|
||||
## 運行程式碼
|
||||
## 運行程式碼 { #run-the-code }
|
||||
|
||||
所有程式碼區塊都可以直接複製和使用(它們實際上是經過測試的 Python 檔案)。
|
||||
|
||||
@@ -15,48 +15,39 @@
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u>
|
||||
<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files
|
||||
<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
|
||||
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:solid">main.py</u>
|
||||
|
||||
╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮
|
||||
│ │
|
||||
│ 🐍 main.py │
|
||||
│ │
|
||||
╰──────────────────────╯
|
||||
<span style="background-color:#009485"><font color="#D3D7CF"> FastAPI </font></span> Starting development server 🚀
|
||||
|
||||
<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font>
|
||||
<font color="#3465A4">INFO </font> Found importable FastAPI app
|
||||
Searching for package file structure from directories
|
||||
with <font color="#3465A4">__init__.py</font> files
|
||||
Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
|
||||
|
||||
╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮
|
||||
│ │
|
||||
│ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │
|
||||
│ │
|
||||
╰──────────────────────────╯
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> module </font></span> 🐍 main.py
|
||||
|
||||
<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font>
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> code </font></span> Importing the FastAPI app object from the module with
|
||||
the following code:
|
||||
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span>
|
||||
<u style="text-decoration-style:solid">from </u><u style="text-decoration-style:solid"><b>main</b></u><u style="text-decoration-style:solid"> import </u><u style="text-decoration-style:solid"><b>app</b></u>
|
||||
|
||||
<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
|
||||
<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit)
|
||||
<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font>
|
||||
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>]
|
||||
<font color="#4E9A06">INFO</font>: Waiting for application startup.
|
||||
<font color="#4E9A06">INFO</font>: Application startup complete.
|
||||
</pre>
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> app </font></span> Using import string: <font color="#3465A4">main:app</font>
|
||||
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> server </font></span> Server started at <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000</u></font>
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> server </font></span> Documentation at <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000/docs</u></font>
|
||||
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> tip </font></span> Running in development mode, for production use:
|
||||
<b>fastapi run</b>
|
||||
|
||||
Logs:
|
||||
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Will watch for changes in these directories:
|
||||
<b>[</b><font color="#4E9A06">'/home/user/code/awesomeapp'</font><b>]</b>
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Uvicorn running on <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000</u></font> <b>(</b>Press CTRL+C
|
||||
to quit<b>)</b>
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Started reloader process <b>[</b><font color="#34E2E2"><b>383138</b></font><b>]</b> using WatchFiles
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Started server process <b>[</b><font color="#34E2E2"><b>383153</b></font><b>]</b>
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Waiting for application startup.
|
||||
<span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span> Application startup complete.
|
||||
```
|
||||
|
||||
</div>
|
||||
@@ -67,7 +58,7 @@ $ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:singl
|
||||
|
||||
---
|
||||
|
||||
## 安裝 FastAPI
|
||||
## 安裝 FastAPI { #install-fastapi }
|
||||
|
||||
第一步是安裝 FastAPI。
|
||||
|
||||
@@ -83,20 +74,22 @@ $ pip install "fastapi[standard]"
|
||||
|
||||
</div>
|
||||
|
||||
/// note
|
||||
/// note | 注意
|
||||
|
||||
當你使用 `pip install "fastapi[standard]"` 安裝時,會包含一些預設的可選標準依賴項。
|
||||
當你使用 `pip install "fastapi[standard]"` 安裝時,會包含一些預設的可選標準依賴項,包含 `fastapi-cloud-cli`,它允許你部署到 <a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>。
|
||||
|
||||
如果你不想包含那些可選的依賴項,你可以使用 `pip install fastapi` 來安裝。
|
||||
如果你不想包含那些可選的依賴項,你可以改為安裝 `pip install fastapi`。
|
||||
|
||||
如果你想安裝標準依賴項,但不包含 `fastapi-cloud-cli`,你可以使用 `pip install "fastapi[standard-no-fastapi-cloud-cli]"` 來安裝。
|
||||
|
||||
///
|
||||
|
||||
## 進階使用者指南
|
||||
## 進階使用者指南 { #advanced-user-guide }
|
||||
|
||||
還有一個**進階使用者指南**你可以稍後閱讀。
|
||||
還有一個**進階使用者指南**你可以在閱讀完這份**教學 - 使用者指南**後再看。
|
||||
|
||||
**進階使用者指南**建立在這個教學之上,使用相同的概念,並教你一些額外的功能。
|
||||
|
||||
但首先你應該閱讀**教學 - 使用者指南**(你正在閱讀的內容)。
|
||||
|
||||
它被設計成你可以使用**教學 - 使用者指南**來建立一個完整的應用程式,然後根據你的需求,使用一些額外的想法來擴展它。
|
||||
它被設計成你可以使用**教學 - 使用者指南**來建立一個完整的應用程式,然後根據你的需求,使用**進階使用者指南**中的一些額外想法,以不同方式來擴展它。
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
# 查詢參數模型
|
||||
# 查詢參數模型 { #query-parameter-models }
|
||||
|
||||
如果你有一組具有相關性的**查詢參數**,你可以建立一個 **Pydantic 模型**來聲明它們。
|
||||
|
||||
這將允許你在**多個地方**去**重複使用模型**,並且一次性為所有參數聲明驗證和元資料 (metadata)。😎
|
||||
|
||||
/// 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,7 +26,7 @@ FastAPI 從 `0.115.0` 版本開始支援這個特性。🤓
|
||||
<img src="/img/tutorial/query-param-models/image01.png">
|
||||
</div>
|
||||
|
||||
## 禁止額外的查詢參數
|
||||
## 禁止額外的查詢參數 { #forbid-extra-query-parameters }
|
||||
|
||||
在一些特殊的使用場景中(可能不是很常見),你可能希望**限制**你要收到的查詢參數。
|
||||
|
||||
@@ -57,7 +57,7 @@ https://example.com/items/?limit=10&tool=plumbus
|
||||
}
|
||||
```
|
||||
|
||||
## 總結
|
||||
## 總結 { #summary }
|
||||
|
||||
你可以使用 **Pydantic 模型**在 **FastAPI** 中聲明**查詢參數**。😎
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# 虛擬環境
|
||||
# 虛擬環境 { #virtual-environments }
|
||||
|
||||
當你在 Python 專案中工作時,你可能會需要使用一個**虛擬環境**(或類似的機制)來隔離你為每個專案安裝的套件。
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
|
||||
///
|
||||
|
||||
## 建立一個專案
|
||||
## 建立一個專案 { #create-a-project }
|
||||
|
||||
首先,為你的專案建立一個目錄。
|
||||
|
||||
@@ -37,23 +37,23 @@
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// 進入主目錄
|
||||
// Go to the home directory
|
||||
$ cd
|
||||
// 建立一個用於存放所有程式碼專案的目錄
|
||||
// Create a directory for all your code projects
|
||||
$ mkdir code
|
||||
// 進入 code 目錄
|
||||
// Enter into that code directory
|
||||
$ cd code
|
||||
// 建立一個用於存放這個專案的目錄
|
||||
// Create a directory for this project
|
||||
$ mkdir awesome-project
|
||||
// 進入這個專案的目錄
|
||||
// Enter into that project directory
|
||||
$ cd awesome-project
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## 建立一個虛擬環境
|
||||
## 建立一個虛擬環境 { #create-a-virtual-environment }
|
||||
|
||||
在開始一個 Python 專案的**第一時間**,**<abbr title="還有其他做法,此處僅作為一個簡單的指引">在你的專案內部</abbr>**建立一個虛擬環境。
|
||||
在開始一個 Python 專案的**第一時間**,**<abbr title="there are other options, this is a simple guideline - 還有其他做法,此處僅作為一個簡單的指引">在你的專案內部</abbr>**建立一個虛擬環境。
|
||||
|
||||
/// tip
|
||||
|
||||
@@ -73,7 +73,7 @@ $ python -m venv .venv
|
||||
|
||||
</div>
|
||||
|
||||
/// details | 上述命令的含義
|
||||
/// details | 這個命令的含義
|
||||
|
||||
* `python`: 使用名為 `python` 的程式
|
||||
* `-m`: 以腳本的方式呼叫一個模組,我們將告訴它接下來使用哪個模組
|
||||
@@ -114,7 +114,7 @@ $ uv venv
|
||||
|
||||
///
|
||||
|
||||
## 啟動虛擬環境
|
||||
## 啟動虛擬環境 { #activate-the-virtual-environment }
|
||||
|
||||
啟動新的虛擬環境來確保你運行的任何 Python 指令或安裝的套件都能使用到它。
|
||||
|
||||
@@ -164,13 +164,13 @@ $ source .venv/Scripts/activate
|
||||
|
||||
/// tip
|
||||
|
||||
每次你在這個環境中安裝一個**新的套件**時,都需要**重新啟動**這個環境。
|
||||
每次你在這個環境中安裝一個**新的套件**時,都需要**再次啟動**這個環境。
|
||||
|
||||
這麼做確保了當你使用一個由這個套件安裝的**終端(<abbr title="命令列介面">CLI</abbr>)程式**時,你使用的是你的虛擬環境中的程式,而不是全域安裝、可能版本不同的程式。
|
||||
這麼做確保了當你使用一個由這個套件安裝的**終端(<abbr title="command line interface - 命令列介面">CLI</abbr>)程式**時,你使用的是你的虛擬環境中的程式,而不是全域安裝、可能版本不同的程式。
|
||||
|
||||
///
|
||||
|
||||
## 檢查虛擬環境是否啟動
|
||||
## 檢查虛擬環境是否啟動 { #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
|
||||
|
||||
</div>
|
||||
|
||||
## 加入 `.gitignore`
|
||||
/// tip
|
||||
|
||||
有時候,你在嘗試升級 pip 時,可能會遇到 **`No module named pip`** 錯誤。
|
||||
|
||||
如果發生這種情況,使用下面的命令來安裝並升級 pip:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python -m ensurepip --upgrade
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
如果尚未安裝 pip,這個命令會安裝 pip,並且也會確保安裝的 pip 版本至少與 `ensurepip` 中可用的版本一樣新。
|
||||
|
||||
///
|
||||
|
||||
## 加入 `.gitignore` { #add-gitignore }
|
||||
|
||||
如果你使用 **Git**(這是你應該使用的),加入一個 `.gitignore` 檔案來排除你的 `.venv` 中的所有內容。
|
||||
|
||||
@@ -266,11 +286,11 @@ $ echo "*" > .venv/.gitignore
|
||||
|
||||
</div>
|
||||
|
||||
/// details | 上述指令的含義
|
||||
/// details | 這個指令的含義
|
||||
|
||||
- `echo "*"`: 將在終端中「顯示」文本 `*`(接下來的部分會對這個操作進行一些修改)
|
||||
- `>`: 使左邊的指令顯示到終端的任何內容實際上都不會被顯示,而是會被寫入到右邊的檔案中
|
||||
- `.gitignore`: 被寫入文本的檔案的名稱
|
||||
* `echo "*"`: 將在終端中「顯示」文本 `*`(接下來的部分會對這個操作進行一些修改)
|
||||
* `>`: 使左邊的指令顯示到終端的任何內容實際上都不會被顯示,而是會被寫入到右邊的檔案中
|
||||
* `.gitignore`: 被寫入文本的檔案的名稱
|
||||
|
||||
而 `*` 對於 Git 來說意味著「所有內容」。所以,它會忽略 `.venv` 目錄中的所有內容。
|
||||
|
||||
@@ -282,19 +302,19 @@ $ echo "*" > .venv/.gitignore
|
||||
|
||||
///
|
||||
|
||||
## 安裝套件
|
||||
## 安裝套件 { #install-packages }
|
||||
|
||||
在啟用虛擬環境後,你可以在其中安裝套件。
|
||||
|
||||
/// tip
|
||||
|
||||
當你需要安裝或升級套件時,執行本操作**一次**;
|
||||
當你需要安裝或升級專案所需的套件時,執行本操作**一次**。
|
||||
|
||||
如果你需要再升級版本或新增套件,你可以**再次執行此操作**。
|
||||
如果你需要升級某個版本或新增套件,你可以**再次執行此操作**。
|
||||
|
||||
///
|
||||
|
||||
### 直接安裝套件
|
||||
### 直接安裝套件 { #install-packages-directly }
|
||||
|
||||
如果你急於安裝,不想使用檔案來聲明專案的套件依賴,你可以直接安裝它們。
|
||||
|
||||
@@ -333,9 +353,9 @@ $ uv pip install "fastapi[standard]"
|
||||
|
||||
////
|
||||
|
||||
### 從 `requirements.txt` 安裝
|
||||
### 從 `requirements.txt` 安裝 { #install-from-requirements-txt }
|
||||
|
||||
如果你有一個 `requirements.txt` 檔案,你可以使用它來安裝其中的套件。
|
||||
如果你有一個 `requirements.txt`,你現在可以使用它來安裝其中的套件。
|
||||
|
||||
//// tab | `pip`
|
||||
|
||||
@@ -365,7 +385,7 @@ $ uv pip install -r requirements.txt
|
||||
|
||||
////
|
||||
|
||||
/// details | 關於 `requirements.txt`
|
||||
/// details | `requirements.txt`
|
||||
|
||||
一個包含一些套件的 `requirements.txt` 檔案看起來應該是這樣的:
|
||||
|
||||
@@ -376,7 +396,7 @@ pydantic==2.8.0
|
||||
|
||||
///
|
||||
|
||||
## 執行程式
|
||||
## 執行你的程式 { #run-your-program }
|
||||
|
||||
在啟用虛擬環境後,你可以執行你的程式,它將使用虛擬環境中的 Python 和你在其中安裝的套件。
|
||||
|
||||
@@ -390,7 +410,7 @@ Hello World
|
||||
|
||||
</div>
|
||||
|
||||
## 設定編輯器
|
||||
## 設定編輯器 { #configure-your-editor }
|
||||
|
||||
你可能會用到編輯器,請確保設定它使用你建立的相同虛擬環境(它可能會自動偵測到),以便你可以獲得自動完成和内嵌錯誤提示。
|
||||
|
||||
@@ -405,9 +425,9 @@ Hello World
|
||||
|
||||
///
|
||||
|
||||
## 退出虛擬環境
|
||||
## 停用虛擬環境 { #deactivate-the-virtual-environment }
|
||||
|
||||
當你完成工作後,你可以**退出**虛擬環境。
|
||||
當你完成工作後,你可以**停用**虛擬環境。
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -419,7 +439,7 @@ $ deactivate
|
||||
|
||||
這樣,當你執行 `python` 時它不會嘗試從已安裝套件的虛擬環境中執行。
|
||||
|
||||
## 開始工作
|
||||
## 準備開始工作 { #ready-to-work }
|
||||
|
||||
現在你已經準備好開始你的工作了。
|
||||
|
||||
@@ -433,7 +453,7 @@ $ deactivate
|
||||
|
||||
///
|
||||
|
||||
## 為什麼要使用虛擬環境
|
||||
## 為什麼要使用虛擬環境 { #why-virtual-environments }
|
||||
|
||||
你需要安裝 <a href="https://www.python.org/" class="external-link" target="_blank">Python</a> 才能使用 FastAPI。
|
||||
|
||||
@@ -443,7 +463,7 @@ $ deactivate
|
||||
|
||||
然而,如果你直接使用 `pip`,套件將會安裝在你的**全域 Python 環境**中(即 Python 的全域安裝)。
|
||||
|
||||
### 存在的問題
|
||||
### 存在的問題 { #the-problem }
|
||||
|
||||
那麼,在全域 Python 環境中安裝套件有什麼問題呢?
|
||||
|
||||
@@ -526,7 +546,7 @@ Python 套件在推出**新版本**時通常會儘量**避免破壞性更改**
|
||||
|
||||
此外,取決於你的操作系統(例如 Linux、Windows、macOS),它可能已經預先安裝了 Python。在這種情況下,它可能已經有一些系統所需的套件和特定版本。如果你在全域 Python 環境中安裝套件,可能會**破壞**某些隨作業系統一起安裝的程式。
|
||||
|
||||
## 套件安裝在哪裡
|
||||
## 套件安裝在哪裡 { #where-are-packages-installed }
|
||||
|
||||
當你安裝 Python 時,它會在你的電腦中建立一些目錄並放置一些檔案。
|
||||
|
||||
@@ -537,7 +557,7 @@ Python 套件在推出**新版本**時通常會儘量**避免破壞性更改**
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// 先別去運行這個指令,這只是個示例 🤓
|
||||
// Don't run this now, it's just an example 🤓
|
||||
$ pip install "fastapi[standard]"
|
||||
---> 100%
|
||||
```
|
||||
@@ -552,7 +572,7 @@ $ pip install "fastapi[standard]"
|
||||
|
||||
預設情況下,這些下載和解壓的檔案會放置於隨 Python 安裝的目錄中,即**全域環境**。
|
||||
|
||||
## 什麼是虛擬環境
|
||||
## 什麼是虛擬環境 { #what-are-virtual-environments }
|
||||
|
||||
解決套件都安裝在全域環境中的問題方法是為你所做的每個專案使用一個**虛擬環境**。
|
||||
|
||||
@@ -577,7 +597,7 @@ flowchart TB
|
||||
stone-project ~~~ azkaban-project
|
||||
```
|
||||
|
||||
## 啟用虛擬環境意味著什麼
|
||||
## 啟用虛擬環境意味著什麼 { #what-does-activating-a-virtual-environment-mean }
|
||||
|
||||
當你啟用了虛擬環境,例如:
|
||||
|
||||
@@ -714,7 +734,7 @@ C:\Users\user\code\awesome-project\.venv\Scripts\python
|
||||
|
||||
啟用虛擬環境還會改變其他一些內容,但這是它所做的最重要的事情之一。
|
||||
|
||||
## 檢查虛擬環境
|
||||
## 檢查虛擬環境 { #checking-a-virtual-environment }
|
||||
|
||||
當你檢查虛擬環境是否啟動時,例如:
|
||||
|
||||
@@ -766,7 +786,7 @@ C:\Users\user\code\awesome-project\.venv\Scripts\python
|
||||
|
||||
///
|
||||
|
||||
## 為什麼要停用虛擬環境
|
||||
## 為什麼要停用虛擬環境 { #why-deactivate-a-virtual-environment }
|
||||
|
||||
例如,你可能正在一個專案 `philosophers-stone` 上工作,**啟動了該虛擬環境**,安裝了套件並使用了該環境,
|
||||
|
||||
@@ -791,7 +811,7 @@ $ cd ~/code/prisoner-of-azkaban
|
||||
|
||||
$ python main.py
|
||||
|
||||
// 匯入 sirius 錯誤,未安裝 😱
|
||||
// Error importing sirius, it's not installed 😱
|
||||
Traceback (most recent call last):
|
||||
File "main.py", line 1, in <module>
|
||||
import sirius
|
||||
@@ -799,20 +819,20 @@ Traceback (most recent call last):
|
||||
|
||||
</div>
|
||||
|
||||
但如果你停用虛擬環境並啟用 `prisoner-of-askaban` 的新虛擬環境,那麼當你執行 `python` 時,它會使用 `prisoner-of-askaban` 中虛擬環境的 Python。
|
||||
但如果你停用虛擬環境並啟用 `prisoner-of-askaban` 的新虛擬環境,那麼當你執行 `python` 時,它會使用 `prisoner-of-azkaban` 中虛擬環境的 Python。
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ cd ~/code/prisoner-of-azkaban
|
||||
|
||||
// 你不需要在舊目錄中操作停用,你可以在任何地方操作停用,甚至在切換到另一個專案之後 😎
|
||||
// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎
|
||||
$ deactivate
|
||||
|
||||
// 啟用 prisoner-of-azkaban/.venv 中的虛擬環境 🚀
|
||||
// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀
|
||||
$ source .venv/bin/activate
|
||||
|
||||
// 現在當你執行 python 時,它會在這個虛擬環境中找到已安裝的 sirius 套件 ✨
|
||||
// Now when you run python, it will find the package sirius installed in this virtual environment ✨
|
||||
$ python main.py
|
||||
|
||||
I solemnly swear 🐺
|
||||
@@ -820,7 +840,7 @@ I solemnly swear 🐺
|
||||
|
||||
</div>
|
||||
|
||||
## 替代方案
|
||||
## 替代方案 { #alternatives }
|
||||
|
||||
這是一個簡單的指南,幫助你入門並教會你如何理解一切**底層**的原理。
|
||||
|
||||
@@ -837,7 +857,7 @@ I solemnly swear 🐺
|
||||
* 確保你有一個**精確**的套件和版本集合來安裝,包括它們的依賴項,這樣你可以確保專案在生產環境中運行的狀態與開發時在你的電腦上運行的狀態完全相同,這被稱為**鎖定**
|
||||
* 還有很多其他功能
|
||||
|
||||
## 結論
|
||||
## 結論 { #conclusion }
|
||||
|
||||
如果你讀過並理解了所有這些,現在**你對虛擬環境的了解已超過許多開發者**。🤓
|
||||
|
||||
|
||||
Reference in New Issue
Block a user