python下保持mysql串連,避免“MySQL server has gone away“方法

來源:互聯網
上載者:User

標籤:mysql   server   檢測   python   recent   

因需要對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 libsimport json# Import salt modulesimport salt.configimport salt.utils.event# Import third party libsimport MySQLdb__opts__ = salt.config.client_config(‘/etc/salt/master‘)# Create MySQL connectconn = 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 Systemevent = 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



python下保持mysql串連,避免“MySQL server has gone away“方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.