about summary refs log tree commit diff
path: root/fscache.py
diff options
context:
space:
mode:
authorStarfall <us@starfall.systems>2022-12-01 13:52:42 -0600
committerStarfall <us@starfall.systems>2022-12-01 13:52:42 -0600
commit1416ec325ac9a35aaa50cd1e7a77cd6112a8e5e0 (patch)
tree4d090c6f6fb9cbc0a9d1fe0fbd4720b86b4b6b9d /fscache.py
parentd528ba125fae31e3caa76471136fa0a821867884 (diff)
cache forecasts on filesystem
Diffstat (limited to 'fscache.py')
-rw-r--r--fscache.py32
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()