import os import time from pathlib import Path class CacheMiss(Exception): pass class Cache: def __init__(self, name, default_ttl=3600): self.default_ttl = default_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, ttl=None): loc = self.cache_dir/key loc.write_text(value, errors='ignore') # store expiry time as mtime to avoid having anything to do ttl = ttl if ttl else self.default_ttl stat = loc.stat() os.utime(loc, (stat.st_atime, stat.st_mtime + ttl)) def read(self, key): loc = self.cache_dir/key if not loc.exists(): raise CacheMiss if time.time() > loc.stat().st_mtime: loc.unlink() raise CacheMiss return loc.read_text()