博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mysql has gone away 自动连接_python下保持mysql连接,避免“MySQL server has gone away“方法...
阅读量:4578 次
发布时间:2019-06-08

本文共 1898 字,大约阅读时间需要 6 分钟。

因需要对saltstack的所有动作进行入库采集,网上采集脚本mysql连接会因超时而断开,导致守护进程在下一次采集数据时提示:Traceback (most recent call last):

File "./salt_event_to_mysql.py", line 39, in 

ret[‘success‘], json.dumps(ret)))

File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 173, in execute

File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler

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

后退出,解决方法是采用类似mysql_ping()的方法在每次数据入库前做一次检测,唤醒连接,以下是完整代码:

#!/bin/env python

#coding=utf8

# Import python libs

import json

# Import salt modules

import salt.config

import salt.utils.event

# Import third party libs

import MySQLdb

__opts__ = salt.config.client_config(‘/etc/salt/master‘)

# Create MySQL connect

conn = MySQLdb.connect(host=__opts__[‘mysql‘][‘host‘], user=__opts__[‘mysql‘][‘user‘], passwd=__opts__[‘mysql‘][‘pass‘], db=__opts__[‘mysql‘][‘db‘], port=__opts__[‘mysql‘][‘port‘])

cursor = conn.cursor()

# Listen Salt Master Event System

event = salt.utils.event.MasterEvent(__opts__[‘sock_dir‘])

for eachevent in event.iter_events(full=True):

####保持连接的部分###########

if conn is None:

conn = MySQLdb.connect(host=__opts__[‘mysql‘][‘host‘], user=__opts__[‘mysql‘][‘user‘], passwd=__opts__[‘mysql‘][‘pass‘], db=__opts__[‘mysql‘][‘db‘], port=__opts__[‘mysql‘][‘port‘])

cursor = conn.cursor()

else:

conn.ping(True)

###########################

ret = eachevent[‘data‘]

if "salt/job/" in eachevent[‘tag‘]:

# Return Event

if ret.has_key(‘id‘) and ret.has_key(‘return‘):

# Igonre saltutil.find_job event

if ret[‘fun‘] == "saltutil.find_job":

continue

if ret[‘fun‘] == "test.ping":

continue

sql = ‘‘‘INSERT INTO `salt_returns`

(`fun`, `jid`, `return`, `id`, `success`, `full_ret` )

VALUES (%s, %s, %s, %s, %s, %s)‘‘‘

cursor.execute(sql, (ret[‘fun‘], ret[‘jid‘],

json.dumps(ret[‘return‘]), ret[‘id‘],

ret[‘success‘], json.dumps(ret)))

cursor.execute("COMMIT")

# Other Event

else:

pass

转载地址:http://elqms.baihongyu.com/

你可能感兴趣的文章
struts (一)
查看>>
【新番推荐】工作细胞
查看>>
NYOJ 16 矩形嵌套
查看>>
Leetcode中的SQL题目练习(二)
查看>>
dubbo 集群容错源码
查看>>
Collection接口的子接口——Queue接口
查看>>
LINUX安装NGINX
查看>>
服务器启动项目抛错 没有到主机的路由
查看>>
python_85_sys模块
查看>>
第九周动手动脑
查看>>
HDU 1811 Rank of Tetris
查看>>
网站UI分析
查看>>
winform 获取当前名称
查看>>
报表分栏后的排序
查看>>
Django中models定义的choices字典使用get_FooName_display()在页面中显示值
查看>>
nohup命令详解(转)
查看>>
别人的Linux私房菜(1)计算机概论
查看>>
系统编程之文件操作
查看>>
ModelState.IsValid
查看>>
React-Native 环境部署
查看>>