
- FastAPI 教程
- FastAPI - 首页
- FastAPI - 简介
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - 类型提示
- FastAPI - IDE 支持
- FastAPI - REST 架构
- FastAPI - 路径参数
- FastAPI - 查询参数
- FastAPI - 参数验证
- FastAPI - Pydantic
- FastAPI - 请求体
- FastAPI - 模板
- FastAPI - 静态文件
- FastAPI - HTML 表单模板
- FastAPI - 访问表单数据
- FastAPI - 上传文件
- FastAPI - Cookie 参数
- FastAPI - 头部参数
- FastAPI - 响应模型
- FastAPI - 嵌套模型
- FastAPI - 依赖项
- FastAPI - CORS
- FastAPI - CRUD 操作
- FastAPI - SQL 数据库
- FastAPI - 使用 MongoDB
- FastAPI - 使用 GraphQL
- FastAPI - WebSockets
- FastAPI - FastAPI 事件处理器
- FastAPI - 挂载子应用
- FastAPI - 中间件
- FastAPI - 挂载 Flask 应用
- FastAPI - 部署
- FastAPI 有用资源
- FastAPI - 快速指南
- FastAPI - 有用资源
- FastAPI - 讨论
FastAPI - Cookie 参数
Cookie 是 HTTP 头部之一。Web 服务器向客户端发送响应时,除了请求的数据外,还会插入一个或多个 Cookie。Cookie 是存储在客户端机器上的一小部分数据。在来自同一客户端的后续连接请求中,此 Cookie 数据也会与 HTTP 请求一起附加。
Cookie 用于记录有关客户端浏览的信息。Cookie 是一种可靠的方法,可以在 HTTP 协议的无状态通信中检索有状态信息。
在 FastAPI 中,可以使用set_cookie() 方法在响应对象上设置 Cookie 参数。
response.set_cookie(key, value)
示例
这是一个set_cookie() 方法的示例。我们有一个名为 content 的 JSON 响应对象。在其上调用set_cookie() 方法以设置 Cookie 为key="usrname" 和value="admin" -
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.post("/cookie/") def create_cookie(): content = {"message": "cookie set"} response = JSONResponse(content=content) response.set_cookie(key="username", value="admin") return response
要在后续访问中读取 Cookie,请在 FastAPI 库中使用 Cookie 对象。
from fastapi import FastAPI, Cookie app = FastAPI() @app.get("/readcookie/") async def read_cookie(username: str = Cookie(None)): return {"username": username}
在 Swagger API 中检查这两个端点。这两个路由为"/cookies" 和"/readcookie"。执行绑定到 "/cookies" 的create_cookie() 函数。响应只是内容,尽管已设置了 Cookie。

当执行read_cookie() 函数时,Cookie 会被读回并显示为响应。此外,请注意文档将用户名识别为 Cookie 参数。

广告