Completed
Pull Request — master (#136)
by Jasper
01:27
created

PictureCache   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
dl 0
loc 43
rs 10
c 3
b 0
f 0
wmc 12

7 Methods

Rating   Name   Duplication   Size   Complexity  
A serializeSingle() 0 6 1
A __init__() 0 4 2
A getBytes() 0 5 2
A new() 0 2 1
A saveToDisk() 0 11 4
A keep() 0 5 1
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
        picture.seek(0)
19
        bytes = picture.read()
20
        _CACHE[imgId] = bytes
21
22
    def getBytes(self, for_):
23
        imgId = for_.provenance['id']
24
        if imgId in _CACHE:
25
            return _CACHE[imgId]
26
        return None
27
28
    def getFilepath(self, for_):
29
        return self.saveToDisk(for_)
30
31
    def saveToDisk(self, for_):
32
        imgId = for_.provenance['id']
33
        fpath = os.path.expanduser('~/.niprov-snapshots/{}.png'.format(imgId))
34
        if os.path.isfile(fpath):
35
            return fpath
36
        elif imgId in _CACHE:
37
            with open(fpath, 'w') as picfile:
38
                picfile.write(_CACHE[imgId])
39
            return fpath
40
        else:
41
            return None
42
43
    def serializeSingle(self, image):
44
        """Provides file path to picture of image.
45
46
        This is part of the :class:`.Format` interface. 
47
        """
48
        return self.getFilepath(for_=image)
49
50