diff --git a/examples/miniapps/mail_service/container.py b/examples/miniapps/mail_service/container.py new file mode 100644 index 00000000..5603d320 --- /dev/null +++ b/examples/miniapps/mail_service/container.py @@ -0,0 +1,41 @@ +"""Mail service and user registration DI container example.""" + +from dependency_injector.containers import DeclarativeContainer +from dependency_injector.providers import Callable, Singleton + +import example + + +class Container(DeclarativeContainer): + """DI container.""" + + mail_service = Singleton(example.MailService, + host='localhost', + port=587, + login='my_login', + password='super_secret_password') + + add_user = Callable(example.add_user, + mailer=mail_service) + + +if __name__ == '__main__': + print('Using real mail service:') + Container.add_user('sample@mail.com', 'password') + # Using real mail service: + # Connecting server localhost:587 with my_login:super_secret_password + # Sending "Your password is password" to "sample@mail.com" + + print('Using mail service stub:') + Container.add_user('sample@mail.com', 'password', + mailer=example.MailServiceStub()) + # Using mail service stub: + # Emulating sending "Your password is password" to "sample@mail.com" + + # Also you can override provider by another provider: + Container.mail_service.override(Singleton(example.MailServiceStub)) + print('Using mail service stub by overriding mail service provider:') + Container.add_user('sample@mail.com', 'password') + # Using mail service stub by overriding mail service provider: + # Emulating sending "Your password is password" to "sample@mail.com" + Container.mail_service.reset_override() # Resetting provider overriding diff --git a/examples/miniapps/mail_service/example.py b/examples/miniapps/mail_service/example.py new file mode 100644 index 00000000..ae69b9aa --- /dev/null +++ b/examples/miniapps/mail_service/example.py @@ -0,0 +1,39 @@ +"""Mail service and user registration example.""" + + +class AbstractMailService(object): + """Abstract mail service.""" + + def send(self, email, body): + """Send email.""" + raise NotImplementedError() + + +class MailService(AbstractMailService): + """Mail service.""" + + def __init__(self, host, port, login, password): + """Initializer.""" + self._host = host + self._port = port + self._login = login + self._password = password + + def send(self, email, body): + """Send email.""" + print('Connecting server {0}:{1} with {2}:{3}'.format( + self._host, self._port, self._login, self._password)) + print('Sending "{0}" to "{1}"'.format(body, email)) + + +class MailServiceStub(AbstractMailService): + """Mail service stub.""" + + def send(self, email, body): + """Send email.""" + print('Emulating sending "{0}" to "{1}"'.format(body, email)) + + +def add_user(email, password, mailer): + """Register user.""" + mailer.send(email, 'Your password is {0}'.format(password))