python data_error ai_generated true

RuntimeError: The request body is already consumed

ID: python/starlette-request-stream-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2025-11-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active
3.11 active

Root Cause

Starlette 请求体流被多次读取或消费

generic

中文

Starlette 请求体流被多次读取或消费

Workarounds

  1. 95% success 一次性消费请求体并缓存
    body = await request.body()
    # 后续使用 body 而非再次读取流
  2. 90% success 使用中间件缓存请求体
    @app.middleware('http')
    async def cache_body(request, call_next):
        if request.method in ['POST', 'PUT']:
            body = await request.body()
            request.state.body = body
        return await call_next(request)

Dead Ends

Common approaches that don't work:

  1. 重新读取已消费的流 90% fail

    流不可重置

  2. 复制请求体到内存 60% fail

    可能消耗大量内存