General notes
Recently, I had the same problem with several conditions that I had to fulfill:
- the solution must be thread safe
- multiple database connections from the same computer can be active at the same time, kill the exact connection / request
- the application contains connections to many different databases - a portable handler for each database host
We had the following class layout (unfortunately, I cannot post real sources):
class AbstractModel: pass class FirstDatabaseModel(AbstractModel): pass
And created several threads for each model.
Python 3.2 Solution
In our application, one model = one database. Therefore, I created a “service connection” for each model (so that we can execute KILL in a parallel connection). Therefore, if one instance of FirstDatabaseModel was created, 2 database connections were created; if 5 instances were created, only 6 compounds were used:
class AbstractModel: _service_connection = None
Now we need a killer:
def _kill_connection(self):
Note: connection.execute = create cursor, execute, close cursor.
And make the cache thread safe with threading.Lock :
def _init_service_connection(self): ''' Initialize one singleton connection for model ''' cls = type(self) if cls._service_connection is not None: return cls._service_connection = MySQLFromConfig(self.config) cls._service_connection_lock = threading.Lock() def _kill_connection(self):
Finally, add the timed execute method using threading.Timer :
def timed_query(self, sql, timeout=5): kill_query_timer = threading.Timer(timeout, self._kill_connection) kill_query_timer.start() try: self.connection.long_query() finally: kill_query_timer.cancel()
Vyktor
source share