1 2
from os import environ
2

3 2
from dynaconf.utils import upperfy
4 2
from dynaconf.utils.parse_conf import parse_conf_data
5 2
from dynaconf.vendor.dotenv import cli as dotenv_cli
6

7

8 2
IDENTIFIER = "env"
9

10

11 2
def load(obj, env=None, silent=True, key=None):
12
    """Loads envvars with prefixes:
13

14
    `DYNACONF_` (default global) or `$(ENVVAR_PREFIX_FOR_DYNACONF)_`
15
    """
16 2
    global_prefix = obj.get("ENVVAR_PREFIX_FOR_DYNACONF")
17 2
    if global_prefix is False or global_prefix.upper() != "DYNACONF":
18 2
        load_from_env(obj, "DYNACONF", key, silent, IDENTIFIER + "_global")
19

20
    # Load the global env if exists and overwrite everything
21 2
    load_from_env(obj, global_prefix, key, silent, IDENTIFIER + "_global")
22

23

24 2
def load_from_env(
25
    obj,
26
    prefix=False,
27
    key=None,
28
    silent=False,
29
    identifier=IDENTIFIER,
30
    env=False,  # backwards compatibility bc renamed param
31
):
32 2
    if prefix is False and env is not False:
33 2
        prefix = env
34

35 2
    env_ = ""
36 2
    if prefix is not False:
37 2
        if not isinstance(prefix, str):
38 2
            raise TypeError("`prefix/env` must be str or False")
39

40 2
        prefix = prefix.upper()
41 2
        env_ = f"{prefix}_"
42

43 2
    if key:
44 2
        key = upperfy(key)
45 2
        value = environ.get(f"{env_}{key}")
46 2
        if value:
47 2
            try:  # obj is a Settings
48 2
                obj.set(key, value, loader_identifier=identifier, tomlfy=True)
49 2
            except AttributeError:  # obj is a dict
50 2
                obj[key] = parse_conf_data(
51
                    value, tomlfy=True, box_settings=obj
52
                )
53
    else:
54 2
        trim_len = len(env_)
55 2
        data = {
56
            key[trim_len:]: parse_conf_data(
57
                data, tomlfy=True, box_settings=obj
58
            )
59
            for key, data in environ.items()
60
            if key.startswith(env_)
61
        }
62 2
        if data:
63 2
            obj.update(data, loader_identifier=identifier)
64

65

66 2
def write(settings_path, settings_data, **kwargs):
67
    """Write data to .env file"""
68 2
    for key, value in settings_data.items():
69 2
        quote_mode = (
70
            isinstance(value, str)
71
            and (value.startswith("'") or value.startswith('"'))
72
        ) or isinstance(value, (list, dict))
73 2
        dotenv_cli.set_key(
74
            str(settings_path),
75
            key,
76
            str(value),
77
            quote_mode="always" if quote_mode else "none",
78
        )

Read our documentation on viewing source code .

Loading