python-dependency-injector/examples/providers/resource.py

42 lines
934 B
Python
Raw Normal View History

2020-10-23 05:34:02 +03:00
"""`Resource` provider example."""
2020-10-23 20:47:47 +03:00
import sys
import logging
from concurrent.futures import ThreadPoolExecutor
2020-10-23 05:34:02 +03:00
from dependency_injector import containers, providers
def init_threat_pool(max_workers: int):
2020-10-23 20:47:47 +03:00
thread_pool = ThreadPoolExecutor(max_workers=max_workers)
2020-10-23 05:34:02 +03:00
yield thread_pool
thread_pool.shutdown(wait=True)
class Container(containers.DeclarativeContainer):
config = providers.Configuration()
thread_pool = providers.Resource(
init_threat_pool,
max_workers=config.max_workers,
)
2020-10-23 20:47:47 +03:00
logging = providers.Resource(
logging.basicConfig,
level=logging.INFO,
stream=sys.stdout,
)
2020-10-23 05:34:02 +03:00
if __name__ == '__main__':
container = Container(config={'max_workers': 4})
container.init_resources()
2020-10-23 20:47:47 +03:00
logging.info('Resources are initialized')
2020-10-23 05:34:02 +03:00
thread_pool = container.thread_pool()
2020-10-23 20:47:47 +03:00
thread_pool.map(print, range(10))
2020-10-23 05:34:02 +03:00
container.shutdown_resources()