python
config_error
ai_generated
true
AssertionError: Middleware must be added before routes
ID: python/starlette-middleware-order
80%Fix Rate
84%Confidence
0Evidence
2024-04-18First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
在 Starlette 中,尝试在路由已定义后添加中间件,导致断言失败。
generic中文
在 Starlette 中,尝试在路由已定义后添加中间件,导致断言失败。
Workarounds
-
90% success
app = Starlette(routes=routes, middleware=[Middleware(AuthenticationMiddleware)])
-
85% success
app = Starlette() app.add_middleware(AuthenticationMiddleware) app.router.routes = routes
Dead Ends
Common approaches that don't work:
-
70% fail
虽然能解决,但代码冗余且不优雅。
-
80% fail
中间件功能(如认证)将失效。