-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.py
More file actions
60 lines (45 loc) · 1.88 KB
/
cache.py
File metadata and controls
60 lines (45 loc) · 1.88 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import json
import os
import time
import common
common.init_env()
class MultiCache:
def __init__(self, filepath_supplier, timeout_sec=os.environ['CACHE_TIMEOUT_SEC']):
self.filepath_supplier = filepath_supplier
# Default timeout is 4 hours, superceded by .env timeout
self._timeout_sec = int(timeout_sec) if timeout_sec and (type(timeout_sec) is not str or len(timeout_sec) != 0) else 14400
self.cache = {}
def get(self, key, updater, force_refresh=False):
used_cached = False
filepath = self.filepath_supplier(key)
refresh = force_refresh or self.is_expired(filepath)
if not refresh and key not in self.cache and os.path.exists(filepath):
with open(filepath, 'r') as fp:
self.cache[key] = json.load(fp)
used_cached = True
if key not in self.cache or refresh:
os.makedirs(filepath[:filepath.rindex('/')], exist_ok=True)
updater(self.cache, key)
with open(filepath, 'w') as fp:
json.dump(self.cache[key], fp, indent=4)
return self.cache[key], used_cached
def set_timeout(self, timeout_sec):
self._timeout_sec = int(timeout_sec)
def is_expired(self, filepath):
return os.path.exists(filepath) and (time.time() - os.path.getmtime(filepath)) > self._timeout_sec
class SingleCache:
def __init__(self, filepath):
self.filepath = filepath
if os.path.exists(filepath):
with open(filepath, 'r') as fp:
self.cache = json.load(fp)
else:
with open(filepath, 'w'):
pass
self.cache = {}
def get(self, key, updater):
if key not in self.cache:
updater(self.cache, key)
with open(self.filepath, 'w') as fp:
json.dump(self.cache, fp)
return self.cache[key]