FastAPI学习-21.response 参数-设置响应Cookies

前言

可以在 路径函数 中定义一个类型为 Response的参数,这样你就可以在这个临时响应对象中设置cookie了。

response 参数

设置cookies

from fastapi import FastAPI, Response

app = FastAPI()


@app.post("/cookie-and-object/")
def create_cookie(response: Response):
    response.set_cookie(key="fakesession", value="fake-cookie-session-value")
    return {"message": "Come to the dark side, we have cookies"}

而且你还可以根据你的需要响应不同的对象,比如常用的 dict,数据库model等。

如果你定义了 response_model,程序会自动根据response_model来过滤和转换你响应的对象。

FastAPI 会使用这个 临时 响应对象去装在这些cookies信息 (同样还有headers和状态码等信息), 最终会将这些信息和通过response_model转化过的数据合并到最终的响应里。

你也可以在depend中定义Response参数,并设置cookie和header。

直接响应 Response

你还可以在直接响应Response时直接创建cookies。

你可以参考Return a Response Directly来创建response

然后设置Cookies,并返回:

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()


@app.post("/cookie/")
def create_cookie():
    content = {"message": "Come to the dark side, we have cookies"}
    response = JSONResponse(content=content)
    response.set_cookie(key="fakesession", value="fake-cookie-session-value")
    return response

需要注意,如果你直接反馈一个response对象,而不是使用Response入参,FastAPI则会直接反馈你封装的response对象。
所以你需要确保你响应数据类型的正确性,如:你可以使用JSONResponse来兼容JSON的场景。
同时,你也应当仅反馈通过response_model过滤过的数据。

posted @   上海-悠悠  阅读(145)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-09-17 node.js 使用教程-2.Gulp 打包构建入门与使用
2021-09-17 python测试开发django-135.CSS如何让左侧浮动(float)元素占满屏幕高度
2021-09-17 python测试开发django-134.CSS页面布局:左侧固定,右侧自适应布局
2020-09-17 pytest文档59-运行未提交git的用例(pytest-picked)
2018-09-17 python笔记28-lxml.etree爬取html内容
2018-09-17 python笔记27-lxml.etree解析html
点击右上角即可分享
微信分享提示