2020-09-01 04:26:21 +03:00
|
|
|
"""`AbstractFactory` providers example."""
|
|
|
|
|
|
|
|
import abc
|
|
|
|
import dataclasses
|
|
|
|
import random
|
|
|
|
from typing import List
|
|
|
|
|
2020-09-03 23:46:03 +03:00
|
|
|
from dependency_injector import containers, providers
|
2020-09-01 04:26:21 +03:00
|
|
|
|
|
|
|
|
|
|
|
class AbstractCacheClient(metaclass=abc.ABCMeta):
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
|
|
@dataclasses.dataclass
|
|
|
|
class RedisCacheClient(AbstractCacheClient):
|
|
|
|
host: str
|
|
|
|
port: int
|
|
|
|
db: int
|
|
|
|
|
|
|
|
|
|
|
|
@dataclasses.dataclass
|
|
|
|
class MemcachedCacheClient(AbstractCacheClient):
|
|
|
|
hosts: List[str]
|
|
|
|
port: int
|
|
|
|
prefix: str
|
|
|
|
|
|
|
|
|
|
|
|
@dataclasses.dataclass
|
|
|
|
class Service:
|
|
|
|
cache: AbstractCacheClient
|
|
|
|
|
|
|
|
|
2020-09-03 23:46:03 +03:00
|
|
|
class Container(containers.DeclarativeContainer):
|
|
|
|
|
|
|
|
cache_client_factory = providers.AbstractFactory(AbstractCacheClient)
|
|
|
|
|
|
|
|
service_factory = providers.Factory(
|
|
|
|
Service,
|
|
|
|
cache=cache_client_factory,
|
|
|
|
)
|
2020-09-01 04:26:21 +03:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2020-09-03 23:46:03 +03:00
|
|
|
container = Container()
|
2020-09-01 04:26:21 +03:00
|
|
|
|
2020-09-03 23:46:03 +03:00
|
|
|
cache_type = random.choice(['redis', 'memcached'])
|
2020-09-01 04:26:21 +03:00
|
|
|
if cache_type == 'redis':
|
2020-09-03 23:46:03 +03:00
|
|
|
container.cache_client_factory.override(
|
2020-09-01 04:26:21 +03:00
|
|
|
providers.Factory(
|
|
|
|
RedisCacheClient,
|
|
|
|
host='localhost',
|
|
|
|
port=6379,
|
|
|
|
db=0,
|
|
|
|
),
|
|
|
|
)
|
|
|
|
elif cache_type == 'memcached':
|
2020-09-03 23:46:03 +03:00
|
|
|
container.cache_client_factory.override(
|
2020-09-01 04:26:21 +03:00
|
|
|
providers.Factory(
|
|
|
|
MemcachedCacheClient,
|
|
|
|
hosts=['10.0.1.1'],
|
|
|
|
port=11211,
|
|
|
|
prefix='my_app',
|
|
|
|
),
|
|
|
|
)
|
|
|
|
|
2020-09-03 23:46:03 +03:00
|
|
|
service = container.service_factory()
|
2020-09-01 04:26:21 +03:00
|
|
|
print(service.cache)
|
|
|
|
# The output depends on cache_type variable value.
|
|
|
|
#
|
|
|
|
# If the value is 'redis':
|
|
|
|
# RedisCacheClient(host='localhost', port=6379, db=0)
|
|
|
|
#
|
|
|
|
# If the value is 'memcached':
|
|
|
|
# MemcachedCacheClient(hosts=['10.0.1.1'], port=11211, prefix='my_app')
|
|
|
|
#
|
|
|
|
# If the value is None:
|
|
|
|
# Error: AbstractFactory(<class '__main__.AbstractCacheClient'>) must be
|
|
|
|
# overridden before calling
|