|
|
|
@ -0,0 +1,46 @@ |
|
|
|
import atexit |
|
|
|
import pickle |
|
|
|
import lzma |
|
|
|
from pathlib import Path |
|
|
|
from tibi_hardlinks.config import CACHE_DIR |
|
|
|
|
|
|
|
|
|
|
|
class Cache: |
|
|
|
def __init__(self): |
|
|
|
self._store = None |
|
|
|
self.filepath = Path(CACHE_DIR) / "cache.pkl.lzma" |
|
|
|
atexit.register(self.save) |
|
|
|
|
|
|
|
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 |
|
|
|
else: |
|
|
|
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() |