From 28f9f32d91bb045f0ef7b852d55a1f0523fa309e Mon Sep 17 00:00:00 2001 From: Roberto Rosario Date: Mon, 30 Jul 2012 10:54:43 -0400 Subject: [PATCH] Add decorator helper for simple locks --- apps/lock_manager/decorators.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 apps/lock_manager/decorators.py diff --git a/apps/lock_manager/decorators.py b/apps/lock_manager/decorators.py new file mode 100644 index 0000000000..c98a7ae1c9 --- /dev/null +++ b/apps/lock_manager/decorators.py @@ -0,0 +1,33 @@ +from __future__ import absolute_import + +from functools import wraps + +from . import logger +from . import Lock +from .exceptions import LockError + + +def simple_locking(lock_id, expiration=None): + """ + A decorator that wraps a function in a single lock getting algorithm + """ + def inner_decorator(function): + def wrapper(*args, **kwargs): + try: + # Trying to acquire lock + lock = Lock.acquire_lock(lock_id, expiration) + except LockError: + # Unable to acquire lock + pass + except Exception: + # Unhandled error, release lock + lock.release() + raise + else: + # Lock acquired, proceed normally, release lock afterwards + logger.debug('acquired lock: %s' % lock_id) + result = function(*args, **kwargs) + lock.release() + return result + return wraps(function)(wrapper) + return inner_decorator