Skip to content

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

Open
@pawelrubin

Description

@pawelrubin

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]

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions