Files
mt5-correlation/mt5_correlation/config.py
T

89 lines
2.1 KiB
Python
Raw Normal View History

2021-02-10 18:21:49 +00:00
import yaml
import definitions
class Config(object):
"""
Provides access to application configuration parameters stored in config.yaml.
"""
2021-02-16 17:15:00 +00:00
config_filepath = None
__config = None
__instance = None
2021-02-10 18:21:49 +00:00
2021-02-16 17:15:00 +00:00
def __new__(cls):
2021-02-10 18:21:49 +00:00
"""
Singleton. Get instance of this class. Create if not already created.
:return:
"""
2021-02-16 17:15:00 +00:00
if cls.__instance is None:
cls.__instance = super(Config, cls).__new__(cls)
return cls.__instance
2021-02-10 18:21:49 +00:00
def load(self, path):
"""
Loads the applications config file
:param path: Path to config file
:return:
"""
with open(path, 'r') as yamlfile:
2021-02-16 17:15:00 +00:00
self.__config = yaml.safe_load(yamlfile)
2021-02-10 18:21:49 +00:00
# Store path so that we can save later
2021-02-16 17:15:00 +00:00
self.config_filepath = path
2021-02-10 18:21:49 +00:00
def save(self):
"""
Saves config file
:return:
"""
2021-02-16 17:15:00 +00:00
with open(self.config_filepath, 'w') as file:
2021-02-10 18:21:49 +00:00
file.write("---\n")
2021-02-16 17:15:00 +00:00
yaml.dump(self.__config, file, sort_keys=False)
2021-02-10 18:21:49 +00:00
file.write("...")
def get(self, path):
"""
Gets a config property value.
:param path: path to property. Path separated by .
:return: property value
"""
elements = path.split('.')
last = None
for element in elements:
if last is None:
2021-02-16 17:15:00 +00:00
last = self.__config[element]
2021-02-10 18:21:49 +00:00
else:
last = last[element]
return last
2021-02-16 17:15:00 +00:00
def get_root_nodes(self):
"""
Returns all root notes as a list
:return: dict of root notes of YAML config file
"""
nodes = []
for key in self.__config:
nodes.append(key)
return nodes
2021-02-10 18:21:49 +00:00
def set(self, path, value):
"""
Sets a config property value
:param path: path to property. Path separated by .
:param value: Value to set property to
:return:
"""
2021-02-16 17:15:00 +00:00
obj = self.__config
2021-02-10 18:21:49 +00:00
key_list = path.split(".")
for k in key_list[:-1]:
obj = obj[k]
obj[key_list[-1]] = value