python runtime_error ai_generated true

RuntimeError: Stream consumed

ID: python/starlette-request-body-already-read

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.30+ active — — —

Root Cause

Middleware read the request body with await request.body() or request.stream(), then the route tried to read it again; the ASGI receive stream is one-shot.

generic

中文

中间件使用 await request.body() 或 request.stream() 读取了请求正文,然后路由再次尝试读取;ASGI 接收流是一次性的。

Workarounds

  1. 85% success
    async def dispatch(self, request, call_next):
        body = await request.body()
        async def receive():
            return {'type':'http.request','body':body}
        request._receive = receive
        return await call_next(request)
  2. 90% success
    raw = await request.body()
    data = json.loads(raw)

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Second call returns empty bytes and downstream parsing fails.

  2. 80% fail

    Race conditions across concurrent requests corrupt data.