from django.conf import settings from sqlalchemy import event, exc from sqlalchemy.pool import Pool
from log import logger
@event.listens_for(Pool, "checkout") def_on_checkout(dbapi_connection, connection_record, connection_proxy): logger.debug("connection retrieved from pool")
if settings.POOL_PESSIMISTIC_MODE: cursor = dbapi_connection.cursor() try: cursor.execute("SELECT 1") except: # raise DisconnectionError - pool will try # connecting again up to three times before raising. raise exc.DisconnectionError() finally: cursor.close()
@event.listens_for(Pool, "checkin") def_on_checkin(*args, **kwargs): logger.debug("connection returned to pool")
2019-08-29 22:17:10,140 db_pool_patch - db_pool_listen.py - DEBUG - connection retrieved from pool (0.000) SELECT "book_tab"."book_id", "book_tab"."title", "book_tab"."author" FROM "book_tab" WHERE "book_tab"."book_id" = 1; args=(1,) 2019-08-29 22:17:10,141 db_pool_patch - views.py - INFO - some shit code begin to run ... 2019-08-29 22:17:15,144 db_pool_patch - views.py - INFO - hmm, shit code finished, it took 5 seconds [29/Aug/2019 22:17:15] "GET /book/get?book_id=1 HTTP/1.1" 200 62 2019-08-29 22:17:15,146 db_pool_patch - db_pool_listen.py - DEBUG - connection returned to pool
# Django 1.11 defpatched_execute_sql(self, result_type=MULTI, chunked_fetch=False): result = execute_sql(self, result_type, chunked_fetch) ifnotself.connection.in_atomic_block: self.connection.close() # return connection to pool by db_pool_patch return result
defpatched_insert_execute_sql(self, return_id=False): result = insert_execute_sql(self, return_id) ifnotself.connection.in_atomic_block: self.connection.close() # return connection to pool by db_pool_patch return result
2019-08-29 22:13:22,373 db_pool_patch - db_pool_listen.py - DEBUG - connection retrieved from pool (0.000) SELECT "book_tab"."book_id", "book_tab"."title", "book_tab"."author" FROM "book_tab" WHERE "book_tab"."book_id" = 1; args=(1,) 2019-08-29 22:13:22,374 db_pool_patch - db_pool_listen.py - DEBUG - connection returned to pool 2019-08-29 22:13:22,374 db_pool_patch - views.py - INFO - some shit code begin to run ... 2019-08-29 22:13:27,378 db_pool_patch - views.py - INFO - hmm, shit code finished, it took 5 seconds [29/Aug/2019 22:13:27] "GET /book/get?book_id=1 HTTP/1.1" 200 62
defpatched_insert_execute_sql(self, return_id=False): try: result = insert_execute_sql(self, return_id) except Exception as e: log.error('[insert_execute_sql]insert_execute_sql_error| exception = %s', e) self.connection.close() raise ifnotself.connection.in_atomic_block: self.connection.close() # return connection to pool by db_pool_patch return result