This commit is contained in:
Roman Mogylatov 2021-01-16 08:47:55 -05:00
parent d3d907d4e5
commit e758fa9d95
3 changed files with 82 additions and 0 deletions

View File

@ -143,6 +143,28 @@ With the ``.as_(callback, *args, **kwargs)`` you can specify a function that wil
before the injection. The value from the config will be passed as a first argument. The returned
value will be injected. Parameters ``*args`` and ``**kwargs`` are handled as any other injections.
Strict mode and required options
--------------------------------
You can use configuration provider in strict mode. In strict mode configuration provider raises an error
on access to any undefined option.
.. literalinclude:: ../../examples/providers/configuration/configuration_strict.py
:language: python
:lines: 3-
:emphasize-lines: 12
You can also use ``.required()`` option modifier when making an injection.
.. literalinclude:: ../../examples/providers/configuration/configuration_required.py
:language: python
:lines: 11-20
:emphasize-lines: 8-9
.. note::
Modifier ``.required()`` should be specified before type modifier ``.as_*()``.
Injecting invariants
--------------------

View File

@ -0,0 +1,30 @@
"""`Configuration` provider strict mode example."""
from dependency_injector import containers, providers, errors
class ApiClient:
def __init__(self, api_key: str, timeout: int):
self.api_key = api_key
self.timeout = timeout
class Container(containers.DeclarativeContainer):
config = providers.Configuration()
api_client_factory = providers.Factory(
ApiClient,
api_key=config.api.key.required(),
timeout=config.api.timeout.required().as_int(),
)
if __name__ == '__main__':
container = Container()
try:
api_client = container.api_client_factory()
except errors.Error:
# raises error: Undefined configuration option "config.api.key"
...

View File

@ -0,0 +1,30 @@
"""`Configuration` provider strict mode example."""
from dependency_injector import containers, providers, errors
class ApiClient:
def __init__(self, api_key: str, timeout: int):
self.api_key = api_key
self.timeout = timeout
class Container(containers.DeclarativeContainer):
config = providers.Configuration(strict=True)
api_client_factory = providers.Factory(
ApiClient,
api_key=config.api.key,
timeout=config.api.timeout.as_int(),
)
if __name__ == '__main__':
container = Container()
try:
api_client = container.api_client_factory()
except errors.Error:
# raises error: Undefined configuration option "config.api.key"
...