Completed
Push — develop ( b34257...4c6de9 )
by Jace
12s
created

Cache._load()   B

Complexity

Conditions 5

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
c 2
b 0
f 0
dl 0
loc 14
ccs 12
cts 12
cp 1
crap 5
rs 8.5454
1 1
import os
2 1
import pickle
3
4
5 1
class Cache(object):
6
7 1
    PATH = os.path.join('.cache', 'coverage.space')
8
9 1
    def __init__(self):
10 1
        self._data = {}
11 1
        self._load()
12
13 1
    def _load(self):
14 1
        try:
15 1
            with open(self.PATH, 'rb') as fin:
16 1
                text = fin.read()
17 1
        except IOError:
18 1
            text = None
19
20 1
        try:
21 1
            data = pickle.loads(text)
22 1
        except (TypeError, KeyError, IndexError):
23 1
            data = None
24
25 1
        if isinstance(data, dict):
26 1
            self._data = data
27
28 1
    def _store(self):
29 1
        directory = os.path.dirname(self.PATH)
30 1
        if not os.path.exists(directory):
31 1
            os.makedirs(directory)
32
33 1
        text = pickle.dumps(self._data)
34 1
        with open(self.PATH, 'wb') as fout:
35 1
            fout.write(text)
36
37 1
    def set(self, url, data, response):
38 1
        slug = self._slugify(url, data)
39 1
        self._data[slug] = response
40 1
        self._store()
41
42 1
    def get(self, url, data):
43 1
        slug = self._slugify(url, data)
44 1
        return self._data.get(slug)
45
46 1
    @staticmethod
47
    def _slugify(url, data):
48
        return (url, hash(frozenset(data.items())))
49