python
runtime_error
ai_generated
true
断言错误:响应体已发送
AssertionError: Response body already sent
ID: python/fastapi-assertionerror-response-body-already-sent
80%修复率
84%置信度
0证据数
2024-09-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
在响应已经发送给客户端后尝试写入响应(例如在中间件或后台任务中)。
English
Trying to write to a response after it has already been sent to the client (e.g., in middleware or background task).
解决方案
-
90% 成功率 Set headers before returning the response
response = JSONResponse(content=data, headers={'X-Custom': 'value'}) return response -
85% 成功率 Use background tasks to modify response before send
from fastapi import BackgroundTasks background_tasks.add_task(some_func)
无效尝试
常见但无效的做法:
-
Adding response headers after returning
80% 失败
Response is immutable after being sent.
-
Using yield in streaming response incorrectly
70% 失败
Multiple yields after stream ends cause assertion error.