天天看点

peewee: OperationalError: (2006, ‘MySQL server has gone away’)

MySQL默认长链接只能保持8小时,超过后就会自动断开。

peewee报错:

OperationalError: (2006, ‘MySQL server has gone away’)      

在peewee2中如何维持长连接,可以如下操作:

from peewee import MySQLDatabase
from playhouse.shortcuts import RetryOperationalError

class RetryMySQLDatabase(RetryOperationalError, MySQLDatabase):
    pass

db = RetryMySQLDatabase(
    host='127.0.0.1',
    database='dataname',
    user="root",
    passwd="123456",
    charset='utf8'
)      

Python3中已经去除

RetryOperationalError

, 后来的版本又加上了(2021-03-03补充)

不过作者不推荐使用,想象如果在一个事务中,断开了链接,进行了自动重连

from peewee import MySQLDatabase
from playhouse.shortcuts import ReconnectMixin

# 防止断开 see: https://github.com/coleifer/peewee/issues/1992
class ReconnectMySQLDatabase(ReconnectMixin, MySQLDatabase):
    """peewee作者不推荐使用"""
    pass
      

参考

peewee解决问题”OperationalError: (2006, ‘MySQL server has gone away’)”