peewee解决问题"OperationalError: (2006, 'MySQL server has gone away')"

用过MySQL的应该都知道,MySQL默认长链接只能保持8小时,超过后就会自动断开。

在peewee中如何维持长连接呢?

解决方法比较晦涩,需要自定义一个支持重试的mixin,然后自定义一种RetryMySQLDatabase混入mixin

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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
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
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正常使用就可以了

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
XXX_DB = RetryMySQLDatabase(
'dbname',
host=MYSQL_HOST,
port=MYSQL_PORT,
user='user',
passwd='pass')
XXX_DB = RetryMySQLDatabase( 'dbname', host=MYSQL_HOST, port=MYSQL_PORT, user='user', passwd='pass')
XXX_DB = RetryMySQLDatabase(
    'dbname',
    host=MYSQL_HOST,
    port=MYSQL_PORT,
    user='user',
    passwd='pass')

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *