Total Complexity | 13 |
Total Lines | 46 |
Duplicated Lines | 0 % |
Changes | 3 | ||
Bugs | 0 | Features | 0 |
1 | from niprov.format import Format |
||
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 |