Add mail_service example

This commit is contained in:
Roman Mogilatov 2017-07-10 23:32:14 +03:00
parent aad164db57
commit 464c4f724f
2 changed files with 80 additions and 0 deletions

View File

@ -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

View File

@ -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))