python runtime_error ai_generated true

RuntimeError: Cannot add middleware after an application has started

ID: python/starlette-staticfiles-mount-order

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100+ active — — —
0.110+ active — — —

Root Cause

app.add_middleware / mount called inside a route handler or after the ASGI app has begun serving requests.

generic

中文

在路由处理程序内部或 ASGI 应用开始处理请求之后调用了 app.add_middleware / mount。

Workarounds

  1. 95% success
    Move app.add_middleware(...) and app.mount(...) to module top-level before uvicorn.run(app).
  2. 80% success
    If dynamic, build a fresh Starlette app per config and swap it in the ASGI server.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Timing issue is runtime, not import order.

  2. 80% fail

    Middleware silently not applied; behavior unchanged.