1 2
import io
2 2
import json
3 2
from pathlib import Path
4

5 2
from dynaconf import default_settings
6 2
from dynaconf.constants import JSON_EXTENSIONS
7 2
from dynaconf.loaders.base import BaseLoader
8 2
from dynaconf.utils import object_merge
9 2
from dynaconf.utils.parse_conf import try_to_encode
10

11
try:  # pragma: no cover
12
    import commentjson
13
except ImportError:  # pragma: no cover
14
    commentjson = None
15

16

17 2
def load(obj, env=None, silent=True, key=None, filename=None):
18
    """
19
    Reads and loads in to "obj" a single key or all keys from source file.
20

21
    :param obj: the settings instance
22
    :param env: settings current env default='development'
23
    :param silent: if errors should raise
24
    :param key: if defined load a single key, else load all in env
25
    :param filename: Optional custom filename to load
26
    :return: None
27
    """
28
    if (
29
        obj.get("COMMENTJSON_ENABLED_FOR_DYNACONF") and commentjson
30
    ):  # pragma: no cover  # noqa
31
        file_reader = commentjson.load
32
        string_reader = commentjson.loads
33
    else:
34 2
        file_reader = json.load
35 2
        string_reader = json.loads
36

37 2
    loader = BaseLoader(
38
        obj=obj,
39
        env=env,
40
        identifier="json",
41
        extensions=JSON_EXTENSIONS,
42
        file_reader=file_reader,
43
        string_reader=string_reader,
44
    )
45 2
    loader.load(filename=filename, key=key, silent=silent)
46

47

48 2
def write(settings_path, settings_data, merge=True):
49
    """Write data to a settings file.
50

51
    :param settings_path: the filepath
52
    :param settings_data: a dictionary with data
53
    :param merge: boolean if existing file should be merged with new data
54
    """
55 2
    settings_path = Path(settings_path)
56
    if settings_path.exists() and merge:  # pragma: no cover
57
        with io.open(
58
            str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
59
        ) as open_file:
60
            object_merge(json.load(open_file), settings_data)
61

62 2
    with io.open(
63
        str(settings_path),
64
        "w",
65
        encoding=default_settings.ENCODING_FOR_DYNACONF,
66
    ) as open_file:
67 2
        json.dump(settings_data, open_file, cls=DynaconfEncoder)
68

69

70 2
class DynaconfEncoder(json.JSONEncoder):
71
    """Transform Dynaconf custom types instances to json representation"""
72

73 2
    def default(self, o):
74 2
        return try_to_encode(o, callback=super().default)

Read our documentation on viewing source code .

Loading