1
2
3
4
5
6
7
8
9
10
11
12
13
14 import os, sys, pickle, base64, threading, glob
15 import tempfile
16
17 _DEFAULT_NOT_SPECIFIED = object()
18
19
22 self.path = path
23 if not os.path.exists(self.path):
24 os.makedirs(self.path)
25 self.gen_key = lambda x: '%s.pickle' % base64.b64encode(x)
26 self.lock = threading.Lock()
27 self._pickleProtocol = protocol
31 return glob.glob(os.path.join(self.path,'*.pickle'))
48 fn = self._makeFileNameFromKey(key)
49 with self.lock:
50
51 tempFd = None
52 tempFn = None
53 try:
54
55 tempFd, tempFn = tempfile.mkstemp(dir=os.path.dirname(fn))
56
57 with os.fdopen(tempFd, "wb") as tempF:
58 tempFd = None
59 pickle.dump((key, value), tempF, protocol=self._pickleProtocol)
60
61
62 os.rename(tempFn, fn)
63 except Exception as ex:
64 if tempFd is not None:
65 os.close(tempFd)
66 raise ex
67 finally:
68 if os.path.exists(tempFn):
69 try:
70 os.remove(tempFn)
71 except (OSError, IOError):
72 pass
81 with self.lock:
82 for fn in self._allFileNames():
83 try:
84 os.remove(fn)
85 except (OSError, IOError):
86 pass
97 for fn in self._allFileNames():
98 yield base64.b64decode(os.path.split(fn)[1][:-7])
103 for fn in self._allFileNames():
104 try:
105 with open(fn,'rb') as f:
106 yield pickle.load(f)
107 except IOError:
108 pass
119 __nonzero__ = __bool__
120
121 if __name__=='__main__':
124 self.name = name
125 self.hits = hits
127 return '%s, %d hits' % (self.name, self.hits)
128 cache = FileCache('test')
129 sites = [Site('cnn.com'), Site('kd7yhr.org', 1), Site('asdf.com', 3)]
130
131
132 for site in sites:
133 cache[site.name] = site
134 testitemname = sites[-1].name
135
136 entry = cache.get(testitemname)
137 if entry:
138 print type(entry), entry
139
140 print cache.keys()
141 import glob
142 for fn in glob.glob('test/*'):
143 print fn
144
145 print testitemname in cache
146
147 del cache[testitemname]
148 print cache.keys()
149 print testitemname in cache
150
151 cache.clear()
152 print cache.keys()
153