Skip to content

Commit

Permalink
Configuration(pydantic_settings=[...]) (#525)
Browse files Browse the repository at this point in the history
* Add implementation

* Update changelog

* Fix deepcopy()

* Add example

* Add tests

* Add docs
  • Loading branch information
rmk135 committed Oct 27, 2021
1 parent 34902db commit 6030950
Show file tree
Hide file tree
Showing 10 changed files with 6,808 additions and 6,169 deletions.
1 change: 1 addition & 0 deletions docs/main/changelog.rst
Expand Up @@ -16,6 +16,7 @@ Develop
- Add support of ``with`` statement for ``container.override_providers()`` method.
- Add ``Configuration(yaml_files=[...])`` argument.
- Add ``Configuration(ini_files=[...])`` argument.
- Add ``Configuration(pydantic_settings=[...])`` argument.
- Drop support of Python 3.4. There are no immediate breaking changes, but Dependency Injector
will no longer be tested on Python 3.4 and any bugs will not be fixed.
- Fix ``Dependency.is_defined`` attribute to always return boolean value.
Expand Down
15 changes: 15 additions & 0 deletions docs/providers/configuration.rst
Expand Up @@ -154,6 +154,21 @@ If you need to pass an argument to this call, use ``.from_pydantic()`` keyword a
container.config.from_pydantic(Settings(), exclude={"optional"})
Alternatively, you can provide a ``pydantic`` settings object over the configuration provider argument. In that case,
the container will call ``config.from_pydantic()`` automatically:

.. code-block:: python
:emphasize-lines: 3
class Container(containers.DeclarativeContainer):
config = providers.Configuration(pydantic_settings=[Settings()])
if __name__ == "__main__":
container = Container() # Config is loaded from Settings()
.. note::

``Dependency Injector`` doesn't install ``pydantic`` by default.
Expand Down
35 changes: 35 additions & 0 deletions examples/providers/configuration/configuration_pydantic_init.py
@@ -0,0 +1,35 @@
"""`Configuration` provider values loading example."""

import os

from dependency_injector import containers, providers
from pydantic import BaseSettings, Field

# Emulate environment variables
os.environ["AWS_ACCESS_KEY_ID"] = "KEY"
os.environ["AWS_SECRET_ACCESS_KEY"] = "SECRET"


class AwsSettings(BaseSettings):

access_key_id: str = Field(env="aws_access_key_id")
secret_access_key: str = Field(env="aws_secret_access_key")


class Settings(BaseSettings):

aws: AwsSettings = AwsSettings()
optional: str = Field(default="default_value")


class Container(containers.DeclarativeContainer):

config = providers.Configuration(pydantic_settings=[Settings()])


if __name__ == "__main__":
container = Container()

assert container.config.aws.access_key_id() == "KEY"
assert container.config.aws.secret_access_key() == "SECRET"
assert container.config.optional() == "default_value"

0 comments on commit 6030950

Please sign in to comment.