Completed
Pull Request — develop (#18)
by Jace
02:11
created

Cache._load()   B

Complexity

Conditions 5

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
c 1
b 0
f 0
dl 0
loc 9
ccs 8
cts 8
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, 'r') as fin:
16 1
                data = pickle.load(fin)
17 1
        except (IOError, KeyError, IndexError):
18 1
            pass
19
        else:
20 1
            if isinstance(data, dict):
21 1
                self._data = data
22
23 1
    def _store(self):
24 1
        directory = os.path.dirname(self.PATH)
25 1
        if not os.path.exists(directory):
26 1
            os.makedirs(directory)
27
28 1
        with open(self.PATH, 'w') as fout:
29 1
            pickle.dump(self._data, fout)
30
31 1
    def set(self, url, data, response):
32 1
        slug = self._slugify(url, data)
33 1
        self._data[slug] = response
34 1
        self._store()
35
36 1
    def get(self, url, data):
37 1
        slug = self._slugify(url, data)
38 1
        return self._data.get(slug)
39
40 1
    @staticmethod
41
    def _slugify(url, data):
42
        return (url, hash(frozenset(data.items())))
43