diff options
author | Sean Finney <seanius@debian.org> | 2009-08-31 23:10:43 +0200 |
---|---|---|
committer | Sean Finney <seanius@debian.org> | 2009-09-01 08:58:00 +0200 |
commit | f28a60d7373b5d23599c111ff18d69a94ae69a36 (patch) | |
tree | 1dec1acfe10c29d1079830e33b66180795de0064 /patchtracker/CacheObject.py | |
parent | ad817fd1bd8d88b242fea45ea1d96315d48c3a47 (diff) | |
download | patch-tracker-f28a60d7373b5d23599c111ff18d69a94ae69a36.tar.gz |
initial implementation of selective output caching
the PackageCmd and PatchCmd classes are now cached on their
first request.
note that this is incomplete, as the PackageCmd is also currently
used to print non-static information as well (when a package name
doesn't find an exact match and it does a query).
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] |