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,18 +31,22 @@ class Service:
cache: AbstractCacheClient cache: AbstractCacheClient
cache_client_factory = providers.AbstractFactory(AbstractCacheClient) class Container(containers.DeclarativeContainer):
service_factory = providers.Factory(
Service, cache_client_factory = providers.AbstractFactory(AbstractCacheClient)
cache=cache_client_factory,
) service_factory = providers.Factory(
Service,
cache=cache_client_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,11 +30,13 @@ class Ludo(Game):
... ...
game_factory = providers.FactoryAggregate( class Container(containers.DeclarativeContainer):
chess=providers.Factory(Chess),
checkers=providers.Factory(Checkers), game_factory = providers.FactoryAggregate(
ludo=providers.Factory(Ludo), chess=providers.Factory(Chess),
) checkers=providers.Factory(Checkers),
ludo=providers.Factory(Ludo),
)
if __name__ == '__main__': if __name__ == '__main__':
@ -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,15 +21,20 @@ class UserRepository:
] ]
user_factory = providers.Factory(User) class Container(containers.DeclarativeContainer):
user_repository_factory = providers.Factory(
UserRepository, user_factory = providers.Factory(User)
user_factory=user_factory.provider,
) user_repository_factory = providers.Factory(
UserRepository,
user_factory=user_factory.provider,
)
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,23 +13,27 @@ class User:
self.main_photo = main_photo self.main_photo = main_photo
photo_factory = providers.Factory(Photo) class Container(containers.DeclarativeContainer):
user_factory = providers.Factory(
User, photo_factory = providers.Factory(Photo)
main_photo=photo_factory,
) user_factory = providers.Factory(
User,
main_photo=photo_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,26 +23,31 @@ class Algorithm:
self.task = task self.task = task
algorithm_factory = providers.Factory( class Container(containers.DeclarativeContainer):
Algorithm,
task=providers.Factory( algorithm_factory = providers.Factory(
ClassificationTask, Algorithm,
loss=providers.Factory( task=providers.Factory(
Loss, ClassificationTask,
regularizer=providers.Factory( loss=providers.Factory(
Regularizer, Loss,
regularizer=providers.Factory(
Regularizer,
),
), ),
), ),
), )
)
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,11 +17,15 @@ class ServiceProvider(providers.Factory):
# Creating service provider with a correct provided type: # Creating service provider with a correct provided type:
some_service_provider = ServiceProvider(SomeService) class Container(containers.DeclarativeContainer):
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:
some_service_provider = ServiceProvider(object) class Container(containers.DeclarativeContainer):
some_service_provider = ServiceProvider(object)
except errors.Error as exception: except errors.Error as exception:
print(exception) print(exception)
# The output is: # The output is: