6 from os.path import join, exists
8 class cache_handler( object ):
9 # 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
11 def __init__( self, debug = False ):
15 self.tempdir = join( tempfile.gettempdir(), "eveapi" )
16 if not exists( self.tempdir ):
17 os.makedirs( self.tempdir )
19 # remove this later --danny
20 def log( self, what ):
22 print "[%d] %s" % ( self.count, what )
24 def retrieve( self, host, path, params ):
25 # eveapi asks if we have this request cached
26 key = hash( ( host, path, frozenset( params.items() ) ) )
31 # see if we have the requested page cached...
32 cached = self.cache.get( key, None )
36 # not in memory, maybe on disk --danny
37 cacheFile = join( self.tempdir, str( key ) + ".cache" )
38 if exists( cacheFile ):
39 self.log( "%s: retreiving from disk." % path )
40 f = open( cacheFile, "rb" )
41 cached = self.cache[key] = cPickle.loads( zlib.decompress( f.read() ) )
45 # check if the cached object is fresh enough
46 if time.time() < cached[0]:
47 self.log( "%s: returning cached document." % path )
48 # return the cached object
51 # if it's stale, purge it --danny
52 self.log( "%s: cache expired, purging!" % path )
55 os.remove( cacheFile )
57 self.log( "%s: not cached, fetching from server..." % path )
58 # We didn't get a cache hit so return None to indicate that the data should be requested from server
61 def store( self, host, path, params, doc, obj ):
62 # eveapi is asking us to cache an item
63 key = hash( ( host, path, frozenset( params.items() ) ) )
65 cachedFor = obj.cachedUntil - obj.currentTime
67 self.log( "%s: cached (%d seconds)." % ( path, cachedFor ) )
69 cachedUntil = time.time() + cachedFor
72 cached = self.cache[key] = ( cachedUntil, obj )
74 # store in cache folder
75 cacheFile = join( self.tempdir, str( key ) + ".cache" )
76 f = open( cacheFile, "wb" )
77 f.write( zlib.compress( cPickle.dumps( cached, -1 ) ) )