Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sub application startup event never triggered #811

Closed
jonathanunderwood opened this issue Dec 22, 2019 · 12 comments
Closed

Sub application startup event never triggered #811

jonathanunderwood opened this issue Dec 22, 2019 · 12 comments
Labels
answered bug Something isn't working confirmed docs Documentation about how to use FastAPI good first issue Good for newcomers reviewed

Comments

@jonathanunderwood
Copy link
Contributor

jonathanunderwood commented Dec 22, 2019

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

@jonathanunderwood jonathanunderwood added the bug Something isn't working label Dec 22, 2019
@jonathanunderwood
Copy link
Contributor Author

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.

@jonathanunderwood jonathanunderwood changed the title [BUG] Sub application startup event never triggered [BUG][DOCUMENTATION] Sub application startup event never triggered Dec 23, 2019
@dmontagu
Copy link
Collaborator

I also think it would be good to document this.

PR welcome!

@tiangolo
Copy link
Member

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

@tiangolo tiangolo added docs Documentation about how to use FastAPI good first issue Good for newcomers labels Feb 12, 2020
@ClericPy
Copy link

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.

@tiangolo
Copy link
Member

@ClericPy it would have to be implemented in Starlette: encode/starlette#649

@tiangolo
Copy link
Member

This was documented in #1554 by @amacfie 🚀

@github-actions
Copy link
Contributor

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

@jonathanunderwood
Copy link
Contributor Author

As an update, looks like there's activity upstream in Starlette to bring this capability in: encode/starlette#1988

@devamin
Copy link

devamin commented Feb 18, 2023

some updates about this feature, sometimes it is required specially when dealing with non-fastapi ASGI apps like socketio one https://github.com/miguelgrinberg/python-socketio/blob/main/src/socketio/asgi.py

@tiangolo tiangolo changed the title [BUG][DOCUMENTATION] Sub application startup event never triggered [DOCUMENTATION] Sub application startup event never triggered Feb 24, 2023
@tiangolo tiangolo changed the title [DOCUMENTATION] Sub application startup event never triggered Sub application startup event never triggered Feb 24, 2023
@OmegAshEnr01n
Copy link

Yes, But there is an easy work around for this for now.
Make a function that is responsible for the start up event for your sub app and call it in the main app startup function.

# Main app
@app.on_event("startup")
def spawn_children():
    model_sub_app.startup_function()

# Sub app
def startup_function():
    # Load model
    pass

I find this super useful for certain cases. For example if I am making an app which has one AI model loaded on each router I wouldnt be able to add features to them like socketio. So for now it appears that having a fastapi instance for such use cases and mounting it is ideal. Paired with the above mentioned startup function hack and its doable...

@dhilst
Copy link

dhilst commented Jun 27, 2023

What I did was to create a function to mount my application and register my event handlers in the parent app

def mount_app(parent_app: FastAPI, path: str) -> None:
    parent_app.on_event("startup")(app_startup)
    parent_app.on_event("shutdown")(app_shutdown)
    parent_app.mount(path, app)

@unights
Copy link

unights commented Dec 27, 2023

I did something similar. Provide a reference for others.

from contextlib import AsyncExitStack, asynccontextmanager

from fastapi import FastAPI
from starlette.routing import Mount


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with AsyncExitStack() as stack:
        for route in app.routes:
            if isinstance(route, Mount) and isinstance(route.app, FastAPI):
                await stack.enter_async_context(
                    route.app.router.lifespan_context(route.app),  # noqa
                )
        yield

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
answered bug Something isn't working confirmed docs Documentation about how to use FastAPI good first issue Good for newcomers reviewed
Projects
None yet
Development

No branches or pull requests

8 participants