set_lock¶
-
lockmgr.lockmgr.
set_lock
(*locks, timeout=600, fail=False, renew=True, create=True, **options) → lockmgr.lockmgr.LockSetResult[source]¶ This function is for advanced users, offering multiple lock creation, renewing, along with “all or nothing” locking with database rollback via the argument
fail
.Unlike other lock management functions, set_lock returns a
LockSetResult
object, which is designed to allow you to see clearly as to what locks were created, renewed, or skipped.Example Usage
Let’s set two locks,
hello
andworld
.>>> res = set_lock('hello', 'world') >>> res['locks'] [<Lock name='hello' locked_by='example.org' locked_until='2019-11-22 02:01:55.439390+00:00'>, <Lock name='world' locked_by='example.org' locked_until='2019-11-22 02:01:55.442734+00:00'>] >>> res['counts'] {'created': 2, 'renewed': 0, 'skip_create': 0, 'skip_renew': 0}
If we run
set_lock
again with the same arguments, we’ll still get the locks list, but we’ll see the counts show that they were renewed instead of created.>>> x = set_lock('hello', 'world') >>> x['locks'] [<Lock name='hello' locked_by='example.org' locked_until='2019-11-22 02:03:06.762620+00:00'>, <Lock name='world' locked_by='example.org' locked_until='2019-11-22 02:03:06.766804+00:00'>] >>> x['counts'] {'created': 0, 'renewed': 2, 'skip_create': 0, 'skip_renew': 0}
Since the result is an object, you can also access attributes via dot notation, as well as dict-like notation.
We can see inside of the
statuses
list - the action that was taken on each lock we specified, so we can see what locks were created, renewed, or skipped etc.>>> x.statuses[0] ('hello', {'was_locked': True, 'status': 'extend', 'locked': True}) >>> x.statuses[1] ('world', {'was_locked': True, 'status': 'extend', 'locked': True})
- Parameters
locks (str) – One or more lock names, as positional arguments, to create or renew.
timeout (int) – On existing locks, update locked_until to
now + timeout
(seconds)fail (bool) – (Default: False) If
True
, all lock creations will be rolled back if an existing lock is encountered, andLockFail
will be raised.renew (bool) – (Default: True) If
True
, any existing locks inlocks
will be renewed tonow + timeout
(seconds). If False, existing locks will just be skipped.create (bool) – (Default: True) If
True
, any names inlocks
which aren’t yet locked, will have a lock created for them, with their expiry set totimeout
seconds from now.
- Key str locked_by
(Default: system hostname) What server/app is trying to obtain this lock?
- Key int process_id
(Optional) The process ID requesting the lock
- Return LockSetResult results
A
LockSetResult
object containing the results of the set_lock operation.