python runtime_error ai_generated true

RuntimeError: Request body is not available after the request has been consumed

ID: python/starlette-request-body-unavailable

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

在 Starlette 中多次读取请求体,例如在中间件和端点中,但流只能读一次。

generic

中文

在 Starlette 中多次读取请求体,例如在中间件和端点中,但流只能读一次。

Workarounds

  1. 85% success
    body = await request.body(); request._body = body 然后后续使用 request._body
  2. 95% success
    确保只调用一次 await request.json() 或 body()

Dead Ends

Common approaches that don't work:

  1. 100% fail

    流已被读取,第二次调用会报错。

  2. 80% fail

    会导致并发问题。