import json import os class SettingsCache: """ Utility to save settings into a cache file. """ cache_default_dir = '.sceptic_cache' def __init__(self, cache_element, cache_target): """ :param cache_element: the name of the cached element (will be a directory) :param cache_target: the specific target of the cache (e.g. a specific configuration) """ # Create dir cache_dir = os.path.join(self.cache_default_dir, cache_element) os.makedirs(cache_dir, exist_ok=True) # File name name = "{}.json".format(cache_target.replace("/", "_")) self.cache_file = os.path.join(cache_dir, name) self.data = None def load(self): """ Load data from the cache file """ if not os.path.exists(self.cache_file): self.data = {} return with open(self.cache_file) as fp: self.data = json.load(fp) def save(self): """ Save data into the cache file """ with open(self.cache_file, "w") as fp: json.dump(self.data, fp) fp.write("\n")