首頁  >  文章  >  後端開發  >  FastAPI:如何使用 Pydantic 宣告查詢參數

FastAPI:如何使用 Pydantic 宣告查詢參數

Linda Hamilton
Linda Hamilton原創
2024-10-10 06:11:30760瀏覽

它大約三週前發布,是 FastAPI 最受期待的功能之一。至少當我們談論 Pydantic Models FastAPI 時。

是的,我說的是使用 Pydantic 模型來映射查詢參數的能力。

所以在這篇文章中,我將盡力向您展示一切?可以和?對這個話題無能為力嗎? :

?映射查詢參數

要開始使用 Pydantic 映射查詢參數,您需要做的第一件事是確保您使用的是 FastAPI 版本 0.115.0。

此後,您可以隨時存取 FastAPI 文件來檢查現有的內容。 Sebastián 和團隊成員在保持文件更新和資訊豐富方面做得非常非常出色 ✨。

?一點點歷史

讓我們從一些範例開始,了解如何在 FastAPI 中對應查詢參數。 ?

最簡單的方法是:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def search(
    limit: int | None = 10,
    skip: int | None = 1,
    filter: str | None = None
):
    return {
        "limit": limit,
        "skip": skip,
        "filter": filter
    }

現在您只需撥打:

GET http://localhost:8000/?limit=42&skip=12&filter=banana

但是如果我們確定此查詢參數將在其他路由中使用,我們將使用以下內容將其隔離:

from typing import Any
from fastapi import Depends, FastAPI, Query

app = FastAPI()

async def pagination_query_string(
    limit: int | None = Query(10, ge=5, le=100),
    skip: int | None = Query(1, ge=1),
    filter: str | None = Query(None)
) -> dict[str, Any]:
    return {
        "limit": limit,
        "skip": skip,
        "filter": filter
    }

@app.get("/")
async def search(q: dict[str, Any] = Depends(pagination_query_string)):
    return q

或因為我們使用 Pydantic 來繪製我們的模型,只需一點重構,我們就會得到:

from fastapi import Depends, FastAPI, Query
from pydantic import BaseModel

app = FastAPI()

class PaginationQueryString(BaseModel):
    limit: int | None = 10
    skip: int | None = 1
    filter: str | None = None

async def pagination_query_string(
    limit: int | None = Query(10, ge=5, le=100),
    skip: int | None = Query(1, ge=1),
    filter: str | None = Query(None)
) -> PaginationQueryString:
    return PaginationQueryString(
        limit=limit,
        skip=skip,
        filter=filter
    )

@app.get("/")
async def search(q: PaginationQueryString = Depends(pagination_query_string)):
    return q

⌨️ 使用 Pydantic 映射查詢字串

FastAPI: How to use Pydantic to declare Query Parameters

現在,如果我們想要取得查詢字串,我們不需要建立一個函數,然後將其新增為依賴項。我們可以簡單地告訴 FastAPI 我們想要一個 PaginationQueryString 類型的對象,並且它是一個查詢字串:

from typing import Annotated
from fastapi import FastAPI, Query
from pydantic import BaseModel

app = FastAPI()

class PaginationQueryString(BaseModel):
    limit: int | None = 10
    skip: int | None = 1
    filter: str | None = None

@app.get("/")
async def search(q: Annotated[PaginationQueryString, Query()]):
    return q

簡單吧? ?

⚠️有什麼限制?

至少在 0.115.0 版本中,它不能很好地處理巢狀模型。

讓我們試試看:

from typing import Annotated
from fastapi import FastAPI, Query
from pydantic import BaseModel

app = FastAPI()

class Filter(BaseModel):
    name: str | None = None
    age: int | None = None
    nickname: str | None = None

class PaginationQueryString(BaseModel):
    limit: int | None = 10
    skip: int | None = 1
    filter: Filter | None = None

@app.get("/")
async def search(q: Annotated[PaginationQueryString, Query()]):
    return q

如果我們像以前那樣稱呼它:

GET http://localhost:8000/?limit=42&skip=12&filter=chocolate

我們會收到一個錯誤,告訴我們過濾器是一個物件:

{
    "detail": [
        {
            "type": "model_attributes_type",
            "loc": [
                "query",
                "filter"
            ],
            "msg": "Input should be a valid dictionary or object to extract fields from",
            "input": "chocolate"
        }
    ]
}

至少現在來說,是絕對正確的!我們將過濾器更改為 Pydantic 模型,而不是字串。但如果我們嘗試將其轉換為字典:

http://localhost:8000/?limit=42&skip=12&filter={%22name%22:%20%22Rafael%22,%20%22age%22:%2038,%20%22nickname%22:%20%22ceb10n%22}

FastAPI 會告訴我們過濾器需要是一個有效的字典? :

{
    "detail": [
        {
            "type": "model_attributes_type",
            "loc": [
                "query",
                "filter"
            ],
            "msg": "Input should be a valid dictionary or object to extract fields from",
            "input": "{\"name\": \"Rafael\", \"age\": 38, \"nickname\": \"ceb10n\"}"
        }
    ]
}

發生這種情況是因為 FastAPI 將依賴 Starlette 的 QueryParams,它將向 FastAPI 提供一個字串,而不是一個字典。至少在 0.115.0 版本中,這會給你一個錯誤。

⁉️ 那麼,我什麼時候應該在查詢參數中使用 Pydantic 模型?

很簡單:

✅ 您有簡單的查詢字串,不需要任何複雜的花俏的嵌套物件?使用它! ?

❌ 您建立了一個複雜的巢狀查詢字串?還沒使用它嗎? (也許您應該嘗試重新考慮您的查詢字串。?越簡單越好?)

以上是FastAPI:如何使用 Pydantic 宣告查詢參數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn