-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcache.py
More file actions
33 lines (26 loc) · 917 Bytes
/
cache.py
File metadata and controls
33 lines (26 loc) · 917 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import json
class Cache:
"""Key-value file cache"""
def __init__(self, directory):
filename = f"{directory}/cache.json"
with open(filename, "a+") as self.cache_file:
self.cache_file.seek(0)
content = self.cache_file.read()
if len(content) == 0:
self.cache = {}
else:
self.cache = json.loads(content)
def put(self, key: str, value: dict):
self.cache[key] = value
self._overwrite()
def get(self, key: str) -> dict | None:
return self.cache.get(key, None)
def delete(self, key: str):
if key not in self.cache:
return
del self.cache[key]
def _overwrite(self):
with open(self.cache_file.name, "w") as self.cache_file:
self.cache_file.seek(0)
self.cache_file.write(json.dumps(self.cache))
self.cache_file.truncate()