Beispiel #1
0
    def handle(self, contentid, productid, userid, usertoken, verifycode, type, sid, fee):
        print('订购接口')
        db = Dbconn()
        retry_num = 0
        while retry_num < 2 and db.conn is None:
            db = Dbconn()
            retry_num += 1
        if db.conn is None:
            log.info('Error! Connect DB server failed by 2 times!!!!!!!')
            self.finish(json.dumps(
                {'code': 'P000008', 'data': {'result': '-1', 'desc': '连接数据库重试2次失败', 'playUrl': ''},
                 'message': '连接数据库重试2次失败',
                 'timestamp': int(time.mktime(datetime.datetime.now().timetuple()))}))
        else:
            # 查询此手机号是否存在十分钟内的有效验证码
            sql = "SELECT verify_code from CONT_VERIFYCODE where  phone_num=\'{0}\' AND verify_code=\'{1}\' AND is_effe='0' and TIMESTAMPDIFF(SECOND,CREATE_TIME,NOW()) <370".format(
                userid, verifycode)
            q_re = db.exeQuery(sql)
            log.info('subcribe code sql------' + sql)
            if q_re.rowcount > 0:
                log.info('verifyCode' + str(verifycode) + ' exist valid records')
                hw_url = config.get("HWurl", "hw_sub")
                statime = datetime.datetime.now()
                endtime = 0
                # 根据产品类型,传入不同的时间
                if str(productid).find('4KSK') >= 0:
                    endtime = (statime + datetime.timedelta(minutes=10)).strftime("%Y%m%d%H%M%S")  # 试看结束大于开始10分钟
                elif str(productid).find('4KDB') >= 0:
                    endtime = (statime + datetime.timedelta(days=2)).strftime("%Y%m%d%H%M%S")  # 点播结束大于开始48小时
                elif str(productid).find('4KBY') >= 0:
                    endtime = 20991231235959  # 包月固定值

                rdata = '{"pid":"' + productid + '", "sid": "' + sid + '", "cid": "' + contentid + '", "supercid": "-2",\
                         "playType": "1", "contentType": "0", "continueType": "0", "orderMode": "1", "orderPrice": "' + str(
                    fee) + '",\
                         "serStarttime": "' + str(statime.strftime("%Y%m%d%H%M%S")) + '", "serEndtime": "' + str(
                    endtime) + '", "businessType": "1",\
                         "BroadBandID": "' + str(userid) + '", "idflag": "1"}'
                log.info('Request HuaWei subscribe parms is -----' + rdata)
                headers = {'Authorization': usertoken, 'cache-control': 'no-cache'}
                h = httplib2.Http(timeout=30)
                try:
                    response, content = h.request(hw_url, 'POST', body=rdata, headers=headers)
                except Exception as e:
                    log.info('Request HuaWei subscribe interface 10s timeout!!!!!')
                    log.info(e)
                    self.finish(json.dumps(
                        {'code': 'P000009',
                         'data': {'result': '-1',
                                  'desc': '请求华为产品订购接口超时失败',
                                  'playUrl': ''},
                         'message': 'OK',
                         'timestamp': int(time.mktime(datetime.datetime.now().timetuple()))}, indent=4))
                    db.connClose()
                    return 0
                if response.status != 200:
                    log.info('Request HuaWei subscribe interface failed! HttpCode is ' + str(response.status))
                    self.write(json.dumps(
                        {'code': 'P000009',
                         'data': {'result': '1', 'desc': '请求华为产品订购接口失败,http状态码' + str(response.status),
                                  'playUrl': ''},
                         'message': 'OK',
                         'timestamp': int(time.mktime(datetime.datetime.now().timetuple()))}, indent=4))
                else:
                    resulcode = json.loads(content.decode('utf-8'))['returncode']
                    description = json.loads(content.decode('utf-8'))['description']
                    urls = json.loads(content.decode('utf-8'))['urls'][0]['playurl'] \
                        if 'urls' in dict(json.loads(
                        content.decode('utf-8'))).keys() else ''
                    # print(urls)
                    log.info('Huawei Response code is ' + str(resulcode) + 'playuri is ---' + urls)
                    if str(resulcode) == '0':
                        log.info('Customer order success!')
                        sucsql = 'insert INTO cont_order_rec (contentId,productId,userId,userToken,verifyCode,sid,billtype,creat_time,update_time)' \
                                 ' VALUES (\'{0}\',\'{1}\',\'{2}\',\'{3}\',\'{4}\',\'{5}\',\'{6}\',\'{7}\',\'{8}\',\'{9}\')'.format(
                            contentid, productid, userid, usertoken, verifycode, sid, type,
                            time.strftime(timefor, time.localtime(time.time())),
                            time.strftime(timefor, time.localtime(time.time())))
                        sta = db.exeUpdate(sucsql)
                        if sta == 1:
                            db.conn.commit()
                            log.info('insert new order record success! sql is: ' + sucsql)
                        else:
                            log.info('insert new order record failed! sql is: ' + sucsql)
                    else:
                        log.info('customer order failed!!!!!' + description)
                    self.write(json.dumps(
                        {'code': 'A000000',
                         'data': {'result': resulcode, 'desc': description, 'playUrl': urls},
                         'message': '请求华为产品订购接口成功,返回状态码' + str(resulcode),
                         'timestamp': int(time.mktime(datetime.datetime.now().timetuple()))}))
            else:
                log.info('The verifyCode ' + str(verifycode) + ' is error!Probably the code is error or invalid')
                self.write(json.dumps({'code': 'P000010', 'message': '您的验证码错误或已失效',
                                       'timestamp': int(time.mktime(datetime.datetime.now().timetuple()))}))
            db.connClose()
Beispiel #2
-2
    def handle(self, phoneNum, userToken):

        db = Dbconn()
        retry_num = 0
        while retry_num < 2 and db.conn is None:
            db = Dbconn()
            retry_num += 1

        # g = lambda a, b: "".join(random.sample(string.ascii_letters, a)) + "".join(random.sample(string.digits, b))
        gcode = lambda a: "".join(random.sample(string.digits, a))
        # print(gcode(6))
        if db.conn is None:
            log.info("Error! Connect DB server failed by 2 times!")
            self.finish(json.dumps(
                {'code': 'P000008', 'message': '连接数据库重试2次失败', 'data': {'result': '-1', 'desc': '连接数据库重试2次失败'},
                 'timestamp': int(time.mktime(datetime.datetime.now().timetuple()))}))
        else:
            q_sql = "SELECT verify_code from CONT_VERIFYCODE where  phone_num=\'{0}\'  AND is_effe='0'  and TIMESTAMPDIFF(SECOND,CREATE_TIME,NOW()) <370 order by CREATE_TIME desc ".format(
                phoneNum)
            print(q_sql)
            q_re = db.exeQuery(q_sql)
            if q_re.rowcount > 0:
                log.info('This phone 10 minutes exist a valid verifycode by querying db')
                validcode = q_re.fetchone()
                # 存在有效的验证码就使用
                code = validcode[0]
            else:
                log.info('This phone does not exist a valid verifycode,it will be create a new code!')
                code = gcode(6)
                sql = "insert into CONT_VERIFYCODE (verify_code,phone_num,create_time,update_time,is_effe)" \
                      " values (\'{0}\',\'{1}\',\'{2}\',\'{3}\','0')".format(code, phoneNum,
                                                                             time.strftime(timefor,
                                                                                           time.localtime(time.time())),
                                                                             time.strftime(timefor,
                                                                                           time.localtime(time.time())))
                sta = db.exeUpdate(sql)
                # log.info(sql)
                if sta == 1:
                    pass
                else:
                    log.info('insert database data failed!')
                    self.write(json.dumps(
                        {'code': 'P000008', 'data': {'result': '-1', 'desc': '插入数据库验证码数据失败'}, 'message': '插入数据库验证码数据失败',
                         'timestamp': int(time.mktime(datetime.datetime.now().timetuple()))}))
                    db.connClose()
                    return 0
            hw_url = config.get("HWurl", "hw_sms")
            rdata = '{"destAddress": "' + phoneNum + '", "messagecontent": "' + code + '"}'
            # headers = {'Authorization': 'St3q2dy3gci8-Stwfa5yqpb'}
            headers = {'Authorization': userToken, 'cache-control': 'no-cache'}  # 无缓存
            # h = httplib2.Http('.cache')#读取缓存
            h = httplib2.Http(timeout=30)
            try:
                response, content = h.request(hw_url, 'POST', body=rdata, headers=headers)
            except Exception as e:
                log.info('Request HuaWei subscribe interface 10s timeout!')
                log.info(e)
                self.finish(json.dumps(
                    {'code': 'P000009',
                     'data': {'result': '-1', 'desc': '请求华为短信接口超时失败'},
                     'message': 'OK',
                     'timestamp': int(time.mktime(datetime.datetime.now().timetuple()))}, indent=4))
                db.connClose()
                return 0
            if response.status != 200:
                log.info('Request HuaWei sendsms interface failed! HttpCode is' + str(response.status))
                self.write(json.dumps(
                    {'code': 'P000009',
                     'data': {'result': '1', 'desc': '请求华为短信接口失败,http状态码' + str(response.status)},
                     'message': 'OK',
                     'timestamp': int(time.mktime(datetime.datetime.now().timetuple()))}, indent=4))
            else:
                # self.write(content.decode('utf-8'))
                resulcode = json.loads(content.decode('utf-8'))['resultcode']
                description = json.loads(content.decode('utf-8'))['description']
                if resulcode == '0':
                    db.conn.commit()
                    log.info('create a new code and save to database success! The verifycode is ' + str(
                        code) + ' ,sql is ;' + sql)
                log.info('HuaWei response code is ' + resulcode + ' ,desc is: ' + description)
                self.write(json.dumps(
                    {'code': 'A000000', 'data': {'result': resulcode, 'desc': description},
                     'message': '请求华为短信接口成功,状态码' + resulcode,
                     'timestamp': int(time.mktime(datetime.datetime.now().timetuple()))}))

            db.connClose()