about summary refs log tree commit diff
path: root/fscache.py
diff options
context:
space:
mode:
Diffstat (limited to 'fscache.py')
-rw-r--r--fscache.py14
1 files changed, 9 insertions, 5 deletions
diff --git a/fscache.py b/fscache.py
index b6d164b..234e659 100644
--- a/fscache.py
+++ b/fscache.py
@@ -6,26 +6,30 @@ class CacheMiss(Exception):
     pass
 
 class Cache:
-    def __init__(self, name, ttl=3600):
-        self.ttl = ttl
+    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):
+    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
 
-        age = time.time() - loc.stat().st_mtime
-        if age > self.ttl:
+        if time.time() > loc.stat().st_mtime:
             raise CacheMiss
         
         return loc.read_text()