python-dependency-injector/examples/di_demo2/demo.py

39 lines
788 B
Python
Raw Normal View History

2020-08-14 04:53:13 +03:00
from dependency_injector import containers, providers
2020-08-15 18:01:58 +03:00
class ApiClient:
def __init__(self, api_key: str, timeout: int):
self.api_key = api_key
self.timeout = timeout
class Service:
def __init__(self, api_client: ApiClient):
self.api_client = api_client
2020-08-14 04:53:13 +03:00
class Container(containers.DeclarativeContainer):
config = providers.Configuration()
api_client = providers.Singleton(
ApiClient,
api_key=config.api_key,
timeout=config.timeout,
)
service = providers.Factory(
Service,
api_client=api_client,
)
if __name__ == '__main__':
container = Container()
2020-08-15 18:01:58 +03:00
container.config.api_key.from_env('API_KEY')
container.config.timeout.from_env('TIMEOUT')
2020-08-14 04:53:13 +03:00
service = container.service()