Skip to content

Settings

Provide settings modules.

EnvironsMixin

Manage environment variables.

prefix: str property writable

Get environment prefix.

load_dotenv() staticmethod

Load environs from .env file.

Source code in compendium/settings.py
58
59
60
61
62
63
64
65
66
67
@staticmethod
def load_dotenv() -> None:
    '''Load environs from .env file.'''
    env_file = os.path.join(os.getcwd(), '.env')
    # if self._check_filepath(env_file):
    if os.path.exists(env_file):
        with open(env_file) as env:
            for line in env:
                k, v = line.partition('=')[::2]
                os.environ[k.strip().upper()] = str(v)

load_environs(self, force=False)

Load environment variables.

Source code in compendium/settings.py
69
70
71
72
73
74
75
76
def load_environs(self, force: bool = False) -> Dict[str, Any]:
    '''Load environment variables.'''
    prefix = str(f"{self.prefix}_" if self.prefix != '' else self.prefix)
    env: Dict[str, Any] = {}
    for k, v in os.environ.items():
        if k.startswith(prefix):
            env = self.merge(env, self.to_dict(k.replace(prefix, ''), v),)
    return env

to_dict(key, value) staticmethod

Convert environment key to dictionary.

Source code in compendium/settings.py
45
46
47
48
49
50
51
52
53
54
55
56
@staticmethod
def to_dict(key: str, value: Any) -> Dict[str, Any]:
    '''Convert environment key to dictionary.'''

    def expand(x):
        '''Convert key part to dictionary key.'''
        if '_' not in x:
            return {x: value}
        k, v = x.split('_', 1)
        return {k: expand(v)}

    return expand(key.lower())

MergeMixin

Merge dictionaries.

merge(source, update) classmethod

Perform recursive merge.

Source code in compendium/settings.py
18
19
20
21
22
23
24
25
26
@classmethod
def merge(self, source, update):
    '''Perform recursive merge.'''
    for k, v in update.items():
        if isinstance(v, Mapping):
            source[k] = self.merge(source.get(k, {}), v)
        else:
            source[k] = v
    return source

SettingsMap

Manage settings loaded from confiugrations using dpath.

__init__(self, *args, **kwargs) special

Initialize settings store.

Source code in compendium/settings.py
82
83
84
85
86
def __init__(self, *args, **kwargs):
    '''Initialize settings store.'''
    if 'separator' in kwargs:
        self.separator: str = kwargs.pop('separator')
    super().__init__(*args)

push(self, settings)

Push settings untop store.

Source code in compendium/settings.py
88
89
90
91
def push(self, settings) -> None:
    '''Push settings untop store.'''
    logging.debug(settings)
    self.maps.insert(0, settings)