From db89bdad5ed68a31828d578ff794982e08f30fdc Mon Sep 17 00:00:00 2001 From: Starfall Date: Mon, 9 Jan 2023 18:38:11 -0600 Subject: fscache: use mtime to store cache expiration time --- fscache.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) (limited to 'fscache.py') 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() -- cgit