Repository: rochacbruno/dynaconf
Pull request #332 (2020-05-05 03:48:09)

Add support for aliased configs
Now when creating a `LazySettings` instance one can use aliases

So instead of `LazySettings("ENV_FOR_DYNACONF='FOO'")` it can be:

`LazySettings(ENV="FOO")`

codecov[bot]: # [Codecov](https://codecov.io/gh/rochacbruno/dynaconf/pull/332?src=pr&el=h1) Report
> Merging [#332](https://codecov.io/gh/rochacbruno/dynaconf/pull/332?src=pr&el=desc) into [master](https://codecov.io/gh/rochacbruno/dynaconf/commit/2041fa83f3da018474b34511678e474662187b29&el=desc) will **not change** coverage.
> The diff coverage is `100.00%`.

[![Impacted file tree graph](https://codecov.io/gh/rochacbruno/dynaconf/pull/332/graphs/tree.svg?width=650&height=150&src=pr&token=GXszVzJcqW)](https://codecov.io/gh/rochacbruno/dynaconf/pull/332?src=pr&el=tree)

```diff
@@            Coverage Diff            @@
##            master      #332   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           18        18           
  Lines          957       957           
=========================================
  Hits           957       957           
```


| [Impacted Files](https://codecov.io/gh/rochacbruno/dynaconf/pull/332?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [dynaconf/contrib/flask\_dynaconf.py](https://codecov.io/gh/rochacbruno/dynaconf/pull/332/diff?src=pr&el=tree#diff-ZHluYWNvbmYvY29udHJpYi9mbGFza19keW5hY29uZi5weQ==) | `100.00% <100.00%> (ø)` | |

------

[Continue to review full report at Codecov](https://codecov.io/gh/rochacbruno/dynaconf/pull/332?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/rochacbruno/dynaconf/pull/332?src=pr&el=footer). Last update [2041fa8...528168a](https://codecov.io/gh/rochacbruno/dynaconf/pull/332?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/dynaconf/base.py b/dynaconf/base.py
index 41969de..a4a462d 100644
--- a/dynaconf/base.py
+++ b/dynaconf/base.py
@@ -56,8 +56,8 @@ class LazySettings(LazyObject):
     in a file `proj/conf.py`::
 
         >>> from dynaconf import LazySettings
-        >>> config = LazySettings(ENV_FOR_DYNACONF='PROJ',
-        ...                       LOADERS_FOR_DYNACONF=[
+        >>> config = LazySettings(ENV='PROJ',
+        ...                       LOADERS=[
         ...                             'dynaconf.loaders.env_loader',
         ...                             'dynaconf.loaders.redis_loader'
         ...                       ])
@@ -87,10 +87,27 @@ class LazySettings(LazyObject):
 
         :param kwargs: values that overrides default_settings
         """
+        self.resolve_config_aliases(kwargs)
         compat_kwargs(kwargs)
         self._kwargs = kwargs
         super(LazySettings, self).__init__()
 
+    def resolve_config_aliases(self, kwargs):
+        """takes aliases for _FOR_DYNACONF configurations
+
+        e.g: ROOT_PATH='/' is transformed into `ROOT_PATH_FOR_DYNACONF`
+        """
+        for_dynaconf_keys = {
+            key
+            for key in dir(default_settings)
+            if key.endswith("_FOR_DYNACONF")
+        }
+        aliases = {
+            key for key in kwargs if f"{key}_FOR_DYNACONF" in for_dynaconf_keys
+        }
+        for alias in aliases:
+            kwargs[f"{alias}_FOR_DYNACONF"] = kwargs.pop(alias)
+
     @evaluate_lazy_format
     def __getattr__(self, name):
         """Allow getting keys from self.store using dot notation"""
diff --git a/dynaconf/contrib/django_dynaconf/dynaconf_django_conf.py b/dynaconf/contrib/django_dynaconf/dynaconf_django_conf.py
index 8dc850b..e68ea25 100644
--- a/dynaconf/contrib/django_dynaconf/dynaconf_django_conf.py
+++ b/dynaconf/contrib/django_dynaconf/dynaconf_django_conf.py
@@ -1,4 +1,4 @@
-# WARNING: THIS EXTENSION IS DEPRECATED
+# WARNING: THIS EXTENSION IS DEPRECATED in favor of django_dynaconf_v2
 # Read more on how to integrate with django on
 # https://dynaconf.readthedocs.io/en/latest/guides/django.html
 import os
@@ -7,20 +7,15 @@ from django.conf import settings as django_settings
 
 from dynaconf import LazySettings
 
-
 dj = {}
+
 for key in dir(django_settings):
     if key.isupper() and key != "SETTINGS_MODULE":
         dj[key] = getattr(django_settings, key, None)
     dj["ORIGINAL_SETTINGS_MODULE"] = django_settings.SETTINGS_MODULE
 
-
-dj.setdefault("ENVVAR_PREFIX_FOR_DYNACONF", "DJANGO")
-
-env_prefix = f"{dj['ENVVAR_PREFIX_FOR_DYNACONF']}_ENV"  # DJANGO_ENV
-
-dj.setdefault(
-    "ENV_FOR_DYNACONF", os.environ.get(env_prefix, "DEVELOPMENT").upper()
-)
+dj.setdefault("ENVVAR_PREFIX", "DJANGO")
+env_prefix = f"{dj['ENVVAR_PREFIX']}_ENV"  # DJANGO_ENV
+dj.setdefault("ENV", os.environ.get(env_prefix, "DEVELOPMENT").upper())
 
 settings = LazySettings(**dj)
diff --git a/dynaconf/contrib/flask_dynaconf.py b/dynaconf/contrib/flask_dynaconf.py
index 6080d16..460a605 100644
--- a/dynaconf/contrib/flask_dynaconf.py
+++ b/dynaconf/contrib/flask_dynaconf.py
@@ -63,8 +63,8 @@ class FlaskDynaconf(object):
         app = Flask(__name__)
         FlaskDynaconf(
             app,
-            ENV_FOR_DYNACONF='MYSITE',
-            SETTINGS_FILE_FOR_DYNACONF='settings.yml',
+            ENV='MYSITE',
+            SETTINGS_FILE='settings.yml',
             EXTRA_VALUE='You can add aditional config vars here'
         )
 
@@ -87,11 +87,9 @@ class FlaskDynaconf(object):
             )
         self.kwargs = kwargs
 
-        kwargs.setdefault("ENVVAR_PREFIX_FOR_DYNACONF", "FLASK")
-
-        env_prefix = f"{kwargs['ENVVAR_PREFIX_FOR_DYNACONF']}_ENV"  # FLASK_ENV
-
-        kwargs.setdefault("ENV_SWITCHER_FOR_DYNACONF", env_prefix)
+        kwargs.setdefault("ENVVAR_PREFIX", "FLASK")
+        env_prefix = f"{kwargs['ENVVAR_PREFIX']}_ENV"  # FLASK_ENV
+        kwargs.setdefault("ENV_SWITCHER", env_prefix)
 
         self.dynaconf_instance = dynaconf_instance
         self.instance_relative_config = instance_relative_config
diff --git a/example/compat.py b/example/compat.py
index acd0f93..8b84420 100644
--- a/example/compat.py
+++ b/example/compat.py
@@ -72,9 +72,9 @@ print(settings.FRESH_VARS_FOR_DYNACONF)
 
 
 settings = LazySettings(
-    NAMESPACE_FOR_DYNACONF="FOO",
+    NAMESPACE="FOO",
     SETTINGS_MODULE="foo.py",
-    PROJECT_ROOT_FOR_DYNACONF="/tmp",
+    PROJECT_ROOT="/tmp",
     DYNACONF_SILENT_ERRORS=True,
     DYNACONF_ALWAYS_FRESH_VARS=["BAR"],
 )
diff --git a/example/validators/with_python/conf.py b/example/validators/with_python/conf.py
index d57c0ff..d8830c7 100644
--- a/example/validators/with_python/conf.py
+++ b/example/validators/with_python/conf.py
@@ -1,7 +1,7 @@
 from dynaconf import LazySettings
 from dynaconf import Validator
 
-settings = LazySettings(ENV_FOR_DYNACONF="EXAMPLE")
+settings = LazySettings(ENV="EXAMPLE")
 
 settings.validators.register(
     Validator("VERSION", "AGE", "NAME", must_exist=True),


Test patch:
diff --git a/tests/test_base.py b/tests/test_base.py
index 643aca8..3ccba53 100644
--- a/tests/test_base.py
+++ b/tests/test_base.py
@@ -739,3 +739,38 @@ def test_preload(tmpdir):
         "github": "rochacbruno.github.io",
         "mastodon": "mastodon.social/@rochacbruno",
     }
+
+
+def test_config_aliases(tmpdir):
+    data = {
+        "hello": {"name": "Bruno", "passwd": 1234},
+        "awesome": {"passwd": 5678},
+    }
+    toml_loader.write(str(tmpdir.join("blarg.toml")), data, merge=False)
+
+    settings = LazySettings(
+        ENVVAR_PREFIX="BRUCE",
+        CORE_LOADERS=["TOML"],
+        LOADERS=["dynaconf.loaders.env_loader"],
+        DEFAULT_ENV="hello",
+        ENV_SWITCHER="BRUCE_ENV",
+        PRELOAD=[],
+        SETTINGS_FILE=["blarg.toml"],
+        INCLUDES=[],
+        ENV="awesome",
+    )
+
+    assert settings.NAME == "Bruno"
+    assert settings.PASSWD == 5678
+
+    assert settings.ENVVAR_PREFIX_FOR_DYNACONF == "BRUCE"
+    assert settings.CORE_LOADERS_FOR_DYNACONF == ["TOML"]
+    assert settings.LOADERS_FOR_DYNACONF == ["dynaconf.loaders.env_loader"]
+    assert len(settings._loaders) == 1
+    assert settings.DEFAULT_ENV_FOR_DYNACONF == "hello"
+    assert settings.ENV_SWITCHER_FOR_DYNACONF == "BRUCE_ENV"
+    assert settings.PRELOAD_FOR_DYNACONF == []
+    assert settings.SETTINGS_FILE_FOR_DYNACONF == ["blarg.toml"]
+    assert settings.INCLUDES_FOR_DYNACONF == []
+    assert settings.ENV_FOR_DYNACONF == "awesome"
+    assert settings.current_env == "awesome"