python下保持mysql连接,避免“MySQL server has gone away“方法
因需要对saltstack的所有动作进行入库采集,网上采集脚本mysql连接会因超时而断开,导致守护进程在下一次采集数据时提示:
Traceback (most recent call last): File "./salt_event_to_mysql.py", line 39, in <module> 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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。