跳转至

Cookie 参数

🌐 Translation by AI and humans

This translation was made by AI guided by humans. 🤝

It could have mistakes of misunderstanding the original meaning, or looking unnatural, etc. 🤖

You can improve this translation by helping us guide the AI LLM better.

English version

定义 Cookie 参数与定义 QueryPath 参数一样。

首先,导入 Cookie

from typing import Annotated

from fastapi import Cookie, FastAPI

app = FastAPI()


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

Tip

Prefer to use the Annotated version if possible.

from fastapi import Cookie, FastAPI

app = FastAPI()


@app.get("/items/")
async def read_items(ads_id: str | None = Cookie(default=None)):
    return {"ads_id": ads_id}

声明 Cookie 参数的方式与声明 QueryPath 参数相同。

第一个值是默认值,还可以传递所有验证参数或注释参数:

from typing import Annotated

from fastapi import Cookie, FastAPI

app = FastAPI()


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

Tip

Prefer to use the Annotated version if possible.

from fastapi import Cookie, FastAPI

app = FastAPI()


@app.get("/items/")
async def read_items(ads_id: str | None = Cookie(default=None)):
    return {"ads_id": ads_id}

技术细节

CookiePathQuery兄弟类,都继承自共用的 Param 类。

注意,从 fastapi 导入的 QueryPathCookie 等对象,实际上是返回特殊类的函数。

信息

必须使用 Cookie 声明 cookie 参数,否则该参数会被解释为查询参数。

信息

请注意,由于浏览器会以特殊方式并在幕后处理 cookies,它们不会轻易允许JavaScript访问它们。

如果你前往位于 /docsAPI 文档界面,你可以看到你的路径操作中有关 cookies 的文档

但即使你填写了数据并点击 "Execute",由于文档界面依赖于JavaScript工作,cookies 也不会被发送,你会看到一个错误消息,好像你没有填写任何值一样。

小结

使用 Cookie 声明 cookie 参数的方式与 QueryPath 相同。