FastAPI 教程翻译 - 用户指南 13 - Cookie 参数
FastAPI Tutorial - User Guide - Cookie Parameters
You can define Cookie parameters the same way you define Query
and Path
parameters.
您可以使用定义 Query
和 Path
参数的相同方式来定义 Cookie 参数。
Import Cookie
导入 Cookie
First import Cookie
:
首先导入 Cookie
:
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(*, ads_id: str = Cookie(None)):
return {"ads_id": ads_id}
Declare Cookie
parameters
声明 Cookie
参数
Then declare the cookie parameters using the same structure as with Path
and Query
.
然后使用与 Path
和 Query
相同的结构声明 cookie 参数。
The first value is the default value, you can pass all the extra validation or annotation parameters:
第一个值是默认值,您可以传递所有其他验证或注释参数:
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(*, ads_id: str = Cookie(None)):
return {"ads_id": ads_id}
Technical Details
技术细节
Cookie
is a “sister” class ofPath
andQuery
. It also inherits from the same commonParam
class.
Cookie
是Path
和Query
的『姐妹』类。它也继承自相同的通用Param
类。But remember that when you import
Query
,Path
,Cookie
and others fromfastapi
, those are actually functions that return special classes.但是请记住,当您从
fastapi
中导入Query
、Path
、Cookie
和其他文件时,这些实际上是返回特殊类的函数。
Info
信息
To declare cookies, you need to use
Cookie
, because otherwise the parameters would be interpreted as query parameters.要声明 cookie,您需要使用
Cookie
,否则参数将被解释为查询参数。
Recap
回顾
Declare cookies with Cookie
, using the same common pattern as Query
and Path
.
使用与 Query
和 Path
相同的通用模式,用 Cookie
声明 cookie。