Completed
Push — master ( 6d0d49...6d6a7d )
by Jasper
02:25 queued 57s
created

PictureCache   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 46
rs 10
wmc 13

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 4 2
A new() 0 2 1
A serializeSingle() 0 6 1
A getBytes() 0 5 2
A saveToDisk() 0 11 4
A keep() 0 8 2
A getFilepath() 0 2 1
1
from niprov.format import Format
2
import io, os
3
4
_CACHE = {}
5
6
class PictureCache(Format):
7
8
    def __init__(self, dependencies):
9
        cachedir = os.path.expanduser('~/.niprov-snapshots')
10
        if not os.path.isdir(cachedir):
11
            os.mkdir(cachedir)
12
13
    def new(self):
14
        return io.BytesIO()
15
16
    def keep(self, picture, for_):
17
        imgId = for_.provenance['id']
18
        if hasattr(picture, 'read'):
19
            picture.seek(0)
20
            bytes = picture.read()
21
        else:
22
            bytes = str(picture)
23
        _CACHE[imgId] = bytes
24
25
    def getBytes(self, for_):
26
        imgId = for_.provenance['id']
27
        if imgId in _CACHE:
28
            return _CACHE[imgId]
29
        return None
30
31
    def getFilepath(self, for_):
32
        return self.saveToDisk(for_)
33
34
    def saveToDisk(self, for_):
35
        imgId = for_.provenance['id']
36
        fpath = os.path.expanduser('~/.niprov-snapshots/{}.png'.format(imgId))
37
        if os.path.isfile(fpath):
38
            return fpath
39
        elif imgId in _CACHE:
40
            with open(fpath, 'w') as picfile:
41
                picfile.write(_CACHE[imgId])
42
            return fpath
43
        else:
44
            return None
45
46
    def serializeSingle(self, image):
47
        """Provides file path to picture of image.
48
49
        This is part of the :class:`.Format` interface. 
50
        """
51
        return self.getFilepath(for_=image)
52
53