#datapersistence

tord_dellsen@diasp.eu

I've been working on this code for storing settings in a JSON file. It's for the mindfulness-at-the-computer project

def settings_file_exists() -> bool:
    return os.path.isfile(JSON_SETTINGS_FILE_NAME)

def save_dict_to_json(i_dict_to_save: dict, i_file_path: str):
    print("save_data_to_json")
    with open(i_file_path, "w") as write_file:
        json.dump(i_dict_to_save, write_file, indent=2)

def load_dict_from_json(i_minimum_dict: dict, i_file_path: str) -> dict:
    print("load_data_from_json")
    ret_dict = i_minimum_dict.copy()
    if os.path.isfile(i_file_path):
        with open(i_file_path, "r") as read_file:
            from_file_dict: dict = json.load(read_file)

            diff_key_list: list = []
            for min_key in i_minimum_dict.keys():
                if min_key not in from_file_dict.keys():
                    diff_key_list.append(min_key)
            print(f"One or more keys needed for the application to work were not "
            f"available in {os.path.basename(i_file_path)} so have been added now. "
            f"These are the keys: {diff_key_list}")

            diff_key_list: list = []
            for file_key in from_file_dict.keys():
                if file_key not in i_minimum_dict.keys():
                    diff_key_list.append(file_key)
            print(f"One or more keys in {os.path.basename(i_file_path)} are not "
            f"used by the application (though may have been used before). "
            f"These are the keys: {diff_key_list}")

            print(f"Before merge {i_minimum_dict=}")
            print(f"Before merge {from_file_dict=}")
            ret_dict.update(from_file_dict)
            # -if there are different values for the same key, the value
            #  in from_file_dict takes precendence
            print(f"After merge {ret_dict=}")
    return ret_dict

SK_SHOW_BREATHING_TEXT = "show breathing text"
SK_REST_ACTIONS = "rest actions"
SK_BREATHING_AUDIO_VOLUME = "breathing audio volume"
SK_BREATHING_BREAK_TIMER_SECS = "breathing break timer secs"

# The values given here are the minimum values needed for the application to work
min_settings_dict = {
    SK_SHOW_BREATHING_TEXT: True,
    SK_BREATHING_AUDIO_VOLUME: 50,
    SK_REST_ACTIONS: {},
    SK_BREATHING_BREAK_TIMER_SECS: 3,
}

# Initial setup
if not settings_file_exists():
    rest_actions: dict = {
        "Making tea": "path/to/image",
        "Cleaning workspace": "/home/user/_",
        "Walking meditation": "path/to/image",
    }
    min_settings_dict.get(SK_REST_ACTIONS).update(rest_actions)

db_file_exists_at_application_startup_bl = settings_file_exists()
settings: dict = load_dict_from_json(min_settings_dict, get_json_file_path())
print(f"{settings=}")

#python #programming #coding #json #datapersistence #mindfulness-at-the-computer #matc