Add commands and handlers example

This commit is contained in:
Roman Mogylatov 2020-11-20 18:09:34 -05:00
parent fbaf35244c
commit cd2c5697c3
9 changed files with 97 additions and 0 deletions

View File

@ -11,6 +11,8 @@ Develop
-------
- Add support of non-string keys for ``Dict`` provider.
- Add simple ``FastAPI`` example.
- Add ``Commands and Handlers`` example from
issue `#327 <https://github.com/ets-labs/python-dependency-injector/issues/327>`_.
- Add extra typing test for provided instance of ``DependenciesContainer`` provider.
4.4.1

View File

@ -0,0 +1,14 @@
Commands and Handlers Example
=============================
This mixed example from issue `#327 <https://github.com/ets-labs/python-dependency-injector/issues/327>`_.
It demonstrates ``Dict`` provider with non-string keys and ``.provided`` attribute.
Run
---
To run the application do:
.. code-block:: bash
python -m application

View File

@ -0,0 +1 @@
"""Top-level package."""

View File

@ -0,0 +1,12 @@
"""Main module."""
from .containers import Container
from .commands import SaveRating, DoSomethingElse
if __name__ == '__main__':
container = Container()
message_bus = container.message_bus()
message_bus.handle(SaveRating)
message_bus.handle(DoSomethingElse)

View File

@ -0,0 +1,12 @@
"""Commands module."""
class Command:
...
class SaveRating(Command):
...
class DoSomethingElse(Command):
...

View File

@ -0,0 +1,23 @@
"""Containers module."""
from dependency_injector import containers, providers
from . import repositories, handler, messagebus, commands
class Container(containers.DeclarativeContainer):
rating_repository = providers.Singleton(repositories.RatingRepository)
command_handler = providers.Singleton(
handler.CommandHandler,
rating_repo=rating_repository,
)
message_bus = providers.Factory(
messagebus.MessageBus,
command_handlers=providers.Dict({
commands.SaveRating: command_handler.provided.save_rating,
commands.DoSomethingElse: command_handler.provided.something_else,
}),
)

View File

@ -0,0 +1,14 @@
"""Handlers module."""
from .repositories import RatingRepository
class CommandHandler:
def __init__(self, rating_repo: RatingRepository):
self.rating_repo = rating_repo
def save_rating(self):
print('Saving rating')
def something_else(self):
print('Doing something else')

View File

@ -0,0 +1,14 @@
"""Message bus module."""
from typing import Dict, Callable, Any
from .commands import Command
class MessageBus:
def __init__(self, command_handlers: Dict[str, Callable[..., Any]]):
self.command_handlers = command_handlers
def handle(self, command: Command):
self.command_handlers[command]()

View File

@ -0,0 +1,5 @@
"""Repositories module."""
class RatingRepository:
...