python-dependency-injector icon indicating copy to clipboard operation
python-dependency-injector copied to clipboard

Resource shutdown not being awaited properly when using FastAPI's on_shutdown

Open pawelrubin opened this issue 3 years ago • 2 comments

Steps to reproduce

Consider the following example:

from typing import Any

from dependency_injector import providers, containers, resources
from fastapi import FastAPI


class SampleResource(resources.AsyncResource[None]):
    async def init(self, *args: Any, **kwargs: Any) -> None:
        return None

    async def shutdown(self, resource: None) -> None:
        pass


class Container(containers.DeclarativeContainer):
    sample_resource = providers.Resource(SampleResource)


def create_app() -> FastAPI:
    container = Container()
    app = FastAPI(
        on_startup=[container.init_resources],
        on_shutdown=[container.shutdown_resources],
    )
    app.container = container  # type: ignore
    return app


app = create_app()

Run it and then quit with CTRL+C

$ uvicorn example.py:app
INFO:     Started server process [75565]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
^CINFO:     Shutting down
INFO:     Waiting for application shutdown.
<path-to-venv>/lib/python3.10/site-packages/starlette/routing.py:610: RuntimeWarning: coroutine 'DynamicContainer.shutdown_resources.<locals>._asyn' was never awaited
  handler()
INFO:     Application shutdown complete.
INFO:     Finished server process [75565]

pawelrubin avatar Mar 15 '22 08:03 pawelrubin

Hi @pawelrubin ,

Thanks a lot for providing the example. I'll debug it and will try to find a solution

rmk135 avatar Mar 25 '22 21:03 rmk135

Any updates on this? Is there an alternative approach to closing resources in a FastAPI app?

robmoore avatar Sep 02 '22 16:09 robmoore