def outgoing(self): """Odjizdi Z pozadoveneho okrsku -> je outgoing""" if not self._outgoing: with db(cursor=True) as cur: cur.execute('SELECT count FROM commuting WHERE `from` = ?', (self.district,)) self._outgoing = cur.fetchone()['count'] return self._outgoing
def incoming(self): """Prijizdi DO pozadoveneho okrsku -> je incoming""" if not self._incoming: with db(cursor=True) as cur: cur.execute('SELECT count FROM commuting WHERE `to` = ?', (self.district,)) self._incoming = cur.fetchone()['count'] return self._incoming
def get_performance(x): SAMPLERATE = 44100 # Hz SAMPLES = 2**14 FREQ = 10000 # Hz AMPLITUDE = 1e-3 DURATION = SAMPLES / SAMPLERATE print("simulation duration: {:.2f}s".format(DURATION)) t = np.linspace(0, DURATION, SAMPLES) sin = np.sin(t * 2 * np.pi * FREQ) * AMPLITUDE input_samples = (sin + 1) / 2 from modulators.pwm import modulate modulated = modulate(input_samples, n_bits=x, oversampling_ratio=2) oversampled_rate = len(modulated) / DURATION print("oversampled rate is {:.2f}Mhz. oversampling factor is {}".format( (oversampled_rate / 10e6), oversampled_rate // SAMPLERATE)) changes = np.sum(modulated[:-1] != modulated[1:]) / 2 switching_rate = changes / DURATION print("average switching frequency is {:.2f}kHz".format(switching_rate / 1000)) from scipy.signal import decimate to_decimate = int(oversampled_rate / SAMPLERATE) decimated = modulated while to_decimate > 1: if to_decimate % 2 == 0: decimated = decimate(decimated, 2, ftype="iir", zero_phase=True) to_decimate /= 2 else: decimated = decimate(decimated, int(to_decimate), ftype="iir", zero_phase=True) to_decimate = 1 noise = decimated - input_samples noise_level = np.abs(np.average(noise)) return db(noise_level), db(np.average(input_samples) / noise_level)
def addTicketToOuter_WJT(config, bought): #print config;print print bought;exit() helper.getLog('thread start - ' + str(bought['id']), 'addTicketToService_WJT.log') dbObj = db.db() try: re = '更新out_app_no为receiving_code:' + bought['receiving_code'] except Exception, e: errMsg = "[Service_WJT - 71]" + str(Exception) + ":" + str(e) re = 'update out_app_no to receiving_code: ' + bought['receiving_code'] helper.getLog(errMsg, 'addTicketToService_WJT.Err.log')
def _get_db_data(self) -> None: """Vyplni raw data z databaze a seradi je""" if self._db_data: return with db(cursor=True) as cur: cur.execute( 'SELECT count, gender, age_start FROM age_groups WHERE district = ?', (self.district, )) self._db_data = cur.fetchall() self._db_data = sorted( [row for row in self._db_data if row['gender'] == self.gender], key=lambda x: (x['age_start'] is None, x['age_start']))
def addTicketToOuterHQ2(config, ticketBought): # print ticketBought # helper.getLog('访问addTicketToOuterHQ2了!!!', 'responseOutCode.HQ2.log') # helper.getLog(ticketBought['id'], 'responseOutCode.HQ2.log') dbObj = db.db() # 查询游客信息 userInfo = dbObj.select( "select user_id, name, mobile, id_number from t_user_identity_info where id = %d" % ticketBought['identity_info_id']) if userInfo == False or len(userInfo) < 1: visitorName = '散客' visitorMobile = '18523876001' else: userInfo = userInfo[0] visitorMobile = userInfo['mobile'] visitorName = userInfo['name'] if len(userInfo['mobile']) < 1: visitorMobile = '18523876001' if len(userInfo['name']) < 1: visitorName = '散客' timeNow = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) #调用日期yyyy-MM-dd HH:mm:ss #构造环企票务所需要的订单信息 postOrder = {} #回传订单及明细json数据 postOrder['Ptime'] = timeNow postOrder['Type'] = '00' #订单类型 00门票 03剧场票 order = {} #order信息 order['OrderNO'] = ticketBought['order_detail_id'] #Ota订单号 order['LinkName'] = visitorName #下单人姓名 order['LinkPhone'] = visitorMobile #下单人电话 order['CreateTime'] = timeNow #下单时间 detail = {} #Details信息 List<Detail> detail['OrderNO'] = ticketBought['order_detail_id'] #Ota订单号 detail['ItemID'] = ticketBought['order_detail_id'] #订单明细ID detail['ProductCode'] = config['productId_' + str(ticketBought['ticket_id'])] #门票编码 detail['ProductPrice'] = str(ticketBought['price']) #门票单价 detail['ProductCount'] = ticketBought['count'] #门票数量 # 时间格式转换 time_str = time.mktime( time.strptime(str(ticketBought['plan_time']), '%Y-%m-%d %H:%M:%S')) time_array = time.localtime(time_str) detail['productSDate'] = time.strftime("%Y-%m-%d", time_array) #游玩日期开始 yyyy-MM-dd detail['ProductEDate'] = time.strftime("%Y-%m-%d", time_array) #游玩日期结束 postOrder['Order'] = json.dumps(order) postOrder['Details'] = '[' + json.dumps(detail) + ']' postOrder['parkCode'] = config['parkCode'] # helper.getLog(postOrder['Order'], 'responseOutCode.HQ2.log') # helper.getLog(postOrder['Details'], 'responseOutCode.HQ2.log') processOuterHQ2(config, ticketBought, postOrder, 1)
def processOuterKZZN2(config, mallBought, data, processCount): dbObj = db.db() try: # 发起同步 url = config['url'] #http://123.11.226.80:8118/service.asmx url = helper.subStr(url, 'http://', '/service') host = helper.subStr(url, '', ':') port = int(helper.subStr(url, ':', '')) responseBody, re = sendDataToOuterKZZN2(host, port, data) reBody = helper.subStr(responseBody, '<nStatus>', '</nStatus>') # print responseBody # print re #成功同步 if '1' == reBody: cQrCode = helper.subStr(responseBody, '<cQrCode>', '</cQrCode>') cUrl = 'http://' + host + ':' + str(port) + helper.subStr( responseBody, '<cUrl>', '</cUrl>') cStatus = helper.subStr(responseBody, '<cStatus>', '</cStatus>') sql = "update t_mall_bought set out_app_code = 'KZZN2', out_app_no = '%s', dimen_code_path='%s', remark2='%s' where id = '%d'" % ( cQrCode, cUrl, cStatus, mallBought['id']) # sql = "update t_mall_bought set out_app_code = '_WJT', out_app_no = '%s' where id = '%d'" % (mallBought['receiving_code'], mallBought['id']) # sql = "update t_ticket_bought set out_app_code = 'KZZN2', temp_receiving_code = '%s', receiving_code = '%s', dimen_code_path='%s', remark2='%s' where id = %d" % (mallBought['receiving_code'], cQrCode, cUrl, cStatus, mallBought['id']) # print sql # print mallBought if not True == dbObj.update(sql): helper.getLog('update t_mall_bought error:' + sql, 'mall.kzzn2.log') # 发送消息 textMessage = '微景通验证码:' + mallBought[ 'receiving_code'] + ' \n票务验证码:' + cQrCode + ' \n购票张数:' + str( mallBought['buy_count']) + ' \n购票时间:' + str( mallBought['create_time']) time = int(helper.thisTime()) re = re + "\nsendMessageToUser:"******"%s \nPostData:%s" % (re, data) # print 'processCount:' + str(processCount) if processCount < 2: processCount += 1 processOuterKZZN2(config, mallBought, data, processCount) return else: re = "%s \nprocessCount:%s" % (re, str(processCount)) except Exception, e: re = str(Exception) + ":" + str(e) re = "%s \nPostData:%s" % (re, data)
def processOuterYBX(config, ticketBought, data, processCount): dbObj = db.db() send_time = time.time() # 错误时 记录信息 sql_error = "update t_ticket_bought set out_app_error='%s' where id = %d" % (1, ticketBought['id']) try: # 记录请求时间 # 发起同步 response = sendDataToOuterYBX(config, data) # 防止票务系统死锁 if -2 == response['resultcode']: for i in range(1, 10): time.sleep(i) response = sendDataToOuterYBX(config, data) if response != -2: break # 成功同步 if 0 == response['resultcode']: # 获取订单详细信息 orderId = response['orderid'] orderDetail = getOrderDetail(config, orderId) # 门票唯一ID ticketId = orderDetail[0]['ticketinnernumber'] # 获取filecode # cQrCodeFile = getQrcodeFile(config, ticketId, orderId) # 获取二维码 cQrCodeInfo = getQrcode(config, ticketId, orderId) # cQrCode = base64.b64decode(cQrCodeInfo['imagebase64']) # 获取二维码成功 if cQrCodeInfo['errcode'] == 0: cQrCode = cQrCodeInfo['imagebase64'] cQrCode = base64.b64encode(cQrCode) qrcodeImgUrl = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/getQrCode?data=' + cQrCode # 替换二维码 、订单号 、门票编码 sql = "update t_ticket_bought set out_app_code = 'YBX', temp_receiving_code = '%s', receiving_code = '%s', dimen_code_path='%s', remark2='%s', out_app_error='%s' where id = %d" % ( ticketBought['receiving_code'], ticketId, qrcodeImgUrl, orderId, 2, ticketBought['id']) try: re = dbObj.update(sql) if not True == re: helper.getLog(sql, 'addTicketToOuterYBX.UpdateTicketboughtlistErr.log') else: re = "%s \npostdata:%s" % (response, data) except Exception, e: dbObj.update(sql_error) re = "%s " % e # 获取二维码不成功 else: dbObj.update(sql_error) re = "%s \n %s \n postdata:%s" % ('获取二维码失败,订单已同步', cQrCodeInfo, data) else:
def processOuterYBX(config, mallBought, data, processCount): dbObj = db.db() # 错误记录 sql_error = "update t_mall_bought set out_app_error = '%s' where id = %d" % (1, mallBought['id']) try: # 记录请求时间 # helper.getLog(helper.now(), 'addTicketToOuterYBX.recordSendTime.log') # 发起同步 response = sendDataToOuterYBX(config, data) # 防止票务系统死锁 if -2 == response['resultcode']: for i in range(1, 10): time.sleep(i) response = sendDataToOuterYBX(config, data) if response != -2: break # 成功同步 if 0 == response['resultcode']: # 获取订单详细信息 orderId = response['orderid'] orderDetail = getOrderDetail(config, orderId) # 门票唯一ID ticketId = orderDetail[0]['ticketinnernumber'] # 获取filecode cQrCodeInfo = getQrcode(config, ticketId, orderId) # 获取二维码 cQrCode = cQrCodeInfo['imagebase64'] if (cQrCodeInfo['errcode'] == 0): cQrCode = base64.b64encode(cQrCode) qrcodeImgUrl = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/getQrCode?data=' + cQrCode # 替换二维码 sql = "update t_mall_bought set out_app_code = 'YBX', out_app_no = '%s', receiving_code = '%s', dimen_code_path='%s' , dimen_code_path='%s', out_app_error ='%s' where id = %d" % ( orderId, ticketId, qrcodeImgUrl, 2, mallBought['id']) re = dbObj.update(sql) if not True == re: helper.getLog(sql, 'addTicketToOuterYBX.UpdateTicketboughtlistErr.log') else: dbObj.update(sql_error) re = "%s \n %s \n PostData:%s" % ('获取二维码失败,订单已同步', cQrCodeInfo, data) # helper.getLog('获取二维码失败,同步失败', 'addTicketToOuterYBX.updateQRcode.log') else: dbObj.update(sql_error) re = "%s \npostdata:%s" % (response, data) except Exception, e: re = str(Exception) + ":" + str(e) re = "%s \nPostData:%s" % (re, data)
def processOuterHQ2(config, ticketBought, data, processCount): # helper.getLog('访问processOuterHQ2!!!', 'responseOutCode.HQ2.log') dbObj = db.db() orderInfo = {} orderInfo['merchantCode'] = config['account'] #获取环企票务的编码 orderInfo['postOrder'] = json.dumps(data).replace(' ', '') tempOrder = config['account'] + config['privateKey'] + orderInfo[ 'postOrder'] orderInfo['signature'] = base64.encodestring( helper.md5(tempOrder.strip()).upper()).strip() try: # 发起同步 response = sendDataToOuterHQ2(config, orderInfo) # # 防止同时发起请求造成唯一ID插入错误 # 成功同步 if '00' == response['ResultCode']: # 获取订单详细信息 orderNo = ticketBought['order_detail_id'] orderDetail = getOrderDetail(config, str(orderNo)) # 获取订单信息成功 if orderDetail['ResultCode'] == '00': result = json.loads(orderDetail['ResultJson'].replace( '[', '').replace(']', '')) for item in result: if 'ECode' == item: qrcodeData = result[item] break qrcodeImgUrl = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/?data=' + qrcodeData # 替换二维码 、订单号 、门票编码 sql = "update t_ticket_bought set out_app_code = 'HQ2', temp_receiving_code = '%s', receiving_code = '%s', dimen_code_path='%s', remark2='%s' where id = %d" % ( ticketBought['receiving_code'], qrcodeData, qrcodeImgUrl, qrcodeData, ticketBought['id']) try: re = dbObj.update(sql) if not True == re: helper.getLog( sql, 'addTicketToOuterHQ2.UpdateTicketboughtlistErr.log' ) else: re = "%s \npostdata:%s" % (response, orderInfo) except Exception, e: re = "%s " % e # 获取订单信息不成功 else: re = "%s \n %s \n postdata:%s" % ('获取订单详情失败,订单已占用', orderDetail, orderInfo) else:
def processOuterJYZY(config, ticketBought, data, processCount): dbObj = db.db() # 发起同步 dataOld = data data = buildParam(data, config['pkey'], 'createOrderForBeforePaySync') re = sendDataToOuterJYZY(config['url'], data) # redata, re = sendDataToOuterJYZY(config['url'], None) try: code = helper.subStr(re, '<code>', '</code>') # print responseBody # print re #成功同步 if '1000' == code: re1 = re partnerorderId = helper.subStr(re, '<partnerorderId>', '</partnerorderId>') re, postData = payTicketToOuterJYZY(config, ticketBought, partnerorderId) # print partnerorderId;exit() code = helper.subStr(re, '<code>', '</code>') if '1000' == code: qrcodeUrl = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/index/?data=' + str(ticketBought['order_detail_id']) sql = "update t_ticket_bought set out_app_code = 'JYZY', temp_receiving_code = '%s', receiving_code = '%s', dimen_code_path='%s' where id = %d" % (ticketBought['receiving_code'], partnerorderId, qrcodeUrl, ticketBought['id']) # print sql if not True == dbObj.update(sql): helper.getLog(sql, 'addTicketToOuterJYZY.UpdateTicketboughtlistErr.log') else: re = "re1:%s \nre2:%s \nPostData1:%s \nPostData2:%s" % (re1, re, data, postData) else: re = "%s \nPostData:%s" % (re, data) print 'processCount:' + str(processCount) if processCount < 2: processCount += 1 processOuterJYZY(config, ticketBought, dataOld, processCount) return else: re = "%s \nprocessCount:%s" % (re, str(processCount)) except Exception, e: re = str(Exception) + ":" + str(e) re = "%s \nPostData:%s" %(re, data)
def addMallToOuter_WJT(config, productConfig, mallBought): # print config;print productConfig;print mallBought;exit() dbObj = db.db() re = '' try: productConfig = dbObj.selectOne( 'select id, out_code from t_mall_product where id = %d' % mallBought['mall_product_id']) if productConfig['out_code'] == '_WJT': re = '更新out_app_no为receiving_code:' + mallBought['receiving_code'] sql = "update t_mall_bought set out_app_code = '_WJT', out_app_no = '%s' where id = '%d'" % ( mallBought['receiving_code'], mallBought['id']) if not True == dbObj.update(sql): re += '(更新出错)' helper.getLog( sql, 'addMallToService_WJT.UpdateMallboughtlistErr.log') else: re = '产品没有配置第三方系统代码。不处理。' except Exception, e: re = str(Exception) + ":" + str(e)
def findOrders(serviceUrl, sql, type): # global dbObj dbObj = db.db() orderList = dbObj.select(sql) # print '==========' # print helper.now() # print sql # print orderList # print len(orderList) # helper.getLog( 'len(orderList)['+ str(type) +']:' + str(len(orderList)) + ' -- ' + sql, 'serviceCheckPay.log' ) ts = [] #线程列表 for order in orderList: if not order['pay_status'] == 0: order['confirmDo'] = 1 t = threading.Thread(target=reBuyDo, args=( serviceUrl, order, sql, )) t.start() ts.append(t) for t in ts: t.join()
def serviceInit(types): # print types; #启动服务 serviceUrl = helper.confGet('host', 'commonService') + 'Order/Index/reBuyDo' now = helper.now(-3600 * 2, '%Y-%m-%d %H:00:00') orderId = 0 paybackId = 0 ids = {} # print now; test = 0 while True: ts = [] #线程列表 #连接数据库 # global dbObj dbObj = db.db() # 不用每次循环都查询配置 if not now == helper.now(-3600 * 1, '%Y-%m-%d %H:00:00'): if test == 1: now = helper.now(-3600 * 20, '%Y-%m-%d %H:00:00') #改变这个时间,重启,则重新开始扫描 else: now = helper.now(-3600 * 1, '%Y-%m-%d %H:00:00') #改变这个时间,重启,则重新开始扫描 # print now; orderId = dbObj.getValue( 'SELECT id FROM t_order WHERE create_time > "%s" ORDER BY id ' % (now), 'id') if orderId == None: orderId = dbObj.getValue( 'SELECT id FROM t_order WHERE 1=1 ORDER BY id DESC limit 0, 1', 'id') if orderId == None: orderId = 0 paybackId = dbObj.getValue( 'SELECT id FROM t_payback WHERE create_time > "%s" ORDER BY id ' % (now), 'id') if paybackId == None: paybackId = dbObj.getValue( 'SELECT id FROM t_payback WHERE 1=1 ORDER BY id DESC limit 0, 1', 'id') if paybackId == None: paybackId = 0 # print orderId; print paybackId; helper.getLog('orderId:%d -- paybackId: %d' % (orderId, paybackId), 'serviceCheckPay.log') for type in types: ids[type] = dbObj.getValue( "SELECT id FROM %s WHERE create_time > '%s' ORDER BY id " % (types[type], now), 'id') if ids[type] == None: ids[type] = dbObj.getValue( "SELECT id FROM %s WHERE 1 =1 ORDER BY id DESC limit 0, 1" % (types[type]), 'id') if ids[type] == None: ids[type] = 0 # print ids; for type in types: # print str(type) + '/' + types[type] status = '1' if test == 1: status = '1, 9' sql = ' '.join([ "SELECT id AS orderId, pay_status, type, client_id AS clientId, create_time FROM t_order WHERE id > %d AND type = %d AND status in (%s) AND pay_time BETWEEN '%s' AND '%s' " % (orderId, type, status, now, helper.now(-5)), "AND id IN ( SELECT order_id FROM t_payback WHERE id > %d AND order_id NOT IN ( SELECT order_id FROM %s WHERE id >= %d ) ) " % (paybackId, types[type], ids[type]), "ORDER BY id DESC LIMIT 0, 10" ]) # print sql t = threading.Thread(target=findOrders, args=( serviceUrl, sql, type, )) t.start() ts.append(t) for t in ts: t.join() time.sleep(10) scanner.dump_all_objects('/logs/python/mem.log')
def addTicketToOuterJKB(config, ticketBought): # global dbObj # dbObj = globalVar.getDbObj() dbObj = db.db() #查询游客信息 # userInfo = '' userInfo = dbObj.select( "select user_id, name, mobile, id_number from t_user_identity_info where id = %d" % ticketBought['identity_info_id']) # userInfo = [] # userInfo.append({ # 'name': '微景通', # 'mobile' : '18523876001' # }) if userInfo == False or len(userInfo) < 1: visitorName = 'weijingtongVisitor' visitorMobile = '18523876001' else: userInfo = userInfo[0] visitorMobile = userInfo['mobile'] ## visitorName = userInfo['user_id'] visitorName = userInfo['name'] visitorName = urllib.quote(visitorName.encode('utf-8')) # visitorName = repr(visitorName.decode('UTF-8'))[2:-1] ## visitorName = '\u5f20\u8001\u5927' ## visitorName = urllib.urlencode({1:visitorName})[2:] # visitorName = 'wjtVisitor' ticketName = dbObj.getValue( "select name from t_ticket where id = %d" % ticketBought['ticket_id'], 'name') ticketName = urllib.quote(ticketName.encode('utf-8')) # ticketName = '成人票' # ticketName = repr(ticketName.decode('UTF-8'))[2:-1][0:48] # ticketName = 'test' visitPerson = {} visitPerson['visitName'] = visitorName visitPerson['visitMobile'] = visitorMobile visitPerson['credentials'] = userInfo['id_number'] visitPerson['credentialsType'] = 'Idcard' body = {} body['productName'] = ticketName body['contactMobile'] = visitorMobile body['contactName'] = visitorName body['orderPrice'] = str(round(ticketBought['price'], 2)) body['orderQuantity'] = ticketBought['count'] body['orderRemark'] = 'weijingtong' body['outOrderId'] = ticketBought['order_detail_id'] body['resourceId'] = config['resourceId_' + str(ticketBought['ticket_id'])] body['sellPrice'] = str(round(ticketBought['list_price'], 2)) body['useDate'] = str(ticketBought['plan_time'])[0:10] body['visitPerson'] = [visitPerson] data = {} data['body'] = body data['appKey'] = config['AppKey'] data = json.dumps(data, ensure_ascii=False) # data = json.dumps(data) # print data # exit() # time = str(helper.thisTime())[0:10] + str(int(str(helper.thisTime())[12:])*100) time = str(int(round(helper.thisTime() * 1000))) # time = '1' print config['AppKey'] + data + time + config['SecretKey'] sign = helper.md5(config['AppKey'] + data + time + config['SecretKey']).upper().strip() # sign = '1' httpHeader = { 'Content-Type': 'application/json;charset=utf-8', 'APPKEY': config['AppKey'], 'TIMESTAMP': time, 'SIGN': sign, } # print httpHeader; print sign # exit() try: # 发起同步 re = helper.httpPost(config['url'] + '?method=createOrder', data, httpHeader) reBody = json.loads(re) # print reBody ;exit() #成功同步 if 200 == reBody['rspCode']: #支付定单 body = {} body['orderId'] = outOrderId = reBody['body']['orderId'] body['paymentSerialno'] = ticketBought['id'] data2 = {} data2['body'] = body data2['appKey'] = config['AppKey'] data2 = json.dumps(data2) # print data2;exit() sign = helper.md5(config['AppKey'] + data2 + time + config['SecretKey']).upper().strip() httpHeader = { 'Content-Type': 'application/json;charset=utf-8', 'APPKEY': config['AppKey'], 'TIMESTAMP': time, 'SIGN': sign, } re2 = helper.httpPost(config['url'] + '?method=payOrder', data2, httpHeader) reBody = json.loads(re2) print reBody if 200 == reBody['rspCode']: re = re + "\n\n" + re2 print re #生成二维码 qrcodeImg = reBody['body']['qrcodeUrl'] sql = "update t_ticket_bought set out_app_code = 'JKB', temp_receiving_code = '%s', receiving_code='%s', dimen_code_path = '%s', remark2 = '%s' where id = %d" % ( ticketBought['receiving_code'], reBody['body']['eticket'], qrcodeImg, '{"outOrderId":"' + outOrderId + '"}', ticketBought['id']) print sql if not True == dbObj.update(sql): helper.getLog( sql, 'addTicketToOuterJKB.UpdateTicketboughtlistErr.log') else: re = "%s\nPostData1:%s\n\n%s\nPostData2:%s" % (re, data, re2, data2) print re pass else: re = "%s \nPostData:%s\nPostHead:%s" % (re, data, json.dumps(httpHeader)) pass except Exception, e: re = str(Exception) + ":" + str(e) re = "%s \nPostData:%s" % (re, data)
def serviceInit(codes): #连接数据库 dbObj = db.db() # try: # dbObj = globalVar.getDbObj() #数据库链接 # except: # dbObj = db.db() # globalVar.setDbObj(dbObj) ts = [] #线程列表 #初始化所有code的maxBoughtId为0 # maxBoughtId = dbObj.getValue("select id from t_mall_bought order by id desc ", 'id') # globalVar.setMaxBoughtId(maxBoughtId) globalVar.setMaxBoughtId('0') globalVar.setMaxBoughtId('6159') ## print maxBoughtId #为了减少数据库查询,初始化时查询出查询商家列表。新添加商家后,需要重启本服务,否则无法监听添加新的。 # clientList = dbObj.select("select client_id, content, code from t_out_app_config where code in('%s')" % "','".join(codes)) #启动服务 i = -1 while True: print i, globalVar.getMaxBoughtId(), '========' # 不用每次循环都查询配置 i += 1 if i > 100: i = 0 if i % 4 == 0: #为了商家修改了配置信息时立即生效,改为每次查询 clientList = dbObj.select( "select client_id, content, code, type from t_mall_out_config where code in('%s')" % "','".join(codes)) clientList2 = dbObj.select( "select client_id, content, code, type from t_out_app_config") #按code给商家列表分组 clientIds = [] #client id clientCodes = {} # clientConfigTypes = {} # clientConfigs = {} #client config #分别合并商城和门票的outconfig,商城优先,可覆盖门票 for client in clientList2: clientCodes[str(client['client_id'])] = client['code'] clientConfigTypes[str(client['client_id'])] = client['type'] clientIds.append(str(client['client_id'])) if client['content'] and (client['type'] == 1 or client['type'] == 2): # print client clientConfigs[str(client['client_id'])] = json.loads( client['content']) for client in clientList: clientCodes[str(client['client_id'])] = client['code'] clientConfigTypes[str(client['client_id'])] = client['type'] clientIds.append(str(client['client_id'])) if client['content'] and (client['type'] == 1 or client['type'] == 2): clientConfigs[str(client['client_id'])] = json.loads( client['content'])[client['code']] # print clientCodes; print clientConfigTypes; exit() #查询product的配置 sql = ' '.join([ 'select id, client_id, out_code, out_config', 'from t_mall_product', "where is_out_app = 1 and out_code in( '%s')" % ("','".join(codes)) ]) mallProductList = dbObj.select(sql) mallProductConfigs = {} #产品的配置信息 for mallProduct in mallProductList: if mallProduct['out_code'] == clientCodes[str( mallProduct['client_id'])]: try: mallProductConfigs[mallProduct['client_id']][ mallProduct['id']] = json.loads( mallProduct['out_config']) except: mallProductConfigs[mallProduct['client_id']] = {} mallProductConfigs[mallProduct['client_id']][ mallProduct['id']] = json.loads( mallProduct['out_config']) # print mallProductConfigs;exit() #查询已购列表 now = helper.now(-3600 * 24 * 160) # now = helper.now(-60) sql = ' '.join([ "select id, client_id, mall_product_id, buy_count, order_id, order_detail_id, price, total_pay_price, identity_info_id, create_time, plan_time, remark, remark2, receiving_code ", # "select id, client_id", "from t_mall_bought ", "where id > '%s' and status = 2 and out_app_code is null and create_time > '%s' and client_id in (%s) " % (globalVar.getMaxBoughtId(), now, ','.join(clientIds)), # "where id = 6778", "order by id asc limit 0, 100", # limit 0, 50 ]) mallBoughtList = dbObj.select(sql) # print sql; # print mallBoughtList; # exit() #把最大的id记录下来 try: maxBoughtId = mallBoughtList[-1]['id'] globalVar.setMaxBoughtId(maxBoughtId) # print maxBoughtIds['YMXY'] except: pass #按client_id给mallBoughtList分组 mallBoughts = {} if len(mallBoughtList) > 0: for mallBought in mallBoughtList: try: mallBoughts[mallBought['client_id']].append(mallBought) except: mallBoughts[mallBought['client_id']] = [] mallBoughts[mallBought['client_id']].append(mallBought) # print mallBoughts;exit() # print clientIds;exit() # print clientConfigs;exit() clientIds = ['1257'] #循环检查每个商家 for clientId in clientIds: # try: code = clientCodes[clientId] try: mallProductConfig = mallProductConfigs[int(clientId)] except: mallProductConfig = {} try: mallBoughtList = mallBoughts[int(clientId)] except: mallBoughtList = None # print code # print clientId # print mallBoughtList # print mallProductConfig # print clientConfigTypes if mallBoughtList: t = threading.Thread(target=runService, args=( clientConfigs[clientId], mallProductConfig, mallBoughtList, code, clientConfigTypes[clientId], )) t.start() ts.append(t) # except: # pass for t in ts: t.join() # print globalVar.getMaxBoughtId() #每x秒执行一次 time.sleep(30)
def serviceInit(): # 连接数据库 dbObj = db.db() # 初始化所有code的maxId为0 # maxId = dbObj.getValue("select id from aaa order by id desc ", 'id') # globalVar.setMaxId(maxId) globalVar.setMaxId(0) # print maxId # 启动服务 while True: ts = [] #线程列表 maxId = globalVar.getMaxId() print maxId print helper.now() # 查询已购门票列表 now = helper.now(-3600 * 1) # now = helper.now(-60) from `t_qrcode_temporary_record` where status = 2 and type = 167 sql = ' '.join([ "select * ", # "select id, client_id", "from t_qrcode_temporary_record ", "where id > %d and status = 2 and type = 167 and create_time > '%s'" % (maxId, now), # "where id > '%d' " % maxId, # "where id = 802010", "order by id asc limit 0, 20", # limit 0, 50 ]) recordList = dbObj.select(sql) # print sql; # print recordList;exit() #查询二维码的scene_id是否属于拉粉宝 sceneIds = [] for record in recordList: sceneIds.append(str(record['scene_id'])) if len(sceneIds) > 0: sql = "select id, client_id, scene_id from t_poster_get_fans_user where scene_id in (%s)" % ','.join( sceneIds) fansUserList = dbObj.select(sql) # print fansUserList; sceneIds = {} for fans in fansUserList: sceneIds[fans['scene_id']] = 1 #把最大的id记录下来 try: maxId = recordList[-1]['id'] globalVar.setMaxId(maxId) # print maxIds['YMXY'] except: pass for record in recordList: # print record try: #拉粉宝的情况 if record['scene_id'] in sceneIds: t = threading.Thread(target=processDoGetFans, args=(record, )) #普通海报接力 else: t = threading.Thread(target=processDoPoster, args=(record, )) t.start() ts.append(t) except: pass # for t in ts : # t.join() # print globalVar.getMaxId() # 每x秒执行一次 # print ' ==== ' + helper.now() time.sleep(5)
def addTicketToOuterKZZN2(config, mallBought): # global dbObj # dbObj = globalVar.getDbObj() dbObj = db.db() #查询游客信息 userInfo = False if mallBought['identity_info_id'] > 0: userInfo = dbObj.select( "select user_id, name, mobile, id_number from t_user_identity_info where id = %d" % mallBought['identity_info_id']) # userInfo = [] # userInfo.append({ # 'name': '微景通', # 'mobile' : '18523876001' # }) if userInfo == False or len(userInfo) < 1: visitorName = '散客' visitorMobile = '18523876001' idNumber = '110101199003075496' else: userInfo = userInfo[0] visitorMobile = userInfo['mobile'] visitorName = userInfo['name'] idNumber = userInfo['id_number'] # visitorName = repr(visitorName.decode('UTF-8'))[2:-1] # visitorName = visitorName.decode('UTF-8') # visitorName = 'wjtVisitor' ticketName = dbObj.getValue( "select name from t_mall_product where id = %d" % mallBought['mall_product_id'], 'name') ticketName = ticketName.decode('UTF-8')[0:10] # ticketName = 'chengrenpiao' # ticketName = '成人票' planDate = '' if mallBought['plan_time']: planDate = str(mallBought['plan_time'])[0:10] orderInfo = [ { 'cid': config['cid'] }, { 'ccipher': config['ccipher'] }, # {'CEntrypriseCode': config['CEntrypriseCode']}, { 'cOrderID': mallBought['order_number'] }, { 'nTicketType': config['mall_nTicketType_' + str(mallBought['mall_product_id'])] }, { 'cTicketType': ticketName }, { 'dDateIn': planDate }, { 'cOtaSource': '微景通' }, { 'nHumanNum': mallBought['buy_count'] }, { 'cPayType': 'weixin' }, { 'cCustName': visitorName[0:24] }, { 'cTel': visitorMobile }, # {'cSecID': str(userInfo['id_number']) + 'X'}, { 'cSecID': idNumber }, ] data = helper.dict2xml('OnWebOrder', orderInfo, 'xmlns="http://127.0.0.1/WebSellWx/"') data = ''.join([ '<?xml version="1.0" encoding="utf-8"?>', '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">', '<soap:Body>%s</soap:Body>' % data, '</soap:Envelope>' ]) # print data; # exit(); processOuterKZZN2(config, mallBought, data, 1)
def serviceInit(codes): #连接数据库 dbObj = db.db() # try: # dbObj = globalVar.getDbObj() #数据库链接 # except: # dbObj = db.db() # globalVar.setDbObj(dbObj) ts = [] #线程列表 #初始化所有code的maxBoughtId为0 # maxBoughtId = dbObj.getValue("select id from t_ticket_bought order by id desc ", 'id') # globalVar.setMaxBoughtId(maxBoughtId) globalVar.setMaxBoughtId(320672) # print maxBoughtId #为了减少数据库查询,初始化时查询出查询商家列表。新添加商家后,需要重启本服务,否则无法监听添加新的。 # clientList = dbObj.select("select client_id, content, code from t_out_app_config where code in('%s')" % "','".join(codes)) #启动服务 i = -1 while True: maxBoughtId = globalVar.getMaxBoughtId() print i, maxBoughtId helper.getLog("%i -- maxBoughtId:%s" % (i, maxBoughtId), 'serviceTicket.log') # 不用每次循环都查询配置 i += 1 if i > 100: i = 0 if i % 4 == 0: #为了商家修改了门票配置信息时立即生效,改为每次查询 clientList = dbObj.select( "select client_id, content, code from t_out_app_config where code in('%s')" % "','".join(codes)) #按code给商家列表分组 clientIds = [] #client id clientCodes = {} # clientConfigs = {} #client config for client in clientList: clientCodes[str(client['client_id'])] = client['code'] clientIds.append(str(client['client_id'])) clientConfigs[str(client['client_id'])] = json.loads( client['content']) # print clientCodes;exit() #查询已购门票列表 now = helper.now(-3600 * 24 * 1) # now = helper.now(-60) sql = ' '.join([ "select id, client_id, ticket_id, count, order_id, order_detail_id, price, list_price, identity_info_id, create_time, plan_time, receiving_code ", # "select id, client_id", "from t_ticket_bought ", "where id > '%d' and status = 1 and out_app_code is null and create_time < '%s' and create_time > '%s' and client_id in (%s) " % (globalVar.getMaxBoughtId(), helper.now(-20), now, ','.join(clientIds)), # "where order_detail_id = 697201", "order by id asc limit 0, 20", # limit 0, 50 ]) ticketBoughtList = dbObj.select(sql) #print sql; print ticketBoughtList; # exit() #把最大的id记录下来 try: maxBoughtId = ticketBoughtList[-1]['id'] globalVar.setMaxBoughtId(maxBoughtId) # print maxBoughtIds['YMXY'] except: pass #按client_id给ticketBoughtList分组 ticketBoughts = {} if len(ticketBoughtList) > 0: for ticketBought in ticketBoughtList: try: ticketBoughts[ticketBought['client_id']].append( ticketBought) except: ticketBoughts[ticketBought['client_id']] = [] ticketBoughts[ticketBought['client_id']].append( ticketBought) # print ticketBoughts;exit() # print clientIds;exit() #循环检查每个商家 for clientId in clientIds: # print clientId try: code = clientCodes[clientId] t = threading.Thread(target=runService, args=( clientConfigs[clientId], ticketBoughts[int(clientId)], code, )) t.start() ts.append(t) except: pass for t in ts: t.join() # print globalVar.getMaxBoughtId() #每x秒执行一次 time.sleep(60)
}, { 'id': 2, 'description': u'Our second algorithm' }, { 'id': 3, 'description': u'Canny Detection algorithm' }, { 'id': 4, 'description': u'google cloud vision API' }, { 'id': 5, 'description': u'clarifai API' }] # init db = db() vision = googleVision() reCaptcha = recaptcha() ocr = ocr() config = GetConfig() uri = config.Web_host + 'upload/' main = main_captcha() benny = benny_captcha() canny = canny_captcha() captcha_methods = [main, benny, canny] @app.route('/BD_Project/api/v1.0/methods', methods=['GET']) def get_methods(): return jsonify({'methods': methods})
def addMallToOuterXiRuan(config, productConfig, mallBought): # print config;print productConfig;print mallBought;exit() # conf = ConfigParser.ConfigParser() # conf.read("%s/config/config.ini" % sys.path[0]) # print "%s/config/config.ini" % sys.path[0] url = helper.confGet( 'host', 'commonService') + 'OuterApp/XiRuan/login/?clientId=' + str( mallBought['client_id']) print url helper.getLog(url) session = json.loads(helper.httpGet(url)) if not session['status']: helper.getLog(session['data']) return # print session;exit() #查询游客信息 # userInfo = '' # dbObj = globalVar.getDbObj() dbObj = db.db() userInfo = dbObj.select( "select user_id, name, mobile, id_number from t_user_identity_info where id = %d" % mallBought['identity_info_id']) if userInfo == False or len(userInfo) < 1: visitorName = 'weijingtongVisitor' visitorMobile = '18523876001' else: userInfo = userInfo[0] visitorMobile = userInfo['mobile'] visitorName = userInfo['user_id'] visitorName = userInfo['name'] # visitorName = 'visitor' visitorName = repr(visitorName.decode('UTF-8'))[2:-1] # visitorName = '\u5f20\u8001\u5927' ## visitorName = urllib.urlencode({1:visitorName})[2:] #使用日期 useDate = mallBought['remark2'].split(',') data = '''{ "sign":"3E365195E5A5CFA2ABC5F5B302182F73", "ts":%s, "session":"%s", "hotelid":"%s", "appkey":"%s", "loc":"zh_CN", "method":"xmsopen.reservation.xopsavereservation", "ver":"1.0.0", "params":[ { "rmtype":"%s", "holdname":"%s", "rmnum":"%s", "hotelid":"%s", "contact_name":"%s", "arr":"%s", "mobile":"%s", "ratecode":"%s", "sex":"", "rate":"%s", "contact_mobile":"%s", "name":"%s", "dep":"%s", "gstno":"%s", "ref":"weixin", "channel":"weixin", "restype":"%s" } ], "cmmcode":"%s" }''' % (str(helper.thisTime()).replace( '.', ''), session['data'], config['hotelid'], config['appkey'], productConfig['rmtype'], visitorName, mallBought['buy_count'], productConfig['hotelid'], visitorName, useDate[0], visitorMobile, productConfig['ratecode'], mallBought['price'], visitorMobile, visitorName, useDate[1], mallBought['buy_count'], productConfig['restype'], config['cmmcode']) # print data re = re2 = '' try: if mallBought['remark']: outappCodes = mallBought['remark'].split(',') rsvno = outappCodes[0] accnt = outappCodes[1] res = {} res['success'] = True else: re = helper.httpPost(config['host'], data) # print re #成功同步 res = json.loads(re) if res['success'] == True: rsvno = res['results'][0]['rsvno'] accnt = res['results'][0]['accnt'] sql = "update t_mall_bought set remark = '%s,%s' where id = '%d'" % ( rsvno, accnt, mallBought['id']) if not True == dbObj.update(sql): helper.getLog( sql, 'addMallToOuterXiRuan.UpdateMallboughtlistErr.log') # print res if res['success'] == True: data2 = '''{ "sign":"3E365195E5A5CFA2ABC5F5B302182F73", "ts":%s, "session":"%s", "hotelid":"%s", "appkey":"%s", "loc":"zh_CN", "method":"xmsopen.accounts.xopdopaymentaccount", "ver":"1.0.0", "params":[ { "pay_money":"%s", "pay_code":"%s", "payno":"%s", "remark":"%s", "hotelid":"%s", "rsvno":"%s", "accnt":"%s" } ], "cmmcode":"%s" }''' % (str(helper.thisTime()).replace( '.', ''), session['data'], config['hotelid'], config['appkey'], mallBought['total_pay_price'], '9034', mallBought['order_detail_id'], 'weixin order', productConfig['hotelid'], rsvno, accnt, config['cmmcode']) # print data2 try: re2 = helper.httpPost(config['host'], data2) # print re2 #成功同步 res = json.loads(re2) if res['success'] == True: sql = "update t_mall_bought set out_app_code = 'XiRuan', out_app_no = '%s' where id = '%d'" % ( rsvno, mallBought['id']) if not True == dbObj.update(sql): helper.getLog( sql, 'addMallToOuterXiRuan.UpdateMallboughtlistErr.log') #失败后,也更新一下bought,不再重复 else: sql = "update t_mall_bought set out_app_code = 'XiRuan' where id = '%d'" % mallBought[ 'id'] if not True == dbObj.update(sql): helper.getLog( sql, 'addMallToOuterXiRuan.UpdateMallboughtlistErr.log') re2 = "resmsg2:%s \npostdata2:%s" % (re2, data2) except Exception, e: re2 = str(Exception) + ":" + str(e) re2 = "errmsg2:%s \npostdata2:%s" % (re2, data2) pass #失败后,也更新一下bought,不再重复 else:
def addTicketToOuterDK(config, ticketBought): # global dbObj # dbObj = globalVar.getDbObj() dbObj = db.db() #查询游客信息 # userInfo = '' userInfo = dbObj.select( "select user_id, name, mobile, id_number from t_user_identity_info where id = %d" % ticketBought['identity_info_id']) # userInfo = [] # userInfo.append({ # 'name': '微景通', # 'mobile' : '18523876001' # }) if userInfo == False or len(userInfo) < 1: visitorName = 'weijingtongVisitor' visitorMobile = '18523876001' else: userInfo = userInfo[0] visitorMobile = userInfo['mobile'] ## visitorName = userInfo['user_id'] visitorName = userInfo['name'] visitorName = repr(visitorName.decode('UTF-8'))[2:-1] ## visitorName = '\u5f20\u8001\u5927' ## visitorName = urllib.urlencode({1:visitorName})[2:] # visitorName = 'wjtVisitor' ticketName = dbObj.getValue( "select name from t_ticket where id = %d" % ticketBought['ticket_id'], 'name') # ticketName = '成人票' ticketName = repr(ticketName.decode('UTF-8'))[2:-1][0:48] # ticketName = 'test' Order = {} Order['OrderNO'] = str(ticketBought['order_detail_id']) Order['LinkName'] = visitorName Order['LinkPhone'] = visitorMobile Order['LinkICNO'] = userInfo['id_number'] Order['TotalAmount'] = str( round(ticketBought['price'] * ticketBought['count'], 2)) Order['CreateTime'] = str(ticketBought['create_time']) Visitor = {} Visitor['VisitorName'] = visitorName Visitor['VisitorPhone'] = visitorMobile Visitor['VisitorICNO'] = userInfo['id_number'] Details = {} Details['OrderNO'] = ticketBought['order_detail_id'] Details['ItemID'] = ticketBought['order_detail_id'] Details['ProductCode'] = config['ProductCode_' + str(ticketBought['ticket_id'])] Details['ProductID'] = config['ProductID_' + str(ticketBought['ticket_id'])] Details['ProductPackID'] = config['ProductPackID_' + str(ticketBought['ticket_id'])] Details['ProductMarketPrice'] = str(round(ticketBought['list_price'], 2)) Details['ProductPrice'] = str(round(ticketBought['price'], 2)) Details['ProductSellPrice'] = str(round(ticketBought['price'], 2)) Details['ProductCount'] = ticketBought['count'] Details['ProductSDate'] = str(ticketBought['plan_time'])[0:10] Details['ProductEDate'] = str(ticketBought['plan_time'])[0:10] Details['Visitor'] = json.dumps(Visitor) postOrder = {} postOrder['Ptime'] = helper.now() postOrder['parkCode'] = config['parkCode'] postOrder['timestamp'] = helper.now() postOrder['Order'] = json.dumps(Order) postOrder['Details'] = json.dumps([Details]) # print postOrder # print json.dumps(postOrder) postOrder = json.dumps(postOrder) # exit() sign = base64.encodestring( helper.md5(config['merchantCode'] + config['privateKey'] + postOrder + str(int(helper.thisTime()))).upper()).strip() # sign = '1' # print sign;exit() data = '''<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <OrderOccupies xmlns="http://tempuri.org/"> <merchantCode>%s</merchantCode> <postOrder>%s</postOrder> <signature>%s</signature> </OrderOccupies> </soap:Body> </soap:Envelope>''' % (config['merchantCode'], postOrder, sign) # print data; # exit(); try: # 发起同步 ''' responseBody = helper.httpPost(config['url'] + '/OrderOccupies', data, {'Content-Type' : 'application/x-www-form-urlencoded'}) ''' url = config['url'] #http://123.11.226.80:8118/service.asmx # url = 'http://112.74.131.57:10006/service.asmx' host = helper.subStr(url, 'http:/', 'service') host = helper.subStr(host, '/', ':') port = helper.subStr(url, '://', 'service') port = helper.subStr(port, ':', '/') # print host;exit() #占用定单 res = helper.webservice(host, int(port), "/service.asmx", data, "http://tempuri.org/OrderOccupies", 0) responseBody = res[0] re = res[1] reBody = json.loads( helper.subStr(responseBody, '<OrderOccupiesResult>', '</OrderOccupiesResult>')) # print reBody #成功同步 if '00' == reBody['ResultCode']: #支付定单 parameters = {} parameters['otaOrderNO'] = str(ticketBought['order_detail_id']) parameters['parkCode'] = config['parkCode'] parameters['timestamp'] = helper.now() parameters = json.dumps(parameters) sign = base64.encodestring( helper.md5(config['merchantCode'] + config['privateKey'] + parameters + str(int(helper.thisTime()))).upper()).strip() data2 = '''<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <OrderFinish xmlns="http://tempuri.org/"> <otaCode>%s</otaCode> <parameters>%s</parameters> <signature>%s</signature> </OrderFinish> </soap:Body> </soap:Envelope>''' % (config['merchantCode'], parameters, sign) res = helper.webservice(host, int(port), "/service.asmx", data2, "http://tempuri.org/OrderFinish", True) responseBody2 = res[0] re2 = res[1] reBody = json.loads( helper.subStr(responseBody2, '<OrderFinishResult>', '</OrderFinishResult>')) # print reBody if '00' == reBody['ResultCode']: re = re + "\n\n" + re2 #生成二维码 resultJson = json.loads(reBody['ResultJson'])[0] qrcodeImg = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/?data=' + resultJson[ 'ECode'] sql = "update t_ticket_bought set out_app_code = 'DK', temp_receiving_code = '%s', receiving_code='%s', dimen_code_path = '%s' where id = %d" % ( ticketBought['receiving_code'], resultJson['ECode'], qrcodeImg, ticketBought['id']) # print sql if not True == dbObj.update(sql): helper.getLog( sql, 'addTicketToOuterDK.UpdateTicketboughtlistErr.log') else: re = "%s\nPostData1:%s\n\n%s\nPostData2:%s" % (re, data, re2, data2) pass else: re = "%s \nPostData:%s" % (re, data) pass except Exception, e: re = str(Exception) + ":" + str(e) re = "%s \nPostData:%s" % (re, data)
def addTicketToOuterKZZN(config, ticketBought): # global dbObj # dbObj = globalVar.getDbObj() dbObj = db.db() #查询游客信息 # userInfo = '' userInfo = dbObj.select("select user_id, name, mobile, id_number from t_user_identity_info where id = %d" % ticketBought['identity_info_id']) # userInfo = [] # userInfo.append({ # 'name': '微景通', # 'mobile' : '18523876001' # }) if userInfo == False or len(userInfo) < 1: visitorName = 'weijingtongVisitor' visitorMobile = '18523876001' else: userInfo = userInfo[0] visitorMobile = userInfo['mobile'] ## visitorName = userInfo['user_id'] visitorName = userInfo['name'] visitorName = repr(visitorName.decode('UTF-8'))[2:-1] ## visitorName = '\u5f20\u8001\u5927' ## visitorName = urllib.urlencode({1:visitorName})[2:] # visitorName = 'wjtVisitor' ticketName = dbObj.getValue("select name from t_ticket where id = %d" % ticketBought['ticket_id'], 'name') # ticketName = '成人票' ticketName = repr(ticketName.decode('UTF-8'))[2:-1][0:48] # ticketName = 'test' orderInfo = [ {'cid': config['cid']}, {'ccipher': config['ccipher']}, {'cOrder': ticketBought['order_detail_id']}, {'nHuman': ticketBought['count']}, {'cName': visitorName[0:24]}, {'cPhone': visitorMobile}, {'nTicketType': config['nTicketType_' + str(ticketBought['ticket_id'])]}, {'cTicketType': ticketName}, {'dDateIn': str(ticketBought['plan_time'])[0:10]}, {'cQrID': ticketBought['receiving_code']}, {'nCustType': 1}, {'cip': socket.gethostbyname(socket.gethostname())}, {'fMoney': ticketBought['price']}, {'cPayType': 'weixin'}, ] data = helper.dict2xml('OnPreSellOrder', orderInfo, 'xmlns="http://localhost/WebSell/"') data = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body>%s</soap:Body></soap:Envelope>' % data # print data; # exit(); try: # 发起同步 url = config['url'] #http://123.11.226.80:8118/service.asmx host = helper.subStr(url, 'http:/', 'service') host = helper.subStr(host, '/', ':') # print host webservice = httplib.HTTPConnection(host, 8118, timeout = 50) # webservice.set_debuglevel(1) # print response.getheaders() #获取头信息 #连接到服务器后的第一个调用。它发送由request字符串到到服务器 webservice.putrequest("POST", "/service.asmx") # webservice.putheader("Accept-Encoding", "text") # webservice.putheader("Host", "123.11.226.80") webservice.putheader("User-Agent", "WeijingtongService-python") webservice.putheader("Content-Type", "text/xml; charset=utf-8") # webservice.putheader("Connection", "Keep-Alive") webservice.putheader("Content-Length", "%d" % len(data)) webservice.putheader("SOAPAction", '"http://localhost/WebSell/OnPreSellOrder"') # webservice.putheader("SOAPAction", '"http://tempuri.org/OnPreSellOrder"') # webservice.putheader("SOAPAction", '"http://123.11.226.80/OnPreSellOrder"') #发送空行到服务器,指示header的结束 webservice.endheaders() #发送报文数据到服务器 webservice.send(data) #获取返回HTTP 响应信息 response = webservice.getresponse() responseBody = response.read() # print 'response:' # print response.read() # exit() res = [] res.append('ReHttpStatus:' + str( response.status )) res.append('ReHttpReason:' + response.reason) res.append('ReHttpBody:' + responseBody) head = [] for header in response.getheaders(): head.append('%s: %s' % ( header[0], header[1] )) head = "\n".join(head) res.append('ReHttpHeader:' + head) #获取头信息 # print res # exit() re = "\n".join(res) # re = re.decode('gb2312').encode('utf-8') webservice.close() #关闭链接 reBody = helper.subStr(responseBody, '<OnPreSellOrderResult>', '</OnPreSellOrderResult>') # print reBody #成功同步 if '1' == reBody: #生成二维码 reMakeQrcode = helper.httpGet( helper.confGet('host', 'commonService') + 'Api/TicketQrcode/saveFile/?clientId=' + str( ticketBought['client_id'] ) + '&receivingCode=' + ticketBought['receiving_code'] ) reMakeQrcodeMap = json.loads(reMakeQrcode) # print reMakeQrcodeMap['code'] if reMakeQrcodeMap['code'] == 0: sql = "update t_ticket_bought set out_app_code = 'KZZN', temp_receiving_code = '%s', dimen_code_path = '%s' where id = %d" % (ticketBought['receiving_code'], reMakeQrcodeMap['filePath'], ticketBought['id']) # print sql if not True == dbObj.update(sql): helper.getLog(sql, 'addTicketToOuterKZZN.UpdateTicketboughtlistErr.log') else: re = "%s \nPostData:%s" % (re, data) pass except Exception, e: re = str(Exception) + ":" + str(e) re = "%s \nPostData:%s" %(re, data)
def addTicketToOuterYBX(config, ticketBought): # global dbObj # dbObj = globalVar.getDbObj() dbObj = db.db() # 查询游客信息 # userInfo = '' userInfo = dbObj.select( "select user_id, name, mobile, id_number from t_user_identity_info where id = %d" % ticketBought[ 'identity_info_id']) # userInfo = [] # userInfo.append({ # 'name': '微景通', # 'mobile' : '18523876001' # }) if userInfo == False or len(userInfo) < 1: visitorName = '散客' visitorMobile = '18523876001' else: userInfo = userInfo[0] visitorMobile = userInfo['mobile'] visitorName = userInfo['name'] if len(userInfo['mobile']) < 1: visitorMobile = '18523876001' if len(userInfo['name']) < 1: visitorName = '散客' orderInfo = {} orderInfo['mobile'] = visitorMobile orderInfo['identificationnumber'] = str(userInfo['id_number']) orderInfo['effectdate'] = str(ticketBought['plan_time'])[0:10] orderInfo['effectdate'] = orderInfo['effectdate'].replace('-', '', 3) orderInfo['otheruserid'] = int(ticketBought['identity_info_id']) # 其他用户ID号,指用户在第三方系统的用户账号,主要用于官方网站和官方微信的对接,第三方OTA不能使用。 orderInfo['senderid'] = str(ticketBought['order_detail_id']) # 被接口方的业务单据ID,示例:同程网接口调用,此值表示同程网业务系统内对应的订单的单据号,此值在接口方系统内应为唯一值。不提供此参数时,系统将不会执行回调通知。提供这个参数还可以防止订单的重复提交。 orderInfo['servicecode'] = "" orderInfo['timespanindex'] = 0 orderInfo['tripbillcode'] = "" orderInfo['guidernumber'] = "" orderInfo['marketareaid'] = "" orderdetails = {} # orderdetails['productid'] = ticketBought['id'] orderdetails['productid'] = config['ProductID_' + str(ticketBought['ticket_id'])] orderdetails['amount'] = ticketBought['count'] orderdetails['identificationnumber'] = str(userInfo['id_number']) orderdetails['fullname'] = visitorName if (orderInfo['identificationnumber'] != ''): orderdetails['identificationtype'] = "1" # 证件类型('1'身份证,‘2’ 军官证(士兵证),‘3’护照,‘4’其他) else: orderdetails['identificationtype'] = "4" # 证件类型('1'身份证,‘2’ 军官证(士兵证),‘3’护照,‘4’其他) orderdetails['mobile'] = visitorMobile # 手机号码,当过闸模式的值为“B”时,此项必填,且必须是一个合法的手机号 orderdetails['gateinmode'] = 'B' # 过闸模式 分别为"I"二代证,“B”手机条码,“T”前台或自助机取票。“T”是默认值。 orderdetailInfo = [orderdetails] payInfo = {} payInfo['orderid'] = str(ticketBought['order_detail_id']) payInfo['paypassword'] = getPayPassword(config) orderInfo['orderdetails'] = orderdetailInfo orderData = {} orderData['orderinfo'] = orderInfo orderData['payinfo'] = payInfo postData = json.dumps(orderData) # print data; # exit(); processOuterYBX(config, ticketBought, postData, 1)
def addTicketToOuterJYZY(config, ticketBought): # global dbObj # dbObj = globalVar.getDbObj() dbObj = db.db() #查询游客信息 # userInfo = '' userInfo = dbObj.select("select user_id, name, mobile, id_number from t_user_identity_info where id = %d" % ticketBought['identity_info_id']) # userInfo = [] # userInfo.append({ # 'name': '微景通', # 'mobile' : '18523876001' # }) if userInfo == False or len(userInfo) < 1: visitorName = '散客' visitorMobile = '18523876001' idNumber = '' else: userInfo = userInfo[0] visitorMobile = userInfo['mobile'] visitorName = userInfo['name'] idNumber = userInfo['id_number'] # visitorName = repr(visitorName.decode('UTF-8'))[2:-1] # visitorName = visitorName.decode('UTF-8') # visitorName = 'wjtVisitor' ticketName = dbObj.getValue("select name from t_ticket where id = %d" % ticketBought['ticket_id'], 'name') ticketName = ticketName.decode('UTF-8')[0:10] # ticketName = 'chengrenpiao' # ticketName = '成人票' data = '''<?xml version="1.0" encoding="UTF-8"?> <request xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoRequestSchema QMRequestDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoRequestSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <header> <application>Qunar.Menpiao.Agent</application> <processor>SupplierDataExchangeProcessor</processor> <version>v2.0.1</version> <bodyType>CreateOrderForBeforePaySyncRequestBody</bodyType> <createUser>SupplierSystemName</createUser> <createTime>%s</createTime> <supplierIdentity>%s</supplierIdentity> </header> <body xsi:type="CreateOrderForBeforePaySyncRequestBody"> <orderInfo> <orderId>%s</orderId> <product> <resourceId>%s</resourceId> <productName>%s</productName> <visitDate>%s</visitDate> <sellPrice>%s</sellPrice> <cashBackMoney>0</cashBackMoney> </product> <contactPerson> <name>%s</name><namePinyin></namePinyin> <mobile>%s</mobile> <idCard>%s</idCard> <email></email> <address></address> <zipCode></zipCode> </contactPerson> <visitPerson> <person> <name></name><namePinyin></namePinyin> <credentials></credentials> <credentialsType></credentialsType> <defined1Value></defined1Value> <defined2Value></defined2Value> </person> </visitPerson> <orderQuantity>%s</orderQuantity> <orderPrice>%s</orderPrice> <orderCashBackMoney></orderCashBackMoney> <orderStatus>CASHPAY_ORDER_INIT</orderStatus> <orderRemark></orderRemark> <orderSource></orderSource> <eticketNo></eticketNo> </orderInfo> </body> </request> ''' % ( helper.now(), config['uid'], ticketBought['order_detail_id'], config['ticketId_' + str(ticketBought['ticket_id'])], ticketName, str(ticketBought['plan_time']), int(ticketBought['price']*100), visitorName, visitorMobile, idNumber, ticketBought['count'], int(ticketBought['count']*ticketBought['price']*100) ) data = data.replace("\n", '') # print data; # exit(); processOuterJYZY(config, ticketBought, data, 1)
def addTicketToOuterSZZWY(config, ticketBought): # global dbObj # dbObj = globalVar.getDbObj() dbObj = db.db() #查询游客信息 # userInfo = '' userInfo = dbObj.select( "select user_id, name, mobile from t_user_identity_info where id = %d" % ticketBought['identity_info_id']) if userInfo == False or len(userInfo) < 1: visitorName = 'wjtVisitor' visitorMobile = '18523876001' else: userInfo = userInfo[0] visitorName = userInfo['user_id'] visitorMobile = userInfo['mobile'] products = [{ 'viewid': config['viewid_' + str(ticketBought['ticket_id'])] }, { 'Viewname': ticketBought['ticket_id'] }, { 'Type': config['Type_' + str(ticketBought['ticket_id'])] }, { 'number': ticketBought['count'] }] orderInfo = [ { 'TimeStamp': helper.now() }, { 'CompanyCode': config['CompanyCode'] }, { 'CompanyName': 'weijingtong' }, { 'CompanyOrderID': ticketBought['order_id'] }, { 'OrderTime': ticketBought['create_time'] }, { 'ArrivalDate': ticketBought['plan_time'] }, { 'PayType': 1 }, { 'VisitorName': visitorName }, { 'VisitorMobile': visitorMobile }, { 'IdCardNeed': 0 }, { 'IdCard': '1X' }, { 'Note': 'weijingtong' }, { 'Products': helper.dict2xml('product', products).replace('<', '<').replace('>', '>') }, ] data = helper.dict2xml('OrderInfo', orderInfo) data = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><OrderReq xmlns="http://tempuri.org/">%s</OrderReq></soap:Body></soap:Envelope>' % data # data = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><OrderReq xmlns="http://tempuri.org/"><OrderInfo><TimeStamp>2017-02-21 19:41:29</TimeStamp><CompanyCode>weijingtong96325812zfr</CompanyCode><CompanyName>weijingtong</CompanyName><CompanyOrderID>225534</CompanyOrderID><OrderTime>2017-02-21 19:34:33</OrderTime><ArrivalDate>2017-02-21 00:00:00</ArrivalDate><PayType>1</PayType><VisitorName>oZ9oauAoKfN1C4OptkqQbSeXhW-k</VisitorName><VisitorMobile>18723012341</VisitorMobile><IdCardNeed>0</IdCardNeed><IdCard>1X</IdCard><Note>weijingtong</Note><Products><product><viewid>E03</viewid><Viewname>2649</Viewname><Type>Adult</Type><number>1</number></product></Products></OrderInfo></OrderReq></soap:Body></soap:Envelope>' # data = '''<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/"><SOAP-ENV:Body><ns1:OrderReq><ns1:OrderInfo><ns1:TimeStamp>2017-02-21 15:34:49</ns1:TimeStamp><ns1:CompanyCode>weijingtong96325812zfr</ns1:CompanyCode><ns1:CompanyName>weijingtong</ns1:CompanyName><ns1:CompanyOrderID>186738</ns1:CompanyOrderID><ns1:OrderTime>2017-02-21 15:34:49</ns1:OrderTime><ns1:ArrivalDate>2017-02-21</ns1:ArrivalDate><ns1:PayType>1</ns1:PayType><ns1:VisitorName>WeijingtongVisitor</ns1:VisitorName><ns1:VisitorMobile>18523876001</ns1:VisitorMobile><ns1:IdCardNeed>0</ns1:IdCardNeed><ns1:IdCard>1X</ns1:IdCard><ns1:Products><product><viewid>E03</viewid><Type>Adult</Type><number>1</number><viewname>21</viewname></product></ns1:Products></ns1:OrderInfo></ns1:OrderReq></SOAP-ENV:Body></SOAP-ENV:Envelope>''' # data = '''<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/"><SOAP-ENV:Body><ns1:OrderCancel><ns1:orderInfo><ns1:TimeStamp>2017-02-21 19:39:50</ns1:TimeStamp><ns1:CompanyCode>weijingtong96325812zfr</ns1:CompanyCode><ns1:CompanyOrderID>186749</ns1:CompanyOrderID><ns1:IdCardNeed>0</ns1:IdCardNeed></ns1:orderInfo></ns1:OrderCancel></SOAP-ENV:Body></SOAP-ENV:Envelope>''' # print data;exit() try: # 发起同步 url = config[ 'url'] #http://ydpt.hdyuanmingxinyuan.com/interface/AgentInterface.asmx host = helper.subStr(url, 'http://', '/interface') webservice = httplib.HTTPConnection(host, 80, timeout=50) # webservice.set_debuglevel(1) # print response.getheaders() #获取头信息 #连接到服务器后的第一个调用。它发送由request字符串到到服务器 webservice.putrequest("POST", "/interface/AgentInterface.asmx") # webservice.putheader("Accept-Encoding", "text") # webservice.putheader("Host", "ydpt.hdyuanmingxinyuan.com") webservice.putheader("User-Agent", "WeijingtongService-python") webservice.putheader("Content-Type", "text/xml; charset=utf-8") # webservice.putheader("Connection", "Keep-Alive") webservice.putheader("Content-Length", "%d" % len(data)) webservice.putheader("SOAPAction", "\"http://tempuri.org/OrderReq\"") # webservice.putheader("SOAPAction", "\"http://tempuri.org/OrderCancel\"") #发送空行到服务器,指示header的结束 webservice.endheaders() #发送报文数据到服务器 webservice.send(data) #获取返回HTTP 响应信息 response = webservice.getresponse() responseBody = response.read() # print 'response:' # print response.read() # exit() res = [] res.append('HttpStatus:' + str(response.status)) res.append('HttpReason:' + response.reason) res.append('HttpBody:' + responseBody) head = [] for header in response.getheaders(): head.append('%s: %s' % (header[0], header[1])) head = "\n".join(head) res.append('HttpHeader:' + head) #获取头信息 # print res # exit() re = "\n".join(res) # re = re.decode('gb2312').encode('utf-8') webservice.close() #关闭链接 #成功同步 if 'true' == helper.subStr(responseBody, '<Result>', '</Result>'): sql = "update t_ticket_bought set out_app_code = 'YMXY', temp_receiving_code = 'None' where id = %d" % ticketBought[ 'id'] if not True == dbObj.update(sql): helper.getLog( sql, 'addTicketToOuterYMXY.UpdateTicketboughtlistErr.log') pass except Exception, e: re = str(Exception) + ":" + str(e) re = "%s \npostdata:%s" % (re, data)
def addTicketToOuterZXK(config, ticketBought): # global dbObj # dbObj = globalVar.getDbObj() dbObj = db.db() #查询游客信息 # userInfo = '' userInfo = dbObj.select( "select user_id, name, mobile, id_number from t_user_identity_info where id = %d" % ticketBought['identity_info_id']) # userInfo = [] # userInfo.append({ # 'name': '微景通', # 'mobile' : '18523876001' # }) if userInfo == False or len(userInfo) < 1: visitorName = 'weijingtongVisitor' visitorMobile = '18523876001' visitorIdNumber = '110102198601018573' else: userInfo = userInfo[0] visitorMobile = userInfo['mobile'] visitorIdNumber = userInfo['id_number'] ## visitorName = userInfo['user_id'] visitorName = userInfo['name'] visitorName = repr(visitorName.decode('UTF-8'))[2:-1] ## visitorName = '\u5f20\u8001\u5927' ## visitorName = urllib.urlencode({1:visitorName})[2:] # visitorName = 'wjtVisitor' ticketName = dbObj.getValue( "select name from t_ticket where id = %d" % ticketBought['ticket_id'], 'name') # ticketName = '成人票' # ticketName = repr(ticketName.decode('UTF-8'))[2:-1][0:48] # ticketName = 'test' visitPerson = '''[ { "name": "%s", "mobile": "%s", "idCard": "%s" } ]''' % (visitorName[0:24], visitorMobile, visitorIdNumber) requestBody = '''{ "orderSerialId": "%s", "productNo": "%s", "payType": 1, "tickets": %s, "price": %s, "contractPrice": %s, "bookName": "%s", "bookMobile": "%s", "idCard": "%s", "travelDate": "%s", "visitPerson": %s }''' % (ticketBought["order_detail_id"], config["productNo_" + str(ticketBought["ticket_id"])], ticketBought["count"], int(ticketBought["price"] * 100), int(ticketBought["price"] * 100), visitorName[0:24], visitorMobile, visitorIdNumber, str(ticketBought["plan_time"])[0:10], visitPerson) # print requestBody;exit(); # data = '{"pageIndex":1,"pageSize":100}' # 1/F4jrg9alyN0uDgJNlEaCLroiTtH9LhlljImdztF8Y= KEY = str(config['user_key']) #密钥 IV = str(config['user_key']) #偏转向量 desObj = des(KEY, ECB, IV, pad=None, padmode=PAD_PKCS5) # 使用DES对称加密算法的CBC模式加密 # requestBody = 'adfasfaf' requestBody = str(requestBody) requestBodyFormat = requestBody # print helper.httpPost('http://123.56.105.30:5677/Tongcheng/Encrypt/', requestBody);exit(); #获取des密文 # print (requestBody); # print (str(config['user_key']) ); requestBody = desObj.encrypt(requestBody) # print base64.encodestring(b2a_hex(requestBody)) requestBody = base64.encodestring(requestBody) # print requestBody; # print "Decrypted: %r" % desObj.decrypt(base64.decodestring(requestBody));exit() timestamp = str(time.time())[0:10] sign = config['user_id'] + 'CreateOrder' + str( timestamp) + 'v1.0' + requestBody + config['user_key'] # print (sign); md5Obj = md5.new() md5Obj.update(sign) sign = md5Obj.hexdigest() requestHead = '''{ "user_id": "%s", "method": "CreateOrder", "timestamp": %s, "version": "v1.0", "sign": "%s" }''' % (config["user_id"], timestamp, sign) data = '''{ "requestHead": %s, "requestBody": "%s" }''' % (requestHead, requestBody) # print (data); # exit(); try: re = helper.httpPost(config['url'], data) #成功同步 res = json.loads(re) # print res; # print res['responseHead']['res_code']; # print json.loads(desObj.decrypt(base64.decodestring(res['responseBody']))) responseBody = desObj.decrypt(base64.decodestring(res['responseBody'])) re = re + "\nResponseBodyFormat:" + responseBody responseBody = json.loads(responseBody) # exit(); #成功同步 if '1000' == res['responseHead']['res_code'] or '2001' == res[ 'responseHead']['res_code']: sql = "update t_ticket_bought set out_app_code='ZXK', temp_receiving_code='%s', dimen_code_path='%s', remark2='%s' where id = %d" % ( responseBody['partnerCode'], responseBody['partnerQRCodeAddress'], responseBody['partnerOrderId'], ticketBought['id']) # print sql if not True == dbObj.update(sql): helper.getLog( sql, 'addTicketToOuterZXK.UpdateTicketboughtlistErr.log') else: re = "%s \nPostData:%s\nRequestBodyFormat:%s" % (re, data, requestBodyFormat) pass except Exception, e: re = str(Exception) + ":" + str(e) re = "%s \nPostData:%s\nRequestBodyFormat:%s" % (re, data, requestBodyFormat)