Atomic test/set/get using django cache API?

350 views
Skip to first unread message

Roy Smith

unread,
May 14, 2013, 8:25:55 AM5/14/13
to Django users
I want to do an atomic "test and set if doesn't exist" on a cache key using the django API. So far, that's easy.; cache.add() gives me exactly that.

But, if the key does exist, I also want to get the current value. All add() gives me back is a flag saying if the key existed. Is there a way to also get the value, inside the atomic perimeter?

--
Roy Smith
r...@panix.com

Shawn Milochik

unread,
May 14, 2013, 10:09:31 AM5/14/13
to django...@googlegroups.com
I love and recommend Redis.

If you can use a Redis key instead of Django's cache, you can call get() on the key. If the result is not None, now you have it. If it is None, you know it didn't exist, so you can set it.

I don't think it's possible to have it work the way you want with the default cache -- there's no way to know that in between checking for it and finding it empty and setting it some other process didn't just set it.

You may have noticed there's still a tiny race condition in the naive use of Redis I described. That's easily handled using Redis's "watch" command.

See:



Reply all
Reply to author
Forward
0 new messages