I want to cache certain methods of a class - but only if a read_only flag is set on the instance of the class.
So, in the object below, I want the get() method to be cacheable, but only if self.readonly is True.
I can't conditionally use the decorator, because it's set when the class is defined, not when it's instantiated.
from beaker.cache import cache_regions, cache_region
cache_regions.update({
'long_term':{
'expire':86400,
'type':'dbm',
'data_dir':'/tmp',
'key_length': 32,
}
})
class Foo(object):
def __init__(self, read_only=True):
self.read_only = read_only
@cache_region('long_term')
def get(self, arg):
return arg + 1
You can use a decorator to call the right (cached or not) function checking the desired attribute:
def conditional(decorator):
def conditional_decorator(fn):
dec = decorator(fn)
def wrapper(self, *args, **kw):
if self.read_only:
return dec(self, *args, **kw)
return fn(self, *args, **kw)
return wrapper
return conditional_decorator
Use like this:
@conditional(cache_region('long_term'))
def get(self, arg):
return arg + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With