Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django atomic increase with initial value

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?

like image 489
vartec Avatar asked Nov 18 '11 16:11

vartec


1 Answers

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
like image 128
Dmitry B. Avatar answered Oct 06 '22 18:10

Dmitry B.