定义 Cookie 参数与定义 Query 和 Path 参数一样。
导入 Cookie
首先,导入 Cookie:
Python 3.10+ Python 3.9+ Python 3.8+Python 3.10+ non-Annotated Python 3.8+ non-Annotated
from typing import Annotatedfrom fastapi import Cookie, FastAPIapp = FastAPI()@app.get("/items/")async def read_items(ads_id: Annotated[str | None, Cookie()] = None):return {"ads_id": ads_id}
from typing import Annotated, Unionfrom fastapi import Cookie, FastAPIapp = FastAPI()@app.get("/items/")async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):return {"ads_id": ads_id}
from typing import Unionfrom fastapi import Cookie, FastAPI from typing_extensions import Annotatedapp = FastAPI()@app.get("/items/")async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):return {"ads_id": ads_id}
尽可能选择使用
Annotated的版本。
from fastapi import Cookie, FastAPIapp = FastAPI()@app.get("/items/")async def read_items(ads_id: str | None = Cookie(default=None)):return {"ads_id": ads_id}
尽可能选择使用
Annotated的版本。
from typing import Unionfrom fastapi import Cookie, FastAPIapp = FastAPI()@app.get("/items/")async def read_items(ads_id: Union[str, None] = Cookie(default=None)):return {"ads_id": ads_id}
声明 Cookie 参数
声明 Cookie 参数的方式与声明 Query 和 Path 参数相同。
第一个值是默认值,还可以传递所有验证参数或注释参数:
Python 3.10+Python 3.9+Python 3.8+Python 3.10+ non-AnnotatedPython 3.8+ non-Annotated
from typing import Annotatedfrom fastapi import Cookie, FastAPIapp = FastAPI()@app.get("/items/")async def read_items(ads_id: Annotated[str | None, Cookie()] = None):return {"ads_id": ads_id}
from typing import Annotated, Unionfrom fastapi import Cookie, FastAPIapp = FastAPI()@app.get("/items/")async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):return {"ads_id": ads_id}
from typing import Unionfrom fastapi import Cookie, FastAPIfrom typing_extensions import Annotatedapp = FastAPI()@app.get("/items/")async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):return {"ads_id": ads_id}
尽可能选择使用
Annotated的版本。
from fastapi import Cookie, FastAPIapp = FastAPI()@app.get("/items/")async def read_items(ads_id: str | None = Cookie(default=None)):return {"ads_id": ads_id}
尽可能选择使用
Annotated的版本。
from typing import Unionfrom fastapi import Cookie, FastAPIapp = FastAPI()@app.get("/items/")async def read_items(ads_id: Union[str, None] = Cookie(default=None)):return {"ads_id": ads_id}
技术细节
Cookie 、Path 、Query 是兄弟类,都继承自共用的 Param 类。
注意,从 fastapi 导入的 Query、Path、Cookie 等对象,实际上是返回特殊类的函数。
说明
必须使用 Cookie 声明 cookie 参数,否则该参数会被解释为查询参数。
小结
使用 Cookie 声明 cookie 参数的方式与 Query 和 Path 相同。
