FastAPI 教程翻译 - 介绍
FastAPI 教程翻譯 - 介紹
FastAPI framework, high performance, easy to learn, fast to code, ready for production
FastAPI 框架,高性能,易于學習,快速編寫代碼,可投入生產(chǎn)
Documentation: https://fastapi.tiangolo.com
文檔:https://fastapi.tiangolo.com
Source Code: https://github.com/tiangolo/fastapi
源代碼:https://github.com/tiangolo/fastapi
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
FastAPI 是一種現(xiàn)代、快速(高性能)的 Web 框架,用于構(gòu)建 API,使用 Python 3.6+,基于標準 Python 類型提示。
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.
快速:非常高的性能,與 NodeJS 和 Go 相當(感謝 Starlette 和 Pydantic)。可用的最快的 Python 框架之一。
-
Fast to code: Increase the speed to develop features by about 200% to 300%.*
快速編寫代碼:將功能開發(fā)速度提高約 200% 至 300%。*
-
Fewer bugs: Reduce about 40% of human (developer) induced errors.
更少的錯誤:減少約 40% 的人為錯誤(開發(fā)人員)。*
-
Intuitive: Great editor support. Completion everywhere. Less time debugging.
直觀:強大的編輯器支持。自動補全無處不在。調(diào)試時間更少。
-
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.
簡短:減少代碼重復。每個參數(shù)聲明中具有多個特性。更少的錯誤。
-
Robust: Get production-ready code. With automatic interactive documentation.
健壯:獲取可用于生產(chǎn)環(huán)境的代碼。具有自動交互式文檔。
-
Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.
基于標準的:基于 API 的開放標準(并與之完全兼容):OpenAPI(以前稱為 Swagger)和 JSON 模式。
* estimation based on tests on an internal development team, building production applications.
*根據(jù)內(nèi)部開發(fā)團隊的測試進行估算,以構(gòu)建生產(chǎn)應用程序。
Opinions
意見
“[…] I’m using FastAPI a ton these days. […] I’m actually planning to use it for all of my team’s ML services at Microsoft*. Some of them are getting integrated into the core* Windows product and some Office products.”
Kabir Khan - Microsoft (ref)
“I’m over the moon excited about FastAPI*. It’s so fun!*”
Brian Okken - Python Bytes podcast host (ref)
“Honestly, what you’ve built looks super solid and polished. In many ways, it’s what I wanted Hug to be - it’s really inspiring to see someone build that.”
Timothy Crosley - Hug creator (ref)
“If you’re looking to learn one modern framework for building REST APIs, check out FastAPI […] It’s fast, easy to use and easy to learn […]”
“We’ve switched over to FastAPI for our APIs […] I think you’ll like it […]”
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
“We adopted the FastAPI library to spawn a REST server that can be queried to obtain predictions*. [for Ludwig]*”
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
Requirements
要求
Python 3.6+
FastAPI stands on the shoulders of giants:
FastAPI 站在巨人的肩膀上:
-
Starlette for the web parts.
Starlette 用于構(gòu)建 Web 部件。
-
Pydantic for the data parts.
Pydantic 用于數(shù)據(jù)部分。
Installation
安裝
pip install fastapiYou will also need an ASGI server, for production such as Uvicorn or Hypercorn.
您還需要一個 ASGI 服務來進行生產(chǎn)部署,例如 Uvicorn 或者 Hypercorn。
pip install uvicornExample
示例
Create it
創(chuàng)建
-
Create a file main.py with:
使用以下命令創(chuàng)建文件 main.py:
Or use async def…
或者使用 asyn def……
If your code uses async / await, use async def:
如果您的代碼使用了 async 或者 await,請使用 async def:
from fastapi import FastAPIapp = FastAPI()@app.get("/") async def read_root():return {"Hello": "World"}@app.get("/items/{item_id}") async def read_item(item_id: int, q: str = None):return {"item_id": item_id, "q": q}Note
注意
If you don’t know, check the “In a hurry?” section about async and await in the docs.
如果您不知道,查看“繁忙?“章節(jié)關(guān)于 async and await in the docs 的部分。
Run it
運行
Run the server with:
使用以下命令運行服務器:
uvicorn main:app --reloadAbout the command uvicorn main:app --reload…
關(guān)于命令 uvicorn main:app --reload
The command uvicorn main:app --reload refers to:
命令 uvicorn main:app --reload 的相關(guān)說明:
-
main: the file main.py (the Python “module”).
main:文件 main.py(Python 模塊)
-
app: the object created inside of main.py with the line app = FastAPI().
app:在 main.py 內(nèi)部創(chuàng)建的對象,其中包含 app = FastAPI() 行。
-
--reload: make the server restart after code changes. Only do this for development.
--reload:使服務器在代碼更改后重新啟動。 僅開發(fā)時使用。
Check it
檢查
Open your browser at http://127.0.0.1:8000/items/5?q=somequery.
用瀏覽器打開 http://127.0.0.1:8000/items/5?q=somequery。
You will see the JSON response as:
您將看到 JSON 響應:
{"item_id": 5, "q": "somequery"}You already created an API that:
您已經(jīng)創(chuàng)建了一個 API:
-
Receives HTTP requests in the paths / and /items/{item_id}.
在路徑 / 和 /items/{item_id} 中接收 HTTP 請求。
-
Both paths take GET operations (also known as HTTP methods).
兩個路徑都采用 GET 操作(也稱為 HTTP 方法)。
-
The path /items/{item_id} has a path parameter item_id that should be an int.
路徑 /items/{item_id} 具有路徑參數(shù) item_id 并且應該是 int。
-
The path /items/{item_id} has an optional str query parameter q.
路徑 /items/{item_id} 具有可選的 str 查詢參數(shù) q。
Interactive API docs
交互式 API 文檔
Now go to http://127.0.0.1:8000/docs.
現(xiàn)在轉(zhuǎn)到 http://127.0.0.1:8000/docs。
You will see the automatic interactive API documentation (provided by Swagger UI):
您將看到自動交互式 API 文檔(由 Swagger UI 提供):
Alternative API docs
備用 API 文檔
And now, go to http://127.0.0.1:8000/redoc.
現(xiàn)在,轉(zhuǎn)到 http://127.0.0.1:8000/redoc。
You will see the alternative automatic documentation (provided by ReDoc):
您將看到備用的自動交互式文檔(由 ReDoc 提供):
Example upgrade
更新示例
Now modify the file main.py to receive a body from a PUT request.
現(xiàn)在修改文件 main.py 以接收來自 PUT 的請求體。
Declare the body using standard Python types, thanks to Pydantic.
感謝 Pydantic,實現(xiàn)用標準的 Python 類來聲明請求體。
from fastapi import FastAPI from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strprice: floatis_offer: bool = None@app.get("/") def read_root():return {"Hello": "World"}@app.get("/items/{item_id}") def read_item(item_id: int, q: str = None):return {"item_id": item_id, "q": q}@app.put("/items/{item_id}") def update_item(item_id: int, item: Item):return {"item_name": item.name, "item_id": item_id}The server should reload automatically (because you added --reload to the uvicorn command above).
服務應該自動重新加載(因為您在上面的 uvicorn 命令中添加了 --reload)。
Interactive API docs upgrade
交互式 API 文檔更新
Now go to http://127.0.0.1:8000/docs.
現(xiàn)在轉(zhuǎn)到 http://127.0.0.1:8000/docs。
-
The interactive API documentation will be automatically updated, including the new body:
交互式 API 文檔將自動更新,包括新的請求體:
-
Click on the button “Try it out”, it allows you to fill the parameters and directly interact with the API:
點擊『Try it out』按鈕,它可以讓您填寫參數(shù)并直接與 API 交互:
-
Then click on the “Execute” button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
然后點擊『Execute』按鈕,用戶界面將與您的 API 通信,發(fā)送參數(shù),獲取結(jié)果并將其顯示在屏幕上:
Alternative API docs upgrade
備用 API 文檔更新
And now, go to http://127.0.0.1:8000/redoc.
現(xiàn)在,轉(zhuǎn)到 http://127.0.0.1:8000/redoc。
-
The alternative documentation will also reflect the new query parameter and body:
備用文檔也將反映新的查詢參數(shù)和請求體:
Recap
回顧
In summary, you declare once the types of parameters, body, etc. as function parameters.
總而言之,您可以一次性將參數(shù)的類型、請求體等聲明為函數(shù)參數(shù)。
You do that with standard modern Python types.
您可以使用標準的現(xiàn)代 Python 類型來做到這一點。
You don’t have to learn a new syntax, the methods or classes of a specific library, etc.
您不必學習新的語法,特定庫的方法或類等。
Just standard Python 3.6+.
只是標準的 Python 3.6+。
For example, for an int:
例如,對于一個 int:
item_id: intor for a more complex Item model:
或更復雜的 Item 模型:
item: Item…and with that single declaration you get:
…… 并且使用該單個聲明,您將獲得:
-
Editor support, including:
編輯器支持,包括:
-
Completion.
自動補全。
-
Type checks.
類型檢查。
-
-
Validation of data:
數(shù)據(jù)驗證:
-
Automatic and clear errors when the data is invalid.
數(shù)據(jù)無效時自動清除錯誤。
-
Validation even for deeply nested JSON objects.
甚至針對深度嵌套的 JSON 對象進行驗證。
-
-
Conversion of input data: coming from the network to Python data and types. Reading from:
輸入數(shù)據(jù)的轉(zhuǎn)換:從網(wǎng)絡到 Python 數(shù)據(jù)和類型。如:
-
JSON.
-
Path parameters.
路徑參數(shù)。
-
Query parameters.
查詢參數(shù)。
-
Cookies.
-
Headers.
-
Forms.
表單。
-
Files.
文件。
-
-
Conversion of output data: converting from Python data and types to network data (as JSON):
輸出數(shù)據(jù)的轉(zhuǎn)換:從 Python 數(shù)據(jù)和類型轉(zhuǎn)換為網(wǎng)絡數(shù)據(jù)(如 JSON):
-
Convert Python types (str, int, float, bool, list, etc).
轉(zhuǎn)換 Python 類型(str、int、float、bool、list 等等)。
-
datetime objects.
datetime 對象。
-
UUID objects.
UUID對象。
-
Database models.
數(shù)據(jù)基礎模型。
-
…and many more.
…… 和更多的。
-
-
Automatic interactive API documentation, including 2 alternative user interfaces:
自動交互式API文檔,包括2個備用用戶界面:
- Swagger UI.
- ReDoc.
Coming back to the previous code example, FastAPI will:
回到前面的代碼示例,**FastAPI **將:
-
Validate that there is an item_id in the path for GET and PUT requests.
驗證路徑中是否有用于 GET 和 PUT 請求的 item_id。
-
Validate that the item_id is of type int for GET and PUT requests.
驗證 item_id 的類型是否為 GET 和 PUT 請求的 int 類型。
-
If it is not, the client will see a useful, clear error.
如果不是,則客戶端將看到一個有用的明確錯誤。
-
Check if there is an optional query parameter named q (as in http://127.0.0.1:8000/items/foo?q=somequery) for GET requests.
檢查是否有一個名為 q 的可選查詢參數(shù)(如 http://127.0.0.1:8000/items/foo?q=somequery),用于 GET 請求。
-
As the q parameter is declared with = None, it is optional.
由于 q 參數(shù)以 =None 聲明,因此它是可選的。
-
Without the None it would be required (as is the body in the case with PUT).
如果沒有 None,則將是必需的(與 PUT 一樣,請求體也是如此)。
-
-
For PUT requests to /items/{item_id}, Read the body as JSON:
對于對 /items/{item_id} 的 PUT 請求,將正文讀取為 JSON:
-
Check that it has a required attribute name that should be a str.
檢查其是否具有必須的屬性 name,該屬性應為 str。
-
Check that it has a required attribute price that has to be a float.
檢查它是否具有必須的屬性 price,該屬性應為 float。
-
Check that it has an optional attribute is_offer, that should be a bool, if present.
檢查它是否具有可選屬性 is_offer,如果存在則應為 bool。
-
All this would also work for deeply nested JSON objects.
所有這些也適用于深度嵌套的 JSON 對象。
-
-
Convert from and to JSON automatically.
自動從 JSON 轉(zhuǎn)換。
-
Document everything with OpenAPI, that can be used by:
使用 OpenAPI 記錄所有內(nèi)容,可用于:
-
Interactive documentation systems.
交互式文檔系統(tǒng)。
-
Automatic client code generation systems, for many languages.
適用于多種語言的自動客戶端代碼生成系統(tǒng)。
-
-
Provide 2 interactive documentation web interfaces directly.
直接提供 2 個交互式文檔 Web 界面。
We just scratched the surface, but you already get the idea of how it all works.
我們僅僅只進行了簡單描繪,但您已經(jīng)了解了所有工作原理。
Try changing the line with:
嘗試使用以下方法更改這行代碼:
return {"item_name": item.name, "item_id": item_id}…from:
…… 從:
... "item_name": item.name ...…to:
…… 到:
... "item_price": item.price ...…and see how your editor will auto-complete the attributes and know their types:
…… 并查看編輯器如何自動完成屬性并了解其類型:
For a more complete example including more features, see the Tutorial - User Guide.
有關(guān)包含更多功能的更完整示例,請參見 Tutorial - User Guide。
Spoiler alert: the tutorial - user guide includes:
劇透警報:本教程 - 用戶指南包括:
-
Declaration of parameters from other different places as: headers, cookies, form fields and files.
從其他不同地方聲明參數(shù),例如:headers、cookies、表單字段和文件。
-
How to set validation constraints as maximum_length or regex.
如何將驗證約束設置為 maximum_length 或 regex。
-
A very powerful and easy to use Dependency Injection system.
一個非常強大且易于使用的依賴注入系統(tǒng)。
-
Security and authentication, including support for OAuth2 with JWT tokens and HTTP Basic auth.
安全性和身份驗證,包括通過 JWT 令牌認證和 HTTP 基礎認證。
-
More advanced (but equally easy) techniques for declaring deeply nested JSON models (thanks to Pydantic).
用于聲明深度嵌套的 JSON 模型的更高級(但同樣容易)的技術(shù)(感謝 Pydantic)。
-
Many extra features (thanks to Starlette) as:
許多額外的功能(感謝 Starlette):
-
WebSockets
-
GraphQL
-
extremely easy tests based on requests and pytest
基于 requests 和 pytest 的極其簡單的測試
-
CORS
-
Cookie Sessions
-
…and more.
…… 和更多。
-
Performance
性能
Independent TechEmpower benchmarks show FastAPI applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
獨立的 TechEmpower 基準測試顯示 FastAPI 應用程序在 Uvicorn(可用的最快 Python 框架之一)上運行,僅低于 Starlette 和 Uvicorn 本身(由 FastAPI 內(nèi)部使用)。
To understand more about it, see the section Benchmarks.
要了解更多信息,請參閱基準部分。
Optional Dependencies
可選依賴項
Used by Pydantic:
由 Pydantic 提供:
-
ujson - for faster JSON “parsing”.
ujson - 用于更快的 JSON『解析』。
-
email_validator - for email validation.
email_validator - 用于電子郵箱驗證。
Used by Starlette:
由 Starlette 提供:
-
requests - Required if you want to use the TestClient.
requests - 如果您想使用TestClient,則為必需。
-
aiofiles - Required if you want to use FileResponse or StaticFiles.
aiofiles - 如果您想使用FileResponse或StaticFiles,則必選。
-
jinja2 - Required if you want to use the default template configuration.
jinja2 - 如果要使用默認模板配置,則為必需。
-
python-multipart - Required if you want to support form “parsing”, with request.form().
python-multipart - 如果您想使用request.form()支持表單“解析”,則為必需。
-
itsdangerous - Required for SessionMiddleware support.
itsdangerous - 需要SessionMiddleware支持。
-
pyyaml - Required for Starlette’s SchemaGenerator support (you probably don’t need it with FastAPI).
pyyaml - Starlette的SchemaGenerator支持所必需的(FastAPI可能不需要它)。
-
graphene - Required for GraphQLApp support.
graphene - 為GraphQLApp支持所必需。
-
ujson - Required if you want to use UJSONResponse.
ujson - 如果要使用UJSONResponse,則為必需。
Used by FastAPI / Starlette:
由 FastAPI / Starlette 提供:
-
uvicorn - for the server that loads and serves your application.
uvicorn - 用于加載和服務您的應用程序的服務器。
-
orjson - Required if you want to use ORJSONResponse.
orjson - 如果要使用ORJSONResponse,則為必需。
You can install all of these with pip install fastapi[all].
您可以使用 pip install fastapi[all] 安裝所有這些內(nèi)容。
License
許可
This project is licensed under the terms of the MIT license.
e/ultrajson) - Required if you want to use UJSONResponse.
ujson - 如果要使用UJSONResponse,則為必需。
Used by FastAPI / Starlette:
由 FastAPI / Starlette 提供:
-
uvicorn - for the server that loads and serves your application.
uvicorn - 用于加載和服務您的應用程序的服務器。
-
orjson - Required if you want to use ORJSONResponse.
orjson - 如果要使用ORJSONResponse,則為必需。
You can install all of these with pip install fastapi[all].
您可以使用 pip install fastapi[all] 安裝所有這些內(nèi)容。
License
許可
This project is licensed under the terms of the MIT license.
該項目根據(jù) MIT 許可條款獲得許可。
總結(jié)
以上是生活随笔為你收集整理的FastAPI 教程翻译 - 介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PMP考试只刷题能否通过呢?
- 下一篇: php笔刷怎么安装,ps笔刷怎么用?PS