python-dependency-injector/examples/catalog.py

64 lines
1.7 KiB
Python
Raw Normal View History

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