Python中FastAPI項(xiàng)目使用 Annotated的參數(shù)設(shè)計(jì)的處理方案
在FastAPI中,你可以使用PEP 593中的Annotated
類型來添加元數(shù)據(jù)到類型提示中。這個功能非常有用,因?yàn)樗试S你在類型提示中添加更多的上下文信息,例如描述、默認(rèn)值或其他自定義元數(shù)據(jù)。
FastAPI支持Annotated
類型,這使得你可以為路徑操作函數(shù)的參數(shù)提供額外的元數(shù)據(jù),例如依賴項(xiàng)、查詢參數(shù)的描述、別名等。
FastAPI介紹
FastAPI 是一個用于構(gòu)建 API 的現(xiàn)代、快速(高性能)web 框架,基于 Python 類型提示。它的主要特點(diǎn)包括自動生成 OpenAPI 和 JSON Schema 文檔、快速代碼編寫、簡潔的代碼結(jié)構(gòu)、高效的性能等。FastAPI 使用 Starlette 作為 Web 框架的核心,并使用 Pydantic 進(jìn)行數(shù)據(jù)驗(yàn)證。
FastAPI 的主要特點(diǎn)
快速:
- FastAPI 的性能非常接近于 NodeJS 和 Go 等速度較快的語言,并且比其他基于 Python 的框架如 Flask 和 Django 快得多。
簡潔:
- 通過類型提示和依賴注入,代碼簡潔易讀。
- 開發(fā)者可以更少的代碼實(shí)現(xiàn)更多的功能。
自動文檔生成:
- FastAPI 自動生成符合 OpenAPI 規(guī)范的文檔,這些文檔可以通過內(nèi)置的 Swagger UI 和 ReDoc UI 查看。
- 自動生成 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 的類型提示,幫助開發(fā)者編寫和維護(hù)代碼。
依賴注入:
- FastAPI 提供了一個簡單但功能強(qiáng)大的依賴注入系統(tǒng),可以方便地管理依賴項(xiàng)。
FastAPI 還支持以下功能:
- 文件上傳
- 安全性(OAuth2、JWT 等)
- 后臺任務(wù)
- 流媒體響應(yīng)
- GraphQL
- SQL(通過 SQLAlchemy 等)
- 數(shù)據(jù)庫事務(wù)
- 后臺任務(wù)
安裝 FastAPI 和 Uvicorn
pip install fastapi pip install "uvicorn[standard]"
FastAPI 是一個非?,F(xiàn)代化和高效的框架,非常適合用于構(gòu)建高性能的 API。其自動文檔生成、數(shù)據(jù)驗(yàn)證和依賴注入等特性,使得開發(fā)者能夠更快、更安全地編寫代碼,并提供出色的用戶體驗(yàn)。
FastAPI項(xiàng)目的參數(shù)設(shè)計(jì),這些您可以在路徑操作函數(shù)參數(shù)或使用Annotated
的依賴函數(shù)中使用的特殊函數(shù),用于從請求中獲取數(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ù)是指我們在URL中帶有的查詢參數(shù)如url/items?q=123&b=234 的類型格式。
假設(shè)我們要創(chuàng)建一個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}
在這個例子中:
- 我們導(dǎo)入了FastAPI和
Query
類,以及Annotated
類型。 - 我們創(chuàng)建了一個FastAPI應(yīng)用實(shí)例。
- 我們定義了一個路徑操作函數(shù)
read_items
,它有一個查詢參數(shù)q
。 - 我們使用
Annotated
類型為查詢參數(shù)q
添加了元數(shù)據(jù),這些元數(shù)據(jù)包括描述、最小長度和最大長度等。 Annotated
的第一個參數(shù)是類型提示,第二個參數(shù)是與此類型相關(guān)的元數(shù)據(jù)。
Annotated
類型允許你將額外的元數(shù)據(jù)與類型提示關(guān)聯(lián),這在創(chuàng)建API時特別有用,因?yàn)樗梢詭椭筛S富的API文檔并確保參數(shù)驗(yàn)證。
下面是一個更復(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
在這個例子中:
- 我們定義了一個依賴函數(shù)
common_parameters
,它返回一個包含查詢參數(shù)q
的字典。 - 我們使用
Annotated
類型和Depends
將這個依賴項(xiàng)注入到路徑操作函數(shù)read_items
中。 read_items
函數(shù)返回了從依賴函數(shù)中獲取的參數(shù)字典。
這種方法不僅簡化了路徑操作函數(shù)的參數(shù)定義,還使得代碼更具可讀性和可維護(hù)性。
2、Path參數(shù)-路徑參數(shù)
路徑參數(shù)通常用于從 URL 路徑中提取信息。例如,如果你有一個獲取用戶信息的路徑 /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}
在這個示例中,Annotated[int, Path(..., title="The ID of the user to get")]
表示 user_id
是一個整數(shù),并且它是從路徑中提取的參數(shù)。此外,我們還為這個參數(shù)添加了一個標(biāo)題,用于生成 API 文檔。
3、Body參數(shù)-請求體參數(shù)
求體參數(shù)用于處理復(fù)雜的數(shù)據(jù)結(jié)構(gòu),例如 JSON 請求體。你可以使用 Pydantic 模型來定義請求體的結(jié)構(gòu),并使用 Annotated
來進(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}
在這個示例中,Annotated[User, Body(..., title="The user to create")]
表示 user
參數(shù)是一個 User
模型實(shí)例,并且它來自請求體。我們同樣為這個參數(shù)添加了一個標(biāo)題。
有時候我們可以結(jié)合路徑參數(shù)和請求體參數(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}
在這個綜合示例中,路徑參數(shù) user_id
和請求體參數(shù) user
都使用了 Annotated
進(jìn)行注解,以明確它們的來源和意圖,同時為生成的 API 文檔提供了更多的上下文信息。
復(fù)雜的請求體通常包括嵌套的結(jié)構(gòu),可以使用 Pydantic 模型來定義。例如:
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}
在這個例子中,User
模型包含一個嵌套的 Address
列表,這樣你就可以在請求體中處理復(fù)雜的嵌套數(shù)據(jù)結(jié)構(gòu)。
一個結(jié)合路徑參數(shù)、查詢參數(shù)和請求體參數(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
在這個綜合示例中,我們使用了路徑參數(shù) item_id
、查詢參數(shù) q
和請求體參數(shù) item
,并通過 Annotated
對這些參數(shù)進(jìn)行注解,明確它們的來源和約束。
應(yīng)用上面的處理方案,我們在項(xiàng)目中應(yīng)用FastApi構(gòu)建文檔如下所示。
到此這篇關(guān)于Python中FastAPI項(xiàng)目使用 Annotated的參數(shù)設(shè)計(jì)的文章就介紹到這了,更多相關(guān)Python FastAPI使用 Annotated內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 用matplotlib畫以時間日期為x軸的圖像
這篇文章主要介紹了Python 用matplotlib畫以時間日期為x軸的圖像,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08python實(shí)現(xiàn)ROA算子邊緣檢測算法
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)ROA算子邊緣檢測算法,以光學(xué)圖像為例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-04-04基于opencv和pillow實(shí)現(xiàn)人臉識別系統(tǒng)(附demo)
人臉識別就是一個程序能識別給定圖像或視頻中的人臉,本文主要介紹了opencv和pillow實(shí)現(xiàn)人臉識別系統(tǒng),本文不涉及分類器、訓(xùn)練識別器等算法原理,感興趣的可以了解一下2021-11-11Pyspark獲取并處理RDD數(shù)據(jù)代碼實(shí)例
這篇文章主要介紹了Pyspark獲取并處理RDD數(shù)據(jù)代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03python3.4+pycharm 環(huán)境安裝及使用方法
這篇文章主要介紹了python3.4+pycharm 環(huán)境安裝及使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06jupyter notebook如何導(dǎo)出pdf并支持中文
這篇文章主要介紹了jupyter notebook如何導(dǎo)出pdf并支持中文問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06