memegen.routes._cache.Cache._skip_cache()   B
last analyzed

Complexity

Conditions 7

Size

Total Lines 19
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 15
nop 2
dl 0
loc 19
ccs 11
cts 11
cp 1
crap 7
rs 8
c 0
b 0
f 0
1 1
import yorm
0 ignored issues
show
introduced by
Unable to import 'yorm'
Loading history...
2
from yorm.types import List, Object
0 ignored issues
show
introduced by
Unable to import 'yorm.types'
Loading history...
3 1
from profanityfilter import ProfanityFilter
0 ignored issues
show
introduced by
Unable to import 'profanityfilter'
Loading history...
4 1
import log
5 1
6
profanity_filter = ProfanityFilter()
7
profanity_filter.remove_word("damn")
8 1
9
10
@yorm.attr(items=List.of_type(Object))
11 1
@yorm.sync("data/cache/{self.name}.yml", auto_resolve=True)
12 1
class Cache:
13
14
    SIZE = 100
15 1
16
    def __init__(self, filtered=True):
17 1
        self.items = []
18 1
        self.disabled = False
19 1
        self.filtered = filtered
20 1
21
    @property
22 1
    def name(self):
23
        return 'filtered' if self.filtered else 'unfiltered'
24 1
25
    def add(self, **kwargs):
26 1
        if self._skip_cache(kwargs):
27 1
            return
28 1
29
        log.info("Caching: %s", kwargs)
30 1
31
        self.items.insert(0, kwargs)
32 1
        while len(self.items) > self.SIZE:
33 1
            self.items.pop()
34
35
    def get(self, index):
36 1
        log.info("Getting cache index: %s", index)
37 1
38
        try:
39 1
            data = self.items[index]
40 1
        except IndexError:
41 1
            data = {}
42 1
43
        if not isinstance(data, dict):
44 1
            log.error("Invalid cache")
45
            self.items = []
46 1
            data = {}
47
48 1
        log.info("Retrieved cache: %s", data)
49 1
50 1
        return data
51 1
52
    def _skip_cache(self, kwargs):
53 1
        if self.disabled:
54 1
            log.debug("Caching disabled")
55 1
            return True
56
57 1
        if kwargs in self.items:
58
            log.debug("Already cached: %s", kwargs)
59 1
            return True
60 1
61 1
        if self.filtered:
62 1
63 1
            if kwargs['key'] == 'custom' or kwargs.get('alt'):
64 1
                log.debug("Skipped caching of custom background: %s", kwargs)
65
                return True
66 1
            if profanity_filter.is_profane(kwargs['path']):
67
                log.debug("Skipped caching of profane content: %s", kwargs)
68
                return True
69
70
        return False
71