用过MySQL的应该都知道,MySQL默认长链接只能保持8小时,超过后就会自动断开。
在peewee中如何维持长连接呢?
解决方法比较晦涩,需要自定义一个支持重试的mixin,然后自定义一种RetryMySQLDatabase混入mixin
from peewee import * from peewee import __exception_wrapper__ class RetryOperationalError(object): def execute_sql(self, sql, params=None, commit=True): try: cursor = super(RetryOperationalError, self).execute_sql( sql, params, commit) except OperationalError: if not self.is_closed(): self.close() with __exception_wrapper__: cursor = self.cursor() cursor.execute(sql, params or ()) if commit and not self.in_transaction(): self.commit() return cursor class RetryMySQLDatabase(RetryOperationalError, MySQLDatabase): pass
之后当作MySQLDatabase正常使用就可以了
XXX_DB = RetryMySQLDatabase( 'dbname', host=MYSQL_HOST, port=MYSQL_PORT, user='user', passwd='pass')