Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

怎样设置 FastAPI 响应头和 Cookie,同时保留响应模型?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

在端点加 response: Response,可以写 response.headers,或调用 set_cookie。返回普通数据时,FastAPI 会把这些元数据合入最终的响应,同时照常处理响应模型。

讲清原理

如果直接构造并返回一个 Response,就在那个实例上设头和 Cookie。会话、认证类 Cookie 的 HTTPS、HttpOnly 和 SameSite 策略需按部署配置。

例子与易错点

示例设置一个自定义响应头与显示偏好 Cookie,再返回普通字典。测试同时核对响应内容和 Cookie 标记。

from fastapi import FastAPI, Response
from fastapi.testclient import TestClient
from pydantic import BaseModel

class Display(BaseModel):
    theme: str

app = FastAPI()

@app.get("/display", response_model=Display)
def get_display(response: Response):
    response.headers["X-Detail-Version"] = "v2"
    response.set_cookie("theme", "dark", httponly=True, secure=True, samesite="lax")
    return {"theme": "dark", "internal_note": "server-only"}

with TestClient(app, base_url="https://testserver") as client:
    reply = client.get("/display")
    assert reply.json() == {"theme": "dark"}
    assert reply.headers["X-Detail-Version"] == "v2"
    cookie = reply.headers["set-cookie"].lower()
    assert "httponly" in cookie and "secure" in cookie and "samesite=lax" in cookie
    print(reply.headers["X-Detail-Version"], reply.json()["theme"])

相关题:第 18 题、第 19 题、第 21 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。