python runtime_error ai_generated true

AssertionError: Response body already sent

ID: python/fastapi-assertionerror-response-body-already-sent

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-09-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  1. 90% success Set headers before returning the response
    response = JSONResponse(content=data, headers={'X-Custom': 'value'})
    return response
  2. 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:

  1. Adding response headers after returning 80% fail

    Response is immutable after being sent.

  2. Using yield in streaming response incorrectly 70% fail

    Multiple yields after stream ends cause assertion error.