Example #1
0
 def cache(self, block_name = None, block_data = None, duration = None):
     '''
     Cache the data.
     
     If *block_name* is not given, it will return the clone of the memory blocks.
     
     If *block_data* is given, the cache data block will be updated.
     
     If *block_name* is given but the data is not available, it will return null pointer.
     
     If *duration* is below 0, the cache memory is kept as long as the server is
     running. If it is more than 0, the cache memory will be purged after the
     cache duration in seconds. If it is 0, it won't cache a thing.
     '''
     global settings
     
     if 'no_cache' in settings and settings['no_cache']:
         return block_data
     
     if base.isNumber(duration):
         if duration < 0:
             duration = None
         elif duration == 0:
             return block_data
     else:
         duration = None
     
     mref = None # reference to shared memory
     mc = None # Memcached client for a GAE app
     try:
         mc = google_cache()
         mref = mc.get(self.flag_memory_cache)
     except:
         pass
     
     global memory
     
     if self.flag_memory_cache not in memory:
         memory[self.flag_memory_cache] = mref and mref or {}
     
     mref = memory[self.flag_memory_cache]
     
     current_time = time()
     
     # If block_name is defined...
     if block_name:
         # If block_name is valid but the memory block is expired, then delete
         # the memory block.
         if block_name in mref and mref[block_name].is_expired():
             log.warn("CB %s is just expired." % block_name)
             del mref[block_name]
         
         # If block_data is defined, set or reset the memory block with
         # the new data (block_data) and return it.
         if block_data:
             mref[block_name] = MemoryBlock(block_data, duration)
             
             # Use Google's Memcached server for a GAE app to store the data
             # in the memory.
             try:
                 mc.set(self.flag_memory_cache, mref)
             except:
                 pass
             
             log.warn("CB %s is updated." % block_name)
             return block_data
     else:
         self.clean_up_cache()
         return dict(memory[self.flag_memory_cache])
     
     # If block_name is defined, block_name is not registered and block_data
     # is not defined, return None.
     return None
Example #2
0
 def __init__(self, data, duration):
     if base.isNumber(duration) and duration < 1:
         raise Exception("A memory block needs to stay longer than 1 second.")
     self.__data = data
     self.__registered_time = time()
     self.__duration = duration