python
runtime_error
ai_generated
true
AssertionError: Response body already sent
ID: python/fastapi-assertionerror-response-body-already-sent
80%Fix Rate
84%Confidence
0Evidence
2024-09-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Trying to write to a response after it has already been sent to the client (e.g., in middleware or background task).
generic中文
在响应已经发送给客户端后尝试写入响应(例如在中间件或后台任务中)。
Workarounds
-
90% success Set headers before returning the response
response = JSONResponse(content=data, headers={'X-Custom': 'value'}) return response -
85% success Use background tasks to modify response before send
from fastapi import BackgroundTasks background_tasks.add_task(some_func)
Dead Ends
Common approaches that don't work:
-
Adding response headers after returning
80% fail
Response is immutable after being sent.
-
Using yield in streaming response incorrectly
70% fail
Multiple yields after stream ends cause assertion error.