Skip to content

请求与响应的处理

视图函数的输入是 request,输出会被转成 Response。中间这层看起来简单,实际藏着不少坑:get_json() 报 415、MAX_CONTENT_LENGTH 不设就被大 body 撑爆、g 在子线程里丢失、jsonify 把 datetime 变成 [object Object] 之类。这篇按"进"和"出"两条线索把它讲完。

一、request 对象:它不是一个全局变量

python
from flask import request

@app.route("/search")
def search():
    q = request.args.get("q", "")
    page = request.args.get("page", 1, type=int)
    return {"q": q, "page": page}

request 是 LocalProxy 对象,每次访问它时动态从当前请求的上下文栈里取出真实的 Request。所以:

  • 多线程/多协程里互不干扰(依赖 contextvars,Python 3.7+ 实现)
  • 脱离请求上下文访问会报 RuntimeError: Working outside of request context
  • 它不能被 pickled 或跨线程传递

底层是这样取的:

python
def _lookup_req_object(name):
    top = _request_ctx_stack.top
    if top is None:
        raise RuntimeError(_request_ctx_err_msg)
    return getattr(top, name)

request = LocalProxy(partial(_lookup_req_object, "request"))

1.1 request 的常用字段

属性类型说明
request.methodstrGET / POST / ...
request.path / full_pathstr/a 与 /a?x=1
request.argsMultiDict查询串,get(key, default, type=)
request.formMultiDict表单 body(application/x-www-form-urlencoded、multipart/form-data)
request.valuesCombinedMultiDictargs + form 合并,先 args 后 form
request.json / get_json()dictJSON body,见第二节
request.databytes无法解析成 form/json 时的原始 body
request.filesMultiDict上传文件,FileStorage 对象
request.headersEnvironHeaders大小写不敏感
request.cookiesdict所有 cookie
request.remote_addrstr客户端 IP(有代理时见部署篇 ProxyFix)
request.user_agentUserAgent.platform / .browser / .version
request.is_json / is_xhr(已移除)bool内容类型判断

MultiDict 是 Werkzeug 提供的结构,同一个 key 可以出现多次:

python
# /tags?tag=a&tag=b
request.args.get("tag")      # "a"   只取第一个
request.args.getlist("tag")  # ["a", "b"]

二、拿 JSON:get_json() 的正确姿势

python
@app.post("/api/orders")
def create_order():
    data = request.get_json(silent=True) or {}
    amount = data.get("amount")
    if amount is None or amount <= 0:
        return {"error": "amount 非法"}, 400
    return {"id": 1}, 201

2.1 415 的根因

get_json() 默认 force=False:只有当 Content-Type 是 application/json 才会解析,否则返回 None(Flask 2.1 起是抛 415 Unsupported Media Type)。

python
# 客户端忘带 Content-Type 时 ↓
# 415 Unsupported Media Type: Did not attempt to load JSON data because
# the request Content-Type was not 'application/json'.

三种应对:

python
data = request.get_json(silent=True)              # 解析失败/类型不对返回 None
data = request.get_json(force=True)               # 无视 Content-Type 强行解析
data = request.get_json(silent=True, cache=True)  # 缓存结果,避免多次调用重复解析

cache=True 在有多个装饰器都要读 body 的场景能省事,默认是 True;显式写 False 反而可能让同一请求解析两遍。

2.2 MAX_CONTENT_LENGTH 不设等于裸奔

python
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024   # 16MB

不设置这个值时,客户端可以一直往 body 里写,直到把内存吃光。超过限制后 Werkzeug 抛 413 Request Entity Too Large,Python 侧会表现为 RequestEntityTooLarge,并且 request.files / get_json() 拿不到任何数据——因为它直接拒绝解析。要在 nginx 侧同步设 client_max_body_size,否则请求到了 Python 层才被拒,白白消耗连接。

2.3 HTML 表单 vs JSON body

python
@app.post("/login")
def login():
    # 同时支持两种提交方式
    if request.is_json:
        body = request.get_json(silent=True) or {}
        username = body.get("username")
    else:
        username = request.form.get("username")

三、响应:Flask 接受哪些返回值

视图函数返回值会经过 app.make_response(),它接受:

返回值形态处理
str / bytes包成 Response,Content-Type text/html
dict / listFlask 1.1+ 自动转 JSON,application/json
(body, status)status 可以是 int 或 str
(body, status, headers)headers 是 dict / list of tuple
Response 实例直接用
WSGI callable直接作为 application
python
@app.route("/a")
def a():
    return {"ok": True}                       # JSON

@app.route("/b")
def b():
    return "created", 201

@app.route("/c")
def c():
    return {"ok": True}, 201, {"X-Token": "abc"}

@app.route("/d")
def d():
    return Response("raw", mimetype="text/plain")

返回 tuple 时 Flask 会识别出 (rv, status, headers);返回两个元素的 tuple 且第二个是 int 才被当成 status,返回 ("a", "b") 这种就是纯 body。

四、jsonify:中文、datetime、排序

4.1 中文变 \uXXXX 的问题

Flask 2.3 起 JSON 行为改由 app.json 提供者控制:

python
app.json.ensure_ascii = False      # 输出真·中文而非 unicode 转义
app.json.sort_keys = False         # 保持插入顺序
app.json.compact = True            # 去掉多余空白

或者直接换实现,比如上 orjson:

python
from flask.json.provider import DefaultJSONProvider
import orjson, datetime

class OrjsonProvider(DefaultJSONProvider):
    @staticmethod
    def default(o):
        if isinstance(o, datetime.datetime):
            return o.isoformat()
        if isinstance(o, set):
            return list(o)
        raise TypeError(type(o))

    def dumps(self, obj, **kwargs):
        return orjson.dumps(obj, default=self.default).decode()

    def loads(self, s, **kwargs):
        return orjson.loads(s)

app.json = OrjsonProvider(app)

4.2 datetime 序列化

默认的 DefaultJSONProvider 只处理了 datetime → http-date 字符串,而不是 ISO8601:

python
>>> jsonify({"t": datetime.datetime(2026, 1, 1)})
# {"t": "Thu, 01 Jan 2026 00:00:00 GMT"}

想要 ISO 格式或 Unix 时间戳,就自己写 provider(如上),或 ORM 层用 marshmallow 的字段格式。

4.3 jsonify vs json.dumps vs 返回 dict

三者的 Content-Type 是一致的 application/json,差别在:

写法场景
return {"a": 1}简单场景,走同上 app.json 配置
jsonify(**data)需要声明式写法,老代码风格
app.json.response(data)想带上自定义 provider 的所有 options

不要在视图里用 json.dumps 手动包 Response——会漏掉 mimetype,还要自己处理 ensure_ascii。

python
from flask import make_response

@app.route("/avatar")
def avatar():
    resp = make_response(render_template("avatar.html"))
    resp.headers["Cache-Control"] = "private, max-age=3600"
    resp.set_cookie("theme", "dark", max_age=30 * 86400,
                    httponly=True, samesite="Lax", secure=True)
    resp.delete_cookie("old_token")
    return resp

set_cookie 的关键参数:

参数作用建议
max_age / expires生命周期不设就是会话 cookie,关浏览器即失效
httponly禁止 JS 读凡是 token / session 一律打开
secure仅 HTTPS 传输生产打开,本地会失效
samesite防 CSRFLax 或 Strict
domain / path作用域多子域共享时才设

注意 set_cookie 每次调用都会在响应头追加一行 Set-Cookie,同一个 key 设两次会以最后一次为准(客户端按覆盖处理)。

六、流式响应

大文件下载、SSE、LLM 打字机效果都要流式。核心是生成器 + stream_with_context:

python
from flask import Response, stream_with_context, request

@app.route("/download/big")
def download_big():
    def generate():
        # 注意:生成器执行时请求上下文已 pop,必须用 stream_with_context 保留
        user = current_user.id
        with open(f"/data/{user}/report.csv", "rb") as f:
            for chunk in iter(lambda: f.read(8192), b""):
                yield chunk

    return Response(
        stream_with_context(generate()),
        mimetype="text/csv",
        headers={"Content-Disposition": "attachment; filename=report.csv"},
    )

不用 stream_with_context 时生成器里访问 request / current_user 会挂:

RuntimeError: Working outside of request context.

SSE(Server-Sent Events)写法:

python
@app.route("/events")
def events():
    def stream():
        q = Queue()
        bus.subscribe(q)
        try:
            while True:
                item = q.get()
                yield f"data: {json.dumps(item)}\n\n"
        finally:
            bus.unsubscribe(q)

    return Response(stream_with_context(stream()),
                    mimetype="text/event-stream",
                    headers={"Cache-Control": "no-cache",
                             "X-Accel-Buffering": "no"})  # 关掉 nginx 缓冲

X-Accel-Buffering: no 是让 nginx 不要攒 buffer,否则 SSE 会被延迟到 4KB 才吐一次。Gunicorn 下响应体的分块也依赖这个 header 之外还需要 --worker-class gevent 才能真正并发推送,普通 sync worker 会阻塞整进程。

七、after_this_request:延迟请求回调

想在响应生成之后、返回客户端之前做点事(比如写入审计日志、清理临时文件):

python
from flask import g, after_this_request

@app.post("/upload")
def upload():
    tmp = save_to_tmp(request.files["file"])
    key = storage.put(tmp)

    @after_this_request
    def cleanup(response):
        os.remove(tmp)                     # 响应已生成,删掉临时文件
        audit_log(action="upload", key=key, status=response.status_code)
        return response                    # 必须返回 response

    return {"key": key}, 201

多个 @after_this_request 按注册顺序倒序执行(后注册的先执行),返回值必须是一个 Response,忘了 return response 会导致:

TypeError: The view function did not return a valid response.

它的原理是把回调塞进 g._after_request_functions,在 app.process_response 阶段执行。

八、g / current_app / session:请求内的三个容器

对象生命周期存什么
g单次请求当前用户、数据库连接、request_id
current_app应用上下文,可被 push 多次app.config、注册的扩展
session跨请求(cookie 载体)用户 ID、闪现消息

g 的典型用法就是 before_request 里解析用户,视图里直接用:

python
@app.before_request
def load_user():
    token = request.cookies.get("sid")
    g.user = User.verify_token(token) if token else None
    g.request_id = request.headers.get("X-Request-ID") or uuid4().hex

@app.route("/me")
@login_required
def me():
    return {"user": g.user.to_dict()}

g 在子线程里是空的。如果你用 ThreadPoolExecutor 做并行处理,必须把需要的数据显式当参数传进去:

python
# 错误:子线程里 g 为空
future = pool.submit(lambda: do_work(g.user.id))

# 正确:值传递
uid = g.user.id
future = pool.submit(do_work, uid)

九、CSR 场景下前后端怎么传数据

现代前端 SPA 通常用 fetch 直接调 API:

javascript
async function createPost(payload) {
  const resp = await fetch("/api/posts", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-CSRFToken": window.csrfToken,   // Flask-WTF 场景
    },
    credentials: "same-origin",          // 带 cookie,session 认证必须的
    body: JSON.stringify(payload),
  });
  if (!resp.ok) {
    const err = await resp.json().catch(() => ({}));
    throw new Error(err.message ?? resp.statusText);
  }
  return resp.json();
}

服务端对应的两个注意点:

  1. credentials: "same-origin" 才能让 cookie 里的 session 生效,跨域时要在 Flask-CORS 里显式 supports_credentials=True,并且 origins 不能写 *
  2. 统一错误结构,别一会儿返回纯文本一会儿返回 JSON
python
@app.errorhandler(400)
def bad_request(e):
    return {"error": "bad_request", "message": str(e)}, 400

如果是传统的服务器端渲染 + 少量局部更新(Jinja 渲染 + fetch 拿片段),最省事的做法是返回一个 HTML 片段而非 JSON:

python
@app.get("/posts/<int:pid>/comments")
def comments(pid):
    items = Comment.query.filter_by(post_id=pid).all()
    return render_template("_comments.html", comments=items)

十、请求响应层的坑清单

坑现象解决
request.get_json() 返回 None 或 415客户端没带 Content-Type: application/json前端补 header,或用 force=True
413 且拿不到任何数据超过 MAX_CONTENT_LENGTH调大配置 + nginx client_max_body_size
request.form 是空的发的是 JSON body 却读 form用 request.get_json()
生成器里 request 报 RuntimeError流响应没有上下文stream_with_context
jsonify 中文是 \uXXXXensure_ascii 默认 Trueapp.json.ensure_ascii = False
datetime 不是 ISO默认 provider 用 HTTP date自定义 provider 或 marshmallow
子线程里 g 为空g 绑定请求上下文显式传值
after_this_request 报 TypeError回调忘了 return response回调末尾返回 response
SaaS 场景 CORS 失效origins="*" 配了凭证指定具体 origin

请求和响应这一层打顺了,剩下的就是模板渲染怎么把这些数据摆到页面上——那是下一篇的内容。

CTO Plus技术栈 Version 1.0.20261024-12