Browse Source

Use shelve module instead of custom object

master
Raphael Roberts 5 years ago
parent
commit
02238eed62
  1. 45
      tibi_hardlinks/cache.py

45
tibi_hardlinks/cache.py

@ -1,47 +1,14 @@
from pathlib import Path
import atexit
import lzma
import pickle
from tibi_hardlinks.config import CACHE_DIR
import shelve
class Cache:
def __init__(self, cache_dir=CACHE_DIR):
self._store = None
self.filepath = Path(cache_dir) / "cache.pkl.lzma"
atexit.register(self.store)
tibi_cache = shelve.open(Path(CACHE_DIR) / "cache")
atexit.register(tibi_cache.close)
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()
def invalidate():
tibi_cache.clear()
tibi_cache.sync()
Loading…
Cancel
Save