Django PGLock

1.8.0 · active · verified Sat Apr 11

django-pglock provides utilities for managing PostgreSQL locks within Django applications, including advisory locks, table locks, and tools for monitoring and managing blocking locks. It is actively maintained, with regular updates to support the latest versions of Python, Django, and PostgreSQL.

Warnings

Install

Imports

Quickstart

Demonstrates how to use `pglock.advisory` as a context manager to ensure only one instance of a critical section runs at a time. The lock ID can be any string, which `django-pglock` hashes to a 64-bit integer for PostgreSQL.

import pglock

def my_exclusive_task():
    # Simulate a task that should only run one instance at a time
    print("Attempting to acquire lock...")
    with pglock.advisory("my_critical_section_lock") as acquired:
        if acquired:
            print("Lock acquired! Running critical section...")
            # Your critical section code here
            import time
            time.sleep(2)
            print("Critical section complete.")
        else:
            print("Could not acquire lock, another instance is running.")

if __name__ == "__main__":
    # In a real Django app, this would run within a Django context
    # For quickstart, we just call the function directly.
    # You'd typically configure Django and a database connection first.
    # To test, run this script twice rapidly.
    my_exclusive_task()

view raw JSON →