Skip to content

Instantly share code, notes, and snippets.

@dgouldin
Created October 10, 2011 21:19
Show Gist options
  • Save dgouldin/1276581 to your computer and use it in GitHub Desktop.
Save dgouldin/1276581 to your computer and use it in GitHub Desktop.
At attempt at an atomic and bounded cache incr/decr function which handles key existence.
from django.core.cache import cache
def _incr_decr(key, incr=True, min=None, max=None, initial=None):
'''Incr/decr function which handles key creation as needed'''
# FIXME: min/max have rampant race conditions which could be fixed using
# memcache's "cas" feature, but current pylibmc + libmemcached causes a
# segfault when used.
initial = initial or min or 0
if incr:
action = cache.incr
else:
action = cache.decr
try:
value = action(key)
except ValueError: # the key doesn't exist, add it
cache.add(key, initial)
value = action(key)
if min is not None and value < min:
print 'min reached, resetting'
value = min
cache.set(key, value)
if max is not None and value > max:
print 'max reached, resetting'
value = max
cache.set(key, value)
return value
def _incr(key, max=None, initial=None):
return _incr_decr(key, max=max, initial=initial)
def _decr(key, min=None, initial=None):
return _incr_decr(key, incr=False, min=min, initial=initial)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment