使用 Peewee 处理数据库断开连接

Handling Database Disconnection With Peewee

我的代码使用 Peewee 和 MySQL。在我尝试将它与用于访问慢速服务器的 requests 一起使用之前,一切都像一个魅力。简而言之,我需要将对象上传到 MySQL 数据库,但我的程序崩溃了 - 在上传了一些条目之后 - 并出现以下错误:

peewee.OperationalError: (2006, 'MySQL server has gone away')

我明白这个错误,我已经在使用 Flask 应用程序时遇到过这个问题,Peewee 文档在这种情况下帮助了我。但在这种情况下,我没有使用 Flask,它只是一个简单的 Python 脚本。因此我还不知道如何解决这个问题。

有趣的是,Peewee 相关部分与 html 请求无关。我正在做一些与 Peewee 无关的任务,然后调用此方法:

def uploadObj (objekt):
    with myDB.atomic():
        entrylist.insert_many(objekt).execute()
        print ("upload")

我假设问题发生在html请求很慢并且连接长时间空闲并断开连接时。

基于this answer我试过:

db = MySQLDatabase(db_name, user=db_username, passwd=db_password, host=db_host, port=db_port)
db.get_conn().ping(True)

但这并没有解决问题。

第二次尝试时,我尝试了以下似乎可以解决问题的代码:

def uploadObj (objekt):
    try:
        with myDB.atomic():
            entrylist.insert_many(objekt).execute()
            print ("upload")
        myDB.close()
    except:
        myDB.connect()
        with myDB.atomic():
            entrylist.insert_many(objekt).execute()
            print ("upload")

如果连接断开,我手动重新连接到数据库。

我的问题是,这是我可以毫无问题地使用的正确解决方案吗?或者有更好的方法来防止这个问题吗?

您可以使用重新连接 mixin:

from playhouse.shortcuts import ReconnectMixin

class ReconnectMySQLDatabase(ReconnectMixin, MySQLDatabase):
    pass

db = ReconnectMySQLDatabase('my_app', ...)

如果您有一个长时间闲置的 运行 脚本,如果没有 activity,MySQL 将终止连接。您可以将 mysql 服务器配置为不执行此操作,或者您可以使用上述方法在某些错误情况下自动重新连接。