Add container usage for all factory provider examples

This commit is contained in:
Roman Mogylatov 2020-09-03 16:46:03 -04:00
parent 33b4416c2c
commit a7afa66e40
8 changed files with 91 additions and 61 deletions

View File

@ -73,7 +73,7 @@ all the classes and use special double-underscore ``__`` syntax for passing the
.. literalinclude:: ../../examples/providers/factory_init_injections_underlying.py .. literalinclude:: ../../examples/providers/factory_init_injections_underlying.py
:language: python :language: python
:lines: 3- :lines: 3-
:emphasize-lines: 24-35,39,42,45 :emphasize-lines: 44,49
When you use ``__`` separator in the name of the keyword argument the ``Factory`` looks for When you use ``__`` separator in the name of the keyword argument the ``Factory`` looks for
the dependency with the same name as the left part of the ``__`` expression. the dependency with the same name as the left part of the ``__`` expression.
@ -98,7 +98,7 @@ attribute of the provider that you're going to inject.
.. literalinclude:: ../../examples/providers/factory_delegation.py .. literalinclude:: ../../examples/providers/factory_delegation.py
:language: python :language: python
:lines: 3- :lines: 3-
:emphasize-lines: 25 :emphasize-lines: 28
.. note:: Any provider has a ``.provider`` attribute. .. note:: Any provider has a ``.provider`` attribute.
@ -135,7 +135,7 @@ provider with two peculiarities:
.. literalinclude:: ../../examples/providers/abstract_factory.py .. literalinclude:: ../../examples/providers/abstract_factory.py
:language: python :language: python
:lines: 3- :lines: 3-
:emphasize-lines: 32 :emphasize-lines: 34
Factory aggregate Factory aggregate
----------------- -----------------
@ -155,7 +155,7 @@ rest of the arguments are passed to the delegated ``Factory``.
.. literalinclude:: ../../examples/providers/factory_aggregate.py .. literalinclude:: ../../examples/providers/factory_aggregate.py
:language: python :language: python
:lines: 3- :lines: 3-
:emphasize-lines: 31-35,43 :emphasize-lines: 33-37,47
You can get a dictionary of the aggregated factories using the ``.factories`` attribute of the You can get a dictionary of the aggregated factories using the ``.factories`` attribute of the
``FactoryAggregate``. To get a game factories dictionary from the previous example you can use ``FactoryAggregate``. To get a game factories dictionary from the previous example you can use

View File

@ -5,7 +5,7 @@ import dataclasses
import random import random
from typing import List from typing import List
from dependency_injector import providers from dependency_injector import containers, providers
class AbstractCacheClient(metaclass=abc.ABCMeta): class AbstractCacheClient(metaclass=abc.ABCMeta):
@ -31,7 +31,10 @@ class Service:
cache: AbstractCacheClient cache: AbstractCacheClient
class Container(containers.DeclarativeContainer):
cache_client_factory = providers.AbstractFactory(AbstractCacheClient) cache_client_factory = providers.AbstractFactory(AbstractCacheClient)
service_factory = providers.Factory( service_factory = providers.Factory(
Service, Service,
cache=cache_client_factory, cache=cache_client_factory,
@ -39,10 +42,11 @@ service_factory = providers.Factory(
if __name__ == '__main__': if __name__ == '__main__':
cache_type = random.choice(['redis', 'memcached', None]) container = Container()
cache_type = random.choice(['redis', 'memcached'])
if cache_type == 'redis': if cache_type == 'redis':
cache_client_factory.override( container.cache_client_factory.override(
providers.Factory( providers.Factory(
RedisCacheClient, RedisCacheClient,
host='localhost', host='localhost',
@ -51,7 +55,7 @@ if __name__ == '__main__':
), ),
) )
elif cache_type == 'memcached': elif cache_type == 'memcached':
cache_client_factory.override( container.cache_client_factory.override(
providers.Factory( providers.Factory(
MemcachedCacheClient, MemcachedCacheClient,
hosts=['10.0.1.1'], hosts=['10.0.1.1'],
@ -60,7 +64,7 @@ if __name__ == '__main__':
), ),
) )
service = service_factory() service = container.service_factory()
print(service.cache) print(service.cache)
# The output depends on cache_type variable value. # The output depends on cache_type variable value.
# #

View File

@ -1,15 +1,19 @@
"""`Factory` provider example.""" """`Factory` provider example."""
from dependency_injector import providers from dependency_injector import containers, providers
class User: class User:
... ...
users_factory = providers.Factory(User) class Container(containers.DeclarativeContainer):
user_factory = providers.Factory(User)
if __name__ == '__main__': if __name__ == '__main__':
user1 = users_factory() container = Container()
user2 = users_factory()
user1 = container.user_factory()
user2 = container.user_factory()

View File

@ -3,7 +3,7 @@
import dataclasses import dataclasses
import sys import sys
from dependency_injector import providers from dependency_injector import containers, providers
@dataclasses.dataclass @dataclasses.dataclass
@ -30,6 +30,8 @@ class Ludo(Game):
... ...
class Container(containers.DeclarativeContainer):
game_factory = providers.FactoryAggregate( game_factory = providers.FactoryAggregate(
chess=providers.Factory(Chess), chess=providers.Factory(Chess),
checkers=providers.Factory(Checkers), checkers=providers.Factory(Checkers),
@ -42,7 +44,9 @@ if __name__ == '__main__':
player1 = sys.argv[2].capitalize() player1 = sys.argv[2].capitalize()
player2 = sys.argv[3].capitalize() player2 = sys.argv[3].capitalize()
selected_game = game_factory(game_type, player1, player2) container = Container()
selected_game = container.game_factory(game_type, player1, player2)
selected_game.play() selected_game.play()
# $ python factory_aggregate.py chess John Jane # $ python factory_aggregate.py chess John Jane

View File

@ -2,7 +2,7 @@
from typing import Callable, List from typing import Callable, List
from dependency_injector import providers from dependency_injector import containers, providers
class User: class User:
@ -21,7 +21,10 @@ class UserRepository:
] ]
class Container(containers.DeclarativeContainer):
user_factory = providers.Factory(User) user_factory = providers.Factory(User)
user_repository_factory = providers.Factory( user_repository_factory = providers.Factory(
UserRepository, UserRepository,
user_factory=user_factory.provider, user_factory=user_factory.provider,
@ -29,7 +32,9 @@ user_repository_factory = providers.Factory(
if __name__ == '__main__': if __name__ == '__main__':
user_repository = user_repository_factory() container = Container()
user_repository = container.user_repository_factory()
user1, user2 = user_repository.get_all() user1, user2 = user_repository.get_all()

View File

@ -1,6 +1,6 @@
"""`Factory` provider init injections example.""" """`Factory` provider init injections example."""
from dependency_injector import providers from dependency_injector import containers, providers
class Photo: class Photo:
@ -13,7 +13,10 @@ class User:
self.main_photo = main_photo self.main_photo = main_photo
class Container(containers.DeclarativeContainer):
photo_factory = providers.Factory(Photo) photo_factory = providers.Factory(Photo)
user_factory = providers.Factory( user_factory = providers.Factory(
User, User,
main_photo=photo_factory, main_photo=photo_factory,
@ -21,15 +24,16 @@ user_factory = providers.Factory(
if __name__ == '__main__': if __name__ == '__main__':
user1 = user_factory(1) container = Container()
user1 = container.user_factory(1)
# Same as: # user1 = User(1, main_photo=Photo()) # Same as: # user1 = User(1, main_photo=Photo())
user2 = user_factory(2) user2 = container.user_factory(2)
# Same as: # user2 = User(2, main_photo=Photo()) # Same as: # user2 = User(2, main_photo=Photo())
# Context keyword arguments have a priority:
another_photo = Photo() another_photo = Photo()
user3 = user_factory( user3 = container.user_factory(
uid=3, uid=3,
main_photo=another_photo, main_photo=another_photo,
) )

View File

@ -1,6 +1,6 @@
"""`Factory` provider - passing injections to the underlying providers example.""" """`Factory` provider - passing injections to the underlying providers example."""
from dependency_injector import providers from dependency_injector import containers, providers
class Regularizer: class Regularizer:
@ -23,6 +23,8 @@ class Algorithm:
self.task = task self.task = task
class Container(containers.DeclarativeContainer):
algorithm_factory = providers.Factory( algorithm_factory = providers.Factory(
Algorithm, Algorithm,
task=providers.Factory( task=providers.Factory(
@ -38,11 +40,14 @@ algorithm_factory = providers.Factory(
if __name__ == '__main__': if __name__ == '__main__':
algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) container = Container()
algorithm_1 = container.algorithm_factory(
task__loss__regularizer__alpha=0.5,
)
assert algorithm_1.task.loss.regularizer.alpha == 0.5 assert algorithm_1.task.loss.regularizer.alpha == 0.5
algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) algorithm_2 = container.algorithm_factory(
task__loss__regularizer__alpha=0.7,
)
assert algorithm_2.task.loss.regularizer.alpha == 0.7 assert algorithm_2.task.loss.regularizer.alpha == 0.7
algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8))
assert algorithm_3.task.loss.regularizer.alpha == 0.8

View File

@ -1,6 +1,6 @@
"""`Factory` specialization with limitation to provided type example.""" """`Factory` specialization with limitation to provided type example."""
from dependency_injector import providers, errors from dependency_injector import containers, providers, errors
class BaseService: class BaseService:
@ -17,10 +17,14 @@ class ServiceProvider(providers.Factory):
# Creating service provider with a correct provided type: # Creating service provider with a correct provided type:
class Container(containers.DeclarativeContainer):
some_service_provider = ServiceProvider(SomeService) some_service_provider = ServiceProvider(SomeService)
# Trying to create service provider an incorrect provided type: # Trying to create service provider an incorrect provided type:
try: try:
class Container(containers.DeclarativeContainer):
some_service_provider = ServiceProvider(object) some_service_provider = ServiceProvider(object)
except errors.Error as exception: except errors.Error as exception:
print(exception) print(exception)