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

42 lines
851 B
Python
Raw Normal View History

2020-09-21 23:46:02 +03:00
import sys
2020-09-26 07:23:11 +03:00
from unittest import mock
2020-08-15 18:01:58 +03:00
2020-09-21 23:46:02 +03:00
from dependency_injector import containers, providers
from dependency_injector.wiring import Provide
2020-08-15 18:01:58 +03:00
2020-09-30 23:47:37 +03:00
from after import ApiClient, Service
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,
2020-08-25 17:27:11 +03:00
timeout=config.timeout.as_int(),
2020-08-14 04:53:13 +03:00
)
service = providers.Factory(
Service,
api_client=api_client,
)
2020-09-21 23:46:02 +03:00
def main(service: Service = Provide[Container.service]):
...
2020-08-14 04:53:13 +03:00
if __name__ == '__main__':
container = Container()
2020-09-21 23:46:02 +03:00
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
2020-09-21 23:46:02 +03:00
container.wire(modules=[sys.modules[__name__]])
main()
2020-09-26 07:23:11 +03:00
with container.api_client.override(mock.Mock()):
main()