Exemple #1
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
Exemple #2
0
    def process_request(self, req, resp):
        # req.stream corresponds to the WSGI wsgi.input environ variable,
        # and allows you to read bytes from the request body.
        #
        # See also: PEP 3333
        if req.content_length in (None, 0):
            # Nothing to do
            self.logger.info(req.headers)
            self.logger.info('Message length is 0')
            return

        if req.content_type.split(';')[0] == 'application/json':
            body = req.stream.read()
            if not body:
                raise falcon.HTTPBadRequest(
                    'Empty request body', 'A valid JSON document is required.')
            try:
                req.context['doc'] = json.loads(body.decode('utf-8'))
                if 'user' in req.context:
                    SysUtil.createOperateLog(req)

            except (ValueError, UnicodeDecodeError):
                raise falcon.HTTPError(
                    falcon.HTTP_753, 'Malformed JSON',
                    'Could not decode the request body. The '
                    'JSON was incorrect or not encoded as '
                    'UTF-8.')
Exemple #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()
 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
Exemple #5
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
Exemple #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
Exemple #7
0
 def __init__(self):
     className = self.__class__.__name__
     LogUtil.initLogBatch(className)
     SysUtil.global_init()
     self.engine = SysUtil.get_engine_handle()
     self.db = SysUtil.get_db_handle()
     self.logger = logging.getLogger('batchLog_' + className)
Exemple #8
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, '系统错误')
Exemple #9
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
Exemple #10
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, '系统错误')
Exemple #11
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()
Exemple #12
0
    def on_get(self, req, resp):
        self.initialize()
        req_para = falcon.util.uri.parse_query_string(req.query_string)

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

            for md, mi, m in self.session.query(MatchData, MatchInfoD, MatchInfo500Time).\
                    filter(MatchData.userid == u.userid).\
                    filter(MatchData.date >= SysUtil.getYesterday()).\
                    filter(MatchData.matchAID == MatchInfoD.matchid).\
                    filter(MatchInfoD.match == MatchInfo500Time.match).all():
                matches.append(m)

            for md, mi, m in self.session.query(MatchData, MatchInfoD, MatchInfo500Time).\
                    filter(MatchData.singleFlag == GLBConfig.M_DUAL).\
                    filter(MatchData.userid == u.userid).\
                    filter(MatchData.date >= SysUtil.getYesterday()).\
                    filter(MatchData.matchBID == MatchInfoD.matchid).\
                    filter(MatchInfoD.match == MatchInfo500Time.match).all():
                matches.append(m)

        else:
            matches = self.session.query(MatchInfo500Time).\
                filter(MatchInfo500Time.mststus != '完').all()
            matchesB = self.session.query(MatchInfo500Time).\
                filter(MatchInfo500Time.mststus == '完').all()
            for m in matchesB:
                matches.append(m)

        maData = []
        if matches:
            for m in matches:
                maData.append({
                    'match': m.match,
                    'mtime': m.mtime.strftime('%Y-%m-%d %H:%M'),
                    'matchtype': m.matchtype,
                    'matchzhu': m.matchzhu,
                    'matchke': m.matchke,
                    'zhuScore': m.zhuScore,
                    'keScore': m.keScore,
                    'zhuHScore': m.zhuHScore,
                    'keHScore': m.keHScore,
                    'mststus': m.mststus
                })

        self.result['data'] = maData

        req.context['result'] = self.result
        resp.set_header('Powered-By', '*****@*****.**')
        resp.status = falcon.HTTP_200
        self.release()
Exemple #13
0
    def on_get(self, req, resp):
        self.initialize()
        req_para = falcon.util.uri.parse_query_string(req.query_string)
        if 'dealerid' not in req_para.keys()\
                or 'matchA' not in req_para.keys() \
                or 'AResult' not in req_para.keys() \
                or 'matchB' not in req_para.keys() \
                or 'BResult' not in req_para.keys() \
                or 'desc' not in req_para.keys():
            self.errorReturn(GLBConfig.API_ERROR, '接口参数不正确.')

        if req_para['AResult'] not in ('W', 'D', 'L'):
            self.errorReturn(GLBConfig.API_ERROR, '接口参数不正确.')
        if req_para['BResult'] not in ('W', 'D', 'L'):
            self.errorReturn(GLBConfig.API_ERROR, '接口参数不正确.')

        d = self.session.query(Dealer).\
            filter(Dealer.uid == req_para['dealerid']).\
            filter(Dealer.dealertype == GLBConfig.D_TYPE_H).first()
        if d is None:
            self.errorReturn(GLBConfig.API_ERROR, 'dealer不存在.')

        mA = self.session.query(MatchInfoD).filter(
            MatchInfoD.matchid == req_para['matchA']).first()
        if mA is None:
            self.errorReturn(GLBConfig.API_ERROR, '比赛不存在.')
        mB = self.session.query(MatchInfoD).filter(
            MatchInfoD.matchid == req_para['matchB']).first()
        if mB is None:
            self.errorReturn(GLBConfig.API_ERROR, '比赛不存在.')

        self.session.query(DealerMatch).\
            filter(DealerMatch.date == SysUtil.getTomorrow()).\
            filter(DealerMatch.dealerid == req_para['dealerid']).delete()
        self.session.flush()

        dm = DealerMatch(
            dealerid=req_para['dealerid'],
            date=SysUtil.getTomorrow(),
            matchAID=req_para['matchA'],
            matchAResult=req_para['AResult'],
            matchBID=req_para['matchB'],
            matchBResult=req_para['BResult'],
            matchdesc=req_para['desc']
        )
        self.session.add(dm)
        self.session.commit()

        self.result['data'] = 'success'

        req.context['result'] = self.result
        resp.set_header('Powered-By', '*****@*****.**')
        resp.status = falcon.HTTP_200
        self.release()
Exemple #14
0
    def getMatch(self, u):
        tomorrow = SysUtil.getTomorrow
        matches = self.session.query(MatchInfoD).\
            filter(or_(and_(MatchInfoD.date == tomorrow, MatchInfoD.matchTime < '22:00:00'),
                       and_(MatchInfoD.date == SysUtil.getToday, MatchInfoD.matchTime >= '22:00:00'))).\
            filter(MatchInfoD.singleFlag == '1').\
            filter(MatchInfoD.minrate > 0.1).\
            order_by(MatchInfoD.wrate).all()

        count = 0
        for m in matches:
            rateList = (m.wrate, m.drate, m.lrate)
            rateAIdex = getMaxIndex(rateList)
            rateBIdex = getMidIndex(rateList)

            if m.minrate < 1.46:
                if m.randDValue > 8 or m.randDValue < -8:
                    rateAIdex = 0
                    rateBIdex = 2

            if m.matchtypename == '欧洲杯' and m.minrate < 1.30:
                rateAIdex = getMinIndex(rateList)
                rateBIdex = getMidIndex(rateList)

            if m.matchtypename == '奥运女足' and m.minrate < 1.351:
                rateAIdex = getMinIndex(rateList)
                rateBIdex = getMidIndex(rateList)

            if m.matchtypename == '奥运男足' and m.minrate < 1.351:
                rateAIdex = getMinIndex(rateList)
                rateBIdex = getMidIndex(rateList)

            mA = MatchData(userid=u.userid,
                           date=tomorrow,
                           matchAID=m.matchid,
                           matchAResult=SysUtil.getMatchResult(rateAIdex),
                           rate=rateList[rateAIdex],
                           singleFlag='1',
                           matchAFflag='0')
            self.session.add(mA)

            mB = MatchData(userid=u.userid,
                           date=tomorrow,
                           matchAID=m.matchid,
                           matchAResult=SysUtil.getMatchResult(rateBIdex),
                           rate=rateList[rateBIdex],
                           singleFlag='1',
                           matchAFflag='0')
            self.session.add(mB)
            self.session.flush()
            count += 1
            if count > 2:
                return count
        return count
Exemple #15
0
def getMatchDraw(date):
    matches = session.query(MatchInfo).\
            filter(MatchInfo.date==date).\
            filter(MatchInfo.singleFlag == '1').\
            filter(MatchInfo.minrate > 0.1).\
            order_by(MatchInfo.wrate).all()
        
    count = 0
    if matches:
        for m in matches:
            rateList = (m.wrate,m.drate,m.lrate)
            rateAIdex = SysUtil.getMaxIndex(rateList)
            rateBIdex = SysUtil.getMidIndex(rateList)
            
            if m.minrate < 1.46:
                if m.rankDValue > 8 or m.rankDValue < -8:
                    rateAIdex = 0
                    rateBIdex = 2
                    
            if m.matchtypename == '欧洲杯' and m.minrate < 1.30:
                rateAIdex = SysUtil.getMinIndex(rateList)
                rateBIdex = SysUtil.getMidIndex(rateList)
            
            if m.matchtypename == '奥运女足' and m.minrate < 1.351:
                rateAIdex = SysUtil.getMinIndex(rateList)
                rateBIdex = SysUtil.getMidIndex(rateList)
            
            if m.matchtypename == '奥运男足' and m.minrate < 1.351:
                rateAIdex = SysUtil.getMinIndex(rateList)
                rateBIdex = SysUtil.getMidIndex(rateList)
            
            mA = MatchDataBatch(date = date,
                    matchAID = m.matchid,
                    matchAResult = SysUtil.getMatchResult(rateAIdex),
                    rate = rateList[rateAIdex],
                    singleFlag = GLBConfig.M_SINGLE)
            session.add(mA)
            
            mB = MatchDataBatch(date = date,
                    matchAID = m.matchid,
                    matchAResult = SysUtil.getMatchResult(rateBIdex),
                    rate = rateList[rateBIdex],
                    singleFlag = GLBConfig.M_SINGLE)
            session.add(mB)
            
            session.commit()
            count += 1
            if count > 2:
                break
    return count
Exemple #16
0
    def getMatch(self, u, udata, dealerid):
        tomorrow = SysUtil.getTomorrow()
        self.session.query(MatchData).\
            filter(MatchData.userid == u.userid).\
            filter(MatchData.date == tomorrow).delete()

        self.session.flush()

        matches = self.session.query(DealerMatch).\
            filter(DealerMatch.dealerid == int(dealerid)).\
            filter(DealerMatch.date == SysUtil.getTomorrow()).first()

        if matches is None:
            self.errorReturn(GLBConfig.API_ERROR, '无推荐内容.')

        ma = self.session.query(MatchInfoD).filter(
            MatchInfoD.matchid == matches.matchAID).first()
        mb = self.session.query(MatchInfoD).filter(
            MatchInfoD.matchid == matches.matchBID).first()

        listA = (ma.wrate, ma.drate, ma.lrate)
        listB = (mb.wrate, mb.drate, mb.lrate)

        account = self.session.query(AccountRunning).\
            filter(AccountRunning.userid == u.userid).\
            filter(AccountRunning.date < tomorrow).\
            order_by(AccountRunning.date.desc()).first()

        money = 0.0
        if account:
            if account.riskMoney < 0:
                money = account.riskMoney

        rate = listA[SysUtil.getResultIndex(
            matches.matchAResult)] * listB[SysUtil.getResultIndex(
                matches.matchBResult)]
        mMoney = (udata.basemony - money) / (rate - 1.00)

        md = MatchData(userid=u.userid,
                       date=tomorrow,
                       matchAID=matches.matchAID,
                       matchAResult=matches.matchAResult,
                       matchBID=matches.matchBID,
                       matchBResult=matches.matchBResult,
                       rate=rate,
                       money=mMoney,
                       singleFlag='2')
        self.session.add(md)
        self.session.flush(md)
Exemple #17
0
    def getMatchModeD(self, u, ud, matchid):
        tomorrow = SysUtil.getTomorrow()
        m = self.session.query(MatchInfoD).\
            filter(MatchInfoD.matchid == matchid).first()

        count = 1
        md1 = MatchData(userid=u.userid,
                        date=tomorrow,
                        singleFlag=GLBConfig.M_SCORE,
                        matchAID=m.matchid,
                        matchAResult='2',
                        rate=m.s2)
        self.session.add(md1)
        md2 = MatchData(userid=u.userid,
                        date=tomorrow,
                        singleFlag=GLBConfig.M_SCORE,
                        matchAID=m.matchid,
                        matchAResult='3',
                        rate=m.s3)
        self.session.add(md2)
        md3 = MatchData(userid=u.userid,
                        date=tomorrow,
                        singleFlag=GLBConfig.M_SCORE,
                        matchAID=m.matchid,
                        matchAResult='4',
                        rate=m.s4)
        self.session.add(md3)
        self.session.flush()
        if count > 0:
            self.calMoney(u, ud, count)
Exemple #18
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()
Exemple #19
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 'dealerid' not in req_para.keys():
            self.errorReturn(GLBConfig.API_ERROR, 'dealerid 不存在.')
        if 'gambleFlag' not in req_para.keys():
            self.errorReturn(GLBConfig.API_ERROR, 'gambleFlag 不存在.')

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

        if u.accounttype != GLBConfig.ATYPE_PERSION:
            self.errorReturn(GLBConfig.API_ERROR, '账户类型错误.')

        if u.expdate > datetime.date.today:
            self.errorReturn(GLBConfig.API_ERROR, '用户已过期.')

        self.matchCalcMoney(u, req_para['dealerid'])

        matches = self.session.query(MatchData).\
            filter(MatchData.userid == u.userid).\
            filter(MatchData.date == SysUtil.getTomorrow()).all()

        maData = []
        sumMoney = 0.00
        for m in matches:
            matInfo = self.session.query(MatchInfoD).filter(
                MatchInfoD.matchid == m.matchAID).first()
            maData.append({
                'match': m.matchAID,
                'matchtype': matInfo.matchtype,
                'zhu': matInfo.matchzhu,
                'ke': matInfo.matchke,
                'wrate': matInfo.wrate,
                'drate': matInfo.drate,
                'lrate': matInfo.lrate,
                'result': m.matchAResult,
                'money': m.money
            })
            sumMoney += m.money
        self.result['data'] = maData
        self.result['sumMoney'] = sumMoney

        if req_para['gambleFlag'] == '1':
            self.session.commit()
        else:
            self.session.rollback()

        req.context['result'] = self.result
        resp.set_header('Powered-By', '*****@*****.**')
        resp.status = falcon.HTTP_200
        self.release()
Exemple #20
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()
Exemple #21
0
    def matchCalcMoney(self, u, dealerid):
        udata = self.session.query(UserData).filter(
            UserData.userid == u.userid).first()
        if udata is None:
            self.errorReturn(GLBConfig.API_ERROR, '目标金额未设置.')

        self.matchresult(u, udata, SysUtil.getYesterday())
        self.matchresult(u, udata, SysUtil.getToday())

        ct = self.session.query(func.count('*')).\
            filter(MatchData.userid == u.userid).\
            filter(MatchData.date == SysUtil.getToday()).\
            filter(func.abs(MatchData.ResultMoney) < 0.001).scalar()

        if datetime.datetime.now().time() < datetime.time(19, 0, 0):
            if ct != 0:
                self.errorReturn(GLBConfig.API_ERROR, '有比赛结果未出.')

        self.getMatch(u, udata, dealerid)
Exemple #22
0
 def searchAct(self,req):
     result = []         
     
     for col in self.session.query(UserGroupInfo).\
         filter(UserGroupInfo.userGroupType!=GLBConfig.GTYPE_ADMINISTRATOR).\
         filter(UserGroupInfo.userGroupName!='administrator').\
         all():
         row = {}
         row = SysUtil.schema2Json(col)
         result.append(row)
     return result
Exemple #23
0
    def getMatchModeASelfChoice(self, u, udata, matchA, AResult, matchB,
                                BResult):
        tomorrow = SysUtil.getTomorrow()
        ma = self.session.query(MatchInfoD).filter(
            MatchInfoD.matchid == matchA).first()
        if ma is None:
            self.errorReturn(GLBConfig.API_ERROR, '比赛不存在.')
        mb = self.session.query(MatchInfoD).filter(
            MatchInfoD.matchid == matchB).first()
        if mb is None:
            self.errorReturn(GLBConfig.API_ERROR, '比赛不存在.')

        listA = (ma.wrate, ma.drate, ma.lrate)
        listB = (mb.wrate, mb.drate, mb.lrate)

        account = self.session.query(AccountRunning).\
            filter(AccountRunning.userid == u.userid).\
            filter(AccountRunning.status == GLBConfig.ENABLE).\
            filter(AccountRunning.date < tomorrow).\
            order_by(AccountRunning.date.desc()).first()

        money = 0.0
        if account:
            if account.riskMoney < 0:
                money = account.riskMoney

        rate = listA[SysUtil.getResultIndex(AResult)] * listB[
            SysUtil.getResultIndex(BResult)]
        mMoney = (udata.basemoney - money) / (rate - 1.00)

        md = MatchData(userid=u.userid,
                       date=tomorrow,
                       matchAID=matchA,
                       matchAResult=AResult,
                       matchBID=matchB,
                       matchBResult=BResult,
                       rate=rate,
                       money=mMoney,
                       singleFlag='2')
        self.session.add(md)
        self.session.flush()
Exemple #24
0
 def searchAct(self, req):
     result = []
     for user, operator in self.session.query(User, OperatorInfo).\
         filter(User.userID==OperatorInfo.userID).\
         filter(User.accountType==GLBConfig.ATYPE_OPERATOR).\
         filter(User.dataStatus==GLBConfig.ENABLE).\
         order_by(User.makeTime.desc()).all():
         row = {}
         row = SysUtil.schema2Json(operator)
         row['userName'] = user.userName
         result.append(row)
     return result
Exemple #25
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()
    def getDealerMatch(self):
        dealers = self.session.query(Dealer).filter(
            Dealer.dealertype == GLBConfig.D_TYPE_C).all()

        for d in dealers:
            if len(self.session.query(DealerMatch).\
                filter(DealerMatch.dealerid == d.uid).\
                filter(DealerMatch.date == SysUtil.getTomorrow()).all()) > 0:
                continue

            if d.uid == 1:
                matches = self.session.query(MatchInfoD).\
                    filter(MatchInfoD.date == SysUtil.getTomorrow()).\
                    filter(MatchInfoD.minrate >= 2.0).\
                    filter(MatchInfoD.minrate <= 3.0).all()
            elif d.uid == 2:
                matches = self.session.query(MatchInfoD).\
                    filter(MatchInfoD.date == SysUtil.getTomorrow()).\
                    filter(MatchInfoD.minrate >= 1.0).\
                    filter(MatchInfoD.minrate <= 2.5).all()
            elif d.uid == 3:
                matches = self.session.query(MatchInfoD).\
                    filter(MatchInfoD.date == SysUtil.getTomorrow()).\
                    filter(MatchInfoD.minrate >= 1.5).\
                    filter(MatchInfoD.minrate <= 2.5).all()

            if len(matches) > 1:
                choice = random.sample(matches, 2)
                rateAList = (choice[0].wrate, choice[0].drate, choice[0].lrate)
                minRateAIdex = SysUtil.getMinIndex(rateAList)

                rateBList = (choice[1].wrate, choice[1].drate, choice[1].lrate)
                minRateBIdex = SysUtil.getMinIndex(rateBList)

                dm = DealerMatch(
                    dealerid=d.uid,
                    date=SysUtil.getTomorrow(),
                    matchAID=choice[0].matchid,
                    matchAResult=SysUtil.getMatchResult(minRateAIdex),
                    matchBID=choice[1].matchid,
                    matchBResult=SysUtil.getMatchResult(minRateBIdex),
                    matchdesc='')
                self.session.add(dm)
                self.session.commit()
Exemple #27
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
Exemple #28
0
    def matchCalcMoney(self, u, udata, req_para):
        self.matchresult(u, udata, SysUtil.getLast2())
        self.matchresult(u, udata, SysUtil.getYesterday())
        self.matchresult(u, udata, SysUtil.getToday())

        ct = self.session.query(func.count('*')).\
            filter(MatchData.userid == u.userid).\
            filter(MatchData.date == SysUtil.getToday()).\
            filter(func.abs(MatchData.ResultMoney) < 0.001).scalar()

        if datetime.datetime.now().time() < datetime.time(19, 0, 0):
            if ct != 0:
                self.errorReturn(GLBConfig.API_ERROR, '有比赛结果未出.')

        self.session.commit()

        self.session.query(MatchData).\
            filter(MatchData.userid == u.userid).\
            filter(MatchData.date == SysUtil.getTomorrow()).delete()

        self.session.flush()
        if u.accounttype == GLBConfig.ATYPE_GROUP:
            self.getMatchGroup(u, udata)
        elif u.accounttype == GLBConfig.ATYPE_PERSION:
            if udata.mode == GLBConfig.MODE_A:
                if 'dealerid' in req_para.keys():
                    self.getMatchModeA(u, udata, req_para['dealerid'])
                if 'matchA' in req_para.keys():
                    self.getMatchModeASelfChoice(u, udata, req_para['matchA'],
                                                 req_para['AResult'],
                                                 req_para['matchB'],
                                                 req_para['BResult'])
            if udata.mode == GLBConfig.MODE_B:
                self.getMatchModeB(u, udata)
            if udata.mode == GLBConfig.MODE_C:
                self.getMatchModeC(u, udata, req_para['matchid'])
            if udata.mode == GLBConfig.MODE_D:
                self.getMatchModeD(u, udata, req_para['matchid'])
Exemple #29
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()
Exemple #30
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, '系统错误')