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?
incr
with an inital fallback. You mustadd
and thenincr
in two separate operations according to that user. You might want to check into the validity of that. – Misconception