import json import os from pathlib import Path from configparser import * import typing class Config(object): _CONFIG_FILE: typing.Optional[str] = None _CONFIG: typing.Optional[dict] = None def __init__(self, config_file=None): if config_file is None: config_file = "config.json" # Check that specified config file exists if not os.path.exists(config_file): Path(config_file).touch() with open(config_file, 'w') as configfile: json.dump({"session": []}, configfile) Config._CONFIG_FILE = config_file with open(config_file, 'r') as f: Config._CONFIG = json.load(f) @staticmethod def save(): with open(Config._CONFIG_FILE, 'w') as configfile: json.dump(Config._CONFIG, configfile) @staticmethod def get_config_file() -> str: return Config._CONFIG_FILE @staticmethod def get_required_env_var(env_var: str) -> str: if env_var not in os.environ: raise Exception(f"Please set the {env_var} environment variable") return os.environ[env_var] @staticmethod def get_required_config_var(config_var: str) -> str: assert Config._CONFIG if config_var not in Config._CONFIG: raise Exception(f"Please set the {config_var} variable in the config file {Config._CONFIG_FILE}") return Config._CONFIG[config_var] @staticmethod def set_config_var(name, value): assert Config._CONFIG Config._CONFIG[name] = value return Config