给tornado的database.py增加dbutils支持
忘记什么时候在邮件订阅中看到smallfish的一个给tornado的database.py增加dbutils支持的文章了,去smaillfish的blog看了一下居然是09年写的一篇文章。小鱼修改的代码为:
def reconnect(self): """Closes the existing database connection and re-opens it.""" self.close() try: from DBUtils import PooledDB pool_con = PooledDB.PooledDB(creator=MySQLdb, **self._db_args) self._db = pool_con.connection() except: self._db = MySQLdb.connect(**self._db_args) self._db.autocommit(True)
小鱼干掉了原有的设置autocommit(True)这一行代码,我估计主要是因为DBUtils没有autocommit()这个方法。干掉此行代码后会有一个小问题,就是如果mysql配置的autocommit=0的话,每次对数据库的修改是不会实时反馈给mysql数据库的。而原版的self._db.autocommit(True)这一行就是为了在保证在执行完一条SQL后,修改内容马上反馈给mysql。
Google一圈后我找到两个解决方案:
- 一个是利用DBUtils的的setsession命令:
def reconnect(self): """Closes the existing database connection and re-opens it.""" self.close() try: from DBUtils import PooledDB pool_con = PooledDB.PooledDB(creator=MySQLdb, setsession=['SET AUTOCOMMIT = 1'], **self._db_args) self._db = pool_con.connection() except: self._db = MySQLdb.connect(**self._db_args) self._db.autocommit(True)
- 另一个就是类似tornado的做法给每个cursors的connection设置autocommit属性为True
def reconnect(self): """Closes the existing database connection and re-opens it.""" self.close() try: from DBUtils import PooledDB pool_con = PooledDB.PooledDB(creator=MySQLdb, **self._db_args) self._db = pool_con.connection() self._db.cursor().connection.autocommit(True) except: self._db = MySQLdb.connect(**self._db_args) self._db.autocommit(True)
