python type_error ai_generated true

TypeError: 'Middleware' object is not callable

ID: python/starlette-middleware-type-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

A middleware class is not instantiated or not used as a callable.

generic

中文

中间件类未实例化或未作为可调用对象使用。

Workarounds

  1. 90% success Instantiate the middleware before adding it to the app.
    from starlette.middleware import Middleware
    middleware = Middleware(SomeMiddleware)
    app.add_middleware(middleware)
  2. 95% success Use the middleware class directly with app.add_middleware.
    app.add_middleware(SomeMiddleware)

Dead Ends

Common approaches that don't work:

  1. Passing the middleware class directly without instantiation. 80% fail

    The middleware must be an instance or a callable; a class is not callable in this context.

  2. Importing the middleware incorrectly from a wrong module. 60% fail

    The imported object may not be a middleware at all.