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
|
|
|
|
|
|
|
|
2021-09-30 22:32:21 +03:00
|
|
|
if __name__ == "__main__":
|
2020-09-03 23:46:03 +03:00
|
|
|
container = Container()
|
2020-09-01 04:26:21 +03:00
|
|
|
|
2021-09-30 22:32:21 +03:00
|
|
|
cache_type = random.choice(["redis", "memcached"])
|
|
|
|
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,
|
2021-09-30 22:32:21 +03:00
|
|
|
host="localhost",
|
2020-09-01 04:26:21 +03:00
|
|
|
port=6379,
|
|
|
|
db=0,
|
|
|
|
),
|
|
|
|
)
|
2021-09-30 22:32:21 +03:00
|
|
|
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,
|
2021-09-30 22:32:21 +03:00
|
|
|
hosts=["10.0.1.1"],
|
2020-09-01 04:26:21 +03:00
|
|
|
port=11211,
|
2021-09-30 22:32:21 +03:00
|
|
|
prefix="my_app",
|
2020-09-01 04:26:21 +03:00
|
|
|
),
|
|
|
|
)
|
|
|
|
|
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.
|
|
|
|
#
|
2021-09-30 22:32:21 +03:00
|
|
|
# If the value is "redis":
|
|
|
|
# RedisCacheClient(host="localhost", port=6379, db=0)
|
2020-09-01 04:26:21 +03:00
|
|
|
#
|
2021-09-30 22:32:21 +03:00
|
|
|
# If the value is "memcached":
|
|
|
|
# MemcachedCacheClient(hosts=["10.0.1.1"], port=11211, prefix="my_app")
|
2020-09-01 04:26:21 +03:00
|
|
|
#
|
|
|
|
# If the value is None:
|
2021-09-30 22:32:21 +03:00
|
|
|
# Error: AbstractFactory(<class "__main__.AbstractCacheClient">) must be
|
2020-09-01 04:26:21 +03:00
|
|
|
# overridden before calling
|