Last active
March 17, 2017 12:42
-
-
Save thulasi-ram/4c43742883948ae493f6d8ab219026b1 to your computer and use it in GitHub Desktop.
If Django is facing Database Timeouts frequently.
This file contains 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
""" | |
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