python config_error ai_generated true

AssertionError: Middleware must be added before routes

ID: python/starlette-middleware-order

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-04-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

在 Starlette 中,尝试在路由已定义后添加中间件,导致断言失败。

generic

中文

在 Starlette 中,尝试在路由已定义后添加中间件,导致断言失败。

Workarounds

  1. 90% success
    app = Starlette(routes=routes, middleware=[Middleware(AuthenticationMiddleware)])
  2. 85% success
    app = Starlette()
    app.add_middleware(AuthenticationMiddleware)
    app.router.routes = routes

Dead Ends

Common approaches that don't work:

  1. 70% fail

    虽然能解决,但代码冗余且不优雅。

  2. 80% fail

    中间件功能(如认证)将失效。