diff options
Diffstat (limited to 'fscache.py')
-rw-r--r-- | fscache.py | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/fscache.py b/fscache.py new file mode 100644 index 0000000..d52ff62 --- /dev/null +++ b/fscache.py @@ -0,0 +1,32 @@ +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() |