def_ping_check(self, ping=1, reconnect=True): """Check whether the connection is still alive using ping(). If the the underlying connection is not active and the ping parameter is set accordingly, the connection will be recreated unless the connection is currently inside a transaction. """ if ping & self._ping: try: # if possible, ping the connection my_reconnect = True alive = self._con.ping(reconnect=my_reconnect) # 源码为: alive = self._con.ping() # print "try to ping by pymysql(reconnect={0})".format(my_reconnect) # my_reconnect = False # try: # print "try to ping by pymysql(reconnect={0})".format(my_reconnect) # alive = self._con.ping(False) # do not reconnect # except TypeError: # print "try to ping by pymysql(reconnect={0}) did not have ping(False)".format(my_reconnect) # alive = self._con.ping() except (AttributeError, IndexError, TypeError, ValueError): print"ping method is not available" self._ping = 0# ping() is not available alive = None reconnect = False except Exception,e : print"try to ping by pymysql(reconnect={0}) fail".format(my_reconnect) alive = False else: if alive isNone: alive = True if alive: reconnect = False print"try to ping by pymysql(reconnect={0}) success".format(my_reconnect) if reconnect andnotself._transaction: try: # try to reopen the connection print"try to reconnect by dbutils" con = self._create() except Exception: print"try to reconnect by dbutils fail" pass else: print"try to reconnect by dbutils success" self._close() self._store(con) alive = True return alive
异常开始: try to ping by pymysql(reconnect=True) try to ping by pymysql(reconnect=True) fail try to reconnect by dbutils try to reconnect by dbutils fail
异常恢复: try to ping by pymysql(reconnect=True) try to ping by pymysql(reconnect=True) success
恢复后,不能入库
测试2:my_reconnect=False,运行demo期间重启数据库。
1 2 3 4 5 6 7 8 9 10 11 12 13
异常开始: try to ping by pymysql(reconnect=False) try to ping by pymysql(reconnect=False) fail try to reconnect by dbutils try to reconnect by dbutils fail
异常恢复: try to ping by pymysql(reconnect=False) try to ping by pymysql(reconnect=False) fail try to reconnect by dbutils try to reconnect by dbutils success