FastAPI 教程翻译 - 用户指南 13 - Cookie 参数

本文详细介绍了如何在FastAPI框架中使用Cookie参数,包括导入Cookie模块、声明Cookie参数的方法,以及与Query和Path参数的相似之处。通过实例展示了Cookie参数的使用场景和技术细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FastAPI 教程翻译 - 用户指南 13 - Cookie 参数

FastAPI Tutorial - User Guide - Cookie Parameters

You can define Cookie parameters the same way you define Query and Path parameters.

您可以使用定义 QueryPath 参数的相同方式来定义 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.

然后使用与 PathQuery 相同的结构声明 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 of Path and Query. It also inherits from the same common Param class.

CookiePathQuery 的『姐妹』类。它也继承自相同的通用 Param 类。

But remember that when you import Query, Path, Cookie and others from fastapi, those are actually functions that return special classes.

但是请记住,当您从 fastapi 中导入 QueryPathCookie 和其他文件时,这些实际上是返回特殊类的函数。

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.

使用与 QueryPath 相同的通用模式,用 Cookie 声明 cookie。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值