python type_error ai_generated true

AttributeError: 'Request' 对象没有属性 'json'

AttributeError: 'Request' object has no attribute 'json'

ID: python/fastapi-attributeerror-starlette-request-json

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

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

在异步处理程序中使用 request.json 而不是 await request.json()。

English

Using request.json directly instead of await request.json() in async handlers.

generic

解决方案

  1. 95% 成功率 Use await request.json()
    @app.post('/data')
    async def handle(request):
        data = await request.json()
        return {'received': data}
  2. 90% 成功率 Use FastAPI's Body dependency
    from fastapi import Body
    @app.post('/data')
    async def handle(data: dict = Body(...)):
        return {'received': data}

无效尝试

常见但无效的做法:

  1. Using request.body() without await 70% 失败

    Similar issue: body is a coroutine.

  2. Importing json module and parsing manually 50% 失败

    Overcomplicates; Starlette provides built-in method.