コード例 #1
0
ファイル: flushtables.py プロジェクト: qbaoma/web
 def FlushofGamelist(self):
     
     ''' No.1 clear table of gamelist '''
     localgamelist = DBSession.query(GameList).all()
     
     if len(localgamelist) != 0:
         for eachlist in range(len(localgamelist)):
             DBSession.delete(localgamelist[eachlist])
             
     DBSession.commit()
     
     ''' No.2 analyst Config and create conn '''
     self.getConfig = readFromConfigFile().get_config_zonelist('/WebserviceInterface/ServiceConfig/setting.ini')
     
     for eachTuple in range(len(self.getConfig['Zonelist'])):
         if self.getConfig['Zonelist'][eachTuple][0] == 'username':
             self.change['username'] = self.getConfig['Zonelist'][eachTuple][1]
         elif self.getConfig['Zonelist'][eachTuple][0] == 'password':
             self.change['password'] = self.getConfig['Zonelist'][eachTuple][1]
         elif self.getConfig['Zonelist'][eachTuple][0] == 'ipaddress':
             self.change['ipaddress'] = self.getConfig['Zonelist'][eachTuple][1]
         elif self.getConfig['Zonelist'][eachTuple][0] == 'port':
             self.change['port'] = int(self.getConfig['Zonelist'][eachTuple][1])
         elif self.getConfig['Zonelist'][eachTuple][0] == 'dbname':
             self.change['dbname'] = self.getConfig['Zonelist'][eachTuple][1]
         elif self.getConfig['Zonelist'][eachTuple][0] == 'tablename':
             self.change['tablename'] = self.getConfig['Zonelist'][eachTuple][1]
     
     (conn, cursor) = Connect().create(self.change)
     
     sql = 'select * from %s' % self.change['tablename']
     cursor.execute(sql)
     result=cursor.fetchall()
     for i in result:
         print i
コード例 #2
0
ファイル: user.py プロジェクト: fy0/fpage
 def get_by_key(cls, key):
     session = DBSession()
     if py_ver == 2:
         the_key = (key or b'').encode('utf-8')
     else:
         the_key = str(key or b'', 'utf-8')
     return session.query(cls).filter(cls.key==the_key).first()
コード例 #3
0
ファイル: localAsset.py プロジェクト: qbaoma/web
    def searchObject(self, machineroom, requestobject):
        
        try:
            allsearch = DBSession.query(ASSET).filter(and_(ASSET.partNum.like("%"+requestobject+"%"), ASSET.machineRoom.like("%"+machineroom+"%"), ASSET.useNow == 'Y')).all()

            for eachAsset in range(len(allsearch)):
                self.assetBack[allsearch[eachAsset].id] = dict(confNum=allsearch[eachAsset].confNum, serialNum=allsearch[eachAsset].serialNum, hostname=allsearch[eachAsset].hostname, companyIp=allsearch[eachAsset].companyIp, outIp=allsearch[eachAsset].outIp, storeIp=allsearch[eachAsset].storeIp, zcbm=allsearch[eachAsset].zcbm)
             
        except Exception, e:
            return dict(Status='false', Return=e)
コード例 #4
0
ファイル: user.py プロジェクト: wuchangqi/fpage
    def auth(cls, username, password):
        session = DBSession()
        u = session.query(cls).filter(cls.username==username).first()
        if not u:
            return False
        password_md5 = md5(password.encode('utf-8')).hexdigest()
        password_final = md5((password_md5 + u.salt).encode('utf-8')).hexdigest()

        if u.password == password_final:
            return u
コード例 #5
0
ファイル: orcl.py プロジェクト: qbaoma/web
 def getDatabase(self):
 
     searchLocal = DBSession.query(ASSET).all()
     if len(searchLocal) > 100:
         print "local table.asset has data. needn't."
     else:
         self.flush(self.cursor)
         
     self.cursor.close()
     self.OracleConn.close()
コード例 #6
0
ファイル: getNode.py プロジェクト: qbaoma/web
    def analyNode(self, AgentZone):

        try:
            getNodeInform = DBSession.query(NodeList).filter_by(NodeZone = AgentZone).all()
            if getNodeInform:
                for eachNodeInform in range(len(getNodeInform)):
                    self.Nodeinform[getNodeInform[eachNodeInform].NodeID]=dict(NodeType=getNodeInform[eachNodeInform].NodeType, NodeZone=getNodeInform[eachNodeInform].NodeZone, NodeName=getNodeInform[eachNodeInform].NodeName, IP=getNodeInform[eachNodeInform].IP, Port=getNodeInform[eachNodeInform].Port)
            else:
                msg = 'MySQLdb : select from table.nodelist error.'
                return msg
      
        except Exception, e:
            return e
コード例 #7
0
ファイル: orcl.py プロジェクト: qbaoma/web
    def Recovery(self):
        
        localAsset = DBSession.query(ASSET).all()

        if len(localAsset) > 100:
            for eachAsset in range(len(localAsset)):
                DBSession.delete(localAsset[eachAsset])
            DBSession.commit()
            
            self.flush(self.cursor)
        else:
            self.flush(self.cursor)
            
        self.cursor.close() 
        self.OracleConn.close()
コード例 #8
0
ファイル: allist.py プロジェクト: qbaoma/web
    def flushAgent(self,  machineroomSimple, Agent='Agent'):
        
        try:
            getSearchAgent = DBSession.query(Translate).filter_by(simple = Agent).first()
            AgentSimple = getSearchAgent.detail
            
            getSearchMachineroom = DBSession.query(Translate).filter_by(simple = machineroomSimple).first()
            MrDetail = getSearchMachineroom.detail
            
            getAgentList = AssetInformation().searchObject(MrDetail, AgentSimple)

            print "######## LEN ", len(getAgentList['Return'])

            for key,value in getAgentList['Return'].items():
                AgentID = key
                AgentZone = machineroomSimple
                AgentName = value['hostname']
                IP = self.iprule(key, machineroomSimple, value['companyIp'], value['outIp'], value['storeIp'])
                Port = 'NULL'
                IsUse = 1
            
            
        except Exception, e:
            return e
コード例 #9
0
ファイル: views.py プロジェクト: bosim/pyramid-talk
def show_article(context, request):
    article = {}
    db_result = DBSession.query(Article).filter(
        Article.id == context.article
    ).first()

    if not db_result:
        raise HTTPNotFound(
            "Article could not be found"
        )

    article['id'] = db_result.id
    article['title'] = db_result.title
    article['body'] = db_result.body

    return {
        'article': article,
        'back_url': route_url('article_list', request)
    }
コード例 #10
0
ファイル: views.py プロジェクト: bosim/pyramid-talk
def article_list(request):
    results = []
    db_results = DBSession.query(Article).all()

    for db_result in db_results:
        results.append({
            'id': db_result.id,
            'url': route_url(
                'show_article',
                request,
                article=str(db_result.id)
            ),
            'title': db_result.title
        })

    return {
        'articles': results,
        'add_article': route_url('add_article', request)
    }
コード例 #11
0
ファイル: localAsset.py プロジェクト: qbaoma/web
 def FromConfNum(self, confNum):
     
     Attitude = ""
     ServerInform = {}
     Internet = {}
     Device = {}
     
     try:
         self.allLineofConfnum = DBSession.query(ASSET).filter_by(confNum = confNum).first()
         print self.allLineofConfnum
         
         if self.allLineofConfnum:
             
             # All information collect
             Attitude = self.allLineofConfnum.useNow
                   
             Device['confNum'] = self.allLineofConfnum.confNum
             Device['partNum'] = self.allLineofConfnum.partNum
             Device['serialNum'] = self.allLineofConfnum.serialNum
             Device['zcbm'] = self.allLineofConfnum.zcbm
             Device['machineRoom'] = self.allLineofConfnum.machineRoom
             
             ServerInform['useProperty'] = self.allLineofConfnum.useProperty
             ServerInform['conProject'] = self.allLineofConfnum.conProject
             ServerInform['username'] = self.allLineofConfnum.username
             ServerInform['userId'] = self.allLineofConfnum.userId
             ServerInform['usage'] = self.allLineofConfnum.usage
             
             Internet['hostname'] = self.allLineofConfnum.hostname
             Internet['companyIp'] = self.allLineofConfnum.companyIp
             Internet['outIp'] = self.allLineofConfnum.outIp
             Internet['storeIp'] = self.allLineofConfnum.storeIp
             
             return dict(State=Attitude, Device=Device, ServerInform=ServerInform, Internet=Internet)
             
         else:
             msg = 'MySQLdb : could not found any confNum.'
             return msg
     
     except Exception, e:
         msg = e
         return msg
コード例 #12
0
ファイル: flushtables.py プロジェクト: qbaoma/web
    def getFlushoftable(self, signal='ALL'):
        
        # No.1 clear table of gamename
        localGameName = DBSession.query(Gameinform).all()
        
        if len(localGameName) != 0:
            for eachGamename in range(len(localGameName)):
                DBSession.delete(localGameName[eachGamename])
        
        DBSession.commit()
       
        # No.2 get each Game information & fill in table
       
        self.flush = Urlex().getInformationMultiple(signal)
    
        for key,value in self.flush.items():
            if key != 'NULL':
                DBSession.add(Gameinform(self.count, key, value['ipaddress'], value['port'], value['dbname']))
                self.count += 1

        DBSession.commit()
コード例 #13
0
    def _save_payments_info(self, tx_receipt, miners, amounts):
        db_session = DBSession()
        try:
            # update transaction status
            pt = db_session.query(PaymentTransaction)\
                .filter_by(transaction_hash=self._web3.toHex(tx_receipt["transactionHash"])).first()
            pt.transaction_status(tx_receipt["status"])
            db_session.add(pt)

            # save payments
            if pt.status == PaymentTransaction.SUCCESS:
                miner_payments = db_session.query(PaymentSummary).all()
                miner_round_payments = db_session.query(RoundPaymentSummary).all()

                payments_map = {}
                for payment in miner_payments:
                    payments_map[payment.holder] = payment
                round_payments_map = {}
                for round_payment in miner_round_payments:
                    round_payments_map[round_payment.holder] = round_payment
                for i in range(len(miners)):
                    # save payments
                    p = Payment()
                    p.holder = miners[i].lower()
                    p.amount = amounts[i]
                    p.pay_time = datetime.datetime.utcnow()
                    p.transaction_id = pt.id
                    db_session.add(p)

                    # save round payments
                    rp = RoundPayment()
                    rp.mining_round = config.MINING_ROUND
                    rp.holder = miners[i].lower()
                    rp.amount = amounts[i]
                    rp.transaction_id = pt.id
                    db_session.add(rp)

                    # update payment summaries
                    payment_summary = payments_map.get(p.holder)
                    if payment_summary is not None:
                        payment_summary.paid_amount += p.amount
                    else:
                        payment_summary = PaymentSummary()
                        payment_summary.holder = p.holder
                        payment_summary.paid_amount = p.amount
                    db_session.add(payment_summary)
                    # update round payment summaries
                    round_payment_summary = round_payments_map.get(p.holder)
                    if round_payment_summary is not None:
                        round_payment_summary.paid_amount += p.amount
                    else:
                        round_payment_summary = RoundPaymentSummary()
                        round_payment_summary.mining_round = rp.mining_round
                        round_payment_summary.holder = rp.holder
                        round_payment_summary.paid_amount = rp.amount
                    db_session.add(round_payment_summary)
            else:
                self._logger.warning(
                    f"transaction not success! tx_receipt:{tx_receipt}")

            db_session.commit()
        except Exception as e:
            self._logger.warning(f'save payment info fail! err:{e}')
            # raise exception for _check_pending_transactions
            raise
        finally:
            db_session.rollback()
コード例 #14
0
ファイル: user.py プロジェクト: fy0/fpage
 def count(cls):
     session = DBSession()
     return session.query(cls).filter(cls.state>0).count()
コード例 #15
0
ファイル: user.py プロジェクト: fy0/fpage
 def get_by_username(cls, username):
     username = username.lower()
     session = DBSession()
     return session.query(cls).filter(cls.username==username).first()
コード例 #16
0
ファイル: initData.py プロジェクト: qbaoma/web
def initcheck(Tableinstance):
    
    getfromSearch = DBSession.query(Tableinstance).all()
    
    return len(getfromSearch)
コード例 #17
0
ファイル: user.py プロジェクト: fy0/fpage
 def exist(cls, username):
     username = username.lower()
     session = DBSession()
     return session.query(cls).filter(cls.username==username).count() > 0
コード例 #18
0
ファイル: dbsearchExpand.py プロジェクト: qbaoma/web
 def searchdoingeventofall(self):
     
     tmpArray = []
     
     try:
         getsearchofdoingeventall = DBSession.query(EventAlarmDoing).order_by(desc(EventAlarmDoing.Eid)).all()
         
         if getsearchofdoingeventall:
             if len(getsearchofdoingeventall) > 10:
                 for eachline in range(10):
                     
                     # GamePYname
                     tmpGamePYname = EventSearch().searchGamelistAboutPYname(getsearchofdoingeventall[eachline].GameID)
                     if tmpGamePYname['Status'] != 'Success':
                         GamePYname = 'None'
                     else:
                         GamePYname = tmpGamePYname['FullName']
                     
                     # OidPYname
                     tmpOidPYname = EventSearch().searchOIDdetailinTemplate(getsearchofdoingeventall[eachline].Oid)
                     if tmpOidPYname['Status'] != 'Success':
                         OidPYname = 'None'
                     else:
                         OidPYname = tmpOidPYname['TemplateName']
                     
                     # Data
                     newData = base64Data().decode64(getsearchofdoingeventall[eachline].Data)
                     newData = eval(newData)
                     newData = json.dumps(newData)    
                     
                     # EventName
                     newEventName = base64Data().decode64(getsearchofdoingeventall[eachline].EventName)
                     
                     # opTime
                     tmpOpTime = getsearchofdoingeventall[eachline].Timestamp
                     tmpOpPYTime = TimeBasic().timeControl(tmpOpTime, 5)
                     
                     # OccurTime
                     tmpOccurTime = getsearchofdoingeventall[eachline].OccurTime
                     tmpOccurPYTime = TimeBasic().timeControl(tmpOccurTime, 5)
                     
                     # ToUser
                     tmpUser = EventTransportExpand().searcheventindesigntoother(getsearchofdoingeventall[eachline].Eid)
                     if tmpUser['Status'] == 'Success':
                         tmpOpuser = tmpUser['ToUser']
                     else:
                         tmpOpuser = '******'
                     
                     tmpArray.append(dict(OperationTime = tmpOpTime, OperationPYTime = tmpOpPYTime, OccurTime = tmpOccurTime, OccurPYTime = tmpOccurPYTime, opUser = tmpOpuser, Eid = getsearchofdoingeventall[eachline].Eid, GameID = getsearchofdoingeventall[eachline].GameID, GamePYname = GamePYname, Oid = getsearchofdoingeventall[eachline].Oid, OidPYname = OidPYname, eventGrade = getsearchofdoingeventall[eachline].eventGrade, Data = newData, EventName = newEventName))
             else:
                 for eachline in getsearchofdoingeventall:
                     
                     # GamePYname
                     tmpGamePYname = EventSearch().searchGamelistAboutPYname(eachline.GameID)
                     if tmpGamePYname['Status'] != 'Success':
                         GamePYname = 'None'
                     else:
                         GamePYname = tmpGamePYname['FullName']
                     
                     # OidPYname
                     tmpOidPYname = EventSearch().searchOIDdetailinTemplate(eachline.Oid)
                     if tmpOidPYname['Status'] != 'Success':
                         OidPYname = 'None'
                     else:
                         OidPYname = tmpOidPYname['TemplateName']
                     
                     # Data
                     newData = base64Data().decode64(eachline.Data)
                     newData = eval(newData)
                     newData = json.dumps(newData) 
                     
                     # EventName
                     newEventName = base64Data().decode64(eachline.EventName)
                     
                     # opTime
                     tmpOpTime = eachline.Timestamp
                     tmpOpPYTime = TimeBasic().timeControl(tmpOpTime, 5)
                     
                     # OccurTime
                     tmpOccurTime = eachline.OccurTime
                     tmpOccurPYTime = TimeBasic().timeControl(tmpOccurTime, 5)
                     
                     # ToUser
                     tmpUser = EventTransportExpand().searcheventindesigntoother(eachline.Eid)
                     if tmpUser['Status'] == 'Success':
                         tmpOpuser = tmpUser['ToUser']
                     else:
                         tmpOpuser = '******'
                     
                     tmpArray.append(dict(OperationTime = tmpOpTime, OperationPYTime = tmpOpPYTime, OccurTime = tmpOccurTime, OccurPYTime = tmpOccurPYTime, opUser = tmpOpuser, Eid = eachline.Eid, GameID = eachline.GameID, GamePYname = GamePYname, Oid = eachline.Oid, OidPYname = OidPYname, eventGrade = eachline.eventGrade, Data = newData, EventName = newEventName))
         else:
             return dict(Status='False', msg='MySQL could not found any thing in Eventalarmdoing.')
         
     except Exception, e:
         DBSession.rollback()
         return dict(Status='False', msg=str(e))
コード例 #19
0
ファイル: dbsearchExpand.py プロジェクト: qbaoma/web
 def searchfinisheddoingeventofbefore(self, startpoint):
     
     tmpArray = []
     
     if type(startpoint).__name__ != 'int':
         startpoint = int(startpoint)
         
     try:
         getsearchfinisheddoingeventofall = DBSession.query(EventFinished).filter((EventFinished.Eid < startpoint)).order_by(desc(EventFinished.Eid)).all()
         
         if getsearchfinisheddoingeventofall:
             if len(getsearchfinisheddoingeventofall) > 10:
                 for eachline in range(10):
                     
                     # GamePYname
                     tmpGamePYname = EventSearch().searchGamelistAboutPYname(getsearchfinisheddoingeventofall[eachline].GameID)
                     if tmpGamePYname['Status'] != 'Success':
                         GamePYname = 'None'
                     else:
                         GamePYname = tmpGamePYname['FullName']
                     
                     # OidPYname
                     tmpOidPYname = EventSearch().searchOIDdetailinTemplate(getsearchfinisheddoingeventofall[eachline].Oid)
                     if tmpOidPYname['Status'] != 'Success':
                         OidPYname = 'None'
                     else:
                         OidPYname = tmpOidPYname['TemplateName']
                     
                     # Data
                     newData = base64Data().decode64(getsearchfinisheddoingeventofall[eachline].Data)
                     newData = eval(newData)
                     newData = json.dumps(newData)    
                     
                     # Timestamp
                     closeTime = getsearchfinisheddoingeventofall[eachline].CloseTime
                     newclosetime = TimeBasic().timeControl(getsearchfinisheddoingeventofall[eachline].CloseTime, 5)
                     
                     # OccurTime
                     occurTime = getsearchfinisheddoingeventofall[eachline].OccurTime
                     newoccurTime = TimeBasic().timeControl(getsearchfinisheddoingeventofall[eachline].OccurTime, 5)
                     
                     # DealTime
                     tmpDealTime = TimeBasic().TimeMinus(getsearchfinisheddoingeventofall[eachline].OccurTime, getsearchfinisheddoingeventofall[eachline].CloseTime)
                     
                     # username
                     username = getsearchfinisheddoingeventofall[eachline].Username
                     
                     # close information
                     Detail = getsearchfinisheddoingeventofall[eachline].Detail
                     
                     tmpArray.append(dict(occurTime = occurTime, occurPYtime = newoccurTime, DealTime = tmpDealTime, closeTime = closeTime, closePYtime = newclosetime, Username = username, CloseDetail=Detail, Eid = getsearchfinisheddoingeventofall[eachline].Eid, GameID = getsearchfinisheddoingeventofall[eachline].GameID, GamePYname = GamePYname, Oid = getsearchfinisheddoingeventofall[eachline].Oid, OidPYname = OidPYname, Data = newData))
             else:
                 for eachline in getsearchfinisheddoingeventofall:
                     
                     # GamePYname
                     tmpGamePYname = EventSearch().searchGamelistAboutPYname(eachline.GameID)
                     if tmpGamePYname['Status'] != 'Success':
                         GamePYname = 'None'
                     else:
                         GamePYname = tmpGamePYname['FullName']
                     
                     # OidPYname
                     tmpOidPYname = EventSearch().searchOIDdetailinTemplate(eachline.Oid)
                     if tmpOidPYname['Status'] != 'Success':
                         OidPYname = 'None'
                     else:
                         OidPYname = tmpOidPYname['TemplateName']
                     
                     # Data
                     newData = base64Data().decode64(eachline.Data) 
                     newData = eval(newData)
                     newData = json.dumps(newData)   
                     
                     # Timestamp
                     closeTime = eachline.CloseTime
                     newclosetime = TimeBasic().timeControl(eachline.CloseTime, 5)
                     
                     # OccurTime
                     occurTime = eachline.OccurTime
                     newoccurTime = TimeBasic().timeControl(eachline.OccurTime, 5)
                     
                     # DealTime
                     tmpDealTime = TimeBasic().TimeMinus(eachline.OccurTime, eachline.CloseTime)
                     
                     # username
                     username = eachline.Username
                     
                     # close information
                     Detail = eachline.Detail
                     
                     tmpArray.append(dict(occurTime = occurTime, occurPYtime = newoccurTime, DealTime = tmpDealTime, closeTime = closeTime, closePYtime = newclosetime, Username = username, CloseDetail=Detail, Eid = eachline.Eid, GameID = eachline.GameID, GamePYname = GamePYname, Oid = eachline.Oid, OidPYname = OidPYname, Data = newData))
         else:
             return dict(Status='False', msg='MySQL could not found any thing in Eventfinshed.')
         
     except Exception, e:
         DBSession.rollback()
         return dict(Status='False', msg=str(e))
コード例 #20
0
ファイル: allist.py プロジェクト: qbaoma/web
 def transportData(self, machineroomSimple, data):
     
     allAgent = DBSession.query(AgentList).all()
     allSwitch = DBSession.query(SwitchList).all()
     
     self.flushAgent(machineroomSimple)
コード例 #21
0
ファイル: oidDetail.py プロジェクト: qbaoma/web
    def DetailforEachOid(self, name, message):
        
        # Oid = 1.1
        if name == 'insert':
            
            ''' Step 1. All information about input detail '''
            tmpProjectName = ""
            tmpProjectFunc = ""
            tmpKernel = ""
            tmpCpuCoreNum = ""
            tmpSerialNum = ""
            tmpZCBM = ""
            tmpMemory = ""
            tmpCpuType = ""
            tmpModel = ""
            tmpHostName = ""
            tmpOS = ""
            tmpManufacturer = ""
            tmpEthInfo = {}
            tmpTimestamp = int(round(time.time()))
            Resultofbody = {}
            
            for key,value in message.items():
                if key == 'Status':
                    if value != 'Success':
                        return dict(Status='False', msg='Message check Failed.')
            
            if type(message['Result']).__name__ == 'str':
                Resultofbody = changeDict().strtodict(message['Result'])
            else:
                Resultofbody = message['Result']
 
            for keys,values in Resultofbody.items():
                if keys == 'Project':
                    for K,V in Resultofbody[keys].items():
                        if K == 'Name':
                            tmpProjectName = self.changestr(V)
                        elif K == 'Func':
                            tmpProjectFunc = self.changestr(V)
                    
                elif keys == 'HwInfo':
                    for KK,VV in Resultofbody[keys].items():
                        if KK == 'Kernel':
                            tmpKernel = self.changestr(VV)
                        elif KK == 'CpuCoreNum':
                            tmpCpuCoreNum = self.changestr(VV)
                        elif KK == 'SN':
                            tmpSerialNum = self.changestr(VV)
                        elif KK == 'ZCBM':
                            tmpZCBM = self.changestr(VV)
                        elif KK == 'Memory':
                            tmpMemory = self.changestr(VV)
                        elif KK == 'CpuType':
                            tmpCpuType = self.changestr(VV)
                        elif KK == 'Model':
                            tmpModel = self.changestr(VV)
                        elif KK == 'HostName':
                            tmpHostName = self.changestr(VV)
                        elif KK == 'OS':
                            tmpOS = self.changestr(VV)
                        elif KK == 'Manufacturer':
                            tmpManufacturer = self.changestr(VV)
                            
                    
                elif keys == 'EthInfo':
                    
                    for eachline in Resultofbody[keys]:
                        tmpStatus = ''
                        tmpip = ''
                        tmpmask = ''
                        tmpethname = ''
                        for KKK, VVV in eachline.items():
                            if KKK == 'status':
                                tmpStatus = self.changestr(VVV)
                            elif KKK == 'ip':
                                tmpip = self.changestr(VVV)
                            elif KKK == 'mask':
                                tmpmask = self.changestr(VVV)
                            elif KKK == 'ethname':
                                tmpethname = self.changestr(VVV)
                                
                        tmpEthInfo[tmpethname] = dict(status=tmpStatus, ip=tmpip, mask=tmpmask)

            if tmpZCBM == '':
                return dict(Status='False', msg='Input Server has not ZCBM.')

            ''' get eth detail '''
            tmpEthDict = {}
            for key,value in tmpEthInfo.items():
                if key == 'eth0':
                    getSearchofeth = DBSession.query(Ethdetail).filter(Ethdetail.ip == value['ip'], Ethdetail.mask == value['mask']).first()
                    if getSearchofeth:
                        tmpEthDict['eth0'] = getSearchofeth.eid
                    else:
                        getethcount = DBSession.query(Ethdetail).count()
                        getethcount = (getethcount + 1)
                        DBSession.add(Ethdetail(getethcount,value['status'],value['ip'],value['mask'],'eth0'))
                        tmpEthDict['eth0'] = getethcount
                elif key == 'eth1':
                    getSearchofethone = DBSession.query(Ethdetail).filter(Ethdetail.ip == value['ip'], Ethdetail.mask == value['mask']).first()
                    if getSearchofethone:
                        tmpEthDict['eth1'] = getSearchofethone.eid
                    else:
                        getethcountone = DBSession.query(Ethdetail).count()
                        getethcountone = (getethcountone + 1)
                        DBSession.add(Ethdetail(getethcountone,value['status'],value['ip'],value['mask'],'eth1'))
                        tmpEthDict['eth1'] = getethcountone

            ''' Step 2. check server information exist. '''
            getSearchofHardware = DBSession.query(AssetForAgent).filter(AssetForAgent.ZCBM == tmpZCBM).first()
            if getSearchofHardware:
                try:
                    if int(getSearchofHardware.Timestamp) < message['SendTime']:

                        DBSession.delete(getSearchofHardware)
                        DBSession.commit()
                        
                        tmpeth0 = ""
                        tmpeth1 = ""
                        
                        for key,value in tmpEthDict.items():
                            if key == 'eth0':
                                tmpeth0 = value
                            elif key == 'eth1':
                                tmpeth1 = value
                        getCountofeth = DBSession.query(EthInfo).count()
                        getCountofeth = (getCountofeth + 1)
                        DBSession.add(EthInfo(getCountofeth,tmpeth0,tmpeth1,'None','None'))
                        
                        DBSession.add(AssetForAgent(tmpProjectName, tmpProjectFunc, tmpKernel, tmpCpuCoreNum, tmpSerialNum, tmpZCBM, tmpMemory, tmpCpuType, tmpModel, tmpHostName, tmpOS, tmpManufacturer, message['SendTime']))
                        DBSession.commit()
                        
                        getTmpid = DBSession.query(AssetForAgent).filter_by(ZCBM = tmpZCBM).first()
                        if getTmpid:
                            Tmpid = getTmpid.Hid
                        else:
                            DBSession.rollback()
                            return dict(Status='False', msg='flush assetforagent Error.')
                        
                        getCountofrelation = DBSession.query(AssetidtoEid).count()
                        getCountofrelation = int(getCountofrelation + 1)
                        DBSession.add(AssetidtoEid(getCountofrelation, Tmpid, getCountofeth))
                        
                        DBSession.commit()
                        return dict(Status='Success')
                        
                    else:
                        return dict(Status='Success', msg='Input Hostname Need not fresh.')
                    
                except Exception, e:
                    DBSession.commit()
                    return dict(Status='False', msg=str(e))
            else:
                try:
                    tmpHidforinsert = ""
                    
                    ''' insert into table'''
                    DBSession.add(AssetForAgent(tmpProjectName, tmpProjectFunc, tmpKernel, tmpCpuCoreNum, tmpSerialNum, tmpZCBM, tmpMemory, tmpCpuType, tmpModel, tmpHostName, tmpOS, tmpManufacturer, message['SendTime']))
                    DBSession.commit()
                    
                    getHid = DBSession.query(AssetForAgent).filter_by(ZCBM = tmpZCBM).first()
                    if getHid:
                        tmpHidforinsert = getHid.Hid
                    else:
                        DBSession.rollback()
                        return dict(Status='False', msg='insert into assetforagent error.')
                    
                    for key,value in tmpEthDict.items():
                        if key == 'eth0':
                            tmpeth0 = value
                        elif key == 'eth1':
                            tmpeth1 = value
                    getCountofeth = DBSession.query(EthInfo).count()
                    getCountofeth = (getCountofeth + 1)
                    DBSession.add(EthInfo(getCountofeth,tmpeth0,tmpeth1,'None','None'))
                    
                    getCountofrelation = DBSession.query(AssetidtoEid).count()
                    getCountofrelation = int(getCountofrelation + 1)
                    DBSession.add(AssetidtoEid(getCountofrelation, tmpHidforinsert, getCountofeth))
                
                except Exception, e:
                    DBSession.rollback()
                    return dict(Status='False', msg=str(e))
                
                DBSession.commit()
                return dict(Status='Success')
コード例 #22
0
ファイル: user.py プロジェクト: wuchangqi/fpage
 def get_by_key(cls, key):
     session = DBSession()
     return session.query(cls).filter(cls.key==str(key or b'', 'utf-8')).first()