单位内部自建及使用的微信小程序应用,后端应用采用Flask+Sqlalchemy。
系统在运行过程中查询数据频繁提示500错误,查阅后台日志中发现频繁出现错误信息sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013,‘Lost connection to MySQL server during query‘)、(2006, "MySQL server has gone away (ConnectionResetError(104,
‘Connection reset by peer’)。
经过在网上查找解决办法多次踩坑后,现记录解决方法。
一、问题现象
系统查询数据,偶尔正常查询,偶尔访问页面返回500错误提示,然后刷新一两次就又可以访问了,查看后台日志文件,发现报错。
...
self._sock.sendall(data)
ConnectionResetError: [Errno 104] Connection reset by peer
During handling of the above exception, another exception occurred:
...
"MySQL server has gone away (%r)" % (e,))
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError)
(2006, "MySQL server has gone away (ConnectionResetError(104,
'Connection reset by peer'))")
...
二、报错原因
项目配置:flask_sqlalchemy自动回收连接的秒数,默认设置的是 -1,即永远不超时
SQLALCHEMY_POOL_RECYCLE =-1
MySQL的wait_timeout默认是28800,也就是超过8小时的连接就会自动失效,而要连接的mysql通过查看发现是120秒
show variables like '%timeout%'
三、解决方法
在应用代码增加请求后处理, 移除每次请求的session
@app.after_request
def close_request_session(response):
# 解决mysql server gone away
db.session.remove()
return response
四、实践情况
通过增加上述代码,完美解决flask与数据库相关的报错问题。