5 from os.path import join, exists
7 from constants import APICACHE_PATH
9 class cache_handler( object ):
10 # adapted from http://home.wanadoo.nl/ntt/eve/library/files/api/apitest.py (does this satisfy the terms of the license?), will need work, but we need basic cache functionality... I feel guilty for abusing the server. FIXME --danny
12 def __init__( self, debug = False ):
16 self.tempdir = APICACHE_PATH
17 if not exists(self.tempdir):
18 os.makedirs(self.tempdir)
20 # remove this later --danny
21 def log( self, what ):
23 print "[%d] %s" % (self.count, what)
25 def retrieve(self, host, path, params):
26 # eveapi asks if we have this request cached
27 key = hash((host, path, frozenset( params.items())))
32 # see if we have the requested page cached...
33 cached = self.cache.get(key, None)
37 # not in memory, maybe on disk --danny
38 cacheFile = join(self.tempdir, str(key) + ".cache")
40 self.log("%s: retreiving from disk." % path)
41 f = open(cacheFile, "rb")
42 cached = self.cache[key] = cPickle.loads(zlib.decompress(f.read()))
47 # check if the cached object is fresh enough
48 if time.time() < cached[0]:
49 self.log("%s: returning cached document." % path)
50 # return the cached object
53 # if it's stale, purge it --danny
54 self.log("%s: cache expired, purging!" % path)
62 self.log("%s: not cached, fetching from server..." % path)
63 # We didn't get a cache hit so return None to indicate that the data should be requested from server
66 def store(self, host, path, params, doc, obj):
67 # eveapi is asking us to cache an item
68 if not exists(self.tempdir):
69 os.makedirs(self.tempdir)
71 key = hash((host, path, frozenset( params.items())))
73 cachedFor = obj.cachedUntil - obj.currentTime
75 self.log("%s: cached (%d seconds)." % (path, cachedFor))
77 cachedUntil = time.time() + cachedFor
80 cached = self.cache[key] = (cachedUntil, obj)
82 # store in cache folder
83 cacheFile = join(self.tempdir, str(key) + ".cache")
84 f = open(cacheFile, "wb")
85 f.write(zlib.compress(cPickle.dumps(cached, -1)))