def __init__(self, conf_args, conn_args): DbManager._lock.acquire() try: self._pool = PooledDB(MySQLdb, *conf_args, **conn_args) # self._pool = PooledDB(creator=MySQLdb, mincached=1, maxcached=20, maxconnections=30, **conn_args) except Exception, e: log.error('初始化数据库失败,请检查,并重试' + str(e))
def reconnectDB(self): if self.conn: try: self._cursor.close() self._conn.close() except Exception, e: log.error('关闭数据库连接失败' + str(e))
def _getConn(self): conn = None DbManager._lock.acquire() try: conn = self._pool.connection() except Exception, e: conn = None log.error('连接mysql数据库失败,请检查,并重试' + str(e))
def deleteFromOldCollectPool(self, uuid): self.lock.acquire() try: if uuid in self.oldCollectPool: self.oldCollectPool.remove(uuid) except Exception, e: log.error('从旧连接池中删除数据' + uuid + ' error:' + str(e)) pass
def deleteData(self, sql): result = True self.lock.acquire() try: cur = self.conn.cursor() cur.execute(sql) except MySQLdb.MySQLError, e: log.error('向数据库删除数据失败:' + sql + ".error:" + str(e)) result = False
def selectData(self, sql): self.lock.acquire() try: cur = self.conn.cursor() num = cur.execute(sql) data = cur.fetchmany(num) except MySQLdb.MySQLError, e: log.error('查询数据失败:' + sql + ".error:" + str(e)) data = []
def selectData(self, sql): # self._lock.acquire() # print 'self._lock.acquire()', multiprocessing.current_process().name, self try: num = self._cursor.execute(sql) data = self._cursor.fetchmany(num) except MySQLdb.OperationalError, e: log.error('查询数据失败:' + sql + ".error:" + str(e)) self.reconnectDB() pass
def connectDb(self): result = False # self._lock.acquire() try: self._conn = MysqlConn._pool.connection(False) self._cursor = self._conn.cursor() result = True except MySQLdb.MySQLError, e: log.error('连接mysql数据库失败,请检查,并重试') result = False
def initDb(self): try: self.conn = MySQLdb.connect(host=self.serverAddr, port=self.serverPort, user=self.serverUser, passwd=self.serverPwd, db=self.database) except MySQLdb.MySQLError, e: log.error('连接mysql数据库失败,请检查,并重试') sys.exit(0)
def deleteTerminal(self, terminalNo): self.lock.acquire() try: if terminalNo in self.collectPool: UUID = self.collectPool[terminalNo] if UUID in self.oldCollectPool: self.oldCollectPool.remove(UUID) del self.collectPool[terminalNo] except Exception, e: log.error('从连接池中删除数据' + terminalNo + ' error:' + str(e))
def insertData(self, sql): result = True # self._lock.acquire() try: self._cursor.execute(sql) self._conn.commit() except MySQLdb.OperationalError, e: log.error('向数据库写数据失败:' + sql + ".error:" + str(e)) self.reconnectDB() pass
def selectData(self, sql): data = [] try: conn = self.getConn() cur = conn.cursor() num = cur.execute(sql) data = cur.fetchmany(num) except MySQLdb.OperationalError, e: log.error('查询数据失败:' + sql + ".error:" + str(e)) self.reconnectDB() pass
def updateData(self, sql): result = True try: conn = self.getConn() cur = conn.cursor() cur.execute(sql) conn.commit() except MySQLdb.OperationalError, e: log.error('向数据库更新数据失败:' + sql + ".error:" + str(e)) self.reconnectDB() pass
def reconnectDB(self): re = False try: self.initDb() log.info('重连mysql数据库成功') re = True except: import traceback traceback.print_exc() log.error('重连mysql数据库失败') finally: return re
def notifyExcepMessage(self, dataType, uploadRecordId, exceptRecordId=''): print '异常推送', dataType, uploadRecordId if not dataType or not uploadRecordId: return dataMsg = { 0x0002: u'震动报警', 0x000a: u'锁没有关好', 0x0010: u'锁内积水', 0x0013: u'锁故障报警', 0x0014: u'锁失联', 0x0015: u'断电', 0x0005: u'开锁', 0x0006: u'关锁' } tags = [] if dataType == 0x0005 or dataType == 0x0006: users = Device.getCorrelationUsers(uploadRecordId) alert = dataMsg.get( dataType, '') + u' %s [%s]' % (Device.getUploadDatetime(uploadRecordId), Device.getFacilityInfo(self.deviceId)) elif dataType != 0x0015: users = Device.getCorrelationUsers(uploadRecordId) alert = dataMsg.get( dataType, '') + u', 请立即前往处理 [%s]' % Device.getFacilityInfo(self.deviceId) else: users = Device.getCorrelationUsersOfTerminal(uploadRecordId) alert = dataMsg.get(dataType, '') + u' 主机编号:' + ( '%010x' % int(self.terminal.terminalId)) for user in users: tags.append(user['userId']) exceptRecordId = '%s' % exceptRecordId try: if dataType == 0x0005 or dataType == 0x0006: jPush.tags(tags, alert, {'mtype': '3'}) elif dataType != 0x0015: jPush.tags( tags, alert, { 'mtype': '3', 'lockNO': self.deviceId, 'exceptRecordId': exceptRecordId }) else: jPush.tags(tags, alert, { 'mtype': '3', 'terminalNo': self.terminal.terminalId }) except Exception, e: log.error('极光推送失败:' + str(e)) pass
def initDb(self): # self._lock.acquire() try: if MysqlConn._pool is None: MysqlConn._pool = PooledDB(creator=MySQLdb, mincached=1, maxcached=20, host=self._serverAddr, port=self._serverPort, user=self._serverUser, passwd=self._serverPwd, db=self._database, use_unicode=False, charset='utf8') except Exception, e: log.error('初始化数据库失败,请检查,并重试')
def notifyExcepMessage(self, dataType, uploadRecordId): print '异常推送', dataType, uploadRecordId if not dataType or not uploadRecordId: return dataMsg = {0x0015: u'断电'} tags = [] if dataType != 0x0015: return users = Device.getCorrelationUsersOfTerminal(uploadRecordId) alert = dataMsg.get(dataType, '') + u' 主机编号:' + ('%010x' % int(self.terminalId)) for user in users: tags.append(user['userId']) try: jPush.tags(tags, alert, { 'mtype': '3', 'terminalNo': self.terminalId }) except Exception, e: log.error('极光推送失败:' + str(e)) pass
class MysqlConn(object): """ """ collectionDict = {} def __init__(self, conf): self._serverAddr = conf.get('mysqlServerAddr'.lower(), '127.0.0.1') self._serverPort = int(conf.get('mysqlServerPort'.lower(), '3306')) self._serverUser = conf.get('mysqlServerUser'.lower(), 'root') self._serverPwd = conf.get('mysqlServerPassword'.lower(), 'root') self._database = conf.get('mysqlDatabaseName'.lower(), 'ecgs') self.initDb() def initDb(self): conf_args = (10, 10, 30, 100, True, 0, None) conn_args = { 'host': "%s" % self._serverAddr, 'port': self._serverPort, 'db': "%s" % self._database, 'charset': "%s" % 'utf8', 'user': "******" % self._serverUser, 'passwd': "%s" % self._serverPwd } self._dbManager = DbManager(conf_args, conn_args) def getConn(self): return self._dbManager._getConn() def testConnection(self): conn = self.getConn() return False if not conn else True def insertData(self, sql): result = True try: conn = self.getConn() cur = conn.cursor() cur.execute(sql) conn.commit() except MySQLdb.OperationalError, e: log.error('向数据库写数据失败:' + sql + ".error:" + str(e)) self.reconnectDB() pass except MySQLdb.MySQLError, e: log.error('向数据库写数据失败:' + sql + ".error:" + str(e)) result = False
log.debug('向数据库写数据成功:' + sql) return result def updateData(self, sql): result = True try: conn = self.getConn() cur = conn.cursor() cur.execute(sql) conn.commit() except MySQLdb.OperationalError, e: log.error('向数据库更新数据失败:' + sql + ".error:" + str(e)) self.reconnectDB() pass except MySQLdb.MySQLError, e: log.error('向数据库更新数据失败:' + sql + ".error:" + str(e)) result = False except Exception, e: log.error('向数据库更新数据失败:' + sql + ".error:" + str(e)) result = False finally: if cur: cur.close() if conn: conn.close() if result: log.debug('向数据库更新数据成功:' + sql) return result def deleteData(self, sql): result = True
self.lock.release() if result: log.debug('向数据库写数据成功:' + sql) return result def updateData(self, sql): result = True self.lock.acquire() try: cur = self.conn.cursor() cur.execute(sql) except MySQLdb.MySQLError, e: log.error('向数据库更新数据失败:' + sql + ".error:" + str(e)) result = False except Exception, e: log.error('向数据库更新数据失败:' + sql + ".error:" + str(e)) result = False finally: cur.close() self.conn.commit() self.lock.release() if result: log.debug('向数据库更新数据成功:' + sql) return result def deleteData(self, sql): result = True self.lock.acquire() try: cur = self.conn.cursor() cur.execute(sql)