bigywater.tech
Flask · 12

make_response() 的响应转换过程

视图函数返回一个字符串、字典、元组或者什么都不返回,Flask 分别怎么处理?这篇把常见返回值和非法返回值都跑一遍。

3
元组返回值的合法形态数:(body, status)、(body, headers)、(body, status, headers)
dict / list
会被自动转成 application/json 的返回值类型
5
触发 500 的非法返回值种类(dataclass、None、int、4 元素元组、set)

返回值与响应

实测 · 本机执行输出
  返回值                        状态                     Content-Type                     正文
  str                        200 OK                 text/html; charset=utf-8         hello
  bytes                      200 OK                 text/html; charset=utf-8         raw bytes
  dict                       200 OK                 application/json                 {"a":1,"b":[1,2]}\n
  list                       200 OK                 application/json                 [1,2,{"k":"v"}]\n
  (body, 201)                201 CREATED            text/html; charset=utf-8         created
  (body, headers)            200 OK                 text/html; charset=utf-8         h
  (body, 202, headers)       202 ACCEPTED           text/html; charset=utf-8         both
  (body, "404 自定义")          404 自定义短语              text/html; charset=utf-8         nf
  generator                  200 OK                 text/html; charset=utf-8         abc
  Response                   200 OK                 text/plain; charset=utf-8        resp
  dict + status              201 CREATED            application/json                 {"ok":true}\n
  dataclass                  500 INTERNAL SERVER ERROR text/html; charset=utf-8         <!doctype html>\n<html lang=en>\n<title>500 
  None                       500 INTERNAL SERVER ERROR text/html; charset=utf-8         <!doctype html>\n<html lang=en>\n<title>500 
  int                        500 INTERNAL SERVER ERROR text/html; charset=utf-8         <!doctype html>\n<html lang=en>\n<title>500 
  tuple 长度 4                 500 INTERNAL SERVER ERROR text/html; charset=utf-8         <!doctype html>\n<html lang=en>\n<title>500 
  set                        500 INTERNAL SERVER ERROR text/html; charset=utf-8         <!doctype html>\n<html lang=en>\n<title>500 

上一篇:abort() 如何生成错误响应;下一篇:WSGI Callable 的真实结构。

非法返回值

实测 · 本机执行输出
  None: TypeError: The view function for None did not return a valid response. The function either returned None or ended without a return statement.
  int: TypeError: The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a int.
  tuple 长度 4: TypeError: The view function did not return a valid response tuple. The tuple must have the form (body, status, headers), (body, status), or (body, headers).
  set: TypeError: The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a set.
  dataclass: TypeError: The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a P.

app.make_response

实测 · 本机执行输出
  app.make_response(("hi", 201, {"X-A": "1"})) → Response 201 CREATED {'X-A': '1', 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': '2'}
  app.make_response({"k": "v"}) → application/json {"k":"v"}
  手动设置 → Set-Cookie: sid=abc; HttpOnly; Path=/ | X-C: 3

Content-Length 与流式

实测 · 本机执行输出
  str        Content-Length = 5 | Transfer-Encoding = None
  generator  Content-Length = None | Transfer-Encoding = None

response_class

实测 · 本机执行输出
  GET /     → 200 OK X-Powered-By = lab | 类型 WrapperTestResponse
  GET /j    → 200 OK X-Powered-By = lab | 类型 WrapperTestResponse
  GET /nope → 404 NOT FOUND X-Powered-By = lab | 类型 WrapperTestResponse

分步演示

返回值转换
本步的对象

    本文用到的工具与边界

    • 本机 macOS 27 arm64 / Python 3.14.7 / Flask 3.1.3 / Werkzeug 3.1.9 / Jinja2 3.1.6 / SQLAlchemy 2.1.1 / gunicorn 26.2.0(都装在自己的虚拟环境里);大多数实验用 Flask 的 test_client(直接调用 WSGI 应用,不经过网络),需要真实 HTTP 时另起 gunicorn 或开发服务器(端口 9600 以上,本机 127.0.0.1);计时用 time.perf_counter,数字每次运行会有小幅抖动
    • 没有验证:Transfer-Encoding: chunked 是否在真实服务器上发送(见第 42 篇)、返回 async 生成器、返回 Pydantic 对象或 Decimal、自定义 JSON provider 对返回 dict 的影响(见第 40 篇)
    京ICP备2026067502号-1京公网安备11010502063487号