-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_config.py
66 lines (50 loc) · 1.84 KB
/
json_config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import os
import json
from .config import *
from ..exceptions import ConfigNotLoadedError
class JsonConfig(BaseConfig):
"""Json config loader"""
def __init__(self, filepath: str, authoload: bool = True):
self._filepath = None
self._config = None
self._config_type: type[list | dict] | None = None
self.set_filepath(filepath)
if authoload:
self.load()
@property
def type(self):
return self._config_type
def set_filepath(self, filepath: str) -> None:
if not os.path.exists(filepath):
raise FileNotFoundError(f'File "{filepath}" not found')
self._filepath = filepath
def load(self):
with open(self._filepath, 'r') as cf:
try:
self._config = json.load(cf)
except json.decoder.JSONDecodeError as e:
raise json.decoder.JSONDecodeError(f'File "{self._filepath}" has wrong format', e.doc, e.pos)
self._config_type = type(self._config)
def save(self):
with open(self._filepath, 'w') as cf:
if self._config:
json.dump(self._config, cf)
def get(self, key: str | int, default: any = None) -> any:
try:
return self.__getitem__(key)
except (KeyError, IndexError):
return default
def __getitem__(self, item):
if self._config:
return self._config[item]
else:
raise ConfigNotLoadedError('Config not loaded yet')
def __iter__(self):
if issubclass(self._config_type, dict):
return iter(self._config.items())
elif issubclass(self._config_type, list):
return iter(self._config)
def __repr__(self):
if self._config:
return json.dumps(self._config, indent=4, sort_keys=True)
return 'Not loaded'