-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.py
64 lines (49 loc) · 1.28 KB
/
cache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from . import utils
from threading import Lock
class _CacheEntry:
def __init__(self):
self.data=None
self.mime=None
@staticmethod
def from_file(path):
ce = _CacheEntry()
with open(path, "rb") as f:
ce.data=f.read()
ce.mime=utils.mime(path)
return ce
@staticmethod
def from_data(data, mime):
ce = _CacheEntry()
ce.data=data
ce.mime=mime
return ce
class Cache:
def __init__(self):
self.db={}
self.lock=Lock()
def cache_file(self, path):
ce = _CacheEntry.from_file(path)
self.lock.acquire()
self.db[path]=ce
self.lock.release()
return ce
def cache_data(self, path, data, mime):
self.lock.acquire()
ce = _CacheEntry.from_data(data, mime)
self.db[path]=ce
self.lock.release()
return ce
def __getitem__(self, item):
if item in self.db:
return self.db[item].data
return None
def mime(self, item):
if item in self.db:
return self.db[item].mime
return None
def get(self, item):
if item in self.db:
return self.db[item]
return None
def has(self, item):
return item in self.db