2016-10-06 22:48:43 +03:00
|
|
|
"""Example of dependency injection in Python."""
|
2016-05-18 23:18:29 +03:00
|
|
|
|
2016-10-06 22:48:43 +03:00
|
|
|
import logging
|
2016-05-18 23:18:29 +03:00
|
|
|
import sqlite3
|
2016-10-06 22:48:43 +03:00
|
|
|
|
2017-03-15 18:26:59 +03:00
|
|
|
import boto3
|
2016-09-18 23:00:10 +03:00
|
|
|
|
|
|
|
import example.main
|
2016-05-18 23:18:29 +03:00
|
|
|
import example.services
|
|
|
|
|
2016-06-01 19:52:10 +03:00
|
|
|
import dependency_injector.containers as containers
|
|
|
|
import dependency_injector.providers as providers
|
2016-05-18 23:18:29 +03:00
|
|
|
|
|
|
|
|
2016-12-02 21:59:12 +03:00
|
|
|
class Core(containers.DeclarativeContainer):
|
|
|
|
"""IoC container of core component providers."""
|
2016-05-18 23:18:29 +03:00
|
|
|
|
2017-03-15 18:26:59 +03:00
|
|
|
config = providers.Configuration('config')
|
2016-12-02 21:43:39 +03:00
|
|
|
|
2016-10-06 22:48:43 +03:00
|
|
|
logger = providers.Singleton(logging.Logger, name='example')
|
|
|
|
|
2016-12-02 21:59:12 +03:00
|
|
|
|
|
|
|
class Gateways(containers.DeclarativeContainer):
|
|
|
|
"""IoC container of gateway (API clients to remote services) providers."""
|
|
|
|
|
2017-03-15 18:26:59 +03:00
|
|
|
database = providers.Singleton(sqlite3.connect, Core.config.database.dsn)
|
2016-05-18 23:18:29 +03:00
|
|
|
|
2017-03-15 18:26:59 +03:00
|
|
|
s3 = providers.Singleton(
|
|
|
|
boto3.client, 's3',
|
|
|
|
aws_access_key_id=Core.config.aws.access_key_id,
|
|
|
|
aws_secret_access_key=Core.config.aws.secret_access_key)
|
2016-05-18 23:18:29 +03:00
|
|
|
|
|
|
|
|
2016-05-27 14:38:42 +03:00
|
|
|
class Services(containers.DeclarativeContainer):
|
2016-05-27 14:57:37 +03:00
|
|
|
"""IoC container of business service providers."""
|
2016-05-18 23:18:29 +03:00
|
|
|
|
2016-10-19 15:25:19 +03:00
|
|
|
users = providers.Factory(example.services.UsersService,
|
2016-12-02 21:59:12 +03:00
|
|
|
db=Gateways.database,
|
|
|
|
logger=Core.logger)
|
2016-05-18 23:18:29 +03:00
|
|
|
|
2016-10-19 15:25:19 +03:00
|
|
|
auth = providers.Factory(example.services.AuthService,
|
2016-12-02 21:59:12 +03:00
|
|
|
db=Gateways.database,
|
|
|
|
logger=Core.logger,
|
2017-03-15 18:26:59 +03:00
|
|
|
token_ttl=Core.config.auth.token_ttl)
|
2016-06-01 19:52:10 +03:00
|
|
|
|
2016-10-19 15:25:19 +03:00
|
|
|
photos = providers.Factory(example.services.PhotosService,
|
2016-12-02 21:59:12 +03:00
|
|
|
db=Gateways.database,
|
|
|
|
s3=Gateways.s3,
|
|
|
|
logger=Core.logger)
|
2016-09-18 23:00:10 +03:00
|
|
|
|
|
|
|
|
|
|
|
class Application(containers.DeclarativeContainer):
|
|
|
|
"""IoC container of application component providers."""
|
|
|
|
|
|
|
|
main = providers.Callable(example.main.main,
|
|
|
|
users_service=Services.users,
|
|
|
|
auth_service=Services.auth,
|
|
|
|
photos_service=Services.photos)
|