Coverage for mddb_workflow / utils / cache.py: 73%
30 statements
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-03 18:45 +0000
« prev ^ index » next coverage.py v7.12.0, created at 2025-12-03 18:45 +0000
1from mddb_workflow.utils.auxiliar import load_json, save_json
2from mddb_workflow.utils.type_hints import *
3from mddb_workflow.tools.get_inchi_keys import InChIKeyData
5class Cache:
6 """The cache is used to store data to be reused between different runs."""
8 def __init__ (self, cache_file : 'File'):
9 # Save the previous cache file
10 self.file = cache_file
11 # Set an auxiliar file which is used to not overwrite directly the previous cache
12 self._aux_file = cache_file.get_prefixed_file('.aux')
13 # Set a dict to store the actual cached data
14 self.data = {}
15 # Load data from the cache file, if it already exists
16 self.load()
17 # Save the entry for the first time
18 self.save()
20 def retrieve (self, key : str, fallback = None):
21 """Read a value from the cache."""
22 return self.data.get(key, fallback)
24 def update (self, key : str, value):
25 """Update the cache and save it to disk."""
26 self.data[key] = value
27 self.save()
29 def delete (self, key : str):
30 """Delete a value in the cache."""
31 if key not in self.data: return
32 del self.data[key]
33 self.save()
35 def reset (self):
36 """Reset the cache. This is called when some input files are modified."""
37 self.data = {}
38 self.save()
40 def load (self):
41 """Load the cache to memory, as a dict."""
42 # Load data from the cache file, if it already exists
43 if not self.file.exists: return
44 # Read the cache in disk
45 self.data = load_json(self.file.path)
46 if 'inchikeys_task_output' in self.data:
47 self.data['inchikeys_task_output'] = InChIKeyData.load_cache(self.data['inchikeys_task_output'])
50 def save (self):
51 """Save the cache to disk, as a json file."""
52 # Write entries to disk
53 # Write to the auxiliar file, thus not overwritting the original cache yet
54 save_json(self.data, self._aux_file.path, indent = 4)
55 # If the new cache is successfully written then replace the old one
56 self._aux_file.rename_to(self.file)