Package entropy :: Package db :: Module cache

Source Code for Module entropy.db.cache

 1  # -*- coding: utf-8 -*- 
 2  """ 
 3   
 4      @author: Fabio Erculiani <[email protected]> 
 5      @contact: [email protected] 
 6      @copyright: Fabio Erculiani 
 7      @license: GPL-2 
 8   
 9      I{EntropyRepository} caching interface. 
10   
11  """ 
12  import weakref 
13   
14  from entropy.core import Singleton 
15   
16  import entropy.tools 
17   
18   
19 -class EntropyRepositoryCacher(Singleton):
20 """ 21 Tiny singleton-based helper class used by EntropyRepository in order 22 to keep cached items in RAM. 23 """
24 - def init_singleton(self):
25 self.__live_cache = {}
26
27 - def clear(self):
28 """ 29 Clear all the cached items 30 """ 31 self.__live_cache.clear()
32
33 - def clear_key(self, key):
34 """ 35 Clear just the cached item at key (hash table). 36 """ 37 try: 38 del self.__live_cache[key] 39 except KeyError: 40 pass
41
42 - def keys(self):
43 """ 44 Return a list of available cache keys 45 """ 46 return list(self.__live_cache.keys())
47
48 - def discard(self, key):
49 """ 50 Discard all the cache items with hash table key starting with "key". 51 """ 52 for dkey in tuple(self.__live_cache.keys()): 53 if dkey.startswith(key): 54 try: 55 self.__live_cache.pop(dkey) 56 except KeyError: 57 pass
58
59 - def get(self, key):
60 """ 61 Get the cached item, if exists. 62 """ 63 obj = self.__live_cache.get(key) 64 if isinstance(obj, weakref.ref): 65 return obj() 66 return obj
67
68 - def set(self, key, value):
69 """ 70 Set item in cache. 71 """ 72 if isinstance(value, (set, frozenset)): 73 self.__live_cache[key] = weakref.ref(value) 74 else: 75 self.__live_cache[key] = value
76 77
78 -class EntropyRepositoryCachePolicies(object):
79 """ 80 Enum listing all the available in-RAM cache policies for EntropyRepository 81 object instances. 82 It is up to EntropyRepositoryBase subclasses to make use of these. 83 """ 84 85 ( 86 # No caching in RAM at all, slower in some cases, but 87 # still acceptably fast. 88 NONE, 89 # All the queries that make sense to cache are cached in RAM. 90 ALL, 91 ) = range(2) 92 93 if entropy.tools.total_memory() >= 4000: 94 DEFAULT_CACHE_POLICY = ALL 95 else: 96 DEFAULT_CACHE_POLICY = NONE
97