Created
December 8, 2011 22:51
-
-
Save danielhfrank/1449074 to your computer and use it in GitHub Desktop.
MC Lock Decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#====== Decorator to use memcached for locking ======= | |
def mc_lock(namespace, on_lock_failed) : | |
''' | |
This uses memcached to provide a lock on a key before performing some operation. | |
The first argument provided to the decorated function will be the key. | |
It will be preceded by $namespace to ensure uniqueness | |
on_lock_failed is a function that will be called if we fail to acquire the lock | |
''' | |
def my_decorator(func) : | |
def wrapped(*args, **kwargs) : | |
if not args: | |
raise Exception("You must pass an un-named arg to use mc_lock on!") | |
lock_mc_key = _utf8('%s.%s' % (namespace, args[0])) | |
if mc.add(lock_mc_key, 1, time=300): | |
try: | |
return func(*args, **kwargs) | |
finally: | |
mc.delete(lock_mc_key) | |
else: | |
on_lock_failed() | |
return wrapped | |
return my_decorator | |
# ==================================================== |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment