blob: e549e926171e665adba1f5caede8c49da3dc606a (
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
33
34
35
36
|
import os
import time
from pathlib import Path
class CacheMiss(Exception):
pass
class Cache:
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, 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
if time.time() > loc.stat().st_mtime:
loc.unlink()
raise CacheMiss
return loc.read_text()
|