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
80%Fix Rate
83%Confidence
0Evidence
2024-06-20First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
95% success
Set all headers before returning the response object, e.g., `response.headers['X-Custom'] = 'value'` before returning.
-
90% success
If using streaming, set headers in the initial response object before streaming begins.
Dead Ends
Common approaches that don't work:
-
90% fail
Modifying headers in a `finally` block after the response is sent still raises the error.
-
85% fail
Using a middleware to modify headers after the endpoint has returned doesn't work because the response is already committed.