跳轉至

Cookie 參數模型

AI coding agents

Use the official FastAPI skill for your installed version. Install it from your project directory:

uvx library-skills

See Develop with AI.

🌐 AI 與人類共同完成的翻譯

此翻譯由人類指導的 AI 完成。🤝

可能會有對原意的誤解,或讀起來不自然等問題。🤖

你可以透過協助我們更好地引導 AI LLM來改進此翻譯。

英文版

如果你有一組彼此相關的「Cookie」,你可以建立一個「Pydantic 模型」來宣告它們。🍪

這樣你就能在多處重複使用該模型,並且能一次性為所有參數宣告驗證與中繼資料。😎

注意

自 FastAPI 版本 0.115.0 起支援。🤓

Tip

同樣的技巧也適用於 Query、Cookie 與 Header。😎

以 Pydantic 模型宣告 Cookie

在 Pydantic 模型中宣告所需的 Cookie 參數,接著將參數宣告為 Cookie:

from typing import Annotated

from fastapi import Cookie, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Cookies(BaseModel):
    session_id: str
    fatebook_tracker: str | None = None
    googall_tracker: str | None = None


@app.get("/items/")
async def read_items(cookies: Annotated[Cookies, Cookie()]):
    return cookies
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import Cookie, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Cookies(BaseModel):
    session_id: str
    fatebook_tracker: str | None = None
    googall_tracker: str | None = None


@app.get("/items/")
async def read_items(cookies: Cookies = Cookie()):
    return cookies

FastAPI 會從請求收到的 Cookie 中擷取 每個欄位 的資料,並交給你定義的 Pydantic 模型。

查看文件

你可以在 /docs 的文件介面中看到已定義的 Cookie:

Note

請注意,由於瀏覽器會以特殊且在背景進行的方式處理 Cookie,因此不會輕易允許 JavaScript 存取它們。

當你前往位於 /docs 的 API 文件介面時,可以看到路徑操作的 Cookie 說明。

但即使你填入資料並點擊「Execute」,因為該文件介面是以 JavaScript 運作,Cookie 不會被送出,你會看到錯誤訊息,就像完全沒有填任何值一樣。

禁止額外的 Cookie

在某些特殊情境(可能不太常見)下,你可能會想限制允許接收的 Cookie。

你的 API 現在也能掌控自己的 Cookie 同意。🤪🍪

你可以使用 Pydantic 的模型設定來 forbid 任何 extra 欄位:

from typing import Annotated

from fastapi import Cookie, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Cookies(BaseModel):
    model_config = {"extra": "forbid"}

    session_id: str
    fatebook_tracker: str | None = None
    googall_tracker: str | None = None


@app.get("/items/")
async def read_items(cookies: Annotated[Cookies, Cookie()]):
    return cookies
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import Cookie, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Cookies(BaseModel):
    model_config = {"extra": "forbid"}

    session_id: str
    fatebook_tracker: str | None = None
    googall_tracker: str | None = None


@app.get("/items/")
async def read_items(cookies: Cookies = Cookie()):
    return cookies

如果客戶端嘗試送出額外的 Cookie,會收到錯誤回應。

可憐的 Cookie 橫幅辛苦收集你的同意,最後卻是為了讓 API 拒絕它。🍪

例如,若客戶端嘗試送出名為 santa_tracker、值為 good-list-please 的 Cookie,客戶端會收到錯誤回應,告知 santa_tracker 這個 Cookie 不被允許:

{
    "detail": [
        {
            "type": "extra_forbidden",
            "loc": ["cookie", "santa_tracker"],
            "msg": "Extra inputs are not permitted",
            "input": "good-list-please",
        }
    ]
}

組合參數模型

你可以將多個 Cookie 參數模型與個別的 Cookie 參數及依賴項目組合使用。每個模型都會獨立擷取資料並進行驗證,如查詢參數模型中所述。

每個模型的 extra 設定都會套用到所有 Cookie 參數,包括在其他模型或依賴項目中宣告的參數。使用 extra="forbid" 時,任何不屬於該模型的 Cookie 都會被拒絕。使用 extra="allow" 時,這些 Cookie 會作為模型的額外欄位納入。

宣告 Cookie 參數模型時,使用 | None 並將預設值設為 None,即可讓整組參數變成可選。

from typing import Annotated

from fastapi import Cookie, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Preferences(BaseModel):
    theme: str
    locale: str


@app.get("/items/")
async def read_items(preferences: Annotated[Preferences | None, Cookie()] = None):
    return preferences
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import Cookie, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Preferences(BaseModel):
    theme: str
    locale: str


@app.get("/items/")
async def read_items(preferences: Preferences | None = Cookie(default=None)):
    return preferences

如果 theme 和 locale 都未送出,preferences 就是 None。如果送出了其中任一個,FastAPI 就會驗證模型,並要求提供這兩個欄位。

預設值、額外欄位與 OpenAPI 的規則,與可選的查詢參數模型相同。

摘要

你可以在 FastAPI 中使用 Pydantic 模型來宣告 Cookie。😎