diff options
Diffstat (limited to 'patchtracker/CacheObject.py')
-rw-r--r-- | patchtracker/CacheObject.py | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/patchtracker/CacheObject.py b/patchtracker/CacheObject.py new file mode 100644 index 0000000..c37c3b5 --- /dev/null +++ b/patchtracker/CacheObject.py @@ -0,0 +1,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] |