memegen.routes._cache   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 52
dl 0
loc 71
rs 10
c 0
b 0
f 0
wmc 16

5 Methods

Rating   Name   Duplication   Size   Complexity  
B Cache._skip_cache() 0 19 7
A Cache.name() 0 3 2
A Cache.__init__() 0 4 1
A Cache.add() 0 9 3
A Cache.get() 0 16 3
1
import yorm
2
from yorm.types import List, Object
3
from profanityfilter import ProfanityFilter
4
import log
5
6
profanity_filter = ProfanityFilter()
7
profanity_filter.remove_word("damn")
8
9
10
@yorm.attr(items=List.of_type(Object))
11
@yorm.sync("data/cache/{self.name}.yml", auto_resolve=True)
12
class Cache:
13
14
    SIZE = 100
15
16
    def __init__(self, filtered=True):
17
        self.items = []
18
        self.disabled = False
19
        self.filtered = filtered
20
21
    @property
22
    def name(self):
23
        return 'filtered' if self.filtered else 'unfiltered'
24
25
    def add(self, **kwargs):
26
        if self._skip_cache(kwargs):
27
            return
28
29
        log.info("Caching: %s", kwargs)
30
31
        self.items.insert(0, kwargs)
32
        while len(self.items) > self.SIZE:
33
            self.items.pop()
34
35
    def get(self, index):
36
        log.info("Getting cache index: %s", index)
37
38
        try:
39
            data = self.items[index]
40
        except IndexError:
41
            data = {}
42
43
        if not isinstance(data, dict):
44
            log.error("Invalid cache")
45
            self.items = []
46
            data = {}
47
48
        log.info("Retrieved cache: %s", data)
49
50
        return data
51
52
    def _skip_cache(self, kwargs):
53
        if self.disabled:
54
            log.debug("Caching disabled")
55
            return True
56
57
        if kwargs in self.items:
58
            log.debug("Already cached: %s", kwargs)
59
            return True
60
61
        if self.filtered:
62
63
            if kwargs['key'] == 'custom' or kwargs.get('alt'):
64
                log.debug("Skipped caching of custom background: %s", kwargs)
65
                return True
66
            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