Does Django caching have a method similar to Rails' cache.fetch? (http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#M001023) The rails cache fetch works like:
cache.fetch("my_key") { // return what I want to put in my_key if it is empty "some_value" }
It's useful because it checks the cache, and returns the value of the cache if it is there. If not, it will store "some_value" in the cache, and then return "some_value".
Is there an equivalent of this in Django? If not, what would the Python syntax for this look like if I were to implement such a function?
I think the code you would have to write would be like this: (EDIT)
and you would call it like this:
Well to get a default value if the key does not exits you can provide a second parameter:
To save the default value in cache if the key does not exist, you can provide your custom cache backend. E.g. this extends the
db
cache backend (but works the same with others):But I don't think that this adds any value.
Update:
In response to the comment on the other post: Yes it compares the default value with the returned value and if both are equal, the value gets added to the cache. But
cache.add
only sets the new value if the key is not already in the cache (contrast tocache.set
which always overrides):Julian's code is quite good but doesn't take positional args (when you want to use sorted() for example). Here's my fix: