-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfig_translator.py
113 lines (93 loc) · 3.09 KB
/
config_translator.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import configparser
import json
from functools import lru_cache
class ConfigTranslator:
"""
Singleton Class which reads the configuration from the configuration file and can retrieve configuration values
"""
instance = None
class __ConfigTranslator:
def __init__(self, filename):
"""
Reads the filename and sets the config parser
:param filename:
"""
self.config = configparser.ConfigParser()
self.filename = filename
self.config.read(filename)
@lru_cache
def get_string(self, block, name):
"""
Return a String from the configuration parser
:param block:
:param name:
:return: String value from the configuration parser or "" as default value.
"""
try:
return self.config.get(block, name)
except configparser.NoOptionError:
return ""
except configparser.NoSectionError:
return ""
@lru_cache
def get_float(self, block, name):
"""
Get a float value from the configuration pareser
:param block:
:param name:
:return: a float value from the configuration parser or 0.0 as default value.
"""
str_value = self.get_string(block, name)
try:
return float(str_value)
except:
return 0.0
@lru_cache
def get_interger(self, block, name):
"""
:param block:
:param name:
:return: an integer value from the configuration parser or 0 as default value.
"""
str_value = self.get_string(block, name)
try:
return int(str_value)
except:
return 0
@lru_cache
def get_boolean(self, block, name):
"""
:param block:
:param name:
:return: an boolean value from the configuration parser or 0 as default value.
"""
str_value = self.get_string(block, name)
try:
return bool(str_value)
except:
return False
@lru_cache
def get_list(self, block, name):
try:
v = self.config.get(block, name)
return set(json.loads(v))
except Exception as e:
print(e)
return set()
def __new__(cls, filename=None):
"""
Implementation of th singleton method.
:param filename:
"""
if ConfigTranslator.instance is None:
ConfigTranslator.instance = ConfigTranslator.__ConfigTranslator(filename)
return ConfigTranslator.instance
def __getattr__(self, name):
return getattr(self.instance, name)
if __name__ == "__main__":
tr = ConfigTranslator("config.cfg")
l = tr.get_list("default", "context")
print(l)
print(type(l))
v = tr.get_boolean("brokerld", "concat_arrays")
print(v)