python type_error ai_generated true

类型错误:协程对象不可调用

TypeError: 'coroutine' object is not callable

ID: python/fastapi-middleware-missing-await

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

版本兼容性

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

根因分析

FastAPI中间件函数定义为异步,但在调用下一个中间件或请求处理器时未使用await。

English

FastAPI middleware function is defined as async but not awaited when calling the next middleware or request handler.

generic

解决方案

  1. 95% 成功率 Ensure middleware function uses await when calling call_next
    @app.middleware('http')
    async def add_process_time_header(request: Request, call_next):
        response = await call_next(request)
        return response
  2. 70% 成功率 Use synchronous middleware with proper decorator
    @app.middleware('http')
    def sync_middleware(request: Request, call_next):
        response = call_next(request)
        return response

无效尝试

常见但无效的做法:

  1. Adding @app.middleware('http') without async def 80% 失败

    FastAPI expects an async function for middleware; synchronous functions cause different errors.

  2. Removing async keyword from middleware function 75% 失败

    Middleware becomes synchronous but FastAPI still treats it as async, leading to runtime issues.