python-dependency-injector/examples/scoped_provider.py

47 lines
1.1 KiB
Python
Raw Normal View History

2015-03-10 01:43:23 +03:00
"""Scoped provider examples."""
2015-01-28 01:21:31 +03:00
from objects import AbstractCatalog
2015-03-10 01:43:23 +03:00
from objects.providers import Singleton
from objects.providers import Scoped
from objects.injections import InitArg
from objects.injections import Attribute
2015-01-28 01:26:38 +03:00
2015-01-28 01:21:31 +03:00
import sqlite3
class ObjectA(object):
2015-03-10 01:43:23 +03:00
"""Example class ObjectA, that has dependency on database."""
2015-01-28 01:21:31 +03:00
def __init__(self, db):
2015-03-10 01:43:23 +03:00
"""Initializer."""
2015-01-28 01:21:31 +03:00
self.db = db
class Catalog(AbstractCatalog):
2015-03-10 01:43:23 +03:00
"""Catalog of objects providers."""
2015-01-28 01:21:31 +03:00
database = Singleton(sqlite3.Connection,
InitArg('database', ':memory:'),
Attribute('row_factory', sqlite3.Row))
2015-03-10 01:43:23 +03:00
""":type: (objects.Provider) -> sqlite3.Connection"""
2015-01-28 01:21:31 +03:00
object_a = Scoped(ObjectA,
InitArg('db', database))
2015-03-10 01:43:23 +03:00
""":type: (objects.Provider) -> ObjectA"""
2015-01-28 01:21:31 +03:00
2015-01-28 01:26:38 +03:00
# Making one more scope using provider methods.
Catalog.object_a.in_scope('request')
2015-01-28 01:21:31 +03:00
object_a1 = Catalog.object_a()
object_a2 = Catalog.object_a()
2015-01-28 16:03:02 +03:00
Catalog.object_a.out_of_scope('request')
2015-01-28 01:21:31 +03:00
assert object_a1 is object_a2
assert object_a1.db is object_a2.db