import os import time from pathlib import Path class CacheMiss(Exception): pass class Cache: def __init__(self, name, ttl=3600): self.ttl = ttl try: self.cache_dir = Path(os.environ['XDG_CACHE_HOME'])/name except KeyError: self.cache_dir = Path(os.environ['HOME'])/'.cache'/name self.cache_dir.mkdir(exist_ok=True) def write(self, key, value): # TODO gracefully handle keys with '/' by creating directories or rewriting loc = self.cache_dir/key loc.write_text(value, errors='ignore') def read(self, key): loc = self.cache_dir/key if not loc.exists(): raise CacheMiss age = time.time() - loc.stat().st_mtime if age > self.ttl: raise CacheMiss return loc.read_text()