python-dependency-injector/examples/catalog.py

67 lines
1.9 KiB
Python
Raw Normal View History

2016-03-13 22:04:55 +00:00
"""Pythonic way for Dependency Injection - Service Providers Catalog."""
2015-03-09 22:54:05 +00:00
2015-01-04 13:54:25 +00:00
import sqlite3
2015-11-23 17:09:35 +00:00
from dependency_injector import catalogs
from dependency_injector import providers
from dependency_injector import injections
2015-01-04 13:54:25 +00:00
2015-10-23 14:04:39 +00:00
class UsersService(object):
"""Users service, that has dependency on database."""
2015-03-09 22:54:05 +00:00
2015-01-04 13:54:25 +00:00
def __init__(self, db):
2015-03-09 22:54:05 +00:00
"""Initializer."""
2015-01-04 13:54:25 +00:00
self.db = db
2015-10-23 14:04:39 +00:00
class AuthService(object):
"""Auth service, that has dependencies on users service and database."""
2015-03-09 22:54:05 +00:00
2015-10-23 14:04:39 +00:00
def __init__(self, db, users_service):
2015-03-09 22:54:05 +00:00
"""Initializer."""
2015-01-04 13:54:25 +00:00
self.db = db
2015-10-23 14:04:39 +00:00
self.users_service = users_service
2015-01-04 13:54:25 +00:00
2015-11-23 17:09:35 +00:00
class Services(catalogs.DeclarativeCatalog):
2015-10-23 14:04:39 +00:00
"""Catalog of service providers."""
2015-01-04 13:54:25 +00:00
2015-11-23 17:09:35 +00:00
database = providers.Singleton(sqlite3.connect, ':memory:')
""":type: providers.Provider -> sqlite3.Connection"""
2015-01-04 13:54:25 +00:00
2015-11-23 17:09:35 +00:00
users = providers.Factory(UsersService,
db=database)
""":type: providers.Provider -> UsersService"""
2015-01-04 13:54:25 +00:00
2015-11-23 17:09:35 +00:00
auth = providers.Factory(AuthService,
db=database,
users_service=users)
""":type: providers.Provider -> AuthService"""
2015-01-04 13:54:25 +00:00
2015-10-23 14:04:39 +00:00
# Retrieving catalog providers:
users_service = Services.users()
auth_service = Services.auth()
2015-01-11 16:10:11 +00:00
2015-10-23 14:04:39 +00:00
# Making some asserts:
assert users_service.db is auth_service.db is Services.database()
assert isinstance(auth_service.users_service, UsersService)
assert users_service is not Services.users()
assert auth_service is not Services.auth()
2015-10-23 14:04:39 +00:00
# Making some "inline" injections:
2015-11-23 17:09:35 +00:00
@injections.inject(users_service=Services.users)
@injections.inject(auth_service=Services.auth)
@injections.inject(database=Services.database)
2015-10-23 14:04:39 +00:00
def example(users_service, auth_service, database):
2015-08-05 14:33:38 +00:00
"""Example callback."""
2015-10-23 14:04:39 +00:00
assert users_service.db is auth_service.db
assert auth_service.db is database
assert database is Services.database()
2015-10-23 14:04:39 +00:00
# Making a call of decorated callback:
example()