about summary refs log tree commit diff
diff options
context:
space:
mode:
authorStarfall <us@starfall.systems>2023-01-09 18:38:11 -0600
committerStarfall <us@starfall.systems>2023-01-09 18:38:11 -0600
commitdb89bdad5ed68a31828d578ff794982e08f30fdc (patch)
tree14f257229ea0a660497dbc84148310a9a06d7a50
parentf7d69f5948f708388df81f76b62dcc11b857dea3 (diff)
fscache: use mtime to store cache expiration time
-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()