FastAPI 教程翻译 - 介绍
FastAPI 教程翻譯 - 介紹
FastAPI framework, high performance, easy to learn, fast to code, ready for production
FastAPI 框架,高性能,易于學(xué)習(xí),快速編寫代碼,可投入生產(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+,基于標(biāo)準(zhǔn) 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 相當(dāng)(感謝 Starlette 和 Pydantic)。可用的最快的 Python 框架之一。
-
Fast to code: Increase the speed to develop features by about 200% to 300%.*
快速編寫代碼:將功能開(kāi)發(fā)速度提高約 200% 至 300%。*
-
Fewer bugs: Reduce about 40% of human (developer) induced errors.
更少的錯(cuò)誤:減少約 40% 的人為錯(cuò)誤(開(kāi)發(fā)人員)。*
-
Intuitive: Great editor support. Completion everywhere. Less time debugging.
直觀:強(qiáng)大的編輯器支持。自動(dòng)補(bǔ)全無(wú)處不在。調(diào)試時(shí)間更少。
-
Easy: Designed to be easy to use and learn. Less time reading docs.
簡(jiǎn)單:易于使用和學(xué)習(xí)。減少閱讀文檔的時(shí)間。
-
Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
簡(jiǎn)短:減少代碼重復(fù)。每個(gè)參數(shù)聲明中具有多個(gè)特性。更少的錯(cuò)誤。
-
Robust: Get production-ready code. With automatic interactive documentation.
健壯:獲取可用于生產(chǎn)環(huán)境的代碼。具有自動(dòng)交互式文檔。
-
Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.
基于標(biāo)準(zhǔn)的:基于 API 的開(kāi)放標(biāo)準(zhǔn)(并與之完全兼容):OpenAPI(以前稱為 Swagger)和 JSON 模式。
* estimation based on tests on an internal development team, building production applications.
*根據(jù)內(nèi)部開(kāi)發(fā)團(tuán)隊(duì)的測(cè)試進(jìn)行估算,以構(gòu)建生產(chǎn)應(yīng)用程序。
Opinions
意見(jiàn)
“[…] 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.
您還需要一個(gè) ASGI 服務(wù)來(lái)進(jìn)行生產(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,請(qǐng)使用 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
運(yùn)行
Run the server with:
使用以下命令運(yùn)行服務(wù)器:
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)說(shuō)明:
-
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)建的對(duì)象,其中包含 app = FastAPI() 行。
-
--reload: make the server restart after code changes. Only do this for development.
--reload:使服務(wù)器在代碼更改后重新啟動(dòng)。 僅開(kāi)發(fā)時(shí)使用。
Check it
檢查
Open your browser at http://127.0.0.1:8000/items/5?q=somequery.
用瀏覽器打開(kāi) http://127.0.0.1:8000/items/5?q=somequery。
You will see the JSON response as:
您將看到 JSON 響應(yīng):
{"item_id": 5, "q": "somequery"}You already created an API that:
您已經(jīng)創(chuàng)建了一個(gè) API:
-
Receives HTTP requests in the paths / and /items/{item_id}.
在路徑 / 和 /items/{item_id} 中接收 HTTP 請(qǐng)求。
-
Both paths take GET operations (also known as HTTP methods).
兩個(gè)路徑都采用 GET 操作(也稱為 HTTP 方法)。
-
The path /items/{item_id} has a path parameter item_id that should be an int.
路徑 /items/{item_id} 具有路徑參數(shù) item_id 并且應(yīng)該是 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):
您將看到自動(dòng)交互式 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):
您將看到備用的自動(dòng)交互式文檔(由 ReDoc 提供):
Example upgrade
更新示例
Now modify the file main.py to receive a body from a PUT request.
現(xiàn)在修改文件 main.py 以接收來(lái)自 PUT 的請(qǐng)求體。
Declare the body using standard Python types, thanks to Pydantic.
感謝 Pydantic,實(shí)現(xiàn)用標(biāo)準(zhǔn)的 Python 類來(lái)聲明請(qǐng)求體。
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).
服務(wù)應(yīng)該自動(dòng)重新加載(因?yàn)槟谏厦娴?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 文檔將自動(dòng)更新,包括新的請(qǐng)求體:
-
Click on the button “Try it out”, it allows you to fill the parameters and directly interact with the API:
點(diǎn)擊『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:
然后點(diǎn)擊『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ù)和請(qǐng)求體:
Recap
回顧
In summary, you declare once the types of parameters, body, etc. as function parameters.
總而言之,您可以一次性將參數(shù)的類型、請(qǐng)求體等聲明為函數(shù)參數(shù)。
You do that with standard modern Python types.
您可以使用標(biāo)準(zhǔn)的現(xiàn)代 Python 類型來(lái)做到這一點(diǎn)。
You don’t have to learn a new syntax, the methods or classes of a specific library, etc.
您不必學(xué)習(xí)新的語(yǔ)法,特定庫(kù)的方法或類等。
Just standard Python 3.6+.
只是標(biāo)準(zhǔn)的 Python 3.6+。
For example, for an int:
例如,對(duì)于一個(gè) int:
item_id: intor for a more complex Item model:
或更復(fù)雜的 Item 模型:
item: Item…and with that single declaration you get:
…… 并且使用該單個(gè)聲明,您將獲得:
-
Editor support, including:
編輯器支持,包括:
-
Completion.
自動(dòng)補(bǔ)全。
-
Type checks.
類型檢查。
-
-
Validation of data:
數(shù)據(jù)驗(yàn)證:
-
Automatic and clear errors when the data is invalid.
數(shù)據(jù)無(wú)效時(shí)自動(dòng)清除錯(cuò)誤。
-
Validation even for deeply nested JSON objects.
甚至針對(duì)深度嵌套的 JSON 對(duì)象進(jìn)行驗(yàn)證。
-
-
Conversion of input data: coming from the network to Python data and types. Reading from:
輸入數(shù)據(jù)的轉(zhuǎn)換:從網(wǎng)絡(luò)到 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)絡(luò)數(shù)據(jù)(如 JSON):
-
Convert Python types (str, int, float, bool, list, etc).
轉(zhuǎn)換 Python 類型(str、int、float、bool、list 等等)。
-
datetime objects.
datetime 對(duì)象。
-
UUID objects.
UUID對(duì)象。
-
Database models.
數(shù)據(jù)基礎(chǔ)模型。
-
…and many more.
…… 和更多的。
-
-
Automatic interactive API documentation, including 2 alternative user interfaces:
自動(dòng)交互式API文檔,包括2個(gè)備用用戶界面:
- 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.
驗(yàn)證路徑中是否有用于 GET 和 PUT 請(qǐng)求的 item_id。
-
Validate that the item_id is of type int for GET and PUT requests.
驗(yàn)證 item_id 的類型是否為 GET 和 PUT 請(qǐng)求的 int 類型。
-
If it is not, the client will see a useful, clear error.
如果不是,則客戶端將看到一個(gè)有用的明確錯(cuò)誤。
-
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.
檢查是否有一個(gè)名為 q 的可選查詢參數(shù)(如 http://127.0.0.1:8000/items/foo?q=somequery),用于 GET 請(qǐng)求。
-
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).
如果沒(méi)有 None,則將是必需的(與 PUT 一樣,請(qǐng)求體也是如此)。
-
-
For PUT requests to /items/{item_id}, Read the body as JSON:
對(duì)于對(duì) /items/{item_id} 的 PUT 請(qǐng)求,將正文讀取為 JSON:
-
Check that it has a required attribute name that should be a str.
檢查其是否具有必須的屬性 name,該屬性應(yīng)為 str。
-
Check that it has a required attribute price that has to be a float.
檢查它是否具有必須的屬性 price,該屬性應(yīng)為 float。
-
Check that it has an optional attribute is_offer, that should be a bool, if present.
檢查它是否具有可選屬性 is_offer,如果存在則應(yīng)為 bool。
-
All this would also work for deeply nested JSON objects.
所有這些也適用于深度嵌套的 JSON 對(duì)象。
-
-
Convert from and to JSON automatically.
自動(dòng)從 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.
適用于多種語(yǔ)言的自動(dòng)客戶端代碼生成系統(tǒng)。
-
-
Provide 2 interactive documentation web interfaces directly.
直接提供 2 個(gè)交互式文檔 Web 界面。
We just scratched the surface, but you already get the idea of how it all works.
我們僅僅只進(jìn)行了簡(jiǎn)單描繪,但您已經(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:
…… 并查看編輯器如何自動(dòng)完成屬性并了解其類型:
For a more complete example including more features, see the Tutorial - User Guide.
有關(guān)包含更多功能的更完整示例,請(qǐng)參見(jiàn) Tutorial - User Guide。
Spoiler alert: the tutorial - user guide includes:
劇透警報(bào):本教程 - 用戶指南包括:
-
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.
如何將驗(yàn)證約束設(shè)置為 maximum_length 或 regex。
-
A very powerful and easy to use Dependency Injection system.
一個(gè)非常強(qiáng)大且易于使用的依賴注入系統(tǒng)。
-
Security and authentication, including support for OAuth2 with JWT tokens and HTTP Basic auth.
安全性和身份驗(yàn)證,包括通過(guò) JWT 令牌認(rèn)證和 HTTP 基礎(chǔ)認(rèn)證。
-
More advanced (but equally easy) techniques for declaring deeply nested JSON models (thanks to Pydantic).
用于聲明深度嵌套的 JSON 模型的更高級(jí)(但同樣容易)的技術(shù)(感謝 Pydantic)。
-
Many extra features (thanks to Starlette) as:
許多額外的功能(感謝 Starlette):
-
WebSockets
-
GraphQL
-
extremely easy tests based on requests and pytest
基于 requests 和 pytest 的極其簡(jiǎn)單的測(cè)試
-
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). (*)
獨(dú)立的 TechEmpower 基準(zhǔn)測(cè)試顯示 FastAPI 應(yīng)用程序在 Uvicorn(可用的最快 Python 框架之一)上運(yùn)行,僅低于 Starlette 和 Uvicorn 本身(由 FastAPI 內(nèi)部使用)。
To understand more about it, see the section Benchmarks.
要了解更多信息,請(qǐng)參閱基準(zhǔn)部分。
Optional Dependencies
可選依賴項(xiàng)
Used by Pydantic:
由 Pydantic 提供:
-
ujson - for faster JSON “parsing”.
ujson - 用于更快的 JSON『解析』。
-
email_validator - for email validation.
email_validator - 用于電子郵箱驗(yàn)證。
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 - 如果要使用默認(rèn)模板配置,則為必需。
-
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 - 用于加載和服務(wù)您的應(yīng)用程序的服務(wù)器。
-
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 - 用于加載和服務(wù)您的應(yīng)用程序的服務(wù)器。
-
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.
該項(xiàng)目根據(jù) MIT 許可條款獲得許可。
總結(jié)
以上是生活随笔為你收集整理的FastAPI 教程翻译 - 介绍的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: PMP考试只刷题能否通过呢?
- 下一篇: 太网交换机芯片-KSZ系列