blob: c37c3b5121ba6451b3450e26bd559f3e8a4d63fa (
plain)
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
|
import errno
import gzip
import md5
import os
import Conf
class CacheMissException (Exception):
pass
class CacheObject:
""" A CacheObject is a compressed on-disk version of a serialized object.
"""
def __init__ (self, key=None, keys=None):
self.obj = None
#print "CacheObject: key=%s keys=%s"%(key, keys)
if not key and not keys:
raise "CacheObject needs at least one of key, keys"
checksum = md5.md5()
if key:
checksum.update(key)
if keys:
for k in keys:
checksum.update(str(k))
self.path = os.path.sep.join([Conf.cachedir, checksum.hexdigest()])
def get(self):
if not self.obj:
try:
if Conf.cachecompress:
self.obj = gzip.GzipFile(self.path).read()
else:
self.obj = file(self.path).read()
except IOError, e:
if e.errno != errno.ENOENT:
raise e
else:
#print "CacheObject: cache miss"
raise CacheMissException("Object not present in cache")
#print "CacheObject: cache hit"
return self.obj
def put(self, obj):
self.obj = obj
#print "CacheObject: cache put"
try:
if Conf.cachecompress:
gzip.GzipFile(self.path, "wb").write(str(self.obj))
else:
file(self.path, "wb").write(str(self.obj))
except Exception, e:
os.unlink(self.path)
raise e
if __name__ == '__main__':
co = CacheObject( key="magic" )
try:
print "going to try to read an object before it exists"
print "first line:", co.get().split()[0]
except CacheMissException:
print "file was missing as expected. now let's try to put it and fetch it"
co.put(file("/etc/passwd").read())
print "first line:", co.get().split()[0]
|