Postgres locking routines and lock table access.
Low maintenance activity. Last release 12 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and release cadence.
pip install django-pglockdjango-pglock
django-pglock performs advisory locks, table locks, and helps manage blocking locks.
Here's some of the functionality at a glance:
pglock.advisoryfor application-level locking, for example, ensuring that tasks don't overlap.pglock.modelfor locking an entire model.pglock.timeoutfor dynamically setting the timeout to acquire a lock.pglock.prioritizeto kill blocking locks for critical code, such as migrations.- The
PGLockandBlockedPGLockmodels for querying active and blocked locks. - The
pglockmanagement command that wraps the models and provides other utilities.
Quickstart
Advisory Locks
Use pglock.advisory to acquire a Postgres advisory lock:
import pglock
with pglock.advisory("my_lock_id"):
# This code blocks until the "my_lock_id" lock is available
Above our code will block until the lock is available, meaning no instances of the function will run simultaneously. Use the timeout argument to configure how long to wait for the lock. A timeout of zero will return immediately:
with pglock.advisory("my_lock_id", timeout=0) as acquired:
if acquired:
# The lock is acquired
Use side_effect=pglock.Raise to raise a django.db.utils.OperationalError if the lock can't be acquired. When using the decorator, you can also use side_effect=pglock.Skip to skip the function if the lock can't be acquired:
@pglock.advisory(timeout=0, side_effect=pglock.Skip)
def non_overlapping_func():
# This function will not run if there's another one already running.
# The decorator lock ID defaults to <module_name>.<function_name>
Model Locks
pglock.model can take a lock on an entire model during a transaction. For example:
from django.db import transaction
import pglock
with transaction.atomic():
pglock.model("auth.User")
# Any operations on auth.User will be exclusive here. Even read access
# for other transactions is blocked
pglock.model uses Postgres's LOCK statement, and it accepts the lock mode as a argument. See the .