I'm trying to have atomic increase-or-create operation in Django cache. I'm using memcache as backend. Memcache client's incr_async()
function takes initial_value
parameter. The meaning is:
If the key does not yet exist in the cache and you specify an initial_value, the key's value will be set to this initial value and then incremented.
However, I don't see how can I do this in Django, as cache.incr()
documentation says:
A ValueError will be raised if you attempt to increment or decrement a nonexistent cache key.
Of course I could do:
cache.add(key,initial_value)
cache.incr(key)
But that is not atomic and may lead to race conditions.
Is there a way around this, which would preserve atomicity of the operation?
As far as I know Django's cache API don't support this. You would have to drop down to the memcache API and do this directly:
from django.core.cache import cache
client = cache._client # <--direct reference to memcached.Client object
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