def _checkConn(self): try: re = self.conn.ping() helper.getLog('check conn mysql: %s -- sql: %s' % (re, self.sql), 'db.%s.log' % helper.now(0, '%Y-%m-%d')) print 'check conn mysql: %s -- sql: %s' % (re, self.sql) except Exception, e: while True: print 're connect mysql' helper.getLog('re conn mysql -- SQL:%s' % self.sql, 'db.%s.log' % helper.now(0, '%Y-%m-%d')) if self._conn(): break time.sleep(2)
def processDoGetFans(record): param = '{"id":"%s","client_id":"%s","user_id":"%s","scene_id":"%s","status":"%s","object_id":"%s"}' % ( record['id'], record['client_id'], record['user_id'], record['scene_id'], record['status'], record['object_id']) # print param # print str(param).replace(' ', '') # print urllib.quote(param) re = os.system( 'nohup /opt/lampp/bin/php /datas/www/php/common-service/cli.php /SystemService/PosterGetFansByPython/process/data/%s' % urllib.quote(param) + ' &') # print re # time.sleep(10) print helper.now() + " == " pass
def _conn(self): try: # 读取数据库配置 conf = ConfigParser.ConfigParser() conf.read("%s/config/config.ini" % sys.path[0]) # print "%s/config/config.ini" % sys.path[0] #链接数据库 conn = MySQLdb.connect(host=conf.get('db', 'dbHost'), user=conf.get('db', 'dbUser'), passwd=conf.get('db', 'dbPasswd'), db=conf.get('db', 'dbName'), port=int(conf.get('db', 'dbPort')), charset=conf.get('db', 'dbCharset')) conn.autocommit(True) cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) self.conn = conn self.cur = cur # print '1t conn mysql' return True except Exception, e: re = str(Exception) + ':' + str(e) print 'conn err: %s' % (re) helper.getLog('conn err: -- SQL:%s -- %s' % (self.sql, re), 'db.%s.log' % helper.now(0, '%Y-%m-%d')) return False
def print_data(self, header, values): max_lengths = [] shorten = {} for i in range(0, len(header)): max_l = 0 for row in values: if len(row[i]) > max_l: max_l = len(row[i]) if len(header[i]) > max_l: key = len(shorten) + 1 shorten[key] = header[i] header[i] = "%s[^%d]" % (header[i][:max(1, max_l - 2)], key) max_l = max(max_l, len(header[i])) max_lengths.append(max_l) self.output.write("# Prepared datasets\n\n") self.output.write("|%s|\n" % "|".join(self.format(header, max_lengths))) self.output.write("|%s|\n" % "|".join(self.separator(max_lengths))) for row in values: self.output.write("|%s|\n" % "|".join(self.format(row, max_lengths))) self.output.write("\n(table was generated at %s)\n" % helper.now()) self.output.write( "\n%s\n" % "\n".join(["[^%s]: %s" % l for l in shorten.items()]))
def store_info(self, info_object): info_object["type"] = type(self).__name__ info_object["written"] = helper.now() info_object["revision"] = helper.git_hash() info_object["shape"] = self.data_shape info_object["sample_shape"] = self.data_shape[1:] info_object["samples"] = self.data_shape[0] info_object["shuffled"] = self.shuffle with open(os.path.join(self.root, "%sinfo.txt" % self.file_prefix), "w") as info_file: for k in info_object: info_file.write("%s: %s\n" % (k, info_object[k]))
def store_info(self, info_object=None, finished=False): if info_object is None: info_object = {} info_object["started"] = self.started info_object["rotate"] = self.rotate info_object["resize"] = self.resize info_object["flip"] = self.flip info_object["translate_limits"] = self.translate_limits info_object["translate"] = self.translations info_object["augment_factor"] = self.get_augment_factor() if finished: info_object["finished"] = helper.now() self.storage.store_info(info_object)
def __init__(self, flip=("", ), resize=(1.0, ), rotate="none", translations=1, translate_limits=(0, 0), augment_class="1", translate="before", translate_axes="", factor=0, normalization="default"): self.flip = flip self.resize = resize self.rotate = rotate self.translations = translations self.translate = translate self.translate_axes = translate_axes self.factor = factor self.translate_limits = translate_limits self.normalization = normalization self.current_scan = None self.current_spacing = None self.current_resize_index = -1 for i, size in enumerate(self.resize): if abs(size - 1.0) < 0.01: self.identity_resize = i self.name = "" self.original_scan = None self.origin = None self.original_spacing = None self.voxel_size = None self.storage = None self.augment_class = augment_class self.started = helper.now() self.__rng = np.random.RandomState(42)
def payTicketToOuterJYZY(config, ticketBought, partnerorderId, count = 1): url = config['url'] 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>PayOrderForBeforePaySyncRequestBody</bodyType> <createUser>SupplierSystemName</createUser> <createTime>%s</createTime> <supplierIdentity>%s</supplierIdentity> </header> <body xsi:type="PayOrderForBeforePaySyncRequestBody"> <orderInfo> <partnerOrderId>%s</partnerOrderId> <orderStatus>PREPAY_ORDER_PRINTING</orderStatus> <orderPrice>%s</orderPrice> <paymentSerialno></paymentSerialno> <eticketNo></eticketNo> </orderInfo> </body> </request> ''' % ( helper.now(), config['uid'], partnerorderId, ticketBought['count']*ticketBought['price']*100 ) data = data.replace("\n", '') data = buildParam(data, config['pkey'], 'payOrderForBeforePaySync'); # print data; re = sendDataToOuterJYZY(url, data) code = helper.subStr(re, '<code>', '</code>') if( count < 2 and '1000' != code ): re, data = payTicketToOuterJYZY(config, ticketBought, partnerorderId, 2) data = data + "\nprocessCount:2" return [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)
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) re = re.replace("'", '"') # print re;exit() #保存日志到数据库 sql = "insert into t_order_outapp_msg (client_id, order_id, order_detail_id, type, outapp_code, content, create_time) \ values ('%d', '%d', '%s', '%d', '%s', '%s', '%s') " values = (mallBought['client_id'], mallBought['order_id'], mallBought['order_number'], 1, 'KZZN2', re, helper.now()) # print sql re = dbObj.insert(sql, values) # print re if not re == True: helper.getLog('insert into t_order_outapp_msg error: ' + re, 'mall.kzzn2') def sendDataToOuterKZZN2(host, port, data): # return ['<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><OnWebOrderResponse xmlns="http://127.0.0.1/WebSellWx/"><OnWebOrderResult><nStatus>1</nStatus><cStatus>OK</cStatus><cUrl>/images/722399640.jpg</cUrl><cQrCode>722399640</cQrCode></OnWebOrderResult></OnWebOrderResponse></soap:Body></soap:Envelope>', ''] webservice = httplib.HTTPConnection(host, port, timeout=50) # webservice.set_debuglevel(1) #连接到服务器后的第一个调用。它发送由request字符串到到服务器 webservice.putrequest("POST", "/service.asmx")
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)
dbObj.update(sql_error) re = "%s \npostdata:%s" % (response, data) except Exception, e: dbObj.update(sql_error) re = str(Exception) + ":" + str(e) re = "%s \nPostData:%s" % (re, data) # re = re.replace("'", '"') # print re;exit() # 记录请求结束时间 helper.getLog(str(ticketBought['order_detail_id']) + '------------' + str((time.time() - send_time)), 'addTicketToOuterYBX.recordEndTime.log') # 保存日志到数据库 sql = "insert into t_order_outapp_msg (client_id, order_id, order_detail_id, type, outapp_code, content, create_time) \ values ('%d', '%d', '%d', '%d', '%s', '%s', '%s')" values = ( ticketBought['client_id'], ticketBought['order_id'], ticketBought['order_detail_id'], 1, 'YBX', re, helper.now()) # print sql re = dbObj.insert(sql, values) # 记录存数据库的时间 # helper.getLog(helper.now(), 'addTicketToOuterYBX.recordSqlTime.log') # print re if not re == True: helper.getLog(re, 'addTicketToOuterYBX.SqlErr.log') # 订单同步 def sendDataToOuterYBX(config, data): url = config['url'] payload = data headers = hawkAuth(url, config) response = requests.request("POST", url, data=payload, headers=headers)
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']) and (not responseBody['partnerCode'] is None): sql = "update t_ticket_bought set out_app_code='ZXK', temp_receiving_code='%s', receiving_code='%s', dimen_code_path='%s', remark2='%s' where id = %d" % (ticketBought['receiving_code'], 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) re = re.replace("'", '"') # print re;exit() #保存日志到数据库 sql = "insert into t_order_outapp_msg (client_id, order_id, order_detail_id, type, outapp_code, content, create_time) \ values ('%d', '%d', '%d', '%d', '%s', '%s', '%s') " values = (ticketBought['client_id'], ticketBought['order_id'], ticketBought['order_detail_id'], 1, 'ZXK', re, helper.now()) # print sql re = dbObj.insert(sql, values) # print re if not re == True: helper.getLog(re, 'addTicketToOuterZXK.SqlErr.log')
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) re = re.replace("'", '"') # print re;exit() #保存日志到数据库 sql = "insert into t_order_outapp_msg (client_id, order_id, order_detail_id, type, outapp_code, content, create_time) \ values ('%d', '%d', '%s', '%d', '%s', '%s', '%s') " values = (mallBought['client_id'], mallBought['order_id'], mallBought['order_number'], 1, '_WJT', re + "\n", helper.now()) # print sql re = dbObj.insert(sql, values) # print re if not re == True: helper.getLog(re, 'addMallToService_WJT.SqlErr.log')
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) #保存日志到数据库 sql = "insert into t_order_outapp_msg (client_id, order_id, order_detail_id, type, outapp_code, content, create_time) \ values ('%d', '%d', '%d', '%d', '%s', '%s', '%s') " values = (ticketBought['client_id'], ticketBought['order_id'], ticketBought['order_detail_id'], 1, 'YMXY', re, helper.now()) # print sql re = dbObj.insert(sql, values) # print re if not re == True: helper.getLog(re, 'addTicketToOuterYMXY.SqlErr.log')
helper.getLog('pos - 77', 'addTicketToService_WJT.log') try: qrcodeUrl = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/index/?data=' + str( bought['receiving_code']) sql = "update t_ticket_bought set out_app_code = '_WJT', temp_receiving_code = '%s', dimen_code_path='%s' where id = '%d'" % ( bought['receiving_code'], qrcodeUrl, bought['id']) if not True == dbObj.update(sql): helper.getLog( sql, 'addTicketToService_WJT.UpdateTicketboughtlistErr.log') except Exception, e: re = str(Exception) + ":" + str(e) helper.getLog('pos - 88', 'addTicketToService_WJT.log') re = re.replace("'", '"') # print re;exit() #保存日志到数据库 sql = "insert into t_order_outapp_msg (client_id, order_id, order_detail_id, type, outapp_code, content, create_time) \ values ('%d', '%d', '%d', '%d', '%s', '%s', '%s') " values = (bought['client_id'], bought['order_id'], bought['order_detail_id'], 1, '_WJT', re + "\n", helper.now()) # print sql re = dbObj.insert(sql, values) helper.getLog('end---', 'addTicketToService_WJT.log') # print re if not re == True: helper.getLog(re, 'addTicketToService_WJT.SqlErr.log')
def get_initial_dir(): return os.path.join(c.str("parent_dir"), c.str("dir").format(timestamp=helper.now()))
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)
processCount += 1 processOuterKZZN2(config, ticketBought, 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) re = re.replace("'", '"') # print re;exit() #保存日志到数据库 sql = "insert into t_order_outapp_msg (client_id, order_id, order_detail_id, type, outapp_code, content, create_time) \ values ('%d', '%d', '%d', '%d', '%s', '%s', '%s') " values = (ticketBought['client_id'], ticketBought['order_id'], ticketBought['order_detail_id'], 1, 'KZZN2', re, helper.now()) # print sql re = dbObj.insert(sql, values) # print re if not re == True: helper.getLog(re, 'addTicketToOuterKZZN2.SqlErr.log') def sendDataToOuterKZZN2(host, port, data): # return ['<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><OnWebOrderResponse xmlns="http://127.0.0.1/WebSellWx/"><OnWebOrderResult><nStatus>1</nStatus><cStatus>OK</cStatus><cUrl>/images/722399640.jpg</cUrl><cQrCode>722399640</cQrCode></OnWebOrderResult></OnWebOrderResponse></soap:Body></soap:Envelope>', ''] webservice = httplib.HTTPConnection(host, port, timeout=50) # webservice.set_debuglevel(1) #连接到服务器后的第一个调用。它发送由request字符串到到服务器 webservice.putrequest("POST", "/service.asmx") # webservice.putheader("Accept-Encoding", "text")
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 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 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 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)
# print re #成功同步 res = json.loads(re) # print res if res['success'] == True: sql = "update t_mall_bought set out_app_code = 'XiRuan', out_app_no = '%s' where id = '%d'" % (res['results'][0]['rsvno'], mallBought['id']) if not True == dbObj.update(sql): helper.getLog(sql, 'addMallToOuterXiRuan.UpdateMallboughtlistErr.log') 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') pass except Exception, e: re = str(Exception) + ":" + str(e) re = "errmsg:%s \npostdata:%s" %(re, data) # print re;exit() #保存日志到数据库 sql = "insert into t_order_outapp_msg (client_id, order_id, order_detail_id, type, outapp_code, content, create_time) \ values ('%d', '%d', '%d', '%d', '%s', '%s', '%s') " values = (mallBought['client_id'], mallBought['order_id'], mallBought['order_detail_id'], 1, 'XiRuan', re, helper.now()) # print sql re = dbObj.insert(sql, values) # print re if not re == True: helper.getLog(re, 'addMallToOuterXiRuan.SqlErr.log')