python runtime_error ai_generated true

RuntimeError: 无法修改头;响应已经开始。

RuntimeError: Cannot modify headers; the response has already started.

ID: python/starlette-immutable-headers

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-12-02首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

中间件在响应体开始流式传输后尝试设置响应头。

English

Middleware attempts to set response headers after the response body has begun streaming.

generic

解决方案

  1. 92% 成功率
    response = await call_next(request)
    response.headers['X-Custom'] = 'v'
    return response
  2. 85% 成功率
    class H(Response):
        def __init__(self, *a, **k):
            super().__init__(*a, **k)
            self.headers['X-Custom'] = 'v'

无效尝试

常见但无效的做法:

  1. 90% 失败

    Headers are already sent before the generator runs.

  2. 80% 失败

    The intended header is silently dropped.