Cache.fetch in Django?

Does Django caching have a method similar to Rails cache? ( http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#M001023 ) Resetting the rail cache works as follows:

  cache.fetch ("my_key") {
   // return what I want to put in my_key if it is empty
   "some_value"
 }

This is useful because it checks the cache and returns the value of the cache, if any. If not, it will store "some_value" in the cache, and then return "some_value".

Is there an equivalent to this in Django? If not, what Python syntax for this looks like if I have to implement such a function?

+2
source share
3 answers

I think the code you need to write will be like this: (EDIT)

def get_value(param1,param2): return "value %s - %s " % (str(param1),str(param2)) def fetch(key,val_function,**kwargs) val = cache.get(key) if not val: val = val_function(**kwargs) cache.set(key,val) return val 

and you would call it like this:

 fetch('key',get_value,param1='first',param2='second') 
+4
source

Julian code is pretty good, but it doesn't accept positional arguments (for example, if you want to use sorted ()). Here is my fix:

 def get_value(param1,param2): return "value %s - %s " % (str(param1),str(param2)) def fetch(key,val_function, *args, **kwargs) val = cache.get(key) if not val: val = val_function(*args, **kwargs) cache.set(key,val) return val 
+2
source

To get the default value if the key does not exit, you can specify the second parameter:

 cache.get('key', 'default') 

cache.get() can take a default argument. This indicates what value should be returned if the object does not exist in the cache.

To keep the default value in the cache, if the key does not exist, you can provide a custom cache server . For instance. this extends the db cache backend (but works with others):

 from django.core.cache.backends import db class CustomCache(db.CacheClass): def get(self, key, default=None): result = super(CustomCache, self).get(key, default) if result == default: self.add(key, default) return default return result 

But I do not think this adds any value.

Update:
In response to a comment on another post: Yes compares the default value with the return value, and if both are equal, the value is added to the cache. But cache.add sets only a new value if the key is not (unlike cache.set , which is always overridden):

To add a key only if it does not already exist , use the add() method. It accepts the same parameters as set() , but will not try to update the cache if the specified key is already present.

0
source

All Articles