1
|
1 |
|
import logging |
2
|
1 |
|
import os |
3
|
1 |
|
import pickle |
4
|
|
|
|
5
|
|
|
|
6
|
1 |
|
log = logging.getLogger(__name__) |
7
|
|
|
|
8
|
|
|
|
9
|
1 |
|
class Cache: |
10
|
|
|
|
11
|
1 |
|
PATH = os.path.join('.cache', 'coveragespace') |
12
|
|
|
|
13
|
1 |
|
def __init__(self): |
14
|
1 |
|
self._data = {} |
15
|
1 |
|
|
16
|
|
|
def _store(self): |
17
|
1 |
|
directory = os.path.dirname(self.PATH) |
18
|
1 |
|
if not os.path.exists(directory): |
19
|
1 |
|
os.makedirs(directory) |
20
|
1 |
|
|
21
|
1 |
|
text = pickle.dumps(self._data) |
22
|
1 |
|
with open(self.PATH, 'wb') as fout: |
23
|
|
|
fout.write(text) |
24
|
1 |
|
|
25
|
1 |
|
def _load(self): |
26
|
1 |
|
try: |
27
|
1 |
|
with open(self.PATH, 'rb') as fin: |
28
|
|
|
text = fin.read() |
29
|
1 |
|
except IOError as e: |
30
|
1 |
|
log.debug("Unable to read cache: %s", e) |
31
|
|
|
return |
32
|
1 |
|
|
33
|
1 |
|
try: |
34
|
1 |
|
data = pickle.loads(text) |
35
|
1 |
|
except (TypeError, KeyError, IndexError) as e: |
36
|
|
|
log.debug("Unable to parse cache: %s", e) |
37
|
1 |
|
|
38
|
1 |
|
if isinstance(data, dict): |
39
|
1 |
|
self._data = data |
40
|
|
|
else: |
41
|
1 |
|
log.debug("Invalid cache value: %s", data) |
42
|
1 |
|
self._data = {} |
43
|
1 |
|
|
44
|
1 |
|
def set(self, key, value): |
45
|
1 |
|
slug = self._slugify(key) |
46
|
|
|
log.debug("Setting cache key: %s", slug) |
47
|
1 |
|
self._data[slug] = value |
48
|
1 |
|
log.debug("Cached value: %s", value) |
49
|
1 |
|
self._store() |
50
|
1 |
|
|
51
|
1 |
|
def get(self, key, default=None): |
52
|
|
|
self._load() |
53
|
1 |
|
slug = self._slugify(key) |
54
|
1 |
|
log.debug("Getting cache key: %s", slug) |
55
|
1 |
|
value = self._data.get(slug, default) |
56
|
1 |
|
log.debug("Cached value: %s", value) |
57
|
1 |
|
return value |
58
|
|
|
|
59
|
1 |
|
def clear(self): |
60
|
1 |
|
self._data = {} |
61
|
1 |
|
self._store() |
62
|
1 |
|
|
63
|
1 |
|
@staticmethod |
64
|
|
|
def _slugify(key): |
65
|
1 |
|
try: |
66
|
|
|
url, data = key |
67
|
1 |
|
except ValueError: |
68
|
|
|
return key |
69
|
|
|
else: |
70
|
|
|
return url, tuple(data.items()) |
71
|
|
|
|