Enable Database Lock Timeout in Django

By default clients requesting database lock should wait until the lock is released. This might take forever. In locking contention situations it might be useful to instrument your database to timeout when lock is not being released for given amount of time, e.g. 5 seconds.

db_lock_timeout_middleware.py
 1from django.conf import settings
 2from django.db import connection
 3from django.core import exceptions
 4
 5class DbLockTimeoutMiddleware:
 6    def __init__(self, get_response):
 7        self.get_response = get_response
 8        self.lock_timeout = int(getattr(settings, "DB_LOCK_TIMEOUT", -1))
 9        if self.lock_timeout == -1:
10            raise exceptions.MiddlewareNotUsed("No lock timeout is required")
11
12    def __call__(self, request):
13        with connection.execute_wrapper(self._set_lock_timeout_execute_wrapper):
14            response = self.get_response(request)
15        return response
16
17    # pylint: disable=too-many-arguments
18    def _set_lock_timeout_execute_wrapper(self, execute, sql, params, many, context):
19        execute(f"SET LOCK_TIMEOUT {self.lock_timeout}", [])
20        result = execute(sql, params, many, context)
21        return result

You can download the source from here.