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

Cache   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 44
ccs 33
cts 33
cp 1
rs 10
wmc 12

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 3 1
B _load() 0 14 5
A set() 0 4 1
A _store() 0 8 3
A _slugify() 0 3 1
A get() 0 3 1
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