Cookie 参数¶
你可以像定义 Query
和 Path
参数一样定义 Cookie 参数。
导入 Cookie
¶
首先导入 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}
from typing import Annotated, Union
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):
return {"ads_id": ads_id}
from typing import Union
from fastapi import Cookie, FastAPI
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):
return {"ads_id": ads_id}
Tip
如果可能,建议使用 Annotated
版本。
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}
Tip
如果可能,建议使用 Annotated
版本。
from typing import Union
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Union[str, None] = Cookie(default=None)):
return {"ads_id": ads_id}
声明 Cookie
参数¶
然后使用与 Path
和 Query
相同的结构来声明 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}
from typing import Annotated, Union
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):
return {"ads_id": ads_id}
from typing import Union
from fastapi import Cookie, FastAPI
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):
return {"ads_id": ads_id}
Tip
如果可能,建议使用 Annotated
版本。
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}
Tip
如果可能,建议使用 Annotated
版本。
from typing import Union
from fastapi import Cookie, FastAPI
app = 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
等时,这些实际上是返回特殊类的函数。
Info
要声明 Cookie,你需要使用 Cookie
,否则参数将被解释为查询参数。
总结¶
使用 Cookie
声明 Cookie,使用与 Query
和 Path
相同的通用模式。