""" config management """ from os import makedirs, path import tempfile from configparser import RawConfigParser current_config = None class DefaultConfig: DEBUG = False SECRET_KEY = "toto" LOG = { "log_file": None, "log_level": "WARNING", } tempdir = path.join(tempfile.gettempdir(), "ITPlanning") BASE = { "database_uri": "sqlite:///" + path.join(tempdir, "ITPlanning.db"), } def __init__(self): if not path.exists(self.tempdir): makedirs(self.tempdir) current_config = self class IniConfig(DefaultConfig): common_paths = [ "/etc/ITPlanning", "c:/programData/ITplanning/ITplanning.conf", path.expanduser("~/.ITPlanning"), path.expanduser("~/.config/ITPlanning/ITPlanning.conf"), "ITPlanning.conf", ] def __init__(self, paths=None): super().__init__() if not paths: paths = self.common_paths parser = RawConfigParser() parser.read(paths) for section in parser.sections(): options = {k: self.__try_parse(v) for k, v in parser.items(section)} section = section.upper() if hasattr(self, section): getattr(self, section).update(options) else: setattr(self, section, options) def __try_parse(self, value): try: return int(value) except ValueError: try: return float(value) except ValueError: lv = value.lower() if lv in ("yes", "true", "on"): return True if lv in ("no", "false", "off"): return False return value def get_current_config(): if current_config is None: DefaultConfig() return current_config