You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.1 KiB
47 lines
1.1 KiB
from pathlib import Path
|
|
import atexit
|
|
import lzma
|
|
import pickle
|
|
|
|
from tibi_hardlinks.config import CACHE_DIR
|
|
|
|
|
|
class Cache:
|
|
def __init__(self, cache_dir=CACHE_DIR):
|
|
self._store = None
|
|
self.filepath = Path(cache_dir) / "cache.pkl.lzma"
|
|
atexit.register(self.store)
|
|
|
|
def read(self, key):
|
|
if self._store is None:
|
|
self.load()
|
|
try:
|
|
return self._store[key]
|
|
except KeyError:
|
|
return None
|
|
|
|
def write(self, key, data):
|
|
if self._store is None:
|
|
self.load()
|
|
self._store[key] = data
|
|
|
|
def load(self):
|
|
if self.filepath.exists():
|
|
|
|
with lzma.open(self.filepath, "rb") as file:
|
|
stored_data = pickle.load(file)
|
|
if isinstance(stored_data, dict):
|
|
self._store = stored_data
|
|
return
|
|
self._store = dict()
|
|
|
|
def store(self):
|
|
with lzma.open(self.filepath, "wb") as file:
|
|
pickle.dump(self._store, file)
|
|
|
|
def invalidate(self):
|
|
self._store = None
|
|
self.filepath.unlink()
|
|
|
|
|
|
tibi_cache = Cache()
|