python runtime_error ai_generated true

RuntimeError: 流已被消费

RuntimeError: Stream consumed

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

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-09-02首次发现

版本兼容性

版本状态引入弃用备注
0.30+ active — — —

根因分析

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

English

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

解决方案

  1. 85% 成功率
    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% 成功率
    raw = await request.body()
    data = json.loads(raw)

无效尝试

常见但无效的做法:

  1. 85% 失败

    Second call returns empty bytes and downstream parsing fails.

  2. 80% 失败

    Race conditions across concurrent requests corrupt data.