Python中FastAPI項(xiàng)目使用 Annotated的參數(shù)設(shè)計(jì)的處理方案
在FastAPI中,你可以使用PEP 593中的Annotated類型來(lái)添加元數(shù)據(jù)到類型提示中。這個(gè)功能非常有用,因?yàn)樗试S你在類型提示中添加更多的上下文信息,例如描述、默認(rèn)值或其他自定義元數(shù)據(jù)。
FastAPI支持Annotated類型,這使得你可以為路徑操作函數(shù)的參數(shù)提供額外的元數(shù)據(jù),例如依賴項(xiàng)、查詢參數(shù)的描述、別名等。
FastAPI介紹
FastAPI 是一個(gè)用于構(gòu)建 API 的現(xiàn)代、快速(高性能)web 框架,基于 Python 類型提示。它的主要特點(diǎn)包括自動(dòng)生成 OpenAPI 和 JSON Schema 文檔、快速代碼編寫(xiě)、簡(jiǎn)潔的代碼結(jié)構(gòu)、高效的性能等。FastAPI 使用 Starlette 作為 Web 框架的核心,并使用 Pydantic 進(jìn)行數(shù)據(jù)驗(yàn)證。
FastAPI 的主要特點(diǎn)
快速:
- FastAPI 的性能非常接近于 NodeJS 和 Go 等速度較快的語(yǔ)言,并且比其他基于 Python 的框架如 Flask 和 Django 快得多。
簡(jiǎn)潔:
- 通過(guò)類型提示和依賴注入,代碼簡(jiǎn)潔易讀。
- 開(kāi)發(fā)者可以更少的代碼實(shí)現(xiàn)更多的功能。
自動(dòng)文檔生成:
- FastAPI 自動(dòng)生成符合 OpenAPI 規(guī)范的文檔,這些文檔可以通過(guò)內(nèi)置的 Swagger UI 和 ReDoc UI 查看。
- 自動(dòng)生成 JSON Schema。
數(shù)據(jù)驗(yàn)證:
- 基于 Pydantic,F(xiàn)astAPI 提供了強(qiáng)大的數(shù)據(jù)驗(yàn)證功能。
- 支持復(fù)雜的數(shù)據(jù)驗(yàn)證和數(shù)據(jù)解析。
類型提示:
- 充分利用 Python 的類型提示,幫助開(kāi)發(fā)者編寫(xiě)和維護(hù)代碼。
依賴注入:
- FastAPI 提供了一個(gè)簡(jiǎn)單但功能強(qiáng)大的依賴注入系統(tǒng),可以方便地管理依賴項(xiàng)。
FastAPI 還支持以下功能:
- 文件上傳
- 安全性(OAuth2、JWT 等)
- 后臺(tái)任務(wù)
- 流媒體響應(yīng)
- GraphQL
- SQL(通過(guò) SQLAlchemy 等)
- 數(shù)據(jù)庫(kù)事務(wù)
- 后臺(tái)任務(wù)
安裝 FastAPI 和 Uvicorn
pip install fastapi pip install "uvicorn[standard]"
FastAPI 是一個(gè)非?,F(xiàn)代化和高效的框架,非常適合用于構(gòu)建高性能的 API。其自動(dòng)文檔生成、數(shù)據(jù)驗(yàn)證和依賴注入等特性,使得開(kāi)發(fā)者能夠更快、更安全地編寫(xiě)代碼,并提供出色的用戶體驗(yàn)。
FastAPI項(xiàng)目的參數(shù)設(shè)計(jì),這些您可以在路徑操作函數(shù)參數(shù)或使用Annotated的依賴函數(shù)中使用的特殊函數(shù),用于從請(qǐng)求中獲取數(shù)據(jù)。
它包括
Query()Path()Body()Cookie()Header()Form()File()
您可以直接從fastapi導(dǎo)入它們
from fastapi import Body, Cookie, File, Form, Header, Path, Query
1、Query參數(shù)-查詢參數(shù)
Query參數(shù)是指我們?cè)赨RL中帶有的查詢參數(shù)如url/items?q=123&b=234 的類型格式。
假設(shè)我們要?jiǎng)?chuàng)建一個(gè)API,其中的查詢參數(shù)需要帶有描述和默認(rèn)值:
from fastapi import FastAPI, Query
from typing import Annotated
app = FastAPI()
@app.get("/items/")
async def read_items(
q: Annotated[str, Query(description="Query string", min_length=3, max_length=50)] = "default"
):
return {"q": q}在這個(gè)例子中:
- 我們導(dǎo)入了FastAPI和
Query類,以及Annotated類型。 - 我們創(chuàng)建了一個(gè)FastAPI應(yīng)用實(shí)例。
- 我們定義了一個(gè)路徑操作函數(shù)
read_items,它有一個(gè)查詢參數(shù)q。 - 我們使用
Annotated類型為查詢參數(shù)q添加了元數(shù)據(jù),這些元數(shù)據(jù)包括描述、最小長(zhǎng)度和最大長(zhǎng)度等。 Annotated的第一個(gè)參數(shù)是類型提示,第二個(gè)參數(shù)是與此類型相關(guān)的元數(shù)據(jù)。
Annotated類型允許你將額外的元數(shù)據(jù)與類型提示關(guān)聯(lián),這在創(chuàng)建API時(shí)特別有用,因?yàn)樗梢詭椭筛S富的API文檔并確保參數(shù)驗(yàn)證。
下面是一個(gè)更復(fù)雜的例子,展示了如何使用Annotated類型與依賴項(xiàng)結(jié)合:
from fastapi import Depends
def common_parameters(
q: Annotated[str, Query(description="Query string", min_length=3, max_length=50)] = "default"
):
return {"q": q}
@app.get("/items/")
async def read_items(params: Annotated[dict, Depends(common_parameters)]):
return params在這個(gè)例子中:
- 我們定義了一個(gè)依賴函數(shù)
common_parameters,它返回一個(gè)包含查詢參數(shù)q的字典。 - 我們使用
Annotated類型和Depends將這個(gè)依賴項(xiàng)注入到路徑操作函數(shù)read_items中。 read_items函數(shù)返回了從依賴函數(shù)中獲取的參數(shù)字典。
這種方法不僅簡(jiǎn)化了路徑操作函數(shù)的參數(shù)定義,還使得代碼更具可讀性和可維護(hù)性。
2、Path參數(shù)-路徑參數(shù)
路徑參數(shù)通常用于從 URL 路徑中提取信息。例如,如果你有一個(gè)獲取用戶信息的路徑 /users/{user_id},你可以這樣定義路徑參數(shù):
from fastapi import FastAPI
from fastapi.params import Path
from typing import Annotated
app = FastAPI()
@app.get("/users/{user_id}")
async def read_user(user_id: Annotated[int, Path(..., title="The ID of the user to get")]):
return {"user_id": user_id}在這個(gè)示例中,Annotated[int, Path(..., title="The ID of the user to get")] 表示 user_id 是一個(gè)整數(shù),并且它是從路徑中提取的參數(shù)。此外,我們還為這個(gè)參數(shù)添加了一個(gè)標(biāo)題,用于生成 API 文檔。
3、Body參數(shù)-請(qǐng)求體參數(shù)
求體參數(shù)用于處理復(fù)雜的數(shù)據(jù)結(jié)構(gòu),例如 JSON 請(qǐng)求體。你可以使用 Pydantic 模型來(lái)定義請(qǐng)求體的結(jié)構(gòu),并使用 Annotated 來(lái)進(jìn)一步注解這些參數(shù)。例如:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Annotated
app = FastAPI()
class User(BaseModel):
name: str
age: int
@app.post("/users/")
async def create_user(user: Annotated[User, Body(..., title="The user to create")]):
return {"user": user}在這個(gè)示例中,Annotated[User, Body(..., title="The user to create")] 表示 user 參數(shù)是一個(gè) User 模型實(shí)例,并且它來(lái)自請(qǐng)求體。我們同樣為這個(gè)參數(shù)添加了一個(gè)標(biāo)題。
有時(shí)候我們可以結(jié)合路徑參數(shù)和請(qǐng)求體參數(shù)進(jìn)行使用,如下例子:
from fastapi import FastAPI, Path, Body
from pydantic import BaseModel
from typing import Annotated
app = FastAPI()
class User(BaseModel):
name: str
age: int
@app.put("/users/{user_id}")
async def update_user(
user_id: Annotated[int, Path(..., title="The ID of the user to update")],
user: Annotated[User, Body(..., title="The new user data")]
):
return {"user_id": user_id, "user": user}在這個(gè)綜合示例中,路徑參數(shù) user_id 和請(qǐng)求體參數(shù) user 都使用了 Annotated 進(jìn)行注解,以明確它們的來(lái)源和意圖,同時(shí)為生成的 API 文檔提供了更多的上下文信息。
復(fù)雜的請(qǐng)求體通常包括嵌套的結(jié)構(gòu),可以使用 Pydantic 模型來(lái)定義。例如:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Annotated
app = FastAPI()
class Address(BaseModel):
street: str
city: str
state: str
zip: str
class User(BaseModel):
name: str
age: int
addresses: List[Address]
@app.post("/users/")
async def create_user(user: Annotated[User, Body(..., title="The user to create")]):
return {"user": user}在這個(gè)例子中,User 模型包含一個(gè)嵌套的 Address 列表,這樣你就可以在請(qǐng)求體中處理復(fù)雜的嵌套數(shù)據(jù)結(jié)構(gòu)。
一個(gè)結(jié)合路徑參數(shù)、查詢參數(shù)和請(qǐng)求體參數(shù)的復(fù)雜示例:
from fastapi import FastAPI, Path, Query, Body
from pydantic import BaseModel
from typing import Annotated
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.put("/items/{item_id}")
async def update_item(
item_id: Annotated[int, Path(..., title="The ID of the item to update")],
q: Annotated[str | None, Query(None, max_length=50, title="Query string")],
item: Annotated[Item, Body(..., title="The item to update")]
):
result = {"item_id": item_id, "item": item}
if q:
result.update({"q": q})
return result在這個(gè)綜合示例中,我們使用了路徑參數(shù) item_id、查詢參數(shù) q 和請(qǐng)求體參數(shù) item,并通過(guò) Annotated 對(duì)這些參數(shù)進(jìn)行注解,明確它們的來(lái)源和約束。
應(yīng)用上面的處理方案,我們?cè)陧?xiàng)目中應(yīng)用FastApi構(gòu)建文檔如下所示。

到此這篇關(guān)于Python中FastAPI項(xiàng)目使用 Annotated的參數(shù)設(shè)計(jì)的文章就介紹到這了,更多相關(guān)Python FastAPI使用 Annotated內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 用matplotlib畫(huà)以時(shí)間日期為x軸的圖像
這篇文章主要介紹了Python 用matplotlib畫(huà)以時(shí)間日期為x軸的圖像,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
python實(shí)現(xiàn)ROA算子邊緣檢測(cè)算法
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)ROA算子邊緣檢測(cè)算法,以光學(xué)圖像為例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04
基于opencv和pillow實(shí)現(xiàn)人臉識(shí)別系統(tǒng)(附demo)
人臉識(shí)別就是一個(gè)程序能識(shí)別給定圖像或視頻中的人臉,本文主要介紹了opencv和pillow實(shí)現(xiàn)人臉識(shí)別系統(tǒng),本文不涉及分類器、訓(xùn)練識(shí)別器等算法原理,感興趣的可以了解一下2021-11-11
五分鐘學(xué)會(huì)怎么用Pygame做一個(gè)簡(jiǎn)單的貪吃蛇
這篇文章主要介紹了五分鐘學(xué)會(huì)怎么用Pygame做一個(gè)簡(jiǎn)單的貪吃蛇,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2021-01-01
Pyspark獲取并處理RDD數(shù)據(jù)代碼實(shí)例
這篇文章主要介紹了Pyspark獲取并處理RDD數(shù)據(jù)代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
python3.4+pycharm 環(huán)境安裝及使用方法
這篇文章主要介紹了python3.4+pycharm 環(huán)境安裝及使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
jupyter notebook如何導(dǎo)出pdf并支持中文
這篇文章主要介紹了jupyter notebook如何導(dǎo)出pdf并支持中文問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06

