Update quotes in provider examples

This commit is contained in:
Roman Mogylatov 2021-09-30 15:32:21 -04:00
parent d827f93816
commit 320d837bea
46 changed files with 174 additions and 174 deletions

View File

@ -41,26 +41,26 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
cache_type = random.choice(['redis', 'memcached']) cache_type = random.choice(["redis", "memcached"])
if cache_type == 'redis': if cache_type == "redis":
container.cache_client_factory.override( container.cache_client_factory.override(
providers.Factory( providers.Factory(
RedisCacheClient, RedisCacheClient,
host='localhost', host="localhost",
port=6379, port=6379,
db=0, db=0,
), ),
) )
elif cache_type == 'memcached': elif cache_type == "memcached":
container.cache_client_factory.override( container.cache_client_factory.override(
providers.Factory( providers.Factory(
MemcachedCacheClient, MemcachedCacheClient,
hosts=['10.0.1.1'], hosts=["10.0.1.1"],
port=11211, port=11211,
prefix='my_app', prefix="my_app",
), ),
) )
@ -68,12 +68,12 @@ if __name__ == '__main__':
print(service.cache) print(service.cache)
# The output depends on cache_type variable value. # The output depends on cache_type variable value.
# #
# If the value is 'redis': # If the value is "redis":
# RedisCacheClient(host='localhost', port=6379, db=0) # RedisCacheClient(host="localhost", port=6379, db=0)
# #
# If the value is 'memcached': # If the value is "memcached":
# MemcachedCacheClient(hosts=['10.0.1.1'], port=11211, prefix='my_app') # MemcachedCacheClient(hosts=["10.0.1.1"], port=11211, prefix="my_app")
# #
# If the value is None: # If the value is None:
# Error: AbstractFactory(<class '__main__.AbstractCacheClient'>) must be # Error: AbstractFactory(<class "__main__.AbstractCacheClient">) must be
# overridden before calling # overridden before calling

View File

@ -7,7 +7,7 @@ from dependency_injector import containers, providers
async def init_async_resource(): async def init_async_resource():
await asyncio.sleep(0.1) await asyncio.sleep(0.1)
yield 'Initialized' yield "Initialized"
class Service: class Service:
@ -31,7 +31,7 @@ async def main(container: Container):
... ...
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
asyncio.run(main(container)) asyncio.run(main(container))

View File

@ -26,7 +26,7 @@ async def main(container: Container):
... ...
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
asyncio.run(main(container)) asyncio.run(main(container))

View File

@ -16,8 +16,8 @@ class Container(containers.DeclarativeContainer):
password_verifier = providers.Callable(passlib.hash.sha256_crypt.verify) password_verifier = providers.Callable(passlib.hash.sha256_crypt.verify)
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
hashed_password = container.password_hasher('super secret') hashed_password = container.password_hasher("super secret")
assert container.password_verifier('super secret', hashed_password) assert container.password_verifier("super secret", hashed_password)

View File

@ -10,19 +10,19 @@ class Container(containers.DeclarativeContainer):
s3_client_factory = providers.Factory( s3_client_factory = providers.Factory(
boto3.client, boto3.client,
's3', "s3",
aws_access_key_id=config.aws.access_key_id, aws_access_key_id=config.aws.access_key_id,
aws_secret_access_key=config.aws.secret_access_key, aws_secret_access_key=config.aws.secret_access_key,
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
container.config.from_dict( container.config.from_dict(
{ {
'aws': { "aws": {
'access_key_id': 'KEY', "access_key_id": "KEY",
'secret_access_key': 'SECRET', "secret_access_key": "SECRET",
}, },
}, },
) )

View File

@ -9,14 +9,14 @@ class Container(containers.DeclarativeContainer):
config = providers.Configuration() config = providers.Configuration()
if __name__ == '__main__': if __name__ == "__main__":
env = Env() env = Env()
container = Container() container = Container()
with container.config.some_plugin_name as plugin: with container.config.some_plugin_name as plugin:
plugin.some_interval_ms.override( plugin.some_interval_ms.override(
env.int( env.int(
'SOME_INTERVAL_MS', "SOME_INTERVAL_MS",
default=30000, default=30000,
), ),
) )
@ -24,13 +24,13 @@ if __name__ == '__main__':
with plugin.kafka as kafka: with plugin.kafka as kafka:
kafka.bootstrap_servers.override( kafka.bootstrap_servers.override(
env.list( env.list(
'KAFKA_BOOTSTRAP_SERVERS', "KAFKA_BOOTSTRAP_SERVERS",
default=['kafka1', 'kafka2'], default=["kafka1", "kafka2"],
), ),
) )
kafka.security_protocol.override( kafka.security_protocol.override(
env.str( env.str(
'KAFKA_SECURITY_PROTOCOL', "KAFKA_SECURITY_PROTOCOL",
default='SASL_SSL', default="SASL_SSL",
), ),
) )

View File

@ -8,27 +8,27 @@ class Container(containers.DeclarativeContainer):
config = providers.Configuration() config = providers.Configuration()
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
container.config.from_dict( container.config.from_dict(
{ {
'aws': { "aws": {
'access_key_id': 'KEY', "access_key_id": "KEY",
'secret_access_key': 'SECRET', "secret_access_key": "SECRET",
}, },
}, },
) )
assert container.config() == { assert container.config() == {
'aws': { "aws": {
'access_key_id': 'KEY', "access_key_id": "KEY",
'secret_access_key': 'SECRET', "secret_access_key": "SECRET",
}, },
} }
assert container.config.aws() == { assert container.config.aws() == {
'access_key_id': 'KEY', "access_key_id": "KEY",
'secret_access_key': 'SECRET', "secret_access_key": "SECRET",
} }
assert container.config.aws.access_key_id() == 'KEY' assert container.config.aws.access_key_id() == "KEY"
assert container.config.aws.secret_access_key() == 'SECRET' assert container.config.aws.secret_access_key() == "SECRET"

View File

@ -10,17 +10,17 @@ class Container(containers.DeclarativeContainer):
config = providers.Configuration() config = providers.Configuration()
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
# Emulate environment variables # Emulate environment variables
os.environ['AWS_ACCESS_KEY_ID'] = 'KEY' os.environ["AWS_ACCESS_KEY_ID"] = "KEY"
os.environ['AWS_SECRET_ACCESS_KEY'] = 'SECRET' os.environ["AWS_SECRET_ACCESS_KEY"] = "SECRET"
container.config.aws.access_key_id.from_env('AWS_ACCESS_KEY_ID') container.config.aws.access_key_id.from_env("AWS_ACCESS_KEY_ID")
container.config.aws.secret_access_key.from_env('AWS_SECRET_ACCESS_KEY') container.config.aws.secret_access_key.from_env("AWS_SECRET_ACCESS_KEY")
container.config.optional.from_env('UNDEFINED', 'default_value') container.config.optional.from_env("UNDEFINED", "default_value")
assert container.config.aws.access_key_id() == 'KEY' assert container.config.aws.access_key_id() == "KEY"
assert container.config.aws.secret_access_key() == 'SECRET' assert container.config.aws.secret_access_key() == "SECRET"
assert container.config.optional() == 'default_value' assert container.config.optional() == "default_value"

View File

@ -10,10 +10,10 @@ class Container(containers.DeclarativeContainer):
config = providers.Configuration() config = providers.Configuration()
if __name__ == '__main__': if __name__ == "__main__":
os.environ.setdefault('ENV_VAR', 'default value') os.environ.setdefault("ENV_VAR", "default value")
container = Container() container = Container()
container.config.from_yaml('config-with-env-var.yml') container.config.from_yaml("config-with-env-var.yml")
assert container.config.section.option() == 'default value' assert container.config.section.option() == "default value"

View File

@ -8,20 +8,20 @@ class Container(containers.DeclarativeContainer):
config = providers.Configuration() config = providers.Configuration()
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
container.config.from_ini('examples/providers/configuration/config.ini') container.config.from_ini("./config.ini")
assert container.config() == { assert container.config() == {
'aws': { "aws": {
'access_key_id': 'KEY', "access_key_id": "KEY",
'secret_access_key': 'SECRET', "secret_access_key": "SECRET",
}, },
} }
assert container.config.aws() == { assert container.config.aws() == {
'access_key_id': 'KEY', "access_key_id": "KEY",
'secret_access_key': 'SECRET', "secret_access_key": "SECRET",
} }
assert container.config.aws.access_key_id() == 'KEY' assert container.config.aws.access_key_id() == "KEY"
assert container.config.aws.secret_access_key() == 'SECRET' assert container.config.aws.secret_access_key() == "SECRET"

View File

@ -14,15 +14,15 @@ class Foo:
class Container(containers.DeclarativeContainer): class Container(containers.DeclarativeContainer):
config = providers.Configuration(default={ config = providers.Configuration(default={
'target': 'A', "target": "A",
'items': { "items": {
'A': { "A": {
'option1': 60, "option1": 60,
'option2': 80, "option2": 80,
}, },
'B': { "B": {
'option1': 10, "option1": 10,
'option2': 20, "option2": 20,
}, },
}, },
}) })
@ -34,10 +34,10 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
container.config.target.from_env('TARGET') container.config.target.from_env("TARGET")
foo = container.foo_factory() foo = container.foo_factory()
print(foo.option1, foo.option2) print(foo.option1, foo.option2)

View File

@ -8,21 +8,21 @@ class Container(containers.DeclarativeContainer):
config = providers.Configuration() config = providers.Configuration()
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
container.config.from_yaml('examples/providers/configuration/config.yml') container.config.from_yaml("./config.yml")
container.config.from_yaml('examples/providers/configuration/config.local.yml') container.config.from_yaml("./config.local.yml")
assert container.config() == { assert container.config() == {
'aws': { "aws": {
'access_key_id': 'LOCAL-KEY', "access_key_id": "LOCAL-KEY",
'secret_access_key': 'LOCAL-SECRET', "secret_access_key": "LOCAL-SECRET",
}, },
} }
assert container.config.aws() == { assert container.config.aws() == {
'access_key_id': 'LOCAL-KEY', "access_key_id": "LOCAL-KEY",
'secret_access_key': 'LOCAL-SECRET', "secret_access_key": "LOCAL-SECRET",
} }
assert container.config.aws.access_key_id() == 'LOCAL-KEY' assert container.config.aws.access_key_id() == "LOCAL-KEY"
assert container.config.aws.secret_access_key() == 'LOCAL-SECRET' assert container.config.aws.secret_access_key() == "LOCAL-SECRET"

View File

@ -6,20 +6,20 @@ from dependency_injector import containers, providers
from pydantic import BaseSettings, Field from pydantic import BaseSettings, Field
# Emulate environment variables # Emulate environment variables
os.environ['AWS_ACCESS_KEY_ID'] = 'KEY' os.environ["AWS_ACCESS_KEY_ID"] = "KEY"
os.environ['AWS_SECRET_ACCESS_KEY'] = 'SECRET' os.environ["AWS_SECRET_ACCESS_KEY"] = "SECRET"
class AwsSettings(BaseSettings): class AwsSettings(BaseSettings):
access_key_id: str = Field(env='aws_access_key_id') access_key_id: str = Field(env="aws_access_key_id")
secret_access_key: str = Field(env='aws_secret_access_key') secret_access_key: str = Field(env="aws_secret_access_key")
class Settings(BaseSettings): class Settings(BaseSettings):
aws: AwsSettings = AwsSettings() aws: AwsSettings = AwsSettings()
optional: str = Field(default='default_value') optional: str = Field(default="default_value")
class Container(containers.DeclarativeContainer): class Container(containers.DeclarativeContainer):
@ -27,11 +27,11 @@ class Container(containers.DeclarativeContainer):
config = providers.Configuration() config = providers.Configuration()
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
container.config.from_pydantic(Settings()) container.config.from_pydantic(Settings())
assert container.config.aws.access_key_id() == 'KEY' assert container.config.aws.access_key_id() == "KEY"
assert container.config.aws.secret_access_key() == 'SECRET' assert container.config.aws.secret_access_key() == "SECRET"
assert container.config.optional() == 'default_value' assert container.config.optional() == "default_value"

View File

@ -20,7 +20,7 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
try: try:

View File

@ -20,7 +20,7 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
try: try:

View File

@ -22,17 +22,17 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
# Emulate environment variables # Emulate environment variables
os.environ['API_KEY'] = 'secret' os.environ["API_KEY"] = "secret"
os.environ['API_TIMEOUT'] = '5' os.environ["API_TIMEOUT"] = "5"
container.config.api.key.from_env('API_KEY') container.config.api.key.from_env("API_KEY")
container.config.api.timeout.from_env('API_TIMEOUT') container.config.api.timeout.from_env("API_TIMEOUT")
api_client = container.api_client_factory() api_client = container.api_client_factory()
assert api_client.api_key == 'secret' assert api_client.api_key == "secret"
assert api_client.timeout == 5 assert api_client.timeout == 5

View File

@ -21,14 +21,14 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
# Emulate environment variables # Emulate environment variables
os.environ['PI'] = '3.1415926535897932384626433832' os.environ["PI"] = "3.1415926535897932384626433832"
container.config.pi.from_env('PI') container.config.pi.from_env("PI")
calculator = container.calculator_factory() calculator = container.calculator_factory()
assert calculator.pi == decimal.Decimal('3.1415926535897932384626433832') assert calculator.pi == decimal.Decimal("3.1415926535897932384626433832")

View File

@ -10,15 +10,15 @@ class Container(containers.DeclarativeContainer):
config = providers.Configuration() config = providers.Configuration()
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
container.config.option1.from_value(date(2021, 6, 13)) container.config.option1.from_value(date(2021, 6, 13))
container.config.option2.from_value(date(2021, 6, 14)) container.config.option2.from_value(date(2021, 6, 14))
assert container.config() == { assert container.config() == {
'option1': date(2021, 6, 13), "option1": date(2021, 6, 13),
'option2': date(2021, 6, 14), "option2": date(2021, 6, 14),
} }
assert container.config.option1() == date(2021, 6, 13) assert container.config.option1() == date(2021, 6, 13)
assert container.config.option2() == date(2021, 6, 14) assert container.config.option2() == date(2021, 6, 14)

View File

@ -8,20 +8,20 @@ class Container(containers.DeclarativeContainer):
config = providers.Configuration() config = providers.Configuration()
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
container.config.from_yaml('examples/providers/configuration/config.yml') container.config.from_yaml("./config.yml")
assert container.config() == { assert container.config() == {
'aws': { "aws": {
'access_key_id': 'KEY', "access_key_id": "KEY",
'secret_access_key': 'SECRET', "secret_access_key": "SECRET",
}, },
} }
assert container.config.aws() == { assert container.config.aws() == {
'access_key_id': 'KEY', "access_key_id": "KEY",
'secret_access_key': 'SECRET', "secret_access_key": "SECRET",
} }
assert container.config.aws.access_key_id() == 'KEY' assert container.config.aws.access_key_id() == "KEY"
assert container.config.aws.secret_access_key() == 'SECRET' assert container.config.aws.secret_access_key() == "SECRET"

View File

@ -15,7 +15,7 @@ class Container(containers.DeclarativeContainer):
coroutine_provider = providers.Coroutine(coroutine, arg1=1, arg2=2) coroutine_provider = providers.Coroutine(coroutine, arg1=1, arg2=2)
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
arg1, arg2 = asyncio.run(container.coroutine_provider()) arg1, arg2 = asyncio.run(container.coroutine_provider())

View File

@ -5,7 +5,7 @@ from dependency_injector import containers, providers
class CustomFactory(providers.Provider): class CustomFactory(providers.Provider):
__slots__ = ('_factory',) __slots__ = ("_factory",)
def __init__(self, provides, *args, **kwargs): def __init__(self, provides, *args, **kwargs):
self._factory = providers.Factory(provides, *args, **kwargs) self._factory = providers.Factory(provides, *args, **kwargs)
@ -40,7 +40,7 @@ class Container(containers.DeclarativeContainer):
factory = CustomFactory(object) factory = CustomFactory(object)
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
object1 = container.factory() object1 = container.factory()

View File

@ -33,7 +33,7 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container1 = Container(database=providers.Singleton(SqliteDbAdapter)) container1 = Container(database=providers.Singleton(SqliteDbAdapter))
container2 = Container(database=providers.Singleton(PostgresDbAdapter)) container2 = Container(database=providers.Singleton(PostgresDbAdapter))

View File

@ -18,7 +18,7 @@ class Container(containers.DeclarativeContainer):
cache = providers.Dependency(instance_of=Cache, default=InMemoryCache()) cache = providers.Dependency(instance_of=Cache, default=InMemoryCache())
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
cache = container.cache() # provides InMemoryCache() cache = container.cache() # provides InMemoryCache()

View File

@ -25,7 +25,7 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
container.user_service() # <-- raises error: container.user_service() # <-- raises error:
# Dependency "Container.database" is not defined # Dependency "Container.database" is not defined

View File

@ -21,25 +21,25 @@ class Container(containers.DeclarativeContainer):
dispatcher_factory = providers.Factory( dispatcher_factory = providers.Factory(
Dispatcher, Dispatcher,
modules=providers.Dict( modules=providers.Dict(
module1=providers.Factory(Module, name='m1'), module1=providers.Factory(Module, name="m1"),
module2=providers.Factory(Module, name='m2'), module2=providers.Factory(Module, name="m2"),
), ),
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
dispatcher = container.dispatcher_factory() dispatcher = container.dispatcher_factory()
assert isinstance(dispatcher.modules, dict) assert isinstance(dispatcher.modules, dict)
assert dispatcher.modules['module1'].name == 'm1' assert dispatcher.modules["module1"].name == "m1"
assert dispatcher.modules['module2'].name == 'm2' assert dispatcher.modules["module2"].name == "m2"
# Call "dispatcher = container.dispatcher_factory()" is equivalent to: # Call "dispatcher = container.dispatcher_factory()" is equivalent to:
# dispatcher = Dispatcher( # dispatcher = Dispatcher(
# modules={ # modules={
# 'module1': Module(name='m1'), # "module1": Module(name="m1"),
# 'module2': Module(name='m2'), # "module2": Module(name="m2"),
# }, # },
# ) # )

View File

@ -46,7 +46,7 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
dispatcher = container.dispatcher_factory() dispatcher = container.dispatcher_factory()

View File

@ -12,7 +12,7 @@ class Container(containers.DeclarativeContainer):
user_factory = providers.Factory(User) user_factory = providers.Factory(User)
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
user1 = container.user_factory() user1 = container.user_factory()

View File

@ -13,8 +13,8 @@ class Game:
def play(self): def play(self):
print( print(
f'{self.player1} and {self.player2} are ' f"{self.player1} and {self.player2} are "
f'playing {self.__class__.__name__.lower()}' f"playing {self.__class__.__name__.lower()}"
) )
@ -39,7 +39,7 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
game_type = sys.argv[1].lower() game_type = sys.argv[1].lower()
player1 = sys.argv[2].capitalize() player1 = sys.argv[2].capitalize()
player2 = sys.argv[3].capitalize() player2 = sys.argv[3].capitalize()

View File

@ -20,7 +20,7 @@ class Container(containers.DeclarativeContainer):
service.add_attributes(client=client) service.add_attributes(client=client)
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
service = container.service() service = container.service()

View File

@ -17,7 +17,7 @@ class UserRepository:
def get_all(self) -> List[User]: def get_all(self) -> List[User]:
return [ return [
self.user_factory(**user_data) self.user_factory(**user_data)
for user_data in [{'uid': 1}, {'uid': 2}] for user_data in [{"uid": 1}, {"uid": 2}]
] ]
@ -31,7 +31,7 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
user_repository = container.user_repository_factory() user_repository = container.user_repository_factory()

View File

@ -23,7 +23,7 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
user1 = container.user_factory(1) user1 = container.user_factory(1)

View File

@ -39,7 +39,7 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
algorithm_1 = container.algorithm_factory( algorithm_1 = container.algorithm_factory(

View File

@ -29,5 +29,5 @@ try:
except errors.Error as exception: except errors.Error as exception:
print(exception) print(exception)
# The output is: # The output is:
# <class '__main__.ServiceProvider'> can provide only # <class "__main__.ServiceProvider"> can provide only
# <class '__main__.BaseService'> instances # <class "__main__.BaseService"> instances

View File

@ -21,25 +21,25 @@ class Container(containers.DeclarativeContainer):
dispatcher_factory = providers.Factory( dispatcher_factory = providers.Factory(
Dispatcher, Dispatcher,
modules=providers.List( modules=providers.List(
providers.Factory(Module, name='m1'), providers.Factory(Module, name="m1"),
providers.Factory(Module, name='m2'), providers.Factory(Module, name="m2"),
), ),
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
dispatcher = container.dispatcher_factory() dispatcher = container.dispatcher_factory()
assert isinstance(dispatcher.modules, list) assert isinstance(dispatcher.modules, list)
assert dispatcher.modules[0].name == 'm1' assert dispatcher.modules[0].name == "m1"
assert dispatcher.modules[1].name == 'm2' assert dispatcher.modules[1].name == "m2"
# Call "dispatcher = container.dispatcher_factory()" is equivalent to: # Call "dispatcher = container.dispatcher_factory()" is equivalent to:
# dispatcher = Dispatcher( # dispatcher = Dispatcher(
# modules=[ # modules=[
# Module(name='m1'), # Module(name="m1"),
# Module(name='m2'), # Module(name="m2"),
# ], # ],
# ) # )

View File

@ -8,7 +8,7 @@ class Container(containers.DeclarativeContainer):
object_provider = providers.Object(1) object_provider = providers.Object(1)
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
assert container.object_provider() == 1 assert container.object_provider() == 1

View File

@ -29,7 +29,7 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
# 1. Use .override() to replace the API client with stub # 1. Use .override() to replace the API client with stub

View File

@ -5,7 +5,7 @@ from dependency_injector import containers, providers
class Service: class Service:
def __init__(self): def __init__(self):
self.value = 'foo' self.value = "foo"
self.values = [self.value] self.values = [self.value]
def get_value(self): def get_value(self):
@ -36,8 +36,8 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
client = container.client_factory() client = container.client_factory()
assert client.value1 == client.value2 == client.value3 == 'foo' assert client.value1 == client.value2 == client.value3 == "foo"

View File

@ -18,23 +18,23 @@ class Container(containers.DeclarativeContainer):
dependency = providers.Object( dependency = providers.Object(
{ {
'foo': { "foo": {
'bar': 10, "bar": 10,
'baz': lambda arg: {'arg': arg} "baz": lambda arg: {"arg": arg}
}, },
}, },
) )
demo_list = providers.List( demo_list = providers.List(
dependency.provided['foo']['bar'], dependency.provided["foo"]["bar"],
dependency.provided['foo']['baz'].call(22)['arg'], dependency.provided["foo"]["baz"].call(22)["arg"],
dependency.provided['foo']['baz'].call(service)['arg'], dependency.provided["foo"]["baz"].call(service)["arg"],
dependency.provided['foo']['baz'].call(service)['arg'].value, dependency.provided["foo"]["baz"].call(service)["arg"].value,
dependency.provided['foo']['baz'].call(service)['arg'].get_value.call(), dependency.provided["foo"]["baz"].call(service)["arg"].get_value.call(),
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
assert container.demo_list() == [ assert container.demo_list() == [

View File

@ -22,13 +22,13 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
container.config.override({'one_or_another': 'one'}) container.config.override({"one_or_another": "one"})
instance_1 = container.selector() instance_1 = container.selector()
assert isinstance(instance_1, SomeClass) assert isinstance(instance_1, SomeClass)
container.config.override({'one_or_another': 'another'}) container.config.override({"one_or_another": "another"})
instance_2 = container.selector() instance_2 = container.selector()
assert isinstance(instance_2, SomeOtherClass) assert isinstance(instance_2, SomeOtherClass)

View File

@ -12,7 +12,7 @@ class Container(containers.DeclarativeContainer):
user_service_provider = providers.Singleton(UserService) user_service_provider = providers.Singleton(UserService)
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
user_service1 = container.user_service_provider() user_service1 = container.user_service_provider()

View File

@ -19,7 +19,7 @@ class Container(containers.DeclarativeContainer):
user_service = providers.Singleton(UserService, db=database) user_service = providers.Singleton(UserService, db=database)
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
user_service1 = container.user_service() user_service1 = container.user_service()

View File

@ -12,7 +12,7 @@ class Container(containers.DeclarativeContainer):
user_service_provider = providers.Singleton(UserService) user_service_provider = providers.Singleton(UserService)
if __name__ == '__main__': if __name__ == "__main__":
container1 = Container() container1 = Container()
user_service1 = container1.user_service_provider() user_service1 = container1.user_service_provider()
assert user_service1 is container1.user_service_provider() assert user_service1 is container1.user_service_provider()

View File

@ -12,7 +12,7 @@ class Container(containers.DeclarativeContainer):
user_service = providers.Singleton(UserService) user_service = providers.Singleton(UserService)
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
user_service1 = container.user_service() user_service1 = container.user_service()

View File

@ -12,7 +12,7 @@ class Container(containers.DeclarativeContainer):
user_service = providers.Singleton(UserService) user_service = providers.Singleton(UserService)
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
user_service1 = container.user_service() user_service1 = container.user_service()

View File

@ -18,7 +18,7 @@ def index_view():
service_2 = current_app.container.service_provider() service_2 = current_app.container.service_provider()
assert service_1 is service_2 assert service_1 is service_2
print(service_1) print(service_1)
return 'Hello World!' return "Hello World!"
def teardown_context(request): def teardown_context(request):
@ -30,9 +30,9 @@ container = Container()
app = Flask(__name__) app = Flask(__name__)
app.container = container app.container = container
app.add_url_rule('/', 'index', view_func=index_view) app.add_url_rule("/", "index", view_func=index_view)
app.after_request(teardown_context) app.after_request(teardown_context)
if __name__ == '__main__': if __name__ == "__main__":
app.run() app.run()

View File

@ -28,14 +28,14 @@ class Container(containers.DeclarativeContainer):
) )
if __name__ == '__main__': if __name__ == "__main__":
container = Container() container = Container()
n = 10 n = 10
threads = [] threads = []
for thread_number in range(n): for thread_number in range(n):
threads.append( threads.append(
container.thread_factory(name='Thread{0}'.format(thread_number)), container.thread_factory(name="Thread{0}".format(thread_number)),
) )
for thread in threads: for thread in threads:
thread.start() thread.start()