Fastapi: [BUG][DOCUMENTATION] Sub application startup event never triggered

Created on 22 Dec 2019  路  7Comments  路  Source: tiangolo/fastapi

Describe the bug

Startup event handlers for sub-applications never trigger.

To Reproduce

from fastapi import FastAPI


sub_app = FastAPI(openapi_prefix="/subapp")


@sub_app.on_event("startup")
async def sub_app_startup():
    print("++++ Sub-app startup event")  # Never fires


app = FastAPI()


@app.on_event("startup")
async def app_startup():
    print("++++ App startup event")


app.mount("/subapp", sub_app)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, port=8000, host="0.0.0.0")  # nosec

Running the above shows:

$ python subapp_events.py
INFO:     Started server process [38462]
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     Waiting for application startup.
++++ App startup event
INFO:     Application startup complete.

Notice that sub_app_startup() is never run.

Expected behavior

I would expect the sub-application startup event handler to also run (although I am not sure what ordering I would expect).

Environment

  • OS: macOS
  • FastAPI Version: 0.45.0
  • Python version: 3.7.5

Additional context

N/A

answered bug confirmed docs good first issue

All 7 comments

Digging in to this a bit more, I can see that FastAPI merely exposes the Starlette lifecycle events and doesn't do anything special about them.

In addition, this issue has been raised previously against Starlette.

Since it's deemed out-of-scope by Starlette developers, I think the only action here would be to document this in the FastAPI docs i.e. call out explicitly that sub-application event handlers are ignored.

I also think it would be good to document this.

PR welcome!

Thanks for the investigation and for reporting back @jonathanunderwood , yep, it makes sense to have it documented.

I found this issue this days, so what should I do to trigger subapp's start_up callbacks?
It seems that fastapi.APIRouter's on_startup param has a similar feature.

@ClericPy it would have to be implemented in Starlette: https://github.com/encode/starlette/issues/649

This was documented in https://github.com/tiangolo/fastapi/pull/1554 by @amacfie :rocket:

Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.

Was this page helpful?
0 / 5 - 0 ratings