1 2
import io
2 2
from pathlib import Path
3

4 2
from dynaconf import default_settings
5 2
from dynaconf.constants import TOML_EXTENSIONS
6 2
from dynaconf.loaders.base import BaseLoader
7 2
from dynaconf.utils import object_merge
8 2
from dynaconf.vendor import toml
9

10

11 2
def load(obj, env=None, silent=True, key=None, filename=None):
12
    """
13
    Reads and loads in to "obj" a single key or all keys from source file.
14

15
    :param obj: the settings instance
16
    :param env: settings current env default='development'
17
    :param silent: if errors should raise
18
    :param key: if defined load a single key, else load all in env
19
    :param filename: Optional custom filename to load
20
    :return: None
21
    """
22
    if toml is None:  # pragma: no cover
23
        BaseLoader.warn_not_installed(obj, "toml")
24
        return
25

26 2
    loader = BaseLoader(
27
        obj=obj,
28
        env=env,
29
        identifier="toml",
30
        extensions=TOML_EXTENSIONS,
31
        file_reader=toml.load,
32
        string_reader=toml.loads,
33
    )
34 2
    loader.load(filename=filename, key=key, silent=silent)
35

36

37 2
def write(settings_path, settings_data, merge=True):
38
    """Write data to a settings file.
39

40
    :param settings_path: the filepath
41
    :param settings_data: a dictionary with data
42
    :param merge: boolean if existing file should be merged with new data
43
    """
44 2
    settings_path = Path(settings_path)
45
    if settings_path.exists() and merge:  # pragma: no cover
46
        with io.open(
47
            str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
48
        ) as open_file:
49
            object_merge(toml.load(open_file), settings_data)
50

51 2
    with io.open(
52
        str(settings_path),
53
        "w",
54
        encoding=default_settings.ENCODING_FOR_DYNACONF,
55
    ) as open_file:
56 2
        toml.dump(encode_nulls(settings_data), open_file)
57

58

59 2
def encode_nulls(data):
60
    """TOML does not support `None` so this function transforms to '@none '."""
61 2
    if data is None:
62 2
        return "@none "
63 2
    if isinstance(data, dict):
64 2
        return {key: encode_nulls(value) for key, value in data.items()}
65 2
    elif isinstance(data, (list, tuple)):
66 2
        return [encode_nulls(item) for item in data]
67 2
    return data

Read our documentation on viewing source code .

Loading