现在位置: 首页 > Flask 教程 > 正文

Flask Response 响应对象 API

Response 类表示 Flask 视图函数返回的 HTTP 响应。大多数情况下你不需要直接创建它——Flask 会自动将视图函数返回值转换为 Response。

需要手动控制时,使用 make_response() 函数。


构造函数

参数 类型 默认值 说明
response str / bytes / iterator 必填 响应体内容
status int / str 200 HTTP 状态码或状态文本,如 404 或 "404 Not Found"
headers dict / list None 响应头,dict 或 (key, value) 元组列表
mimetype str None MIME 类型,如 "application/json"
content_type str None Content-Type 头,含编码,如 "text/html; charset=utf-8"
direct_passthrough bool False 为 True 时直接传递响应体,不做任何处理

核心属性

属性 类型 说明
status str 响应状态(文本形式),如 "200 OK"、"404 Not Found"
status_code int HTTP 状态码,如 200、404
headers Headers 响应头对象,支持字典式操作
data bytes 响应体的字节表示
mimetype str MIME 类型(不含编码),如 "text/html"
content_type str Content-Type(含编码),如 "text/html; charset=utf-8"
content_length int 响应体字节长度

响应头操作

方法 说明
headers.get(key) 获取指定响应头的值
headers[key] = value 设置响应头
headers.update(dict) 批量更新响应头

Cookie 操作

方法 说明
set_cookie(key, value, max_age, expires, path, domain, secure, httponly, samesite) 设置一个 Cookie。max_age 为秒数,expires 为 datetime,secure 仅 HTTPS
delete_cookie(key, path, domain) 删除指定的 Cookie
set_cookie 参数:max_age Cookie 有效秒数,如 max_age=3600 表示 1 小时
set_cookie 参数:secure 默认为 SESSION_COOKIE_SECURE 配置值,True 时仅 HTTPS 发送
set_cookie 参数:httponly 默认为 True,禁止 JavaScript 访问此 Cookie
set_cookie 参数:samesite "Strict"、"Lax" 或 None,控制跨站 Cookie 发送行为

其他方法

方法 说明
get_json(force=False, silent=False) 将响应体解析为 JSON(主要用于测试)
freeze() 将响应冻结为不可变状态
force_type(response, environ) 类方法,将其他类型的响应强制转为 Response 类型

代码示例

实例

from flask import Flask, make_response

app = Flask(__name__)

@app.route("/custom")
def custom_response():
    # 使用 make_response 手动构建响应
    resp = make_response("<h1>Hello, RUNOOB!</h1>")

    # 设置状态码
    resp.status_code = 201

    # 设置自定义响应头
    resp.headers["X-Custom-Header"] = "my-value"

    # 设置 Cookie
    resp.set_cookie("theme", "dark", max_age=86400)    # 24 小时有效
    resp.set_cookie("lang", "zh-CN", samesite="Lax")   # SameSite 限制

    return resp

@app.route("/delete-cookie")
def delete_cookie():
    resp = make_response("Cookie 已删除")
    resp.delete_cookie("theme")
    return resp

@app.route("/api/data")
def api_data():
    # 直接返回 dict,Flask 自动序列化为 JSON Response
    return {"status": "ok", "data": [1, 2, 3]}