热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

解决peewee的MySQL长连接问题

MySQL的默认长链接只能保持8小时,超过后就会自动断开。在peewee中如何维持长连接呢?解决方法比较晦涩,需要自定义一个支持重试的

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

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

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

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 cursorclass RetryMySQLDatabase(RetryOperationalError, MySQLDatabase):pass

之后当作MySQLDatabase正常使用就可以了


Links = {"host": Config.mysql_host,"port": Config.mysql_port,"user": Config.mysql_usr,"password": Config.mysql_pass,"database":Config.mysql_db
}
db = RetryMySQLDatabase(**Links, charset="utf8mb4")


推荐阅读
author-avatar
幻竞_847
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有