Skip to content

Instantly share code, notes, and snippets.

@thulasi-ram
Last active March 17, 2017 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thulasi-ram/4c43742883948ae493f6d8ab219026b1 to your computer and use it in GitHub Desktop.
Save thulasi-ram/4c43742883948ae493f6d8ab219026b1 to your computer and use it in GitHub Desktop.
If Django is facing Database Timeouts frequently.
"""
TO OVERRIDE DJANGO's CursorWrapper which causes to use dead connections.
Use case: Deployed Pgbouncer and if its terminating your connections and django thinks it's still alive.
On attempt to access db django's psycopg driver raises DatabaseError.
WARNING: Have tested only on postgres. Didn't test the effect of this on rollbacks and edge cases.
"""
from django.db.backends.utils import CursorWrapper
class CustomCursorWrapper(CursorWrapper):
def execute(self, sql, params=None):
self.db.validate_no_broken_transaction()
if not self.db.is_usable():
self.db.close()
self.db.ensure_connection()
self.cursor = self.db.cursor()
with self.db.wrap_database_errors:
if params is None:
return self.cursor.execute(sql)
else:
return self.cursor.execute(sql, params)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment