Esempio n. 1
0
    def modifyAct(self, req):
        opuser = req.context['user']
        doc = req.context['doc']
        try:
            u = self.session.query(User).filter_by(userID=opuser.userID).first()
            if u is None:
                self.errorReturn(GLBConfig.API_ERROR, '用户不存在.')
            if doc['headImg']:
                if u.headImg != doc['headImg']:
                    u.headImg = SysUtil.fileMmove(doc['headImg'], 'dir', 'headimg')
            if doc['mobile']:
                u.mobile = doc['mobile']

            exInfo = None
            if u.accountType == GLBConfig.ATYPE_OPERATOR:
                exInfo = self.session.query(OperatorInfo).filter_by(userID=u.userID).first()

            if exInfo is not None:
                if doc['mobile']:
                    exInfo.mobile = doc['mobile']

                if doc['name']:
                    exInfo.name = doc['name']
            self.session.commit()
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            self.logger.error(doc)
            self.session.rollback()
            self.errorReturn(GLBConfig.SYSTEM_ERROR, '系统错误')
Esempio n. 2
0
    def getTtg(self):
        urlM = "http://i.sporttery.cn/odds_calculator/get_odds?i_format=json&i_callback=getData&poolcode[]=ttg&_=1486376411945"
        try:
            content = urllib.request.urlopen(urlM, timeout=10).read()
            message = content.decode('gbk')
            message = message.replace('getData(', '')
            message = message.replace(');', '')
            decode = json.loads(message)
            matchInfos = decode['data']
            for match in matchInfos:
                if matchInfos[match]['status'] != 'Selling':
                    continue
                matchid = matchInfos[match]['date'].replace(
                    '-', '') + matchInfos[match]['num']
                m = self.session.query(MatchInfoD).filter(
                    MatchInfoD.matchid == matchid).first()
                if m is not None:
                    m.s0 = float(matchInfos[match]['ttg']['s0'])
                    m.s1 = float(matchInfos[match]['ttg']['s1'])
                    m.s2 = float(matchInfos[match]['ttg']['s2'])
                    m.s3 = float(matchInfos[match]['ttg']['s3'])
                    m.s4 = float(matchInfos[match]['ttg']['s4'])
                    m.s5 = float(matchInfos[match]['ttg']['s5'])
                    m.s6 = float(matchInfos[match]['ttg']['s6'])
                    m.s7 = float(matchInfos[match]['ttg']['s7'])
            self.session.commit()

            return True
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            return False
Esempio n. 3
0
def token2user(req,logging):
    token_str = req.get_header('authorization')
    db = SysUtil.get_db_handle()
    session = db()
    if not token_str:
        logging.info('no token')
        return None
    try:
        L = token_str.split('-')
        if len(L) != 4:
            return None
        
        uid, magicNo, expires, sha1 = L
        if int(expires) < time.time():
            logging.info('expires')
            return None
        
        user = session.query(User).filter_by(userID=uid, dataStatus=GLBConfig.ENABLE).first()
        if user is None:
            logging.info('user do not exist')
            return None
        magicNo, idf = Cryptor.encrypt(user.userName, user.password, magicNo)
        s = '%s-%s-%s-%s' % (uid, idf, expires, settings.SECRET_KEY)
        if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest():
            logging.info('invalid sha1')
            return None
        if userAuthCheck(session, req, user, logging) == False:
            logging.info('userAuthCheck Failed')
            return None
        return user
    except Exception as e:
        SysUtil.exceptionPrint(logging, e)
        return None
    finally:
        session.close()
Esempio n. 4
0
 def addAct(self, req):
     opuser = req.context['user']
     doc = req.context['doc']
     user = self.session.query(User).filter_by(
         userName=doc['userName']).first()
     if user is not None:
         self.errorReturn(GLBConfig.API_ERROR, '用户已存在.')
     else:
         try:
             user = User(userID=SysUtil.genUserID(),
                         userName=doc['userName'],
                         password=GLBConfig.INITPASSWORD,
                         accountType=GLBConfig.ATYPE_OPERATOR,
                         mobile=doc['mobile'],
                         email=doc['email'])
             self.session.add(user)
             self.session.flush()  # flush the session
             operator = OperatorInfo(
                 userID=user.userID,
                 userGroupID=doc['userGroupID'],
                 helpMark=doc['helpMark'],
                 name=doc['name'],
                 mobile=doc['mobile'],
                 email=doc['email'],
             )
             self.session.add(operator)
             self.session.commit()
         except Exception as ex:
             SysUtil.exceptionPrint(self.logger, ex)
             self.session.rollback()
             self.errorReturn(GLBConfig.SYSTEM_ERROR, '系统错误')
     return user
 def getContent(self, url):
     try:
         content = urllib.request.urlopen(url, timeout=10).read()
         return content
     except Exception as ex:
         SysUtil.exceptionPrint(self.logger, ex)
         return None
Esempio n. 6
0
    def modifyAct(self, req):
        opuser = req.context['user']
        doc = req.context['doc']
        user = self.session.query(User).filter_by(
            userName=doc['old']['userName']).first()
        if user is None:
            self.logger.info(doc)
            self.errorReturn(GLBConfig.API_ERROR, '用户不存在')
        else:
            if user.userID != doc['old']['userID'] or doc['old'][
                    'userID'] != doc['new']['userID']:
                self.errorReturn(GLBConfig.SYSTEM_ERROR, '用户信息错误')
            try:
                user.userName = doc['new']['userName']
                user.mobile = doc['new']['mobile']
                user.email = doc['new']['email']

                operator = self.session.query(OperatorInfo).filter_by(
                    userID=user.userID).first()
                if operator is None:
                    self.errorReturn(GLBConfig.API_ERROR, '用户不存在')
                operator.userGroupID = doc['new']['userGroupID']
                operator.name = doc['new']['name']
                operator.helpMark = doc['new']['helpMark'],
                operator.mobile = doc['new']['mobile']
                operator.email = doc['new']['email']
                self.session.commit()
            except Exception as ex:
                SysUtil.exceptionPrint(self.logger, ex)
                self.session.rollback()
                self.errorReturn(GLBConfig.SYSTEM_ERROR, '系统错误')
        return user
Esempio n. 7
0
    def getHafu(self):
        urlM = "http://i.sporttery.cn/odds_calculator/get_odds?i_format=json&i_callback=getData&poolcode[]=hafu&_=1486372321610"
        try:
            content = urllib.request.urlopen(urlM, timeout=10).read()
            message = content.decode('gbk')
            message = message.replace('getData(', '')
            message = message.replace(');', '')
            decode = json.loads(message)
            matchInfos = decode['data']
            for match in matchInfos:
                if matchInfos[match]['status'] != 'Selling':
                    continue
                matchid = matchInfos[match]['date'].replace(
                    '-', '') + matchInfos[match]['num']
                m = self.session.query(MatchInfoD).filter(
                    MatchInfoD.matchid == matchid).first()
                if m is not None:
                    m.ww = float(matchInfos[match]['hafu']['hh'])
                    m.wd = float(matchInfos[match]['hafu']['ad'])
                    m.wl = float(matchInfos[match]['hafu']['ha'])
                    m.dw = float(matchInfos[match]['hafu']['dh'])
                    m.dd = float(matchInfos[match]['hafu']['dd'])
                    m.dl = float(matchInfos[match]['hafu']['da'])
                    m.lw = float(matchInfos[match]['hafu']['ah'])
                    m.ld = float(matchInfos[match]['hafu']['ad'])
                    m.ll = float(matchInfos[match]['hafu']['aa'])
            self.session.commit()

            return True
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            return False
Esempio n. 8
0
 def uploadAct(self,req):
     try:
         uploadurl = SysUtil.fileSave(req,self.logger)
         return uploadurl
     except Exception as ex:
         SysUtil.exceptionPrint(self.logger, ex)
         self.session.rollback()
         self.errorReturn(GLBConfig.SYSTEM_ERROR, '系统错误')
Esempio n. 9
0
    def run(self):
        self.initialize()
        try:
            year = str(datetime.datetime.now().year) + '-'
            the_page = glb_browser.page_source
            soup = BeautifulSoup(the_page, 'html.parser')
            table = soup.find('table', id='table_match')
            if table:
                trs = table.find('tbody').find_all('tr')
                self.session.query(MatchInfo500Time).delete()
                self.session.commit()
                for line in trs:
                    tds = line.find_all('td')
                    if len(tds) < 5:
                        continue
                    if line.has_attr('time'):
                        mtime = datetime.datetime.strptime(
                            line['time'], "%Y-%m-%d %H:%M:%S")
                    else:
                        mtime = datetime.datetime.strptime(
                            year + tds[3].text, "%Y-%m-%d %H:%M")

                    matchid = mtime.strftime('%Y%m%d') + tds[0].text
                    match = tds[0].text
                    matchtype = tds[1].text
                    matchzhu = tds[5].find('a').text
                    matchke = tds[7].find('a').text
                    scores = tds[6].find_all('a')
                    if scores[0].text == '':
                        zhuScore = None
                    else:
                        zhuScore = int(scores[0].text)

                    if scores[2].text == '':
                        keScore = None
                    else:
                        keScore = int(scores[2].text)

                    hScore = self.getScore(tds[8].text)

                    m = MatchInfo500Time(matchid=matchid,
                                         match=match,
                                         mtime=mtime,
                                         matchtype=matchtype,
                                         matchzhu=matchzhu,
                                         matchke=matchke,
                                         zhuScore=zhuScore,
                                         keScore=keScore,
                                         zhuHScore=hScore[0],
                                         keHScore=hScore[1],
                                         mststus=tds[4].text)
                    self.session.add(m)
                    self.session.flush()
                self.session.commit()
                self.logger.info('finish')
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
        self.release()
Esempio n. 10
0
    def on_get(self, req, resp):
        self.initialize()
        req_para = falcon.util.uri.parse_query_string(req.query_string)

        if 'userid' not in req_para.keys():
            self.errorReturn(GLBConfig.API_ERROR, 'userid 不存在.')

        if 'reset' not in req_para.keys():
            self.errorReturn(GLBConfig.API_ERROR, 'reset 不存在.')

        try:
            user = self.session.query(User).filter(
                User.userid == req_para['userid']).first()
            if user is None:
                self.errorReturn(GLBConfig.API_ERROR, '用户不存在.')

            self.session.query(UserData).filter(
                UserData.userid == user.userid).delete()
            self.session.query(MatchData).filter(
                MatchData.userid == user.userid).update(
                    {MatchData.status: '0'})

            if req_para['reset'] == '1':
                self.session.query(AccountRunning).filter(
                    AccountRunning.userid == user.userid).update(
                        {AccountRunning.status: '0'})
            self.session.flush()

            if 'mode' in req_para.keys():
                mode = req_para['mode']
            else:
                mode = 'A'
            udata = UserData(userid=user.userid,
                             basemoney=SysUtil.moneyNumFormat(
                                 req_para['basemoney']),
                             mode=mode)
            self.session.add(udata)
            self.session.commit()
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            self.session.rollback()
            self.errorReturn(GLBConfig.SYSTEM_ERROR, '系统错误')

        req.context['result'] = self.result
        resp.set_header('Powered-By', '*****@*****.**')
        resp.status = falcon.HTTP_200
        self.release()
Esempio n. 11
0
    def on_get(self, req, resp):
        self.initialize()
        req_para = falcon.util.uri.parse_query_string(req.query_string)

        if 'userid' not in req_para.keys():
            self.errorReturn(GLBConfig.API_ERROR, 'userid 不存在.')
        if 'username' not in req_para.keys():
            self.errorReturn(GLBConfig.API_ERROR, 'username不存在.')
        if 'phone' not in req_para.keys():
            self.errorReturn(GLBConfig.API_ERROR, 'phone不存在.')

        if 'accounttype' not in req_para.keys():
            accounttype = '0'  # 0 业主版 #1 彩民版
        else:
            accounttype = req_para['accounttype']

        user = self.session.query(User).filter(
            User.userid == req_para['userid']).first()
        if user is not None:
            self.errorReturn(GLBConfig.API_ERROR, '用户已经存.')

        try:
            d = datetime.datetime.now()
            delta = datetime.timedelta(days=30)
            expD = d + delta
            user = User(userid=req_para['userid'],
                        username=req_para['username'],
                        accounttype=accounttype,
                        phone=req_para['phone'],
                        local=req_para['local'],
                        IDNo=req_para['IDNo'],
                        expdate=expD)
            self.session.add(user)
            self.session.commit()
            self.result['data'] = 'successReg'
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            self.session.rollback()
            self.errorReturn(GLBConfig.SYSTEM_ERROR, '系统错误')

        req.context['result'] = self.result
        resp.set_header('Powered-By', '*****@*****.**')
        resp.status = falcon.HTTP_200
        self.release()
Esempio n. 12
0
    def on_post(self, req, resp):
        self.initialize()
        doc = req.context['doc']
        username = doc['username']
        try:
            user = self.session.query(User).filter_by(
                userName=username, dataStatus=GLBConfig.ENABLE).first()
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            self.errorReturn(GLBConfig.SYSTEM_ERROR, '系统错误')
        if user is None:
            self.errorReturn(GLBConfig.API_ERROR, '用户不存在或密码错误')
        else:
            if doc['username'] != user.userName:
                self.errorReturn(GLBConfig.API_ERROR, '用户不存在或密码错误')
            try:
                decrypted = Cryptor.decrypt(doc['identifyCode'], user.password,
                                            doc['magicNo'])
            except Exception as ex:
                SysUtil.exceptionPrint(self.logger, ex)
                self.errorReturn(GLBConfig.API_ERROR, '用户不存在或密码错误')

            if decrypted != username:
                self.errorReturn(GLBConfig.API_ERROR, '用户不存在或密码错误')
            else:
                session_token = Security.user2token(user, doc['identifyCode'],
                                                    doc['magicNo'],
                                                    settings.TOKEN_AGE)
                resp.append_header('authorization', session_token)
                #                resp.set_cookie(settings.COOKIE_NAME, session_token,
                #                        max_age=settings.COOKIE_AGE, domain='NULL', secure=False )
                returnd = self.loginInit(user)
                if not returnd:
                    self.errorReturn(GLBConfig.SYSTEM_ERROR, '系统错误')
                self.result['data'] = returnd

        req.context['result'] = self.result
        resp.set_header('Powered-By', 'putBox')
        resp.status = falcon.HTTP_200
        self.release()
Esempio n. 13
0
 def get500Wan(self, date):
     try:
         urlid500W = 'http://trade.500.com/jczq/?date=' + date + '&playtype=both'
         content500W = urllib.request.urlopen(urlid500W, timeout=10).read()
         message500W = content500W.decode('gbk').encode('utf8')
         #    fp = open("test.txt",'w')
         #    fp.write(message500W)
         #    fp.close()
         #    fp = open("test.txt",'r')
         #    soup500W = BeautifulSoup.BeautifulSOAP(fp.read())
         #    fp.close
         soup500W = BeautifulSoup(message500W, 'html.parser')
         tb500Wdate = soup500W.findAll('div', 'bet_date')
         for i in range(0, len(tb500Wdate)):
             dateInfo = self.getDate(tb500Wdate[i].contents[0])
             tb500Wtb = soup500W.findAll('table', 'bet_table')
             trs500W = tb500Wtb[i].findAll('tr')
             self.getMatchSync(trs500W, dateInfo, i)
         return True
     except Exception as ex:
         SysUtil.exceptionPrint(self.logger, ex)
         return False
Esempio n. 14
0
    def on_post(self, req, resp):
        self.initialize()
        doc = req.context['doc']
        try:
            domain = self.session.query(Domain).filter_by(
                domain=doc['domain']).first()

            if domain is None:
                self.errorReturn(GLBConfig.API_ERROR, 'auth_01')

            user = self.session.query(User).filter_by(
                domain_id=domain.uid, username=doc['username'], state=GLBConfig.ENABLE).first()
            if user is None:
                self.errorReturn(GLBConfig.API_ERROR, 'auth_01')
            else:
                if doc['username'] != user.username:
                    self.errorReturn(GLBConfig.API_ERROR, 'auth_01')
                try:
                    decrypted = Cryptor.decrypt(
                        doc['identifyCode'], user.password, doc['magicNo'])

            if decrypted != username:
                self.errorReturn(GLBConfig.API_ERROR, 'auth_01')
            else:
                session_token = Security.user2token(
                    user, doc['identifyCode'], doc['magicNo'], settings.TOKEN_AGE)
                resp.append_header('authorization', session_token)
                returnd = self.loginInit(user)
                if not returnd:
                    self.errorReturn(GLBConfig.SYSTEM_ERROR, 'common_02')
                self.result['info'] = returnd
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            self.errorReturn(GLBConfig.API_ERROR, 'auth_01')

        req.context['result'] = self.result
        resp.status = falcon.HTTP_200
        self.release()
Esempio n. 15
0
    def modifyAct(self, req):
        doc = req.context['doc']

        try:
            self.session.query(UserGroupMenu).filter(
                UserGroupMenu.userGroupID == doc['userGroupID']).delete()
            self.session.flush()

            for menu in doc['userGroupMenu']:
                userGroupMenu = UserGroupMenu(userGroupID=doc['userGroupID'],
                                              menuID=menu['menuID'],
                                              menuType=menu['menuType'],
                                              fMenuID=menu['fMenuID'],
                                              menuName=menu['menuName'],
                                              menuPath=menu['menuPath'],
                                              menuIcon=menu['menuIcon'],
                                              menuIdx=menu['menuIdx'])
                self.session.add(userGroupMenu)
                self.session.flush()
            self.session.commit()
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            self.session.rollback()
            self.errorReturn(GLBConfig.SYSTEM_ERROR, '系统错误')
Esempio n. 16
0
 def deleteAct(self, req):
     opuser = req.context['user']
     doc = req.context['doc']
     user = self.session.query(User).filter_by(
         userName=doc['userName']).first()
     if user is None:
         self.errorReturn(GLBConfig.API_ERROR, '用户不存在')
     else:
         if user.userID != doc['userID']:
             self.errorReturn(GLBConfig.SYSTEM_ERROR, '用户信息错误')
         operator = self.session.query(OperatorInfo).filter_by(
             userID=user.userID).first()
         if operator is None:
             self.errorReturn(GLBConfig.API_ERROR, '用户不存在')
         try:
             operator.dataStatus = GLBConfig.DISABLE
             operator.modifyTime = datetime.datetime.now()
             user.dataStatus = GLBConfig.DISABLE
             user.modifyTime = datetime.datetime.now()
             self.session.commit()
         except Exception as ex:
             SysUtil.exceptionPrint(self.logger, ex)
             self.session.rollback()
             self.errorReturn(GLBConfig.SYSTEM_ERROR, '系统错误')
Esempio n. 17
0
    def getWDLRate(self, urlWDL):
        try:
            contentWDL = urllib.request.urlopen(urlWDL, timeout=10).read()
            messageWDL = contentWDL.decode('gbk').encode('utf8')
            soupWDL = BeautifulSoup(messageWDL, 'html.parser')
            tbWDL = soupWDL.findAll('table')
            trrWDL = tbWDL[2].findAll('tr')
            tddWDL = trrWDL[-1].findAll('td')
            tmpRate = re.search("[\d]+\.[\d]+", repr(tddWDL[1]))
            rateA = (99.99, 99.99, 99.99)
            if tmpRate is not None:
                rateA = (float(
                    re.search("[\d]+\.[\d]+", repr(tddWDL[1])).group()),
                         float(
                             re.search("[\d]+\.[\d]+",
                                       repr(tddWDL[2])).group()),
                         float(
                             re.search("[\d]+\.[\d]+",
                                       repr(tddWDL[3])).group()))

            rateB = ('0', 99.99, 99.99, 99.99)
            trrWDLS = tbWDL[1].findAll('tr')
            tddWDLS = trrWDLS[-1].findAll('td')
            if len(tddWDLS) > 3:
                tmpRateS = re.search("[\d]+\.[\d]+", repr(tddWDLS[3]))
                if tddWDLS[1].text is None:
                    if tmpRateS is not None:
                        rateA = (float(
                            re.search("[\d]+\.[\d]+",
                                      repr(tddWDLS[2])).group()),
                                 float(
                                     re.search("[\d]+\.[\d]+",
                                               repr(tddWDLS[3])).group()),
                                 float(
                                     re.search("[\d]+\.[\d]+",
                                               repr(tddWDLS[4])).group()))
                else:
                    if tmpRateS is not None:
                        rateB = (int(tddWDLS[1].text),
                                 float(
                                     re.search("[\d]+\.[\d]+",
                                               repr(tddWDLS[2])).group()),
                                 float(
                                     re.search("[\d]+\.[\d]+",
                                               repr(tddWDLS[3])).group()),
                                 float(
                                     re.search("[\d]+\.[\d]+",
                                               repr(tddWDLS[4])).group()))

            trrScore = tbWDL[3].findAll('tr')
            tddScore = trrScore[-1].findAll('td')
            #        print tddScore[1].text
            rateC = (99.99, 99.99, 99.99, 99.99, 99.99, 99.99, 99.99, 99.99)
            tmpRateScore = re.search("[\d]+\.[\d]+", repr(tddScore[1].text))
            if tmpRateScore is not None:
                rateC = (float(tddScore[1].text), float(tddScore[2].text),
                         float(tddScore[3].text), float(tddScore[4].text),
                         float(tddScore[5].text), float(tddScore[6].text),
                         float(tddScore[7].text), float(tddScore[8].text))

            trrHF = tbWDL[4].findAll('tr')
            tddHF = trrHF[-1].findAll('td')
            rateD = (99.99, 99.99, 99.99, 99.99, 99.99, 99.99, 99.99, 99.99,
                     99.99)
            tmpRateHF = re.search("[\d]+\.[\d]+", repr(tddHF[1].text))
            if tmpRateHF is not None:
                rateD = (float(tddHF[1].text), float(tddHF[2].text),
                         float(tddHF[3].text), float(tddHF[4].text),
                         float(tddHF[5].text), float(tddHF[6].text),
                         float(tddHF[7].text), float(tddHF[8].text),
                         float(tddHF[9].text))

            return (rateA, rateB, rateC, rateD)
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            return None
Esempio n. 18
0
    def getPage(self, start, end):
        pageSize = 200
        for num in range(int(start), int(end), pageSize):
            time.sleep(random.randint(1, 20))
            start_str = "%05d" % num
            print(start_str)
            endNum = num + pageSize - 1
            if endNum > int(end):
                endNum = int(end)
            end_str = "%05d" % endNum
            url = 'http://datachart.500.com/ssq/history/newinc/history.php?start=' + \
                start_str + '&end=' + end_str

            content = self.getContent(url)
            i = 0
            while not content:
                time.sleep(10)
                content = self.getContent(url)
                i = i + 1
                if i > 10:
                    break

            if not content:
                return

            soup = BeautifulSoup(content, 'html.parser')
            table = soup.find_all(id="tdata")
            if len(table) > 0:
                for trr in table[0].findAll('tr'):
                    tds = trr.findAll('td')
                    try:
                        d = DuotoneBallLottery(
                            nper=tds[0].text,
                            r1=int(tds[1].text),
                            r2=int(tds[2].text),
                            r3=int(tds[3].text),
                            r4=int(tds[4].text),
                            r5=int(tds[5].text),
                            r6=int(tds[6].text),
                            rArray=str([
                                tds[1].text, tds[2].text, tds[3].text,
                                tds[4].text, tds[5].text, tds[6].text
                            ]),
                            b=int(tds[7].text),
                            hSun=int(tds[8].text.replace(',', ''))
                            if tds[8].text != '\xa0' else 0,  # 快乐星期天
                            jackpotBonuses=int(tds[9].text.replace(',', '')),
                            firstPrizeNum=tds[10].text.replace(',',
                                                               ''),  # 一等奖注数
                            firstPrizeMoney=tds[11].text.replace(',',
                                                                 ''),  # 一等奖奖金
                            secondPrizeNum=tds[12].text.replace(',',
                                                                ''),  # 二等奖注数
                            secondPrizeMoney=tds[13].text.replace(',',
                                                                  ''),  # 二等奖奖金
                            totalBet=tds[14].text.replace(',', ''),
                            lotteryDate=datetime.datetime.strptime(
                                tds[15].text, '%Y-%m-%d').date())
                        self.session.add(d)
                        self.session.commit()
                    except Exception as ex:
                        SysUtil.exceptionPrint(self.logger, ex)
            else:
                pass
Esempio n. 19
0
    def getMatchSync(self, trs500W, dateInfo, num):
        try:
            for line in trs500W:
                tds = line.findAll('td')

                mid = line['mid']
                match = dateInfo[2] + tds[0].a.contents[0]
                date = datetime.datetime.strptime(dateInfo[1],
                                                  "%Y-%m-%d").date()
                mdate = self.getMDate(date, line['pendtime'])
                matchid = mdate.isoformat().replace(u'-', '') + match
                mtime = datetime.datetime.strptime(line['pendtime'],
                                                   "%Y-%m-%d %H:%M:%S")

                matchtype = line['lg']
                matchzhu = tds[3].a['title']
                zhuRank = self.getNum(tds[3].span.text)

                matchke = tds[5].a['title']
                keRank = self.getNum(tds[5].span.text)
                rankDValue = zhuRank - keRank
                if int(zhuRank) == 0:
                    rankDValue = 4
                rates = self.getWDLRate(tds[7])
                wrate, drate, lrate = rates[0]
                wrateS, drateS, lrateS = rates[1]
                minrate = self.getMinRate(
                    (rates[0][0], rates[0][1], rates[0][2]))
                minrateS = self.getMinRate(
                    (rates[1][0], rates[1][1], rates[1][2]))

                fixScore = int(tds[6].findAll('p')[1].text)
                singleFlag = '0'
                if tds[0].has_attr('class'):
                    singleFlag = '1'

                zhuScore = None
                keScore = None
                mResult = ''
                fixResult = ''
                status = '0'
                if len(tds[4].text) > 0:
                    scores = self.getScore(tds[4].text)
                    zhuScore = scores[0]
                    if not zhuScore:
                        zhuScore = None
                    keScore = scores[1]
                    if not keScore:
                        keScore = None
                    mResult = self.getMResult(scores)
                    fixResult = self.getMResultF(scores, fixScore)
                    status = '1'

                m5 = self.session.query(MatchInfo500).filter(
                    MatchInfo500.matchid == matchid).first()
                if m5:
                    self.session.delete(m5)
                    self.session.flush()

                mi = MatchInfo500(matchid=matchid,
                                  mid=mid,
                                  match=match,
                                  date=date,
                                  mdate=mdate,
                                  mtime=mtime,
                                  matchtype=matchtype,
                                  matchzhu=matchzhu,
                                  zhuRank=zhuRank,
                                  matchke=matchke,
                                  keRank=keRank,
                                  rankDValue=rankDValue,
                                  zhuScore=zhuScore,
                                  keScore=keScore,
                                  mResult=mResult,
                                  status=status,
                                  wrate=wrate,
                                  drate=drate,
                                  lrate=lrate,
                                  minrate=minrate,
                                  fixScore=fixScore,
                                  fixResult=fixResult,
                                  wrateS=wrateS,
                                  drateS=drateS,
                                  lrateS=lrateS,
                                  minrateS=minrateS,
                                  singleFlag=singleFlag)
                self.session.add(mi)

                m = self.session.query(MatchInfo).filter(
                    MatchInfo.matchid == mi.matchid).first()
                if m is not None:
                    m.matchTime = mi.mtime.time()
                    m.zhuRank = mi.zhuRank
                    m.keRank = mi.keRank
                    m.rankDValue = mi.rankDValue
                self.session.flush()

            self.session.commit()

            return True
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            return False
Esempio n. 20
0
    def getMatch(self):
        urlM = "http://i.sporttery.cn/odds_calculator/get_odds?i_format=json&i_callback=getData&poolcode[]=hhad&poolcode[]=had&_=1460170422871"
        try:
            #            self.session.execute(text('truncate table tbl_matchinfod'))
            self.session.query(MatchInfoD).delete()
            self.session.flush()
            content = urllib.request.urlopen(urlM, timeout=10).read()
            message = content.decode('gbk')
            message = message.replace('getData(', '')
            message = message.replace(');', '')
            decode = json.loads(message)
            matchInfos = decode['data']
            for match in matchInfos:
                wrate = drate = lrate = wrateS = drateS = lrateS = 0.0
                fixScore = '0'
                if matchInfos[match]['status'] != 'Selling':
                    continue
                matchid = matchInfos[match]['date'].replace(
                    '-', '') + matchInfos[match]['num']
                singleFlag = '0'
                if matchInfos[match].get('had') is not None:
                    wrate = float(matchInfos[match]['had']['h'])
                    drate = float(matchInfos[match]['had']['d'])
                    lrate = float(matchInfos[match]['had']['a'])
                    singleFlag = matchInfos[match]['had']['single']
                minrate = min(wrate, drate, lrate)
                if matchInfos[match].get('hhad') is not None:
                    fixScore = matchInfos[match]['hhad']['fixedodds']
                    wrateS = float(matchInfos[match]['hhad']['h'])
                    drateS = float(matchInfos[match]['hhad']['d'])
                    lrateS = float(matchInfos[match]['hhad']['a'])
                minrateS = min(wrateS, drateS, lrateS)
                orderP = re.compile('(\d+)')
                rankMsg = orderP.findall(matchInfos[match]['h_order'])
                zhuRank = int(rankMsg[0]) if len(rankMsg) > 0 else 7
                rankMsg = orderP.findall(matchInfos[match]['a_order'])
                keRank = int(rankMsg[0]) if len(rankMsg) > 0 else 7

                mi = MatchInfoD(matchid=matchid,
                                match=matchInfos[match]['num'],
                                date=datetime.datetime.strptime(
                                    matchInfos[match]['date'],
                                    '%Y-%m-%d').date(),
                                matchTime=datetime.datetime.strptime(
                                    matchInfos[match]['time'],
                                    '%H:%M:%S').time(),
                                matchtype=matchInfos[match]['l_cn'],
                                matchtypename=matchInfos[match]['l_cn_abbr'],
                                matchzhu=matchInfos[match]['h_cn'],
                                matchke=matchInfos[match]['a_cn'],
                                status=matchInfos[match]['status'],
                                wrate=wrate,
                                drate=drate,
                                lrate=lrate,
                                minrate=minrate,
                                fixScore=fixScore,
                                wrateS=wrateS,
                                drateS=drateS,
                                lrateS=lrateS,
                                minrateS=minrateS,
                                zhuRank=zhuRank,
                                keRank=keRank,
                                rankDValue=zhuRank - keRank,
                                singleFlag=singleFlag)
                self.session.add(mi)
            self.session.commit()

            return True
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            return False
Esempio n. 21
0
    def on_get(self, req, resp):
        self.initialize()
        req_para = falcon.util.uri.parse_query_string(req.query_string)

        if 'userid' not in req_para.keys():
            self.errorReturn(GLBConfig.API_ERROR, 'userid 不存在.')

        maData = []
        for a in self.session.query(AccountRunning).\
                filter(AccountRunning.userid == req_para['userid']).\
                filter(AccountRunning.status == GLBConfig.ENABLE).\
                order_by(AccountRunning.date.desc()).all():
            maData.append({
                'date': a.date.isoformat(),
                'usemoney': a.useMoney,
                'dresult': a.dResult,
                'totalresult': a.totalResult + a.fixTotal
            })
        accountMsg = {}
        try:
            result = self.session.execute(
                text('select basemoney from tbl_userdata where userid = :uid'),
                {
                    'uid': req_para['userid']
                }).first()
            accountMsg['baseMoney'] = result[0]

            result = self.session.execute(
                text('select expdate from tbl_user where userid = :uid'), {
                    'uid': req_para['userid']
                }).first()
            accountMsg['expdate'] = result[0].isoformat()

            result = self.session.execute(
                text(
                    'select min(date) from tbl_account_running where status = "1" and userid = :uid'
                ), {
                    'uid': req_para['userid']
                }).first()
            accountMsg['fromDate'] = result[0].isoformat()

            result = self.session.execute(
                text(
                    'select max(date) from tbl_account_running where status = "1" and userid = :uid'
                ), {
                    'uid': req_para['userid']
                }).first()
            accountMsg['toDate'] = result[0].isoformat()

            result = self.session.execute(
                text(
                    'select max(usemoney) from tbl_account_running where status = "1" and  userid = :uid'
                ), {
                    'uid': req_para['userid']
                }).first()
            accountMsg['maxUse'] = result[0]

            result = self.session.execute(
                text(
                    'select sum(usemoney) from tbl_account_running where status = "1" and userid = :uid'
                ), {
                    'uid': req_para['userid']
                }).first()
            accountMsg['sumUse'] = result[0]

            result = self.session.execute(
                text(
                    'select truncate(sum(usemoney + dResult),2) from tbl_account_running where status = "1" and userid = :uid'
                ), {
                    'uid': req_para['userid']
                }).first()
            accountMsg['sumWin'] = result[0]

            result = self.session.execute(
                text(
                    'select max(usemoney)*0.08 from tbl_account_running where status = "1" and userid = :uid'
                ), {
                    'uid': req_para['userid']
                }).first()
            accountMsg['sumCommission'] = result[0]
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            self.errorReturn(GLBConfig.SYSTEM_ERROR, '系统错误.')

        self.result['data'] = maData
        self.result['accountMsg'] = accountMsg
        req.context['result'] = self.result
        resp.set_header('Powered-By', '*****@*****.**')
        resp.status = falcon.HTTP_200
        self.release()
Esempio n. 22
0
    def getMatch(self, urlM):
        try:
            content = urllib.request.urlopen(urlM, timeout=10).read()
            message = content.decode('gbk')
            soup = BeautifulSoup(message, 'html.parser')
            for tabb in soup.findAll('table')[1:2]:
                for trr in tabb.findAll('tr'):
                    tds = trr.findAll('td')
                    if len(tds) < 3:
                        continue
                    if tds[6].text == u'进行中' or tds[6].text == u'取消':
                        continue
                    if tds[7].a is None:
                        continue
                    matchid = tds[0].text.replace('-', '') + tds[1].text
                    singleF = re.search(r'(single\.gif)', repr(tds[3]))
                    singleFlag = '0'
                    if singleF:
                        singleFlag = '1'
                    teams = tds[3].findAll('span')
                    scoreh = re.search(r'([\d+]):([\d+])', tds[4].span.text)
                    score = re.search(r'([\d+]):([\d+])', tds[5].span.text)
                    if int(score.groups()[0]) > int(score.groups()[1]):
                        mResult = 'W'
                    elif int(score.groups()[0]) == int(score.groups()[1]):
                        mResult = 'D'
                    else:
                        mResult = 'L'
                    rateurl = 'http://info.sporttery.cn/football/' + tds[7].a[
                        'href']
                    rates = self.getWDLRate(rateurl)
                    while not rates:
                        self.logger.info(urlM)
                        self.logger.info(rateurl)
                        rates = self.getWDLRate(rateurl)
                    fixResult = ' '
                    if int(score.groups()[0]) + rates[1][0] > int(
                            score.groups()[1]):
                        fixResult = 'W'
                    elif int(score.groups()[0]) + rates[1][0] == int(
                            score.groups()[1]):
                        fixResult = 'D'
                    else:
                        fixResult = 'L'

                    minrate = self.getMinRate(
                        (rates[0][0], rates[0][1], rates[0][2]))
                    minrateS = self.getMinRate(
                        (rates[1][1], rates[1][2], rates[1][3]))

                    totalScore = int(score.groups()[0]) + int(
                        score.groups()[1])

                    mp = self.session.query(MatchInfo).filter(
                        MatchInfo.matchid == matchid).first()
                    if mp:
                        self.session.delete(mp)
                        self.session.flush()

                    m = MatchInfo(matchid=matchid,
                                  match=tds[1].text,
                                  date=datetime.datetime.strptime(
                                      tds[0].text, '%Y-%m-%d').date(),
                                  matchtype=tds[2]['title'],
                                  matchtypename=tds[2].text,
                                  matchzhu=teams[0]['title'],
                                  matchke=teams[2]['title'],
                                  matchzhuf=teams[0].text,
                                  matchkef=teams[2].text,
                                  zhuHScore=int(scoreh.groups()[0]),
                                  keHScore=int(scoreh.groups()[1]),
                                  zhuScore=int(score.groups()[0]),
                                  keScore=int(score.groups()[1]),
                                  mResult=mResult,
                                  status=tds[6].text,
                                  wrate=rates[0][0],
                                  drate=rates[0][1],
                                  lrate=rates[0][2],
                                  minrate=minrate,
                                  fixScore=rates[1][0],
                                  fixResult=fixResult,
                                  wrateS=rates[1][1],
                                  drateS=rates[1][2],
                                  lrateS=rates[1][3],
                                  minrateS=minrateS,
                                  singleFlag=singleFlag,
                                  score=totalScore,
                                  s0=rates[2][0],
                                  s1=rates[2][1],
                                  s2=rates[2][2],
                                  s3=rates[2][3],
                                  s4=rates[2][4],
                                  s5=rates[2][5],
                                  s6=rates[2][6],
                                  s7=rates[2][7],
                                  ww=rates[3][0],
                                  wd=rates[3][1],
                                  wl=rates[3][2],
                                  dw=rates[3][3],
                                  dd=rates[3][4],
                                  dl=rates[3][5],
                                  lw=rates[3][6],
                                  ld=rates[3][7],
                                  ll=rates[3][8],
                                  infoUrl=rateurl)
                    self.session.add(m)
                    self.session.commit()

            return True
        except Exception as ex:
            SysUtil.exceptionPrint(self.logger, ex)
            return False