From 2a0fbfe4a10628e4b649b01c647cfee7579d9591 Mon Sep 17 00:00:00 2001 From: Carlos Sanchez Date: Sun, 30 Apr 2023 21:12:14 -0400 Subject: [PATCH] Neat, loads from configs! --- main.py | 8 ++++++-- myutils.py | 10 +++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index 04b82bb..553a7c5 100644 --- a/main.py +++ b/main.py @@ -11,6 +11,7 @@ CONFIGFILE="config.toml" # The entire config object with all defaults config = { "api" : "https://oboy.smilebasicsource.com/api", + "default_loglevel" : "WARNING", "expire_seconds" : 31536000, # 365 days in seconds, expiration for token "tokenfile" : ".qcstoken" } @@ -18,7 +19,7 @@ config = { def main(): print("Program start") load_or_create_global_config() - logging.debug("Config: " + json.dumps(config, indent = 2)) + logging.info("Config: " + json.dumps(config, indent = 2)) context = contentapi.ApiContext(config["api"], logging) print("Program end") @@ -31,13 +32,16 @@ def load_or_create_global_config(): if os.path.exists(CONFIGFILE): # Read and deserialize the config file with open(CONFIGFILE, 'r', encoding='utf-8') as f: - config = toml.load(f) + temp_config = toml.load(f) + myutils.merge_dictionary(temp_config, config) else: # Serialize and write the config dictionary to the config file logging.warn("No config found at " + CONFIGFILE + ", creating now") with open(CONFIGFILE, 'w', encoding='utf-8') as f: toml.dump(config, f) + myutils.set_logging_level(config["default_loglevel"]) + # Because python reasons if __name__ == "__main__": diff --git a/myutils.py b/myutils.py index f31530f..39a9928 100644 --- a/myutils.py +++ b/myutils.py @@ -1,3 +1,4 @@ +import logging # Merge the "new_values" dictionary recursively into the "base_values" dictionary, # assigning where new_values is assigned but not fully overwriting nested dictionaries @@ -7,4 +8,11 @@ def merge_dictionary(new_values, base_values): if key in base_values and isinstance(base_values[key], dict) and isinstance(new_values[key], dict): merge_dictionary(new_values[key], base_values[key]) else: - base_values[key] = new_values[key] \ No newline at end of file + base_values[key] = new_values[key] + +# Set the DEFAULT logging level based on a string representation of it +def set_logging_level(level_str): + level = getattr(logging, level_str.upper(), None) + if not isinstance(level, int): + raise ValueError('Invalid logging level: %s' % level_str) + logging.basicConfig(level=level) \ No newline at end of file