python config_error ai_generated true

AssertionError: ASGI app not mounted on lifespan

ID: python/starlette-assertionerror-app-not-mounted

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Lifespan handler is not properly configured in the Starlette application.

generic

中文

Starlette 应用程序中的生命周期处理程序未正确配置。

Workarounds

  1. 90% success Implement lifespan correctly
    from contextlib import asynccontextmanager
    @asynccontextmanager
    async def lifespan(app):
        # startup
        yield
        # shutdown
    app = Starlette(lifespan=lifespan)
  2. 85% success Use on_startup and on_shutdown directly
    async def startup():
        print('start')
    app.add_event_handler('startup', startup)
    app.add_event_handler('shutdown', lambda: print('stop'))

Dead Ends

Common approaches that don't work:

  1. Adding lifespan without async context manager 80% fail

    Lifespan requires async generator or context manager.

  2. Ignoring lifespan entirely 60% fail

    Some servers require lifespan for startup/shutdown.