feat: Add resource_type argument on init_resources and shutdown_resources methods to provide a more granular way to initialize the desired resources and add the possibility to scope that ones.

This commit is contained in:
Aran Moncusi Ramirez 2025-02-21 20:51:21 +01:00
parent 46646b1acf
commit 6f4d23cf44
2 changed files with 7 additions and 7 deletions

View File

@ -17,7 +17,7 @@ from typing import (
overload,
)
from .providers import Provider, Self, ProviderParent
from .providers import Provider, Resource, Self, ProviderParent
C_Base = TypeVar("C_Base", bound="Container")
@ -57,8 +57,8 @@ class Container:
def is_auto_wiring_enabled(self) -> bool: ...
def wire(self, modules: Optional[Iterable[Any]] = None, packages: Optional[Iterable[Any]] = None, from_package: Optional[str] = None) -> None: ...
def unwire(self) -> None: ...
def init_resources(self) -> Optional[Awaitable]: ...
def shutdown_resources(self) -> Optional[Awaitable]: ...
def init_resources(self, resource_type: Type[Resource]=None) -> Optional[Awaitable]: ...
def shutdown_resources(self, resource_type: Type[Resource]=None) -> Optional[Awaitable]: ...
def load_config(self) -> None: ...
def apply_container_providers_overridings(self) -> None: ...
def reset_singletons(self) -> SingletonResetContext[C_Base]: ...

View File

@ -333,11 +333,11 @@ class DynamicContainer(Container):
self.wired_to_modules.clear()
self.wired_to_packages.clear()
def init_resources(self):
def init_resources(self, resource_type=providers.Resource):
"""Initialize all container resources."""
futures = []
for provider in self.traverse(types=[providers.Resource]):
for provider in self.traverse(types=[resource_type]):
resource = provider.init()
if __is_future_or_coroutine(resource):
@ -346,7 +346,7 @@ class DynamicContainer(Container):
if futures:
return asyncio.gather(*futures)
def shutdown_resources(self):
def shutdown_resources(self, resource_type=providers.Resource):
"""Shutdown all container resources."""
def _independent_resources(resources):
for resource in resources:
@ -378,7 +378,7 @@ class DynamicContainer(Container):
for resource in resources_to_shutdown:
resource.shutdown()
resources = list(self.traverse(types=[providers.Resource]))
resources = list(self.traverse(types=[resource_type]))
if any(resource.is_async_mode_enabled() for resource in resources):
return _async_ordered_shutdown(resources)
else: