|
| 1 | +import sys |
| 2 | +from abc import ABCMeta, abstractmethod |
| 3 | +from typing import Any, Callable, Coroutine, Optional |
| 4 | + |
| 5 | +if sys.version_info >= (3, 11): # pragma: no cover |
| 6 | + from typing import Self |
| 7 | +else: # pragma: no cover |
| 8 | + from typing_extensions import Self |
| 9 | + |
| 10 | +from dependency_injector.containers import Container |
| 11 | + |
| 12 | + |
| 13 | +class Lifespan: |
| 14 | + """A starlette lifespan handler performing container resource initialization and shutdown. |
| 15 | +
|
| 16 | + See https://www.starlette.io/lifespan/ for details. |
| 17 | +
|
| 18 | + Usage: |
| 19 | +
|
| 20 | + .. code-block:: python |
| 21 | +
|
| 22 | + from dependency_injector.containers import DeclarativeContainer |
| 23 | + from dependency_injector.ext.starlette import Lifespan |
| 24 | + from dependency_injector.providers import Factory, Self, Singleton |
| 25 | + from starlette.applications import Starlette |
| 26 | +
|
| 27 | + class Container(DeclarativeContainer): |
| 28 | + __self__ = Self() |
| 29 | + lifespan = Singleton(Lifespan, __self__) |
| 30 | + app = Factory(Starlette, lifespan=lifespan) |
| 31 | +
|
| 32 | + :param container: container instance |
| 33 | + """ |
| 34 | + |
| 35 | + container: Container |
| 36 | + |
| 37 | + def __init__(self, container: Container) -> None: |
| 38 | + self.container = container |
| 39 | + |
| 40 | + def __call__(self, app: Any) -> Self: |
| 41 | + return self |
| 42 | + |
| 43 | + async def __aenter__(self) -> None: |
| 44 | + result = self.container.init_resources() |
| 45 | + |
| 46 | + if result is not None: |
| 47 | + await result |
| 48 | + |
| 49 | + async def __aexit__(self, *exc_info: Any) -> None: |
| 50 | + result = self.container.shutdown_resources() |
| 51 | + |
| 52 | + if result is not None: |
| 53 | + await result |
0 commit comments