python runtime_error ai_generated true

RuntimeError: Response headers cannot be modified after the response has started

ID: python/starlette-response-headers-set-after-start

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2024-06-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Trying to set or modify response headers after the response has already been sent to the client (e.g., in a background task or after yielding in a streaming response).

generic

中文

在响应已发送给客户端后尝试设置或修改响应头(如在后台任务或流式响应中yield之后)。

Workarounds

  1. 95% success
    Set all headers before returning the response object, e.g., `response.headers['X-Custom'] = 'value'` before returning.
  2. 90% success
    If using streaming, set headers in the initial response object before streaming begins.

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Modifying headers in a `finally` block after the response is sent still raises the error.

  2. 85% fail

    Using a middleware to modify headers after the endpoint has returned doesn't work because the response is already committed.