zhangqf 6 年之前
父节点
当前提交
353ec5cc74

+ 150 - 0
src/AirasiaWeb.py

@@ -0,0 +1,150 @@
+#-*- coding:utf-8 -*-
+
+import tornado.web
+import tornado.ioloop
+import json
+import time
+import _thread
+from order.OrderServer import OrderServer
+from utils.CallbackOrderUtils import CallbackOrderUtils as call
+import logging
+
+def config_log():
+    level = logging.INFO
+    fmt = '%(asctime)s - %(levelname)s - %(message)s - %(thread)d'
+    logging.basicConfig(filename='AirasiaWeb.log', level=level, format=fmt)
+    console = logging.StreamHandler()
+    console.setLevel(level)
+    console.setFormatter(logging.Formatter(fmt))
+    logging.getLogger('').addHandler(console)
+
+#定义处理类型
+class AirasiaWeb(tornado.web.RequestHandler):
+    #添加一个处理get请求方式的方法
+    def get(self):
+        #向响应中,添加数据
+        self.write('这里是亚航生单API。')
+    def post(self):
+        param = self.request.body.decode('utf-8')
+        prarm = json.loads(param)
+        try:
+            _thread.start_new_thread(self.akorder,(prarm,))
+        except:
+            print('Error: 无法启动线程')
+        
+        self.write('Ok')
+    def akorder(self,prarm):
+        #开始执行时间
+        try:
+            start = time.clock()
+            orderStatus = '1' #生单成功
+            orderPnr = '' #下单成功后PNR
+            orderServer = OrderServer(prarm)
+            orderServer.LoadPrarm()
+            #代理代理Log self.proxy_handler
+            logging.info('代理:'+orderServer.oinfo.cid+str(orderServer.proxy_handler))
+            if orderServer.isContinue:
+                orderServer.CurrencyQuery()
+                #-------------------查询官网价格与Big会员价格方法---------------------
+                try:
+                    #验证是否Web查询成功(3次重试机会) 
+                    _thread.start_new_thread(orderServer.WebQuery,())
+                    _thread.start_new_thread(orderServer.WebQuery,())
+                    _thread.start_new_thread(orderServer.WebQuery,())
+                    #验证是否Big查询成功(3次重试机会)
+                    _thread.start_new_thread(orderServer.BigQuery,())
+                    _thread.start_new_thread(orderServer.BigQuery,())
+                    _thread.start_new_thread(orderServer.BigQuery,())
+                except:
+                    logging.info('Error: 无法启动线程')
+                logging.info('-------------------查询发起成功,刷新执行结果-------')
+                counter = 1
+                while counter < 15:
+                    if orderServer.checkQuery():
+                        print('----------------亲,已经刷新到结果啦.......可以继续下一步了')
+                        break
+                    logging.info('-----------我在这里刷新查询结果:'+str(counter))
+                    time.sleep(1)
+                    counter += 1
+                #开始执行时间
+                start = time.clock()
+                #-------------------Agent操作----------------------
+                if orderServer.AagenLogin():
+                    orderServer.AgentSearch()#发起查询
+                    orderServer.Parity()#比价
+                    flightHtml = orderServer.FlightSelected()#提交选择航班
+                    passHtml = orderServer.Passenger(flightHtml) #提交乘机人信息
+                    unitMapHtml = orderServer.AddOns(passHtml) #提交租车信息
+                    payHtml = orderServer.UnitMap(unitMapHtml) #选座
+                    PNR = orderServer.Payment(payHtml)#进行支付并且获取PNR码
+                    logging.info("-------哈哈,得到结果啦PNR:"+PNR)
+                    if len(PNR) == 6:
+                        orderPnr = PNR
+                    else:
+                        orderStatus = '2' #生单失败
+            else:
+                logging.info('-----生单失败')
+                logging.info('-----orderServer.isContinue'+str(orderServer.isContinue))
+                orderStatus = '2' #生单出错 BaseException Exception
+        except BaseException as e:
+            logging.info('-----生单失败'+str(e))
+            orderStatus = '2' #生单出错
+        cl = call()
+        cl.BallbackOrder(orderServer.oinfo.cid, orderStatus, orderPnr, '代理人占座', 'CNTRIPTOPK_ADMIN')
+        logging.info('-------------------end time(s)-------------------')
+        end = time.clock()
+        logging.info("read: %f s" % (end - start))
+#定义亚航代理人直接生单
+class AirasiaAgentWeb(tornado.web.RequestHandler):
+    #添加一个处理get请求方式的方法
+    def get(self):
+        #向响应中,添加数据
+        self.write('这里是亚航代理人生单API。')
+    def post(self):
+        param = self.request.body.decode('utf-8')
+        prarm = json.loads(param)
+        try:
+            _thread.start_new_thread(self.akorder,(prarm,))
+        except:
+            logging.info('Error: 无法启动线程')
+        self.write('Ok')
+    def akorder(self,prarm):
+        #开始执行时间
+        start = time.clock()
+        orderStatus = '1' #生单成功
+        orderPnr = '' #下单成功后PNR
+        try:
+            orderServer = OrderServer(prarm)
+            orderServer.LoadPrarm() #组装数据
+            logging.info('代理:'+orderServer.oinfo.cid+str(orderServer.proxy_handler))
+            orderServer.CurrencyQuery()#查询币种
+            #-------------------Agent操作----------------------
+            if orderServer.AagenLogin():
+                orderServer.AgentSearch()#发起查询
+                orderServer.AgentDirectOrder()#设置为代理人占座
+                flightHtml = orderServer.FlightSelected()#提交选择航班
+                passHtml = orderServer.Passenger(flightHtml) #提交乘机人信息
+                unitMapHtml = orderServer.AddOns(passHtml) #提交租车信息
+                payHtml = orderServer.UnitMap(unitMapHtml) #选座
+                PNR = orderServer.Payment(payHtml)#进行支付并且获取PNR码
+                logging.info("-------哈哈,得到结果啦PNR:"+PNR)
+                if len(PNR) == 6:
+                    orderPnr = PNR
+                else:
+                    orderStatus = '2' #生单失败
+        except:
+            logging.info('-----生单失败')
+            orderStatus = '2' #生单出错
+        cl = call()
+        cl.BallbackOrder(orderServer.oinfo.cid, orderStatus, orderPnr, '代理人占座', 'CNTRIPTOPK_ADMIN')
+        logging.info('-------------------end time(s)-------------------')
+        end = time.clock()
+        logging.info("read: %f s" % (end - start))
+if __name__ == '__main__':
+    config_log()
+    #创建一个应用对象
+    app = tornado.web.Application([(r'/akOrder',AirasiaWeb),(r'/akAgOrder',AirasiaAgentWeb)])
+    #绑定一个监听端口
+    app.listen(8888)
+    #启动web程序,开始监听端口的连接
+    tornado.ioloop.IOLoop.current().start()

+ 0 - 0
src/__init__.py


文件差异内容过多而无法显示
+ 3 - 0
src/entity/OrderInfo.py


二进制
src/entity/__pycache__/OrderInfo.cpython-36.pyc


二进制
src/entity/__pycache__/__init__.cpython-36.pyc


+ 88 - 0
src/log/AkAgOrderLog.py

@@ -0,0 +1,88 @@
+# -*- coding: utf-8 -*-
+import logging  
+   
+# #Ak代理人生单日志记录
+# class AkAgOrderLog():
+#  
+#     def __init__(self):
+#         self.logger = logging.getLogger(__name__)
+#         self.logger.setLevel(level = logging.INFO)
+#         handler = logging.FileHandler("E://Book.log")
+#         handler.setLevel(logging.INFO)
+#         formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+#         handler.setFormatter(formatter)
+#         console = logging.StreamHandler()
+#         console.setLevel(logging.INFO)
+#         self.logger.addHandler(console)
+#         self.logger.addHandler(handler)
+#         
+# #         self.logger.info("Start print log")
+# #         self.logger.debug("Do something")
+# #         self.logger.warning("Something maybe fail.")
+# #         self.logger.info("Finish")
+#     #WebBig查询日志记录
+#     def WebBigQueryLog(self,msg):
+#         self.logger.info(msg)
+#         
+# if __name__ == '__main__':
+#     lg = AkAgOrderLog()
+#     lg.WebBigQueryLog('111111111111111111111111111我就测试一下')
+
+
+
+
+
+
+import logging, logging.handlers
+import time
+
+'''
+TimedRotatingFileHandler构造函数声明
+class logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None)
+filename    日志文件名前缀
+when        日志名变更时间单位
+    'S' Seconds
+    'M' Minutes
+    'H' Hours
+    'D' Days
+    'W0'-'W6' Weekday (0=Monday)
+    'midnight' Roll over at midnight
+interval    间隔时间,是指等待N个when单位的时间后,自动重建文件
+backupCount 保留日志最大文件数,超过限制,删除最先创建的文件;默认值0,表示不限制。
+delay       延迟文件创建,直到第一次调用emit()方法创建日志文件
+atTime      在指定的时间(datetime.time格式)创建日志文件。
+'''
+
+def test_TimedRotatingFileHandler():
+    # 定义日志输出格式
+    fmt_str = '%(asctime)s[level-%(levelname)s][%(name)s]:%(message)s'
+    # 初始化
+    logging.basicConfig()
+
+    # 创建TimedRotatingFileHandler处理对象
+    # 间隔5(S)创建新的名称为myLog%Y%m%d_%H%M%S.log的文件,并一直占用myLog文件。
+    fileshandle = logging.handlers.TimedRotatingFileHandler('myLog', when='S', interval=5, backupCount=3)
+    # 设置日志文件后缀,以当前时间作为日志文件后缀名。
+    fileshandle.suffix = "%Y%m%d_%H%M%S.log"
+    # 设置日志输出级别和格式
+    fileshandle.setLevel(logging.DEBUG)
+    formatter = logging.Formatter(fmt_str)
+    fileshandle.setFormatter(formatter)
+    # 添加到日志处理对象集合
+    logging.getLogger('').addHandler(fileshandle)
+
+if __name__ == '__main__':
+    test_TimedRotatingFileHandler()
+
+    # 测试在200s内创建文件多个日志文件
+    for i in range(0, 100):
+        logging.debug("logging.debug")
+        logging.info("logging.info")
+        logging.warning("logging.warning")
+        logging.error("logging.error")
+        time.sleep(2)
+
+
+
+
+

+ 0 - 0
src/log/__init__.py


+ 77 - 57
src/order/OrderServer.py

@@ -5,6 +5,7 @@ import requests
 import time
 import datetime
 import re
+import random
 from lxml import etree
 from pyquery import PyQuery as pq
 from entity.OrderInfo import OrderInfo,Contact,Passengers,Segments
@@ -12,14 +13,23 @@ from utils.CallbackOrderUtils import CallbackOrderUtils as call
 from query.AkWebQuery import AkWebQuery
 from query.AkBigQuery import AkBigQuery
 urllib3.disable_warnings()
+import logging
 
 class OrderServer():
     def __init__(self,prarm):
-        print('初始化')
+        self.salt = ''
+        self.isContinue = True
         self.json_str = prarm
         self.oinfo = OrderInfo();
         self.queryInputJson = {}
         self.session = requests.session()
+        self.num = random.randint(0,168)
+        self.proxyurl = self.oinfo.proxiesList[self.num]
+        self.proxy_handler = {
+            'http': 'http://'+self.proxyurl,
+            'https': 'https://'+self.proxyurl,
+        }
+        self.session.proxies = self.proxy_handler
         #请求头
         self.headers = {
             'Accept-Encoding': 'gzip',
@@ -46,6 +56,7 @@ class OrderServer():
         self.luggageDict = {20:'PBAB',25:'PBAC',30:'PBAD',40:'PBAF'} 
     #获取订单信息
     def LoadPrarm(self):
+        self.salt = self.json_str['cid']+'|'
         self.oinfo.cid =self.json_str['cid']             #CID 唯一标识
         self.oinfo.tripType =self.json_str['tripType']   #行程类型 1.单程 2.往返
         self.oinfo.formCity =self.json_str['formCity']   #去程三字码
@@ -99,6 +110,11 @@ class OrderServer():
             seg.flightNumber = kfsa['flightNumber']  #航班号 ZQ555
             seg.aircraftCode = kfsa['aircraftCode']  #机型  空客A380
             seg.cabin = kfsa['cabin']         #舱位等级 EC.特惠 EP.低航费 VF.超值套餐 HF.常飞客 PM.豪华平躺
+            if 'E' == seg.cabin:
+                seg.cabin = 'EC'
+            if 'EC' != seg.cabin:
+                self.isContinue = False
+                return
             seg.depAirport = kfsa['depAirport']    #出发机场IATA三字码   KUL
             seg.arrAirport = kfsa['arrAirport']    #到达机场IATA三字码   DPS
             seg.arrTime = kfsa['arrTime']       #起飞时间20180428053
@@ -119,6 +135,11 @@ class OrderServer():
                 seg.flightNumber = kfsa['flightNumber']  #航班号 ZQ555
                 seg.aircraftCode = kfsa['aircraftCode']  #机型  空客A380
                 seg.cabin = kfsa['cabin']         #舱位等级 EC.特惠 EP.低航费 VF.超值套餐 HF.常飞客 PM.豪华平躺
+                if 'E' == seg.cabin:
+                    seg.cabin = 'EC'
+                if 'EC' != seg.cabin:
+                    self.isContinue = False
+                    return
                 seg.depAirport = kfsa['depAirport']    #出发机场IATA三字码   KUL
                 seg.arrAirport = kfsa['arrAirport']    #到达机场IATA三字码   DPS
                 seg.arrTime = kfsa['arrTime']       #起飞时间20180428053
@@ -128,13 +149,13 @@ class OrderServer():
                 fromSegments.append(seg)
             self.oinfo.retFlight = retFlight
             self.oinfo.retSegments = retSegments
-        print('数据解析完毕,现在可以输出数据了')       
-        print(self.oinfo.fromFlight)
-        print(self.oinfo.retFlight)
-        print(self.oinfo.formCity)
-        print(self.oinfo.toCity)
-        print(self.oinfo.fromDate)
-        print(self.oinfo.retDate)
+        logging.info(self.salt+'数据解析完毕,现在可以输出数据了')       
+        logging.info(self.salt+self.oinfo.fromFlight)
+        logging.info(self.salt+self.oinfo.retFlight)
+        logging.info(self.salt+self.oinfo.formCity)
+        logging.info(self.salt+self.oinfo.toCity)
+        logging.info(self.salt+self.oinfo.fromDate)
+        logging.info(self.salt+self.oinfo.retDate)
         #查询字符串JSON
         self.queryInputJson = {
             "adultNum": self.oinfo.adultNum,
@@ -148,6 +169,7 @@ class OrderServer():
             "uuid": "AKBigWeb",
             "currency": self.oinfo.currencyCode
         }
+        logging.info(self.salt+'查询提交参数:'+str(self.queryInputJson))
     #调用货币查询结果
     def CurrencyQuery(self):
         cl = call()
@@ -155,17 +177,17 @@ class OrderServer():
         self.oinfo.currency = currency
         self.oinfo.fxRate = currency.AkOriginRate
         self.oinfo.currencyCode = currency.currencyCode
-        print(self.oinfo.fxRate)
-        print(self.oinfo.currencyCode)
+        logging.info(self.salt+str(self.oinfo.fxRate))
+        logging.info(self.salt+str(self.oinfo.currencyCode))
     #发起Web查询
     def WebQuery(self):
         akwebQuer = AkWebQuery(self.queryInputJson,self.oinfo.tripType,self.oinfo.fromFlight,self.oinfo.retFlight,self.oinfo.fxRate)
         akQueryWebFrom,akQueryWebRet,isOk = akwebQuer.StartQuery()
         if self.oinfo.webIsOk:
             return
-        print('WebQuer:'+str(isOk))
-        print('Web去程:'+json.dumps(akQueryWebFrom))
-        print('Web返程:'+json.dumps(akQueryWebRet))
+        logging.info(self.salt+'WebQuer:'+str(isOk))
+        logging.info(self.salt+'Web去程:'+json.dumps(akQueryWebFrom))
+        logging.info(self.salt+'Web返程:'+json.dumps(akQueryWebRet))
         #判断对象是否为空
         if self.oinfo.webIsOk == False:
             self.oinfo.webIsOk = isOk
@@ -177,9 +199,9 @@ class OrderServer():
         akQueryBigFrom,akQueryBigRet,isOk = akbigQuer.StartQuery()
         if self.oinfo.bigIsOk:
             return
-        print('BigQuer:'+str(isOk))
-        print('Big去程:'+json.dumps(akQueryBigFrom))
-        print('Big返程:'+json.dumps(akQueryBigRet))
+        logging.info(self.salt+'BigQuer:'+str(isOk))
+        logging.info(self.salt+'Big去程:'+json.dumps(akQueryBigFrom))
+        logging.info(self.salt+'Big返程:'+json.dumps(akQueryBigRet))
         if self.oinfo.bigIsOk == False:
             self.oinfo.bigIsOk = isOk
             self.oinfo.bigFromJson = akQueryBigFrom
@@ -192,8 +214,10 @@ class OrderServer():
     #代理人进行登录
     def AagenLogin(self):
         self.session.get("https://www.airasia.com/my/en/login/travel-agent.page")
-        res = self.session.post("https://booking2.airasia.com/LoginAgent.aspx", data=self.logindata, verify=False, timeout=30)
+        res = self.session.post("https://booking2.airasia.com/LoginAgent.aspx", data=self.logindata, verify=False, timeout=60)
         agentHomeUrl = res.url
+        logging.info(self.salt+agentHomeUrl)
+        logging.info(self.salt+str(self.logindata))
         htmlContent = res.content.decode()
         isReload = 'window.location.reload'
         if isReload in htmlContent:
@@ -201,23 +225,23 @@ class OrderServer():
             htmlContent = res.content.decode()
         if 'ZENG' in htmlContent:
             #登录成功
-            print('AK_Agent登录成功')
+            logging.info(self.salt+'AK_Agent登录成功')
             return True
         else:
             #登录失败
-            print('AK_Agent登录失败')
+            logging.info(self.salt+'AK_Agent登录失败')
             return False
     #代理人查询
     def AgentSearch(self):
         res = self.session.get("https://booking2.airasia.com/Search.aspx")
-        print('打开查询页面')
+        logging.info(self.salt+'打开查询页面')
         externalRateList = re.findall(r'ExternalRateList":(.*)},\n', res.text)[0]
         rateinfo = json.loads(externalRateList)
         currencyAkId = 'default'
         for rate in rateinfo:
             if rate['quotedCurrency'] == self.oinfo.currencyCode and rate['collectedCurrency'] == 'CNY':
                 currencyAkId = rate['code']
-        print('币种ID:'+str(currencyAkId)) 
+        logging.info(self.salt+'币种ID:'+str(currencyAkId)) 
         self.oinfo.currenctAkCode = currencyAkId
         
         #--------------------------组织请求参数-----------------
@@ -258,7 +282,7 @@ class OrderServer():
                 '__VIEWSTATEGENERATOR':'05F9A2B0'
             }
         
-        res = self.session.post('https://booking2.airasia.com/Search.aspx',verify=False,data=searchDate,timeout=30)
+        res = self.session.post('https://booking2.airasia.com/Search.aspx',verify=False,data=searchDate,timeout=60)
         #解析代理人查询结果
         self.AgentSearchAnalysis(res.text)
 
@@ -300,8 +324,8 @@ class OrderServer():
                     typsJson['radioValue'] = radioValue
                     fromJson[cabinObj[index]['code']] =  typsJson
                 index +=1
-        print(fromJson)
-        print('-------------------返程数据---------------------')    
+        logging.info(self.salt+str(fromJson))
+        logging.info(self.salt+'-------------------返程数据---------------------')    
         retJson = {}
         if self.oinfo.tripType == 2:
             fromTableTr =  b("tr[class='rgRow']", tablessss[1])
@@ -331,8 +355,8 @@ class OrderServer():
                         typsJson['radioValue'] = radioValue
                         retJson[cabinObj[index]['code']] =  typsJson
                     index +=1
-        print(retJson)
-        print('............................................')
+        logging.info(self.salt+str(retJson))
+        logging.info(self.salt+'............................................')
         self.oinfo.agentIsOk = True
         self.oinfo.agentFromJson = fromJson
         self.oinfo.agentRetJson = retJson
@@ -436,8 +460,8 @@ class OrderServer():
         self.oinfo.fromRadioValue = agfromVal
         self.oinfo.retRadioValue = agretVal
     
-        print('去程字符串:'+self.oinfo.fromRadioValue)
-        print('回程字符串:'+self.oinfo.retRadioValue)
+        logging.info(self.salt+'去程字符串:'+self.oinfo.fromRadioValue)
+        logging.info(self.salt+'回程字符串:'+self.oinfo.retRadioValue)
     
         
     #航班选定
@@ -485,13 +509,13 @@ class OrderServer():
             flightData['ControlGroupSelectView$AvailabilityInputSelectView$market2'] = self.oinfo.retRadioValue
         else:
             flightData['oneWayOnly'] = '1'
-        print('--------提交航班 ')
-        print('go:'+self.oinfo.fromRadioValue)
-        print('back:'+self.oinfo.retRadioValue)
-        res = self.session.post('https://booking2.airasia.com/Select.aspx', data=flightData, verify=False,timeout = 30)
-        print('提交成功,打开填写乘客信息页面')
-        print(res.status_code)
-        print(res.url)
+        logging.info(self.salt+'--------提交航班 ')
+        logging.info(self.salt+'go:'+self.oinfo.fromRadioValue)
+        logging.info(self.salt+'back:'+self.oinfo.retRadioValue)
+        res = self.session.post('https://booking2.airasia.com/Select.aspx', data=flightData, verify=False,timeout = 60)
+        logging.info(self.salt+'提交成功,打开填写乘客信息页面')
+        logging.info(self.salt+str(res.status_code))
+        logging.info(self.salt+res.url)
         return res.text
     #乘机人信息填写
     def Passenger(self,passHtml):
@@ -580,11 +604,11 @@ class OrderServer():
             passengerData["CONTROLGROUP_OUTERTRAVELER$CONTROLGROUPTRAVELER$PassengerInputTravelerView$DropDownListBirthDateDay_%d_%d" % (idx, idx)] = passenger.birthday[-2:]
             passengerData["CONTROLGROUP_OUTERTRAVELER$CONTROLGROUPTRAVELER$PassengerInputTravelerView$DropDownListBirthDateMonth_%d_%d" % (idx, idx)] = passenger.birthday[5:7]
             passengerData["CONTROLGROUP_OUTERTRAVELER$CONTROLGROUPTRAVELER$PassengerInputTravelerView$DropDownListBirthDateMonth_ONTROLGROUPTRAVELER$PassengerInputTravelerView$DropDownListBirthDateYear_%d_%d" % (idx, idx)] = passenger.birthday[:4]
-        print('------------------------------------------提交乘机人---:')
-        res = self.session.post('https://booking2.airasia.com/Traveler.aspx', data=passengerData, verify=False,timeout = 30)
-        print('乘机人提交成功,进入下一步!')
-        print(res.status_code)
-        print(res.url)
+        logging.info(self.salt+'------------------------------------------提交乘机人---:')
+        res = self.session.post('https://booking2.airasia.com/Traveler.aspx', data=passengerData, verify=False,timeout = 60)
+        logging.info(self.salt+'乘机人提交成功,进入下一步!')
+        logging.info(self.salt+str(res.status_code))
+        logging.info(self.salt+res.url)
         return res.text
     def AddOns(self,addOnsHtml):    
         page = etree.HTML(addOnsHtml)
@@ -627,12 +651,11 @@ class OrderServer():
             }
         for row in page.xpath("//div[starts-with(@class,'ctw-book')]/input/@name"):
             AddOnsData[row]='0'
-        print('-------------提交租车服务')
-        print(AddOnsData)
-        res = self.session.post('https://booking2.airasia.com/AddOns.aspx', data=AddOnsData, verify=False,timeout = 30)
-        print('附加服务提交成功,进入下一步!')
-        print(res.status_code)
-        print(res.url)
+        logging.info(self.salt+'-------------提交租车服务')
+        res = self.session.post('https://booking2.airasia.com/AddOns.aspx', data=AddOnsData, verify=False,timeout = 60)
+        logging.info(self.salt+'附加服务提交成功,进入下一步!')
+        logging.info(self.salt+str(res.status_code))
+        logging.info(self.salt+res.url)
         return res.text
     def UnitMap(self,unitMapHtml):
         b = pq(unitMapHtml) 
@@ -652,13 +675,10 @@ class OrderServer():
         inputList = b.find("#passengerListBody input")
         for row in inputList:
             UnitMapData[pq(row).attr("name")] = ''
-        res = self.session.post('https://booking2.airasia.com/UnitMap.aspx', data=UnitMapData, verify=False,timeout = 30)
-        print('选择舱位提交成功,进入下一步!')
-        print(res.status_code)
-        print(res.url)
-        f3 = open('E://testUnitMap.html', 'w',encoding='utf-8')
-        f3.write(res.text.replace('position: fixed; top: 0; left: 0; background: #ffffff; filter:alpha(opacity=70); -moz-opacity:0.7; opacity: 0.7; z-index:9997; width:100%; height:100%;',''))
-        f3.close()
+        res = self.session.post('https://booking2.airasia.com/UnitMap.aspx', data=UnitMapData, verify=False,timeout = 60)
+        logging.info(self.salt+'选择舱位提交成功,进入下一步!')
+        logging.info(self.salt+str(res.status_code))
+        logging.info(self.salt+res.url)
         return res.text
     #支付选择
     def Payment(self,payHtml):
@@ -681,10 +701,10 @@ class OrderServer():
             'HiddenFieldPageBookingData':page.xpath('//input[@id="HiddenFieldPageBookingDataId"]/@value')[0],
             '__VIEWSTATEGENERATOR':'05F9A2B0'
             }
-        res = self.session.post('https://booking2.airasia.com/Payment.aspx', data=PaymentData, verify=False,timeout = 30)
-        print('支付选择提交成,进入下一步!')
-        print(res.status_code)
-        print(res.url)
+        res = self.session.post('https://booking2.airasia.com/Payment.aspx', data=PaymentData, verify=False,timeout = 60)
+        logging.info(self.salt+'支付选择提交成,进入下一步!')
+        logging.info(self.salt+str(res.status_code))
+        logging.info(self.salt+res.url)
         f4 = open('E://testPayment.html', 'w',encoding='utf-8')
         f4.write(res.text.replace('position: fixed; top: 0; left: 0; background: #ffffff; filter:alpha(opacity=70); -moz-opacity:0.7; opacity: 0.7; z-index:9997; width:100%; height:100%;',''))
         f4.close()

+ 24 - 5
src/query/AkBigQuery.py

@@ -2,6 +2,10 @@
 import json
 import requests
 import datetime
+import logging
+import time
+import random
+import string
 
 class AkBigQuery:
     def __init__(self,queryInputJson,tripType,flightList,retFlights,fxRate):
@@ -11,14 +15,23 @@ class AkBigQuery:
         self.queryInputJson = queryInputJson
         self.fxRate = fxRate
     def StartQuery(self):
+        #开始执行时间
+        salt = ''.join(random.sample(string.ascii_letters + string.digits, 8))
+        start = time.clock()
         queryUrl = 'http://128.14.29.146/bigsearch/airasia/big/app/testsearch'
         headers = {'Content-Type': 'application/json'}
         fromJson = {}
         retJson = {}
         isOk = True
         session = requests.session()
+        logging.info(salt+"|queryUrl:"+queryUrl)
+        logging.info(salt+"|tripType:"+str(self.tripType))
+        logging.info(salt+"|flightList:"+str(self.flightList))
+        logging.info(salt+"|retFlights:"+str(self.retFlights))
+        logging.info(salt+"|fxRate:"+str(self.fxRate))
+        logging.info(salt+"|queryInputJson:"+str(self.queryInputJson))
         res = session.post(queryUrl, headers=headers, json=self.queryInputJson)
-        print(res.text)
+        logging.info(salt+"|retJson:"+res.text)
         json_str = json.loads(res.text)
         if 200 == json_str['status']:
             fromSegments = json_str['attachment']['fromSegments']
@@ -81,16 +94,22 @@ class AkBigQuery:
                         break
         else:
             isOk =False
+        end = time.clock()
+        logging.info(salt+"|isOk:"+str(isOk))
+        logging.info(salt+"|fromJson:"+str(fromJson))
+        logging.info(salt+"|retJson:"+str(retJson))
+        logging.info(salt+"|read: %f s" % (end - start))
         return (fromJson,retJson,isOk)
 if __name__ == '__main__':
-    begin = datetime.datetime.now()
-
     
+    
+    
+    begin = datetime.datetime.now()    
     queryInputJson = {"adultNum":1,"childNum":0,"formCity":"KUL","fromDate":"2018-04-29","id":0,"retDate":"2018-05-29","toCity":"DPS","tripType":"2","uuid":"AKBing","currency":"CNY"}
     flightList = 'QZ555'
     retFlights = 'AK377'
-    akbig = AkBigQuery(queryInputJson,2,flightList,retFlights)
-    fromQueryJson,retQuerJson = akbig.StartQuery()
+    akbig = AkBigQuery(queryInputJson,2,flightList,retFlights,1)
+    fromQueryJson,retQuerJson,isOk = akbig.StartQuery()
     print(fromQueryJson)
     print(retQuerJson)
         

+ 21 - 3
src/query/AkWebQuery.py

@@ -2,6 +2,10 @@
 import json
 import requests
 import datetime
+import logging
+import time
+import random
+import string
 
 class AkWebQuery:
     def __init__(self,queryInputJson,tripType,flightList,retFlights,fxRate):
@@ -11,14 +15,23 @@ class AkWebQuery:
         self.queryInputJson = queryInputJson
         self.fxRate = fxRate
     def StartQuery(self):
+        start = time.clock()
+        salt = ''.join(random.sample(string.ascii_letters + string.digits, 8))
         queryUrl = 'http://128.14.29.146/bigsearch/ariasiaweb/newsearch'
         headers = {'Content-Type': 'application/json'}
         fromJson = {}
         retJson = {}
         isOk = True
         session = requests.session()
+        logging.info(salt+"|queryUrl:"+queryUrl)
+        logging.info(salt+"|tripType:"+str(self.tripType))
+        logging.info(salt+"|flightList:"+str(self.flightList))
+        logging.info(salt+"|retFlights:"+str(self.retFlights))
+        logging.info(salt+"|fxRate:"+str(self.fxRate))
+        logging.info(salt+"|queryInputJson:"+str(self.queryInputJson))
         res = session.post(queryUrl, headers=headers, json=self.queryInputJson)
         #print(res.status_code)
+        logging.info(salt+"|retJson:"+res.text)
         print(res.text)
         json_str = json.loads(res.text)
         if 200 == json_str['status']:
@@ -42,7 +55,7 @@ class AkWebQuery:
                         typsJson['adultPrice'] = i['adultPrice']
                         typsJson['adultTax'] = i['adultTax']
                         typsJson['priceTotal'] = round(i['adultPrice']+i['adultTax'],2)
-                        typsJson['radioValue'] = '0~O~~O00H00~AAB1~~2024~X|QZ~ 555~ ~~KUL~04/29/2018 21:50~DPS~04/30/2018 00:55~@04/29/2018 13:50:00'
+                        typsJson['radioValue'] = i['dataMap']['priceKey']
                         fromJson[i['cabin']] =  typsJson
                     break
             if 2 == self.tripType:
@@ -66,11 +79,16 @@ class AkWebQuery:
                             typsJson['adultPrice'] = i['adultPrice']
                             typsJson['adultTax'] = i['adultTax']
                             typsJson['priceTotal'] = round(i['adultPrice']+i['adultTax'],2)
-                            typsJson['radioValue'] = '0~O~~O00H00~AAB1~~2024~X|QZ~ 555~ ~~KUL~04/29/2018 21:50~DPS~04/30/2018 00:55~@04/29/2018 13:50:00'
+                            typsJson['radioValue'] = i['dataMap']['priceKey']
                             retJson[i['cabin']] =  typsJson
                         break
         else:
             isOk =False
+        logging.info(salt+"|isOk:"+str(isOk))
+        logging.info(salt+"|fromJson:"+str(fromJson))
+        logging.info(salt+"|retJson:"+str(retJson))
+        end = time.clock()
+        logging.info(salt+"|read: %f s" % (end - start))
         return (fromJson,retJson,isOk)
 if __name__ == '__main__':
     begin = datetime.datetime.now()
@@ -79,7 +97,7 @@ if __name__ == '__main__':
     flightList = 'QZ555'
     retFlights = 'AK377'
     akweb = AkWebQuery(queryInputJson,2,flightList,retFlights,1)
-    fromQueryJson,retQuerJson = akweb.StartQuery()
+    fromQueryJson,retQuerJson,isOk = akweb.StartQuery()
     print(fromQueryJson)
     print(retQuerJson)
     

文件差异内容过多而无法显示
+ 28 - 13
src/test/GreatHtmlTest.py


+ 20 - 13
src/utils/CallbackOrderUtils.py

@@ -3,18 +3,21 @@ import requests
 import json
 from entity.OrderInfo import Currency
 
+import logging
+import random
+import string
+
 class CallbackOrderUtils():
     
-    #callbackurl = "http://203.130.42.247/mgr/"
-    callbackurl = "http://192.168.1.5:11009/"
+    callbackurl = "http://123.103.51.83/mgr/"
+    #callbackurl = "http://192.168.1.5:11009/"
     
     def __init__(self):
-        '''
-        Constructor
-        '''
+        self.salt = ''.join(random.sample(string.ascii_letters + string.digits, 16))+'|'
     #回调占座结果
     def BallbackOrder(self,orderNo,orderStatus,orderPnr,accountType,userName):
         url = self.callbackurl+"orOrdertb/orderCallBack"
+        self.salt = orderNo+'|'
         fromParam = {}
         fromParam['orderNo'] = orderNo
         fromParam['orderStatus'] = orderStatus
@@ -22,31 +25,35 @@ class CallbackOrderUtils():
         fromParam['accountType'] = accountType
         fromParam['userName'] = userName
         session = requests.session()
+        logging.info(self.salt+'回调占座结果:'+url)
+        logging.info(self.salt+str(fromParam))
         res = session.post(url,data=fromParam)
-        print(res.text)
+        logging.info(self.salt+res.text)
     #回调价格
     def BallbackPrice(self,orderNo,webPriceGo,webPriceBack,agentPriceGo,agentPriceBack,bigPriceGo,bigPriceBack):
         url = self.callbackurl+"orOrdertb/ballbackPrice"
-        print('价格回调:'+url)
+        self.salt = orderNo+'|'
         fromParam = {}
-        fromParam['orderNo'] = '2018021015034810637110181' #orderNo
+        fromParam['orderNo'] =   '2018030915450779734174620'  #orderNo
         fromParam['webPrice'] = str({'go':webPriceGo,'back':webPriceBack})
         fromParam['agentPrice'] = str({'go':agentPriceGo,'back':agentPriceBack})
         fromParam['bigPrice'] = str({'go':bigPriceGo,'back':bigPriceBack})
-        print(str(fromParam))
+        logging.info(self.salt+'价格回调:'+url)
+        logging.info(self.salt+str(fromParam))
         session = requests.session()
         res = session.post(url,data=fromParam)
-        print(res.text)
+        logging.info(self.salt+res.text)
     #通过机场三字码查询币种与汇率
     def cityToCurrency(self,stationCode):
         url = self.callbackurl+"scCitycurrency/cityToCurrency"
-        print(url)
         fromParam = {}
         fromParam['stationCode'] = stationCode
         session = requests.session()
+        logging.info(self.salt+url)
+        logging.info(self.salt+str(fromParam))
         res = session.post(url,data=fromParam)
+        logging.info(self.salt+res.text)
         json_str = json.loads(res.text)
-        print(json_str)
         if 200 == json_str['status']:
             json_str = json_str['attachment']
             currency = Currency()
@@ -62,7 +69,7 @@ class CallbackOrderUtils():
         return
 if __name__ == '__main__':
     cout = CallbackOrderUtils()
-    #cout.BallbackOrder('2018030915450779734174620', '1', 'YUNIHJ', '代理人占座', 'CNTRIPTOPK_ADMIN')
+    cout.BallbackOrder('2018030915450779734174620', '1', 'YUNIHJ', '代理人占座', 'CNTRIPTOPK_ADMIN')
     currency = cout.cityToCurrency('CAN')
     print(currency.currencyCode)
     

二进制
src/utils/__pycache__/CallbackOrderUtils.cpython-36.pyc


二进制
src/utils/__pycache__/__init__.cpython-36.pyc