1 2
import io
2 2
from pathlib import Path
3

4 2
from dynaconf import default_settings
5 2
from dynaconf.constants import INI_EXTENSIONS
6 2
from dynaconf.loaders.base import BaseLoader
7 2
from dynaconf.utils import object_merge
8

9 2
try:
10 2
    from configobj import ConfigObj
11
except ImportError:  # pragma: no cover
12
    ConfigObj = None
13

14

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

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

30 2
    loader = BaseLoader(
31
        obj=obj,
32
        env=env,
33
        identifier="ini",
34
        extensions=INI_EXTENSIONS,
35
        file_reader=lambda fileobj: ConfigObj(fileobj).dict(),
36
        string_reader=lambda strobj: ConfigObj(strobj.split("\n")).dict(),
37
    )
38 2
    loader.load(filename=filename, key=key, silent=silent)
39

40

41 2
def write(settings_path, settings_data, merge=True):
42
    """Write data to a settings file.
43

44
    :param settings_path: the filepath
45
    :param settings_data: a dictionary with data
46
    :param merge: boolean if existing file should be merged with new data
47
    """
48 2
    settings_path = Path(settings_path)
49
    if settings_path.exists() and merge:  # pragma: no cover
50
        with io.open(
51
            str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
52
        ) as open_file:
53
            object_merge(ConfigObj(open_file).dict(), settings_data)
54 2
    new = ConfigObj()
55 2
    new.update(settings_data)
56 2
    new.write(open(str(settings_path), "bw"))

Read our documentation on viewing source code .

Loading