python runtime_error ai_generated true

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

ID: python/starlette-immutable-headers

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-12-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Headers are already sent before the generator runs.

  2. 80% fail

    The intended header is silently dropped.