Created
June 22, 2012 13:16
-
-
Save jul/2972676 to your computer and use it in GitHub Desktop.
A cache maker for repoze.lru so you can invalidate your cache of decorated functions if needed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from repoze.lru import LRUCache, _MARKER | |
from repoze.lru import ExpiringLRUCache,lru_cache,_DEFAULT_TIMEOUT | |
"""A (decorator) cache maker for lru.repoze so you can clear | |
your cache if needed""" | |
class CacheMaker(): | |
def __init__(self,default={}): | |
self._maxsize=default.get("maxsize",_MARKER) | |
self._time_out=default.get("time_out",_DEFAULT_TIMEOUT) | |
self._cache=dict() | |
def lrucache(self,name,maxsize=_MARKER): | |
if name in self._cache: | |
raise KeyError("cache %s already in use" % name) | |
cache = self._cache[name]=LRUCache( | |
self._maxsize if maxsize is _MARKER else maxsize | |
) | |
return lru_cache(maxsize, cache) | |
def expiring_lrucache(self,name,maxsize=_MARKER, timeout=_MARKER): | |
if name in self._cache: | |
raise KeyError("cache %s already in use" % name) | |
cache = self._cache[name]=ExpiringLRUCache( | |
self._maxsize if maxsize is _MARKER else maxsize, | |
self._time_out if timeout is _MARKER else timeout | |
) | |
return lru_cache(maxsize, cache) | |
def clear(self, name = _MARKER): | |
"""clear all cache if no arguments, else clear given cache""" | |
to_clear = self._cache.keys() if name is _MARKER else [ name ] | |
for cache_name in to_clear: | |
self._cache[cache_name].clear() | |
if '__main__' == __name__: | |
cm = CacheMaker() | |
@cm.lrucache("this",10) | |
def a(x): | |
return x+10 | |
a(10) | |
#20 | |
cm._cache["this"] | |
#<repoze.lru.LRUCache object at 0x7f1a8544d410> | |
cm._cache["this"].data | |
#{(10,): (0, 20)} | |
a(20) | |
#30 | |
cm._cache["this"].data | |
#{(10,): (0, 20), (20,): (1, 30)} | |
cm.clear() | |
cm._cache["this"].data | |
#{} | |
a(20) | |
#30 | |
cm.clear('this') | |
cm._cache["this"].data | |
#{} | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment