検索
ホームページバックエンド開発Python チュートリアルFastAPI: Pydantic を使用してクエリ パラメーターを宣言する方法

これは、FastAPI で最も期待されていた機能の 1 つで、約 3 週間前にリリースされました。少なくとも、Pydantic モデル 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

クエリ文字列を取得したい場合、関数を作成して依存関係として追加する必要はありません。 PaginationQueryString 型のオブジェクトが必要であり、それがクエリ文字列であることを FastAPI に伝えるだけです:

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 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Pythonのハイブリッドアプローチ:コンピレーションと解釈を組み合わせたPythonのハイブリッドアプローチ:コンピレーションと解釈を組み合わせたMay 08, 2025 am 12:16 AM

pythonusesahybridapproach、コンコイリティレーショントビテコードと解釈を組み合わせて、コードコンピレッドフォームと非依存性bytecode.2)

Pythonの「for」と「while」ループの違いを学びますPythonの「for」と「while」ループの違いを学びますMay 08, 2025 am 12:11 AM

keydifferencesは、「for」と「while "loopsare:1)" for "for" loopsareideal forterating overencesonownowiterations、while2) "for" for "for" for "for" for "for" for "for" for for for for "wide" loopsarebetterunuinguntinunuinguntinisisisisisisisisisisisisisisisisisisisisisisisisisisisations.un

重複したPython Concatenateリスト重複したPython ConcatenateリストMay 08, 2025 am 12:09 AM

Pythonでは、さまざまな方法でリストを接続して重複要素を管理できます。1)オペレーターを使用するか、すべての重複要素を保持します。 2)セットに変換してから、リストに戻ってすべての重複要素を削除しますが、元の順序は失われます。 3)ループを使用するか、包含をリストしてセットを組み合わせて重複要素を削除し、元の順序を維持します。

Pythonリスト連結パフォーマンス:速度比較Pythonリスト連結パフォーマンス:速度比較May 08, 2025 am 12:09 AM

fasteStMethodDodforListConcatenationinpythOndontsonistize:1)forsmallLists、operatorisefficient.2)forlargerlists、list.extend()orlistcomlethingisfaster、withextend()beingmorememory-efficient bymodifyigniviselistinistin-place。

Pythonリストに要素をどのように挿入しますか?Pythonリストに要素をどのように挿入しますか?May 08, 2025 am 12:07 AM

to insertelementsIntopeaseThonList、useappend()toaddtotheend、insert()foraspificposition、andextend()formultipleElements.1)useappend()foraddingsingleitemstotheend.2)useintert()toaddataspecificindex、cont'slowerforforgelists.3)

Pythonリストは、フードの下に動的な配列またはリンクリストですか?Pythonリストは、フードの下に動的な配列またはリンクリストですか?May 07, 2025 am 12:16 AM

PythonListsareimplementedasdynamicarrays、notlinkedlists.1)they restorediguourmemoryblocks、それはパフォーマンスに影響を与えることに影響を与えます

Pythonリストから要素をどのように削除しますか?Pythonリストから要素をどのように削除しますか?May 07, 2025 am 12:15 AM

pythonoffersfourmainmethodstoremoveelements fromalist:1)removesthefirstoccurrenceofavalue、2)pop(index(index(index)removes regvess returnsaspecifiedindex、3)delstatementremoveselementselementsbyindexorseLice、および4)clear()

スクリプトを実行しようとするときに「許可を拒否された」エラーを取得した場合、何を確認する必要がありますか?スクリプトを実行しようとするときに「許可を拒否された」エラーを取得した場合、何を確認する必要がありますか?May 07, 2025 am 12:12 AM

toresolvea "許可denided" errors whenrunningascript、sofflowthesesteps:1)checkandadaddadaddadadaddaddadadadaddadaddadaddadaddaddaddaddaddadaddadaddaddaddaddadaddaddaddadadaddadaddadaddadadisionsisingmod xmyscript.shtomakeitexexutable.2)

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン