Back to index

plone3  3.1.7
cache.py
Go to the documentation of this file.
00001 """Cache
00002 """
00003 from time import time
00004 from Acquisition import aq_base
00005 
00006 class Cache:
00007 
00008     def __init__(self, context, _id='_v_transform_cache'):
00009         self.context = context
00010         self._id =_id
00011 
00012     def _genCacheKey(self, identifier, *args):
00013         key = identifier
00014         for arg in args:
00015             key = '%s_%s' % (key, arg)
00016         key = key.replace('/', '_')
00017         key = key.replace('+', '_')
00018         key = key.replace('-', '_')
00019         key = key.replace(' ', '_')
00020         return key
00021 
00022     def setCache(self, key, value):
00023         """cache a value indexed by key"""
00024         if not value.isCacheable():
00025             return
00026         context = self.context
00027         key = self._genCacheKey(key)
00028         if getattr(aq_base(context), self._id, None) is None:
00029             setattr(context, self._id, {})
00030         getattr(context, self._id)[key] = (time(), value)
00031         return key
00032 
00033     def getCache(self, key):
00034         """try to get a cached value for key
00035 
00036         return None if not present
00037         else return a tuple (time spent in cache, value)
00038         """
00039         context = self.context
00040         key = self._genCacheKey(key)
00041         dict = getattr(context, self._id, None)
00042         if dict is None :
00043             return None
00044         try:
00045             orig_time, value = dict.get(key, None)
00046             return time() - orig_time, value
00047         except TypeError:
00048             return None
00049         
00050     def purgeCache(self, key=None):
00051         """Remove cache
00052         """
00053         context = self.context
00054         id = self._id
00055         if not shasattr(context, id):
00056             return
00057         if key is None:
00058             delattr(context, id)
00059         else:
00060             cache = getattr(context, id)
00061             key = self._genCacheKey(key)
00062             if cache.has_key(key):
00063                 del cache[key]