Created
July 14, 2015 16:42
-
-
Save systemsoverload/b0f47bb4555ccc1d5134 to your computer and use it in GitHub Desktop.
Simple context manager to wrap django utilities in pg_advisory locks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import connection, transaction | |
from contextlib import contextmanager | |
@contextmanager | |
def pg_advisory_xact_lock(*keys): | |
""" | |
Acquire an exclusive database lock against an arbitrary string key | |
""" | |
string_key = '.'.join(keys) | |
lock_key = sha1(string_key).digest().__hash__() | |
lockstring = 'SELECT pg_advisory_xact_lock({0});'.format(lock_key) | |
transaction.set_autocommit(False) | |
try: | |
connection.cursor().execute(lockstring) | |
yield | |
finally: | |
transaction.commit() | |
transaction.set_autocommit(True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
WARNING in case anyone stumbles upon this nine+ years later, don't use as-is without rolling your own hashing mechanism:
__hash__()
isn't stable so you'll end up getting different locks for the same keys.