about summary refs log tree commit diff
path: root/fscache.py
blob: d52ff62da265d8d27ac2a52141059f655a32ca64 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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()