Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Last active June 16, 2024 15:27
Show Gist options
  • Save mariocesar/fc6862a1588ce053a09f0c90e1592674 to your computer and use it in GitHub Desktop.
Save mariocesar/fc6862a1588ce053a09f0c90e1592674 to your computer and use it in GitHub Desktop.

This small snippet can be implemented in your Django project to handle locks. It is particularly useful for replacing Redis locks, reducing dependency overhead. To use this snippet, simply copy and adapted to your Django project.

The hash_string function is used to convert a string value into a numerical hash value, as PostgreSQL advisory lock mechanism requires an integer.

Tested on Python3.11 and Django4

Learn more about advisory locks in:

import hashlib
from contextlib import contextmanager
from django.db import connection
def hash_string(value: str) -> int:
hash_object = hashlib.sha256(value.encode())
lock_id = int(hash_object.hexdigest()[:16], 16)
return lock_id
@contextmanager
def advisory_lock(namespace_id: int, lock_name: str) -> None:
lock_id = hash_string(lock_name)
try:
with connection.cursor() as cursor:
cursor.execute("SELECT pg_advisory_lock(%s, %s);", [namespace_id, lock_id])
yield
finally:
with connection.cursor() as cursor:
cursor.execute("SELECT pg_advisory_unlock(%s, %s);", [namespace_id, lock_id])
company = 1
lock_name = "sales_code"
with advisory_lock(company, lock_name):
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment