def test_apis(self):
        wrapcache.flush()
        # get api
        key_1 = wrapcache.keyof(self.test_class.test_input_cache, i=1, j="hello world")
        value_1 = wrapcache.get(key_1)
        self.assertEqual(value_1, None, "test_apis fail")
        # set api
        value_2 = wrapcache.set(key_1, "test_value", timeout=3)
        self.assertEqual(value_2, "test_value", "test_keyof_api fail")
        # get api / timeout
        value_3 = wrapcache.get(key_1)
        self.assertEqual(value_3, "test_value", "test_keyof_api fail")
        time.sleep(3)
        self.assertEqual(wrapcache.get(key_1), None, "test_apis fail")

        # remove api
        value_4 = wrapcache.set(key_1, "test_value 4", timeout=3)
        self.assertEqual(value_4, "test_value 4", "test_keyof_api fail")
        value_5 = wrapcache.remove(key_1)
        self.assertEqual(value_4, value_5, "test_keyof_api fail")
        self.assertEqual(wrapcache.get(key_1), None, "test_apis fail")

        # flush api
        value_6 = wrapcache.set(key_1, "test_value 4", timeout=3)
        self.assertEqual(value_6, "test_value 4", "test_keyof_api fail")
        self.assertTrue(wrapcache.flush(), "test_keyof_api fail")
        self.assertEqual(wrapcache.get(key_1), None, "test_apis fail")
Example #2
0
    def test_apis(self):
        wrapcache.flush()
        #get api
        key_1 = wrapcache.keyof(self.test_class.test_input_cache,
                                i=1,
                                j='hello world')
        value_1 = wrapcache.get(key_1)
        self.assertEqual(value_1, None, 'test_apis fail')
        #set api
        value_2 = wrapcache.set(key_1, 'test_value', timeout=3)
        self.assertEqual(value_2, 'test_value', 'test_keyof_api fail')
        #get api / timeout
        value_3 = wrapcache.get(key_1)
        self.assertEqual(value_3, 'test_value', 'test_keyof_api fail')
        time.sleep(3)
        self.assertEqual(wrapcache.get(key_1), None, 'test_apis fail')

        #remove api
        value_4 = wrapcache.set(key_1, 'test_value 4', timeout=3)
        self.assertEqual(value_4, 'test_value 4', 'test_keyof_api fail')
        value_5 = wrapcache.remove(key_1)
        self.assertEqual(value_4, value_5, 'test_keyof_api fail')
        self.assertEqual(wrapcache.get(key_1), None, 'test_apis fail')

        #flush api
        value_6 = wrapcache.set(key_1, 'test_value 4', timeout=3)
        self.assertEqual(value_6, 'test_value 4', 'test_keyof_api fail')
        self.assertTrue(wrapcache.flush(), 'test_keyof_api fail')
        self.assertEqual(wrapcache.get(key_1), None, 'test_apis fail')
    def get_passenger_ticket_strlist_and_oldpassenger_str(self, secret_str, secret_list):
        """
        获取提交车次人内容格式
        passengerTicketStr	O,0,1,文贤平,1,43052419950223XXXX,15618715583,N_O,0,1,梁敏,1,43052719920118XXXX,,N
        oldPassengerStr	文贤平,1,43052719920118XXXX,1_梁敏,1,43052719920118XXXX,1
        ps: 如果is_more_ticket打开了的话,那就是读取联系人列表里面前符合车次数量的前几个联系人
        :return:
        """
        passenger_ticket_str_list = []
        old_passenger_str = []
        tickers = []
        set_type = ""
        if wrapcache.get("user_info"):  # 如果缓存中有联系人方式,则读取缓存中的联系人
            user_info = wrapcache.get("user_info")
            print(u"使用缓存中查找的联系人信息")
        else:
            user_info = self.send_get_passenger_dtos()
            wrapcache.set("user_info", user_info, timeout=9999999)
        if not user_info:
            raise PassengerUserException(Ticket.DTO_NOT_IN_LIST)
        if len(user_info) < self.is_more_ticket_num:  # 如果乘车人填错了导致没有这个乘车人的话,可能乘车人数会小于自动乘车人
            self.is_more_ticket_num = len(user_info)
        if secret_str:
            set_type = self.get_passenger_ticket_str(self.set_type)
            if self.is_more_ticket_num is 1:
                passenger_ticket_str_list.append(
                    '0,' + user_info[0]['passenger_type'] + "," + user_info[0][
                        "passenger_name"] + "," +
                    user_info[0]['passenger_id_type_code'] + "," + user_info[0]['passenger_id_no'] + "," +
                    user_info[0]['mobile_no'] + ',N,' + user_info[0]["allEncStr"])
                old_passenger_str.append(
                    user_info[0]['passenger_name'] + "," + user_info[0]['passenger_id_type_code'] + "," +
                    user_info[0]['passenger_id_no'] + "," + user_info[0]['passenger_type'] + '_')
            else:
                for i in range(self.is_more_ticket_num):
                    passenger_ticket_str_list.append(
                        '0,' + user_info[i]['passenger_type'] + "," + user_info[i][
                            "passenger_name"] + "," + user_info[i]['passenger_id_type_code'] + "," + user_info[i][
                            'passenger_id_no'] + "," + user_info[i]['mobile_no'] + ',N,' + user_info[i]["allEncStr"] + '_' + set_type)
                    old_passenger_str.append(
                        user_info[i]['passenger_name'] + "," + user_info[i]['passenger_id_type_code'] + "," +
                        user_info[i]['passenger_id_no'] + "," + user_info[i]['passenger_type'] + '_')
        elif secret_list:
            """
            候补订单有多少个联系人,就候补多少个联系人了,没有优先提交之说
            1#XXXX#1#***************77X#bf6ae40d3655ae7eff005ee21d95876b38ab97a8031b464bc2f74a067e3ec957;
            """
            for user in user_info:
                tickers.append(f"1#{user['passenger_name']}#1#{user['passenger_id_no']}#{user['allEncStr']};")

        return {
            "passengerTicketStrList": set_type + "," + ",".join(passenger_ticket_str_list),
            "passengerTicketStrByAfterLate": "".join(tickers),
            "oldPassengerStr": "".join(old_passenger_str),
            "code": Ticket.SUCCESS_CODE,
            "set_type": set_type,
            "status": True,
            "user_info": user_info,
        }
Example #4
0
 def sendCheckUser(self):
     """
     检查用户登录, 检查间隔为2分钟
     :return:
     """
     CHENK_TIME = 0.3
     if wrapcache.get("user_time") is None:
         check_user_url = self.session.urls["check_user_url"]
         data = {"_json_att": ""}
         check_user = self.session.httpClint.send(check_user_url, data)
         if check_user.get("data", False):
             check_user_flag = check_user["data"]["flag"]
             if check_user_flag is True:
                 wrapcache.set("user_time",
                               datetime.datetime.now(),
                               timeout=60 * CHENK_TIME)
             else:
                 if check_user['messages']:
                     print(
                         ticket.LOGIN_SESSION_FAIL.format(
                             check_user['messages']))
                     self.session.call_login()
                     wrapcache.set("user_time",
                                   datetime.datetime.now(),
                                   timeout=60 * CHENK_TIME)
                 else:
                     print(
                         ticket.LOGIN_SESSION_FAIL.format(
                             check_user['messages']))
                     self.session.call_login()
                     wrapcache.set("user_time",
                                   datetime.datetime.now(),
                                   timeout=60 * CHENK_TIME)
Example #5
0
 def sendCheckUser(self):
     """
     检查用户登录, 检查间隔为2分钟
     :return:
     """
     CHENK_TIME = 0.3
     while 1:
         time.sleep(0.1)  # 防止cpu占用过高
         configCommon.checkSleepTime(self.session)   # 修复晚上查询线程休眠时,检查登录线程为休眠,造成快豆迅速消耗
         if wrapcache.get("user_time") is None:
             check_user_url = self.session.urls["check_user_url"]
             data = {"_json_att": ""}
             check_user = self.session.httpClint.send(check_user_url, data)
             if check_user.get("data", False):
                 check_user_flag = check_user["data"]["flag"]
                 if check_user_flag is True:
                     wrapcache.set("user_time", datetime.datetime.now(), timeout=60 * CHENK_TIME)
                 else:
                     if check_user['messages']:
                         print (ticket.LOGIN_SESSION_FAIL.format(check_user['messages']))
                         self.session.call_login()
                         wrapcache.set("user_time", datetime.datetime.now(), timeout=60 * CHENK_TIME)
                     else:
                         print (ticket.LOGIN_SESSION_FAIL.format(check_user['messages']))
                         self.session.call_login()
                         wrapcache.set("user_time", datetime.datetime.now(), timeout=60 * CHENK_TIME)
Example #6
0
 def user_is_connecting(self):
     """
     检查用户登录, 检查间隔为五分钟
     :return:
     """
     check_user_url = self.session.urls["check_user_url"]
     data = {"_json_att": ""}
     if wrapcache.get("user_time") is None:
         check_user = self.session.httpClint.send(check_user_url, data)
         if check_user.get("data", False):
             check_user_flag = check_user["data"]["flag"]
             if check_user_flag is True:
                 wrapcache.set("user_time",
                               datetime.datetime.now(),
                               timeout=60 * 5)
                 return True
             else:
                 if check_user['messages']:
                     print(
                         ticket.LOGIN_SESSION_FAIL.format(
                             check_user['messages']))
                 else:
                     print(
                         ticket.LOGIN_SESSION_FAIL.format(
                             check_user['messages']))
         return False
     else:
         return True
Example #7
0
 def getPassengerTicketStrListAndOldPassengerStr(self):
     """
     获取提交车次人内容格式
     passengerTicketStr	O,0,1,文贤平,1,43052419950223XXXX,15618715583,N_O,0,1,梁敏,1,43052719920118XXXX,,N
     oldPassengerStr	文贤平,1,43052719920118XXXX,1_梁敏,1,43052719920118XXXX,1
     ps: 如果is_more_ticket打开了的话,那就是读取联系人列表里面前符合车次数量的前几个联系人
     :return:
     """
     passengerTicketStrList = []
     oldPassengerStr = []
     if wrapcache.get("user_info"):  # 如果缓存中有联系人方式,则读取缓存中的联系人
         user_info = wrapcache.get("user_info")
         print(u"缓存中找到联系人信息: {0}".format(user_info))
     else:
         user_info = self.sendGetPassengerDTOs()
         wrapcache.set("user_info", user_info, timeout=9999999)
     set_type = self.getPassengerTicketStr(self.set_type)
     if not user_info:
         raise PassengerUserException(ticket.DTO_NOT_IN_LIST)
     if len(user_info) < self.is_more_ticket_num:  # 如果乘车人填错了导致没有这个乘车人的话,可能乘车人数会小于自动乘车人
         self.is_more_ticket_num = len(user_info)
     if self.is_more_ticket_num is 1:
         passengerTicketStrList.append(
             '0,' + user_info[0]['passenger_type'] + "," + user_info[0][
                 "passenger_name"] + "," +
             user_info[0]['passenger_id_type_code'] + "," + user_info[0]['passenger_id_no'] + "," +
             user_info[0]['mobile_no'] + ',N')
         oldPassengerStr.append(
             user_info[0]['passenger_name'] + "," + user_info[0]['passenger_id_type_code'] + "," +
             user_info[0]['passenger_id_no'] + "," + user_info[0]['passenger_type'] + '_')
     else:
         for i in xrange(self.is_more_ticket_num):
             passengerTicketStrList.append(
                 '0,' + user_info[i]['passenger_type'] + "," + user_info[i][
                     "passenger_name"] + "," + user_info[i]['passenger_id_type_code'] + "," + user_info[i][
                     'passenger_id_no'] + "," + user_info[i]['mobile_no'] + ',N_' + set_type)
             oldPassengerStr.append(
                 user_info[i]['passenger_name'] + "," + user_info[i]['passenger_id_type_code'] + "," +
                 user_info[i]['passenger_id_no'] + "," + user_info[i]['passenger_type'] + '_')
     return {
         "passengerTicketStrList": set_type + "," + ",".join(passengerTicketStrList),
         "oldPassengerStr": "".join(oldPassengerStr),
         "code": ticket.SUCCESS_CODE,
         "set_type": set_type,
         "status": True,
         "user_info": user_info,
     }
Example #8
0
 def getPassengerTicketStrListAndOldPassengerStr(self):
     """
     获取提交车次人内容格式
     passengerTicketStr	O,0,1,文贤平,1,43052419950223XXXX,15618715583,N_O,0,1,梁敏,1,43052719920118XXXX,,N
     oldPassengerStr	文贤平,1,43052719920118XXXX,1_梁敏,1,43052719920118XXXX,1
     ps: 如果is_more_ticket打开了的话,那就是读取联系人列表里面前符合车次数量的前几个联系人
     :return:
     """
     passengerTicketStrList = []
     oldPassengerStr = []
     if wrapcache.get("user_info"):  # 如果缓存中有联系人方式,则读取缓存中的联系人
         user_info = wrapcache.get("user_info")
         print(u"缓存中找到联系人信息: {0}".format(user_info))
     else:
         user_info = self.sendGetPassengerDTOs()
         wrapcache.set("user_info", user_info, timeout=9999999)
     set_type = self.getPassengerTicketStr(self.set_type)
     if not user_info:
         raise PassengerUserException(ticket.DTO_NOT_IN_LIST)
     if len(user_info) < self.is_more_ticket_num:  # 如果乘车人填错了导致没有这个乘车人的话,可能乘车人数会小于自动乘车人
         self.is_more_ticket_num = len(user_info)
     if self.is_more_ticket_num is 1:
         passengerTicketStrList.append(
             '0,' + user_info[0]['passenger_type'] + "," + user_info[0][
                 "passenger_name"] + "," +
             user_info[0]['passenger_id_type_code'] + "," + user_info[0]['passenger_id_no'] + "," +
             user_info[0]['mobile_no'] + ',N')
         oldPassengerStr.append(
             user_info[0]['passenger_name'] + "," + user_info[0]['passenger_id_type_code'] + "," +
             user_info[0]['passenger_id_no'] + "," + user_info[0]['passenger_type'] + '_')
     else:
         for i in xrange(self.is_more_ticket_num):
             passengerTicketStrList.append(
                 '0,' + user_info[i]['passenger_type'] + "," + user_info[i][
                     "passenger_name"] + "," + user_info[i]['passenger_id_type_code'] + "," + user_info[i][
                     'passenger_id_no'] + "," + user_info[i]['mobile_no'] + ',N_' + set_type)
             oldPassengerStr.append(
                 user_info[i]['passenger_name'] + "," + user_info[i]['passenger_id_type_code'] + "," +
                 user_info[i]['passenger_id_no'] + "," + user_info[i]['passenger_type'] + '_')
     return {
         "passengerTicketStrList": set_type + "," + ",".join(passengerTicketStrList),
         "oldPassengerStr": "".join(oldPassengerStr),
         "code": ticket.SUCCESS_CODE,
         "set_type": set_type,
         "status": True,
         "user_info": user_info,
     }
Example #9
0
    def test_apis(self):
        wrapcache.flush()
        #get api
        key_1 = wrapcache.keyof(self.test_class.test_input_cache, i = 1, j = 'hello world')
        value_1 = wrapcache.get(key_1)
        if not value_1:
            keyNone = True
        self.assertEqual(keyNone, True, 'test_apis fail')
        #set api
        value_2 =  wrapcache.set(key_1, 'test_value', timeout = 3)
        self.assertEqual(value_2, 'test_value', 'test_keyof_api fail')
        #get api / timeout
        value_3 = wrapcache.get(key_1)
        self.assertEqual(value_3, 'test_value', 'test_keyof_api fail')
        time.sleep(3)
        value_3 = wrapcache.get(key_1)
        if not value_3:
            keyNone = True
        self.assertEqual(keyNone, True, 'test_apis fail')

        #remove api
        value_4 =  wrapcache.set(key_1, 'test_value 4', timeout = 3)
        self.assertEqual(value_4, 'test_value 4', 'test_keyof_api fail')
        value_5 = wrapcache.remove(key_1)
        self.assertEqual(value_4, value_5, 'test_keyof_api fail')

        value_3 = wrapcache.get(key_1)
        if not value_5:
            keyNone = True
        self.assertEqual(keyNone, True, 'test_apis fail')

        #flush api
        value_6 =  wrapcache.set(key_1, 'test_value 4', timeout = 3)
        self.assertEqual(value_6, 'test_value 4', 'test_keyof_api fail')
        self.assertTrue(wrapcache.flush(), 'test_keyof_api fail')

        value_6 = wrapcache.get(key_1)
        if not value_6:
            keyNone = True
        self.assertEqual(keyNone, True, 'test_apis fail')
Example #10
0
 def sendCheckUser(self):
     """
     检查用户登录, 检查间隔为2分钟
     :return:
     """
     CHENK_TIME = 0.3
     while 1:
         time.sleep(0.1)  # 防止cpu占用过高
         configCommon.checkSleepTime(
             self.session)  # 修复晚上查询线程休眠时,检查登录线程为休眠,造成快豆迅速消耗
         if wrapcache.get("user_time") is None:
             check_user_url = self.session.urls["check_user_url"]
             data = {"_json_att": ""}
             check_user = self.session.httpClint.send(check_user_url, data)
             if check_user.get("data", False):
                 check_user_flag = check_user["data"]["flag"]
                 if check_user_flag is True:
                     wrapcache.set("user_time",
                                   datetime.datetime.now(),
                                   timeout=random.randint(60, 80) *
                                   CHENK_TIME)
                 else:
                     if check_user['messages']:
                         print(
                             ticket.LOGIN_SESSION_FAIL.format(
                                 check_user['messages']))
                         self.session.call_login()
                         wrapcache.set("user_time",
                                       datetime.datetime.now(),
                                       timeout=random.randint(60, 80) *
                                       CHENK_TIME)
                     else:
                         print(
                             ticket.LOGIN_SESSION_FAIL.format(
                                 check_user['messages']))
                         self.session.call_login()
                         wrapcache.set("user_time",
                                       datetime.datetime.now(),
                                       timeout=random.randint(60, 80) *
                                       CHENK_TIME)
Example #11
0
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import wrapcache
from time import sleep
import random


@wrapcache.wrapcache(timeout=3)
def need_cache_function(input, t=2, o=3):
    sleep(2)
    return random.randint(1, 100)


if __name__ == "__main__":
    for i in range(10):
        # sleep(1)
        print(need_cache_function(1, t=2, o=3))

    # get cache Programmatic
    key_func = wrapcache.keyof(need_cache_function)
    print(wrapcache.get(key_func))

    # remove cache Programmatic
    # print(wrapcache.remove(wrapcache.keyof(need_cache_function, 1, o=3, t=2)))
Example #12
0
 def send_query(self):
     """
     查询
     :return:
     """
     if TickerConfig.IS_CDN == 1 and self.session.cdn_list:
         self.httpClient.cdn = self.session.cdn_list[random.randint(
             4,
             len(self.session.cdn_list) - 1)]
     for station_date in self.station_dates:
         select_url = copy.copy(self.urls["select_url"])
         select_url["req_url"] = select_url["req_url"].format(
             station_date, self.from_station, self.to_station,
             self.session.queryUrl)
         station_ticket = self.httpClient.send(select_url)
         value = station_ticket.get("data", "")
         if not value:
             print(
                 u'{0}-{1} 车次坐席查询为空,查询url: https://kyfw.12306.cn{2}, 可以手动查询是否有票'
                 .format(self.from_station_h, self.to_station_h,
                         select_url["req_url"]))
         else:
             result = value.get('result', [])
             if result:
                 for i in value['result']:
                     ticket_info = i.split('|')
                     if self.session.flag:
                         print(
                             f"车次:{ticket_info[3]} 出发站:{self.from_station_h} 到达站:{self.to_station_h} 历时:{ticket_info[10]}"
                             f" 商务/特等座:{ticket_info[32] or '--'}"
                             f" 一等座:{ticket_info[31] or '--'}"
                             f" 二等座:{ticket_info[30] or '--'}"
                             f" 动卧:{ticket_info[33] or '--'}"
                             f" 硬卧:{ticket_info[28] or '--'}"
                             f" 软座:{ticket_info[23] or '--'}"
                             f" 硬座:{ticket_info[29] or '--'}"
                             f" 无座:{ticket_info[26] or '--'}"
                             f" {ticket_info[1] or '--'}")
                     if ticket_info[1] == "预订" and self.check_is_need_train(
                             ticket_info):  # 筛选未在开始时间内的车次
                         for j in self._station_seat:
                             is_ticket_pass = ticket_info[j]
                             if ticket_info[11] == "Y":
                                 if is_ticket_pass != '' and is_ticket_pass != '无' and is_ticket_pass != '*':  # 过滤有效目标车次
                                     secret_str = ticket_info[0]
                                     train_no = ticket_info[2]
                                     query_from_station_name = ticket_info[
                                         6]
                                     query_to_station_name = ticket_info[7]
                                     train_location = ticket_info[15]
                                     station_train_code = ticket_info[3]
                                     left_ticket = ticket_info[12]
                                     start_time = ticket_info[8]
                                     arrival_time = ticket_info[9]
                                     distance_time = ticket_info[10]
                                     print(start_time, arrival_time,
                                           distance_time)
                                     seat = j
                                     try:
                                         ticket_num = int(ticket_info[j])
                                     except ValueError:
                                         ticket_num = "有"
                                     print(
                                         u'车次: {0} 始发车站: {1} 终点站: {2} {3}: {4}'
                                         .format(ticket_info[3],
                                                 self.from_station_h,
                                                 self.to_station_h,
                                                 seat_conf_2[j],
                                                 ticket_num))
                                     if seat_conf_2[
                                             j] == "无座" and ticket_info[3][
                                                 0] in ["G", "D", "C"]:
                                         seat = 30  # GD开头的无座直接强制改为二等座车次
                                     if wrapcache.get(train_no):
                                         print(
                                             Ticket.QUERY_IN_BLACK_LIST.
                                             format(train_no))
                                         continue
                                     else:
                                         if ticket_num != "有" and self.ticke_peoples_num > ticket_num:
                                             if TickerConfig.IS_MORE_TICKET:
                                                 print(
                                                     u"余票数小于乘车人数,当前余票数: {}, 删减人车人数到: {}"
                                                     .format(
                                                         ticket_num,
                                                         ticket_num))
                                                 is_more_ticket_num = ticket_num
                                             else:
                                                 print(
                                                     u"余票数小于乘车人数,当前设置不提交,放弃此次提交机会"
                                                 )
                                                 continue
                                         else:
                                             print(u"设置乘车人数为: {}".format(
                                                 self.ticke_peoples_num))
                                             is_more_ticket_num = self.ticke_peoples_num
                                         print(Ticket.QUERY_C)
                                         return {
                                             "secretStr": secret_str,
                                             "train_no": train_no,
                                             "stationTrainCode":
                                             station_train_code,
                                             "train_date": station_date,
                                             "query_from_station_name":
                                             query_from_station_name,
                                             "query_to_station_name":
                                             query_to_station_name,
                                             "seat": seat,
                                             "leftTicket": left_ticket,
                                             "train_location":
                                             train_location,
                                             "code": Ticket.SUCCESS_CODE,
                                             "is_more_ticket_num":
                                             is_more_ticket_num,
                                             "cdn": self.httpClient.cdn,
                                             "status": True,
                                         }
                             elif is_ticket_pass == '无' and ticket_info[
                                     37] == "1" and TickerConfig.TICKET_TYPE is 2:
                                 """
                                 is_ticket_pass如果有别的显示,但是可以候补,可以提issues提出来,附上query log,我将添加上
                                 判断车次是否可以候补
                                 目前的候补机制是只要一有候补位置,立马提交候补
                                 """
                                 # 如果最后一位为1,则是可以候补的,不知道这些正确嘛?
                                 nate = list(ticket_info[38])
                                 if wrapcache.get(f"hb{ticket_info[2]}"):
                                     continue
                                 for set_type in TickerConfig.SET_TYPE:
                                     if TickerConfig.PASSENGER_TICKER_STR[
                                             set_type] not in nate:
                                         if ticket_info[3][0] in [
                                                 "G", "D", "C"
                                         ] and set_type in [
                                                 "一等座", "特等座", "二等座", "商务座",
                                                 "无座"
                                         ]:
                                             return {
                                                 "secretList":
                                                 ticket_info[0],
                                                 "seat": [set_type],
                                                 "train_no": ticket_info[2],
                                                 "status": True,
                                                 "cdn": self.httpClient.cdn,
                                             }
                                         elif ticket_info[3][0] in [
                                                 "T", "Z", "K"
                                         ] and set_type in [
                                                 "硬卧", "硬座", "无座", "软座",
                                                 "软卧"
                                         ]:
                                             return {
                                                 "secretList":
                                                 ticket_info[0],
                                                 "seat": [set_type],
                                                 "train_no": ticket_info[2],
                                                 "status": True,
                                                 "cdn": self.httpClient.cdn,
                                             }
             else:
                 print(u"车次配置信息有误,或者返回数据异常,请检查 {}".format(station_ticket))
     self.session.flag = False
     return {
         "code": Ticket.FAIL_CODE,
         "status": False,
         "cdn": self.httpClient.cdn,
     }
Example #13
0
    def main(self):
        l = liftTicketInit(self)
        l.reqLiftTicketInit()
        getDrvicesID(self)
        self.call_login()
        check_user = checkUser(self)
        t = threading.Thread(target=check_user.sendCheckUser)
        t.setDaemon(True)
        t.start()
        from_station, to_station = self.station_table(
            TickerConfig.FROM_STATION, TickerConfig.TO_STATION)
        num = 0
        s = getPassengerDTOs(selectObj=self,
                             ticket_peoples=TickerConfig.TICKET_PEOPLES)
        passenger = s.sendGetPassengerDTOs()
        wrapcache.set("user_info", passenger, timeout=9999999)

        now = datetime.datetime.now()
        if TickerConfig.ORDER_MODEL is 1:
            print(
                f"预售还未开始,阻塞中,预售时间为{TickerConfig.OPEN_TIME}, 当前时间为: {now.strftime('%H:%M:%S')}"
            )
            sleep_time_s = 0.1
            sleep_time_t = 0.3
            # 测试了一下有微妙级的误差,应该不影响,测试结果:2019-01-02 22:30:00.004555,预售还是会受到前一次刷新的时间影响,暂时没想到好的解决方案
            while now.strftime("%H:%M:%S") < TickerConfig.OPEN_TIME:
                now = datetime.datetime.now()
                time.sleep(0.0001)
            print(f"预售开始,开启时间为: {now.strftime('%H:%M:%S')}")
        else:
            sleep_time_s = TickerConfig.MIN_TIME
            sleep_time_t = TickerConfig.MAX_TIME

        while 1:
            try:
                num += 1
                now = datetime.datetime.now()  # 感谢群里大佬提供整点代码
                configCommon.checkSleepTime(self)  # 晚上到点休眠
                q = query(
                    selectObj=self,
                    from_station=from_station,
                    to_station=to_station,
                    from_station_h=TickerConfig.FROM_STATION,
                    to_station_h=TickerConfig.TO_STATION,
                    _station_seat=self._station_seat,
                    station_trains=TickerConfig.STATION_TRAINS,
                    station_dates=TickerConfig.STATION_DATES,
                    ticke_peoples_num=len(TickerConfig.TICKET_PEOPLES),
                )
                queryResult = q.sendQuery()
                # 查询接口
                if queryResult.get("status"):
                    train_no = queryResult.get("train_no", "")
                    train_date = queryResult.get("train_date", "")
                    stationTrainCode = queryResult.get("stationTrainCode", "")
                    secretStr = queryResult.get("secretStr", "")
                    secretList = queryResult.get("secretList", "")
                    seat = queryResult.get("seat", "")
                    leftTicket = queryResult.get("leftTicket", "")
                    query_from_station_name = queryResult.get(
                        "query_from_station_name", "")
                    query_to_station_name = queryResult.get(
                        "query_to_station_name", "")
                    is_more_ticket_num = queryResult.get(
                        "is_more_ticket_num", len(TickerConfig.TICKET_PEOPLES))
                    if wrapcache.get(train_no):
                        print(ticket.QUEUE_WARNING_MSG.format(train_no))
                    else:
                        # 获取联系人
                        s = getPassengerDTOs(
                            selectObj=self,
                            ticket_peoples=TickerConfig.TICKET_PEOPLES,
                            set_type=""
                            if isinstance(seat, list) else seat_conf_2[seat],
                            # 候补订单需要设置多个坐席
                            is_more_ticket_num=is_more_ticket_num)
                        getPassengerDTOsResult = s.getPassengerTicketStrListAndOldPassengerStr(
                            secretStr, secretList)
                        if getPassengerDTOsResult.get("status", False):
                            self.passengerTicketStrList = getPassengerDTOsResult.get(
                                "passengerTicketStrList", "")
                            self.passengerTicketStrByAfterLate = getPassengerDTOsResult.get(
                                "passengerTicketStrByAfterLate", "")
                            self.oldPassengerStr = getPassengerDTOsResult.get(
                                "oldPassengerStr", "")
                            self.set_type = getPassengerDTOsResult.get(
                                "set_type", "")
                        # 提交订单
                        # 订单分为两种,一种为抢单,一种为候补订单
                        if secretStr:  # 正常下单
                            if TickerConfig.ORDER_TYPE == 1:  # 快速下单
                                a = autoSubmitOrderRequest(
                                    selectObj=self,
                                    secretStr=secretStr,
                                    train_date=train_date,
                                    passengerTicketStr=self.
                                    passengerTicketStrList,
                                    oldPassengerStr=self.oldPassengerStr,
                                    train_no=train_no,
                                    stationTrainCode=stationTrainCode,
                                    leftTicket=leftTicket,
                                    set_type=self.set_type,
                                    query_from_station_name=
                                    query_from_station_name,
                                    query_to_station_name=query_to_station_name,
                                )
                                a.sendAutoSubmitOrderRequest()
                            elif TickerConfig.ORDER_TYPE == 2:  # 普通下单
                                sor = submitOrderRequest(
                                    self, secretStr, from_station, to_station,
                                    train_no, self.set_type,
                                    self.passengerTicketStrList,
                                    self.oldPassengerStr, train_date,
                                    TickerConfig.TICKET_PEOPLES)
                                sor.sendSubmitOrderRequest()
                        elif secretList:  # 候补订单
                            c = chechFace(self, secretList, train_no)
                            c.sendChechFace()
                else:
                    random_time = round(
                        random.uniform(sleep_time_s, sleep_time_t), 2)
                    nateMsg = ' 无候补机会' if TickerConfig.ORDER_TYPE == 2 else ""
                    print(
                        f"正在第{num}次查询 停留时间:{random_time} 乘车日期: {','.join(TickerConfig.STATION_DATES)} 车次:{','.join(TickerConfig.STATION_TRAINS) or '所有车次'} 下单无票{nateMsg} 耗时:{(datetime.datetime.now() - now).microseconds / 1000} {queryResult.get('cdn')}"
                    )
                    time.sleep(random_time)
            except PassengerUserException as e:
                print(e)
                break
            except ticketConfigException as e:
                print(e)
                break
            except ticketIsExitsException as e:
                print(e)
                break
            except ticketNumOutException as e:
                print(e)
                break
            except UserPasswordException as e:
                print(e)
                break
            except ValueError as e:
                if e == "No JSON object could be decoded":
                    print(u"12306接口无响应,正在重试")
                else:
                    print(e)
            except KeyError as e:
                print(e)
            except TypeError as e:
                print(u"12306接口无响应,正在重试 {0}".format(e))
            except socket.error as e:
                print(e)
Example #14
0
 def sendQuery(self):
     """
     查询
     :return:
     """
     if self.session.is_cdn == 1:
         if self.session.cdn_list:
             self.httpClint.cdn = self.session.cdn_list[random.randint(
                 0,
                 len(self.session.cdn_list) - 1)]
     for station_date in self.station_dates:
         select_url = copy.copy(self.urls["select_url"])
         select_url["req_url"] = select_url["req_url"].format(
             station_date, self.from_station, self.to_station,
             self.session.queryUrl)
         station_ticket = self.httpClint.send(select_url)
         if station_ticket.get("c_url", ""):
             print(station_ticket.get("c_url", ""))
             self.session.queryUrl = station_ticket.get("c_url",
                                                        "")  # 重设查询接口
             continue
         value = station_ticket.get("data", "")
         if not value:
             print(
                 u'{0}-{1} 车次坐席查询为空, 查询url: https://kyfw.12306.cn{2}, 可以手动查询是否有票'
                 .format(self.from_station_h, self.to_station_h,
                         select_url["req_url"]))
         else:
             result = value.get('result', [])
             if result:
                 for i in value['result']:
                     ticket_info = i.split('|')
                     if ticket_info[11] == "Y" and ticket_info[1].encode(
                             "utf8") == "预订":  # 筛选未在开始时间内的车次
                         for j in self._station_seat:
                             is_ticket_pass = ticket_info[j]
                             if is_ticket_pass != '' and is_ticket_pass != '无' and is_ticket_pass != '*' and self.check_is_need_train(
                                     ticket_info):  # 过滤有效目标车次
                                 secretStr = ticket_info[0]
                                 train_no = ticket_info[2]
                                 query_from_station_name = ticket_info[6]
                                 query_to_station_name = ticket_info[7]
                                 train_location = ticket_info[15]
                                 stationTrainCode = ticket_info[3]
                                 leftTicket = ticket_info[12]
                                 start_time = ticket_info[8]
                                 arrival_time = ticket_info[9]
                                 distance_time = ticket_info[10]
                                 print start_time, arrival_time, distance_time
                                 seat = j
                                 try:
                                     ticket_num = int(ticket_info[j])
                                 except ValueError:
                                     ticket_num = "有"
                                 print(
                                     u'车次: {0} 始发车站: {1} 终点站: {2} {3}: {4}'.
                                     format(ticket_info[3],
                                            self.from_station_h,
                                            self.to_station_h,
                                            seat_conf_2[j], ticket_num))
                                 if wrapcache.get(train_no):
                                     print(
                                         ticket.QUERY_IN_BLACK_LIST.format(
                                             train_no))
                                     continue
                                 else:
                                     if ticket_num != "有" and self.ticke_peoples_num > ticket_num:
                                         if self.session.is_more_ticket:
                                             print(
                                                 u"余票数小于乘车人数,当前余票数: {}, 删减人车人数到: {}"
                                                 .format(
                                                     ticket_num,
                                                     ticket_num))
                                             is_more_ticket_num = ticket_num
                                         else:
                                             print(
                                                 u"余票数小于乘车人数,当前设置不提交,放弃此次提交机会"
                                             )
                                             continue
                                     else:
                                         print(u"设置乘车人数为: {}".format(
                                             self.ticke_peoples_num))
                                         is_more_ticket_num = self.ticke_peoples_num
                                     print(ticket.QUERY_C)
                                     return {
                                         "secretStr": secretStr,
                                         "train_no": train_no,
                                         "stationTrainCode":
                                         stationTrainCode,
                                         "train_date": station_date,
                                         "query_from_station_name":
                                         query_from_station_name,
                                         "query_to_station_name":
                                         query_to_station_name,
                                         "seat": seat,
                                         "leftTicket": leftTicket,
                                         "train_location": train_location,
                                         "code": ticket.SUCCESS_CODE,
                                         "is_more_ticket_num":
                                         is_more_ticket_num,
                                         "cdn": self.httpClint.cdn,
                                         "status": True,
                                     }
             else:
                 print u"车次配置信息有误,或者返回数据异常,请检查 {}".format(station_ticket)
     return {"code": ticket.FAIL_CODE, "status": False}
Example #15
0
 def sendQuery(self):
     """
     查询
     :return:
     """
     if self.session.is_cdn == 1:
         if self.session.cdn_list:
             self.httpClint.cdn = self.session.cdn_list[random.randint(0, len(self.session.cdn_list) - 1)]
     for station_date in self.station_dates:
         select_url = copy.copy(self.urls["select_url"])
         select_url["req_url"] = select_url["req_url"].format(station_date, self.from_station, self.to_station,
                                                              self.session.queryUrl)
         station_ticket = self.httpClint.send(select_url)
         if station_ticket.get("c_url", ""):
             print(u"设置当前查询url为: {}".format(station_ticket.get("c_url", "")))
             self.session.queryUrl = station_ticket.get("c_url", "")  # 重设查询接口
             continue
         value = station_ticket.get("data", "")
         if not value:
             print (u'{0}-{1} 车次坐席查询为空,ip网络异常,查询url: https://kyfw.12306.cn{2}, 可以手动查询是否有票'.format(self.from_station_h,
                                                                                            self.to_station_h,
                                                                                            select_url["req_url"]))
         else:
             result = value.get('result', [])
             if result:
                 for i in value['result']:
                     ticket_info = i.split('|')
                     if ticket_info[11] == "Y" and ticket_info[1].encode("utf8") == "预订":  # 筛选未在开始时间内的车次
                         for j in self._station_seat:
                             is_ticket_pass = ticket_info[j]
                             if is_ticket_pass != '' and is_ticket_pass != '无' and is_ticket_pass != '*' and self.check_is_need_train(
                                     ticket_info):  # 过滤有效目标车次
                                 secretStr = ticket_info[0]
                                 train_no = ticket_info[2]
                                 query_from_station_name = ticket_info[6]
                                 query_to_station_name = ticket_info[7]
                                 train_location = ticket_info[15]
                                 stationTrainCode = ticket_info[3]
                                 leftTicket = ticket_info[12]
                                 start_time = ticket_info[8]
                                 arrival_time = ticket_info[9]
                                 distance_time = ticket_info[10]
                                 print(start_time, arrival_time, distance_time)
                                 seat = j
                                 try:
                                     ticket_num = int(ticket_info[j])
                                 except ValueError:
                                     ticket_num = "有"
                                 print (u'车次: {0} 始发车站: {1} 终点站: {2} {3}: {4}'.format(ticket_info[3],
                                                                                      self.from_station_h,
                                                                                      self.to_station_h,
                                                                                      seat_conf_2[j],
                                                                                      ticket_num))
                                 if wrapcache.get(train_no):
                                     print(ticket.QUERY_IN_BLACK_LIST.format(train_no))
                                     continue
                                 else:
                                     if ticket_num != "有" and self.ticke_peoples_num > ticket_num:
                                         if self.session.is_more_ticket:
                                             print(
                                                 u"余票数小于乘车人数,当前余票数: {}, 删减人车人数到: {}".format(ticket_num, ticket_num))
                                             is_more_ticket_num = ticket_num
                                         else:
                                             print(u"余票数小于乘车人数,当前设置不提交,放弃此次提交机会")
                                             continue
                                     else:
                                         print(u"设置乘车人数为: {}".format(self.ticke_peoples_num))
                                         is_more_ticket_num = self.ticke_peoples_num
                                     print (ticket.QUERY_C)
                                     return {
                                         "secretStr": secretStr,
                                         "train_no": train_no,
                                         "stationTrainCode": stationTrainCode,
                                         "train_date": station_date,
                                         "query_from_station_name": query_from_station_name,
                                         "query_to_station_name": query_to_station_name,
                                         "seat": seat,
                                         "leftTicket": leftTicket,
                                         "train_location": train_location,
                                         "code": ticket.SUCCESS_CODE,
                                         "is_more_ticket_num": is_more_ticket_num,
                                         "cdn": self.httpClint.cdn,
                                         "status": True,
                                     }
             else:
                 print(u"车次配置信息有误,或者返回数据异常,请检查 {}".format(station_ticket))
     return {"code": ticket.FAIL_CODE, "status": False, "cdn": self.httpClint.cdn,}
Example #16
0
    def go_qiangpiao(self, tricket_info, log_info=[], num=1):
        try:
            from_station_h = tricket_info['from_station']
            to_station_h = tricket_info['to_station']
            from_station, to_station = self.station_name_map[
                from_station_h], self.station_name_map[to_station_h]
        except:
            return log_info.append(u'站点输入有误,请检查!')
        try:
            checkUser(self).sendCheckUser()
            now_time = time.strftime('%H:%M:%S', time.localtime(time.time()))
            while now_time > "23:00:00" or now_time < "06:00:00":
                time.sleep(5)
                now_time = time.strftime('%H:%M:%S',
                                         time.localtime(time.time()))
                if "06:00:00" < now_time < "23:00:00":
                    log_info.append(ticket.REST_TIME_PAST)
                    print(ticket.REST_TIME_PAST)
                    self.call_login()
                    break

            start_time = datetime.datetime.now()
            q = query(session=self,
                      from_station=from_station,
                      to_station=to_station,
                      from_station_h=from_station_h,
                      to_station_h=to_station_h,
                      _station_seat=tricket_info['seat'],
                      station_trains=tricket_info['trains'],
                      station_dates=tricket_info['date'])

            queryResult = q.sendQuery(log_info)
            # 查询接口
            # tmp = queryResult.get("status", False)
            # assert tmp == False
            if queryResult.get("status", False):
                train_no = queryResult.get("train_no", "")
                train_date = queryResult.get("train_date", "")
                stationTrainCode = queryResult.get("stationTrainCode", "")
                set_type = queryResult.get("set_type", "")
                secretStr = queryResult.get("secretStr", "")
                leftTicket = queryResult.get("leftTicket", "")
                query_from_station_name = queryResult.get(
                    "query_from_station_name", "")
                query_to_station_name = queryResult.get(
                    "query_to_station_name", "")
                if wrapcache.get(train_no):
                    print(ticket.QUEUE_WARNING_MSG.format(train_no))
                    log_info.append(ticket.QUEUE_WARNING_MSG.format(train_no))
                else:
                    # 获取联系人
                    if not self.passengerTicketStrList and not self.oldPassengerStr:
                        s = getPassengerDTOs(
                            session=self,
                            ticket_peoples=tricket_info['person_name'],
                            set_type=set_type)
                        #
                        getPassengerDTOsResult = s.getPassengerTicketStrListAndOldPassengerStr(
                        )
                        if getPassengerDTOsResult.get("status", False):
                            self.passengerTicketStrList = getPassengerDTOsResult.get(
                                "passengerTicketStrList", "")
                            self.oldPassengerStr = getPassengerDTOsResult.get(
                                "oldPassengerStr", "")
                            set_type = getPassengerDTOsResult.get(
                                "set_type", "")
                    self.order_type = 2
                    # 提交订单
                    if self.order_type == 1:  # 快读下单
                        a = autoSubmitOrderRequest(
                            session=self,
                            secretStr=secretStr,
                            train_date=train_date,
                            passengerTicketStr=self.passengerTicketStrList,
                            oldPassengerStr=self.oldPassengerStr,
                            train_no=train_no,
                            stationTrainCode=stationTrainCode,
                            leftTicket=leftTicket,
                            set_type=set_type,
                            query_from_station_name=query_from_station_name,
                            query_to_station_name=query_to_station_name,
                        )
                        a.sendAutoSubmitOrderRequest(log_info)
                    elif self.order_type == 2:  # 普通下单
                        sor = submitOrderRequest(
                            self, secretStr, from_station, to_station,
                            train_no, set_type, self.passengerTicketStrList,
                            self.oldPassengerStr, train_date,
                            self.ticke_peoples)
                        sor.sendSubmitOrderRequest(log_info)
            else:
                random_time = round(random.uniform(1, 4), 2)
                time.sleep(random_time)
                mess = u"正在第{0}次查询 随机停留时长:{6}s 乘车日期: {1} 车次:{2} 查询无票 cdn轮询IP:{4}当前cdn总数:{5} 总耗时:{3}ms".format(
                    num, ",".join(tricket_info['date']),
                    tricket_info['trains'],
                    (datetime.datetime.now() - start_time).microseconds / 1000,
                    self.httpClint.cdn, len(self.cdn_list), random_time)
                print mess
                log_info.append(mess)
        except PassengerUserException as e:
            print e.message
            log_info.append(e.message)
            # break
        except ticketConfigException as e:
            print e.message
            log_info.append(e.message)
            # break
        except ticketIsExitsException as e:
            print e.message
            log_info.append(e.message)
            # break
        except ticketNumOutException as e:
            print e.message
            log_info.append(e.message)
            # break
        except UserPasswordException as e:
            print e.message
            log_info.append(e.message)
            # break
        except ValueError as e:
            if e.message == "No JSON object could be decoded":
                print(u"12306接口无响应,正在重试")
                log_info.append(u"12306接口无响应,正在重试")
            else:
                print(e.message)
                log_info.append(e.message)
        except KeyError as e:
            print(e.message)
            log_info.append(e.message)
        except TypeError as e:
            print(u"12306接口无响应,正在重试 {0}".format(e.message))
            log_info.append(u"12306接口无响应,正在重试 {0}".format(e.message))
        except socket.error as e:
            print e
            log_info.append(e.message)
Example #17
0
 def main(self):
     # autoSynchroTime()  # 同步时间
     self.cdn_certification()
     l = liftTicketInit(self)
     l.reqLiftTicketInit()
     self.call_login()
     check_user = checkUser(self)
     t = threading.Thread(target=check_user.sendCheckUser)
     t.setDaemon(True)
     t.start()
     from_station, to_station = self.station_table(self.from_station,
                                                   self.to_station)
     num = 0
     s = getPassengerDTOs(session=self, ticket_peoples=self.ticke_peoples)
     passenger = s.sendGetPassengerDTOs()
     wrapcache.set("user_info", passenger, timeout=9999999)
     while 1:
         try:
             num += 1
             now = datetime.datetime.now()  # 感谢群里大佬提供整点代码
             configCommon.checkSleepTime(self)  # 晚上到点休眠
             if self.order_model is 1:
                 sleep_time_s = 0.5
                 sleep_time_t = 0.6
                 # 测试了一下有微妙级的误差,应该不影响,测试结果:2019-01-02 22:30:00.004555,预售还是会受到前一次刷新的时间影响,暂时没想到好的解决方案
                 while not now.strftime("%H:%M:%S") == self.open_time:
                     now = datetime.datetime.now()
                     if now.strftime("%H:%M:%S") > self.open_time:
                         break
                     time.sleep(0.0001)
             else:
                 sleep_time_s = 0.5
                 sleep_time_t = 3
             q = query(
                 session=self,
                 from_station=from_station,
                 to_station=to_station,
                 from_station_h=self.from_station,
                 to_station_h=self.to_station,
                 _station_seat=self._station_seat,
                 station_trains=self.station_trains,
                 station_dates=self.station_dates,
                 ticke_peoples_num=len(self.ticke_peoples),
             )
             queryResult = q.sendQuery()
             # 查询接口
             if queryResult.get("status", False):
                 train_no = queryResult.get("train_no", "")
                 train_date = queryResult.get("train_date", "")
                 stationTrainCode = queryResult.get("stationTrainCode", "")
                 secretStr = queryResult.get("secretStr", "")
                 seat = queryResult.get("seat", "")
                 leftTicket = queryResult.get("leftTicket", "")
                 query_from_station_name = queryResult.get(
                     "query_from_station_name", "")
                 query_to_station_name = queryResult.get(
                     "query_to_station_name", "")
                 is_more_ticket_num = queryResult.get(
                     "is_more_ticket_num", len(self.ticke_peoples))
                 if wrapcache.get(train_no):
                     print(ticket.QUEUE_WARNING_MSG.format(train_no))
                 else:
                     # 获取联系人
                     s = getPassengerDTOs(
                         session=self,
                         ticket_peoples=self.ticke_peoples,
                         set_type=seat_conf_2[seat],
                         is_more_ticket_num=is_more_ticket_num)
                     getPassengerDTOsResult = s.getPassengerTicketStrListAndOldPassengerStr(
                     )
                     if getPassengerDTOsResult.get("status", False):
                         self.passengerTicketStrList = getPassengerDTOsResult.get(
                             "passengerTicketStrList", "")
                         self.oldPassengerStr = getPassengerDTOsResult.get(
                             "oldPassengerStr", "")
                         self.set_type = getPassengerDTOsResult.get(
                             "set_type", "")
                     # 提交订单
                     if self.order_type == 1:  # 快读下单
                         a = autoSubmitOrderRequest(
                             session=self,
                             secretStr=secretStr,
                             train_date=train_date,
                             passengerTicketStr=self.passengerTicketStrList,
                             oldPassengerStr=self.oldPassengerStr,
                             train_no=train_no,
                             stationTrainCode=stationTrainCode,
                             leftTicket=leftTicket,
                             set_type=self.set_type,
                             query_from_station_name=query_from_station_name,
                             query_to_station_name=query_to_station_name,
                         )
                         a.sendAutoSubmitOrderRequest()
                     elif self.order_type == 2:  # 普通下单
                         sor = submitOrderRequest(
                             self, secretStr, from_station, to_station,
                             train_no, self.set_type,
                             self.passengerTicketStrList,
                             self.oldPassengerStr, train_date,
                             self.ticke_peoples)
                         sor.sendSubmitOrderRequest()
             else:
                 random_time = round(
                     random.uniform(sleep_time_s, sleep_time_t), 2)
                 print(
                     u"正在第{0}次查询 随机停留时长:{6} 乘车日期: {1} 车次:{2} 查询无票 cdn轮询IP:{4}当前cdn总数:{5} 总耗时:{3}ms"
                     .format(num, ",".join(self.station_dates),
                             ",".join(self.station_trains),
                             (datetime.datetime.now() - now).microseconds /
                             1000, queryResult.get("cdn", None),
                             len(self.cdn_list), random_time))
                 time.sleep(random_time)
         except PassengerUserException as e:
             print(e)
             break
         except ticketConfigException as e:
             print(e)
             break
         except ticketIsExitsException as e:
             print(e)
             break
         except ticketNumOutException as e:
             print(e)
             break
         except UserPasswordException as e:
             print(e)
             break
         except ValueError as e:
             if e == "No JSON object could be decoded":
                 print(u"12306接口无响应,正在重试")
             else:
                 print(e)
         except KeyError as e:
             print(e)
         except TypeError as e:
             print(u"12306接口无响应,正在重试 {0}".format(e))
         except socket.error as e:
             print(e)
Example #18
0
    def main(self):
        self.cdn_certification()
        l = liftTicketInit(session=self)
        l.reqLiftTicketInit()
        self.call_login()
        checkUser(self).sendCheckUser()
        from_station, to_station = self.station_table(self.from_station, self.to_station)
        num = 0
        while 1:
            try:
                num += 1
                checkUser(self).sendCheckUser()
                if time.strftime('%H:%M:%S', time.localtime(time.time())) > "23:00:00" or time.strftime('%H:%M:%S',
                                                                                                        time.localtime(
                                                                                                            time.time())) < "06:00:00":
                    print(ticket.REST_TIME)
                    # while 1:
                    #     time.sleep(1)
                    #     if "06:00:00" < time.strftime('%H:%M:%S', time.localtime(time.time())) < "23:00:00":
                    #         print(ticket.REST_TIME_PAST)
                    #         self.call_login()
                    #         break
                start_time = datetime.datetime.now()

                q = query(session=self,
                          from_station=from_station,
                          to_station=to_station,
                          from_station_h=self.from_station,
                          to_station_h=self.to_station,
                          _station_seat=self._station_seat,
                          station_trains=self.station_trains,
                          station_dates=self.station_dates, )
                queryResult = q.sendQuery()
                # 查询接口
                # tmp = queryResult.get("status", False)
                # assert tmp == False
                if queryResult.get("status", False):
                    train_no = queryResult.get("train_no", "")
                    train_date = queryResult.get("train_date", "")
                    stationTrainCode = queryResult.get("stationTrainCode", "")
                    set_type = queryResult.get("set_type", "")
                    secretStr = queryResult.get("secretStr", "")
                    leftTicket = queryResult.get("leftTicket", "")
                    query_from_station_name = queryResult.get("query_from_station_name", "")
                    query_to_station_name = queryResult.get("query_to_station_name", "")
                    if wrapcache.get(train_no):
                        print(ticket.QUEUE_WARNING_MSG.format(train_no))
                    else:
                        # 获取联系人
                        if not self.passengerTicketStrList and not self.oldPassengerStr:
                            s = getPassengerDTOs(session=self, ticket_peoples=self.ticke_peoples, set_type=set_type)
                            #
                            getPassengerDTOsResult = s.getPassengerTicketStrListAndOldPassengerStr()
                            if getPassengerDTOsResult.get("status", False):
                                self.passengerTicketStrList = getPassengerDTOsResult.get("passengerTicketStrList", "")
                                self.oldPassengerStr = getPassengerDTOsResult.get("oldPassengerStr", "")
                                set_type = getPassengerDTOsResult.get("set_type", "")
                        # 提交订单
                        if self.order_type == 1:  # 快读下单
                            a = autoSubmitOrderRequest(session=self,
                                                       secretStr=secretStr,
                                                       train_date=train_date,
                                                       passengerTicketStr=self.passengerTicketStrList,
                                                       oldPassengerStr=self.oldPassengerStr,
                                                       train_no=train_no,
                                                       stationTrainCode=stationTrainCode,
                                                       leftTicket=leftTicket,
                                                       set_type=set_type,
                                                       query_from_station_name=query_from_station_name,
                                                       query_to_station_name=query_to_station_name,
                                                       )
                            a.sendAutoSubmitOrderRequest()
                        elif self.order_type == 2:  # 普通下单
                            sor = submitOrderRequest(self, secretStr, from_station, to_station, train_no, set_type,
                                                     self.passengerTicketStrList, self.oldPassengerStr, train_date,
                                                     self.ticke_peoples)
                            sor.sendSubmitOrderRequest()


                else:
                    random_time = round(random.uniform(1, 4), 2)
                    time.sleep(random_time)
                    print u"正在第{0}次查询 随机停留时长:{6} 乘车日期: {1} 车次:{2} 查询无票 cdn轮询IP:{4}当前cdn总数:{5} 总耗时:{3}ms".format(num,
                                                                                                                ",".join(
                                                                                                                    self.station_dates),
                                                                                                                ",".join(
                                                                                                                    self.station_trains),
                                                                                                                (datetime.datetime.now() - start_time).microseconds / 1000,
                                                                                                                self.httpClint.cdn,
                                                                                                                len(self.cdn_list),
                                                                                                                random_time)
            except PassengerUserException as e:
                print e.message
                break
            except ticketConfigException as e:
                print e.message
                break
            except ticketIsExitsException as e:
                print e.message
                break
            except ticketNumOutException as e:
                print e.message
                break
            except UserPasswordException as e:
                print e.message
                break
            except ValueError as e:
                if e.message == "No JSON object could be decoded":
                    print(u"12306接口无响应,正在重试")
                else:
                    print(e.message)
            except KeyError as e:
                print(e.message)
            except TypeError as e:
                print(u"12306接口无响应,正在重试 {0}".format(e.message))
            except socket.error as e:
                print(e.message)
Example #19
0
 def sendQuery(self):
     """
     查询
     :return:
     """
     for station_date in self.station_dates:
         select_url = copy.copy(self.urls["select_url"])
         select_url["req_url"] = select_url["req_url"].format(
             station_date, self.from_station, self.to_station)
         station_ticket = self.httpClint.send(select_url)
         value = station_ticket.get("data", "")
         if not value:
             print(u'{0}-{1} 车次坐席查询为空'.format(self.from_station_h,
                                              self.to_station_h))
         else:
             result = value.get('result', [])
             if result:
                 for i in value['result']:
                     ticket_info = i.split('|')
                     if ticket_info[11] == "Y" and ticket_info[1].encode(
                             "utf8") == "预订":  # 筛选未在开始时间内的车次
                         for j in xrange(len(self._station_seat)):
                             is_ticket_pass = ticket_info[self.station_seat(
                                 self._station_seat[j].encode("utf8"))]
                             if is_ticket_pass != '' and is_ticket_pass != '无' and ticket_info[
                                     3] in self.station_trains and is_ticket_pass != '*':  # 过滤有效目标车次
                                 secretStr = ticket_info[0]
                                 train_no = ticket_info[2]
                                 query_from_station_name = ticket_info[6]
                                 query_to_station_name = ticket_info[7]
                                 train_location = ticket_info[15]
                                 stationTrainCode = ticket_info[3]
                                 leftTicket = ticket_info[12]
                                 seat = self._station_seat[j].encode("utf8")
                                 try:
                                     ticket_num = int(
                                         ticket_info[self.station_seat(
                                             self._station_seat[j].encode(
                                                 "utf8"))])
                                 except ValueError:
                                     ticket_num = "有"
                                 print(
                                     u'车次: {0} 始发车站: {1} 终点站: {2} {3}: {4}'.
                                     format(
                                         ticket_info[3],
                                         self.from_station_h,
                                         self.to_station_h,
                                         self._station_seat[j].encode(
                                             "utf8"), ticket_num))
                                 if wrapcache.get(train_no):
                                     print(
                                         ticket.QUERY_IN_BLACK_LIST.format(
                                             train_no))
                                     continue
                                 else:
                                     if ticket_num != "有" and self.ticke_peoples_num > ticket_num:
                                         if self.session.is_more_ticket:
                                             print(
                                                 u"余票数小于乘车人数,当前余票数: {}, 删减人车人数到: {}"
                                                 .format(
                                                     ticket_num,
                                                     ticket_num))
                                             is_more_ticket_num = ticket_num
                                         else:
                                             print(
                                                 u"余票数小于乘车人数,当前设置不提交,放弃此次提交机会"
                                             )
                                             continue
                                     else:
                                         print(u"设置乘车人数为: {}".format(
                                             self.ticke_peoples_num))
                                         is_more_ticket_num = self.ticke_peoples_num
                                     print(ticket.QUERY_C)
                                     return {
                                         "secretStr": secretStr,
                                         "train_no": train_no,
                                         "stationTrainCode":
                                         stationTrainCode,
                                         "train_date": station_date,
                                         "query_from_station_name":
                                         query_from_station_name,
                                         "query_to_station_name":
                                         query_to_station_name,
                                         "seat": seat,
                                         "leftTicket": leftTicket,
                                         "train_location": train_location,
                                         "code": ticket.SUCCESS_CODE,
                                         "is_more_ticket_num":
                                         is_more_ticket_num,
                                         "status": True,
                                     }
             else:
                 print(u"车次配置信息有误,或者返回数据异常,请检查 {}".format(station_ticket))
     return {"code": ticket.FAIL_CODE, "status": False}
Example #20
0
 def sendQuery(self):
     """
     查询
     :return:
     """
     for station_date in self.station_dates:
         select_url = copy.copy(self.session.urls["select_url"])
         select_url["req_url"] = select_url["req_url"].format(
             station_date, self.from_station, self.to_station)
         station_ticket = self.session.httpClint.send(select_url)
         value = station_ticket.get("data", "")
         if not value:
             print(u'{0}-{1} 车次坐席查询为空'.format(self.from_station_h,
                                              self.to_station_h))
         else:
             result = value.get('result', [])
             if result:
                 for i in value['result']:
                     ticket_info = i.split('|')
                     if ticket_info[11] == "Y" and ticket_info[1].encode(
                             "utf8") == "预订":  # 筛选未在开始时间内的车次
                         for j in xrange(len(self._station_seat)):
                             is_ticket_pass = ticket_info[self.station_seat(
                                 self._station_seat[j].encode("utf8"))]
                             if is_ticket_pass != '' and is_ticket_pass != '无' and ticket_info[
                                     3] in self.station_trains and is_ticket_pass != '*':  # 过滤有效目标车次
                                 secretStr = ticket_info[0]
                                 train_no = ticket_info[2]
                                 query_from_station_name = ticket_info[6]
                                 query_to_station_name = ticket_info[7]
                                 train_location = ticket_info[15]
                                 stationTrainCode = ticket_info[3]
                                 leftTicket = ticket_info[12]
                                 set_type = self._station_seat[j]
                                 print(
                                     u'车次: {0} 始发车站: {1} 终点站: {2} {3}: {4}'.
                                     format(
                                         ticket_info[3],
                                         self.from_station_h,
                                         self.to_station_h,
                                         self._station_seat[j].encode(
                                             "utf8"),
                                         ticket_info[self.station_seat(
                                             self._station_seat[j].encode(
                                                 "utf8"))]))
                                 if wrapcache.get(train_no):
                                     print(
                                         ticket.QUERY_IN_BLACK_LIST.format(
                                             train_no))
                                     break
                                 else:
                                     print(ticket.QUERY_C)
                                     return {
                                         "secretStr": secretStr,
                                         "train_no": train_no,
                                         "stationTrainCode":
                                         stationTrainCode,
                                         "train_date": station_date,
                                         "query_from_station_name":
                                         query_from_station_name,
                                         "query_to_station_name":
                                         query_to_station_name,
                                         "set_type": set_type,
                                         "leftTicket": leftTicket,
                                         "train_location": train_location,
                                         "code": ticket.SUCCESS_CODE,
                                         "status": True,
                                     }
             else:
                 print u"车次配置信息有误,或者返回数据异常,请检查 {}".format(station_ticket)
     return {"code": ticket.FAIL_CODE, "status": False}
Example #21
0
 def sendQuery(self):
     """
     查询
     :return:
     """
     if TickerConfig.IS_CDN == 1:
         if self.session.cdn_list:
             self.httpClint.cdn = self.session.cdn_list[random.randint(
                 0,
                 len(self.session.cdn_list) - 1)]
     for station_date in self.station_dates:
         select_url = copy.copy(self.urls["select_url"])
         select_url["req_url"] = select_url["req_url"].format(
             station_date, self.from_station, self.to_station,
             self.session.queryUrl)
         station_ticket = self.httpClint.send(select_url)
         if station_ticket.get("c_url", ""):
             print(u"设置当前查询url为: {}".format(station_ticket.get("c_url",
                                                               "")))
             self.session.queryUrl = station_ticket.get("c_url",
                                                        "")  # 重设查询接口
             continue
         value = station_ticket.get("data", "")
         if not value:
             print(
                 u'{0}-{1} 车次坐席查询为空,查询url: https://kyfw.12306.cn{2}, 可以手动查询是否有票'
                 .format(self.from_station_h, self.to_station_h,
                         select_url["req_url"]))
         else:
             result = value.get('result', [])
             if result:
                 for i in value['result']:
                     ticket_info = i.split('|')
                     # if TickerConfig.TICKET_TYPE is 2 and self.check_is_need_train(ticket_info):
                     #     # 如果最后一位为1,则是可以候补的,不知道这些正确嘛?
                     #     if ticket_info[-2] == "1":
                     #         nate = list(ticket_info[-1])
                     #         for set_type in TickerConfig.SET_TYPE:
                     #             if TickerConfig.PASSENGER_TICKER_STR(set_type) not in nate:
                     #                 continue
                     #         print("当前订单可以候补,尝试提交候补订单")
                     #         return {
                     #             "secretStr":  ticket_info[0],
                     #             "seat": TickerConfig.SET_TYPE,
                     #             "status": True,
                     #         }
                     # elif TickerConfig.TICKET_TYPE is 1:
                     if ticket_info[1] == "预订" and self.check_is_need_train(
                             ticket_info):  # 筛选未在开始时间内的车次
                         for j in self._station_seat:
                             is_ticket_pass = ticket_info[j]
                             if ticket_info[11] == "Y":
                                 if is_ticket_pass != '' and is_ticket_pass != '无' and is_ticket_pass != '*':  # 过滤有效目标车次
                                     secretStr = ticket_info[0]
                                     train_no = ticket_info[2]
                                     query_from_station_name = ticket_info[
                                         6]
                                     query_to_station_name = ticket_info[7]
                                     train_location = ticket_info[15]
                                     stationTrainCode = ticket_info[3]
                                     leftTicket = ticket_info[12]
                                     start_time = ticket_info[8]
                                     arrival_time = ticket_info[9]
                                     distance_time = ticket_info[10]
                                     print(start_time, arrival_time,
                                           distance_time)
                                     seat = j
                                     try:
                                         ticket_num = int(ticket_info[j])
                                     except ValueError:
                                         ticket_num = "有"
                                     print(
                                         u'车次: {0} 始发车站: {1} 终点站: {2} {3}: {4}'
                                         .format(ticket_info[3],
                                                 self.from_station_h,
                                                 self.to_station_h,
                                                 seat_conf_2[j],
                                                 ticket_num))
                                     if wrapcache.get(train_no):
                                         print(
                                             ticket.QUERY_IN_BLACK_LIST.
                                             format(train_no))
                                         continue
                                     else:
                                         if ticket_num != "有" and self.ticke_peoples_num > ticket_num:
                                             if self.session.is_more_ticket:
                                                 print(
                                                     u"余票数小于乘车人数,当前余票数: {}, 删减人车人数到: {}"
                                                     .format(
                                                         ticket_num,
                                                         ticket_num))
                                                 is_more_ticket_num = ticket_num
                                             else:
                                                 print(
                                                     u"余票数小于乘车人数,当前设置不提交,放弃此次提交机会"
                                                 )
                                                 continue
                                         else:
                                             print(u"设置乘车人数为: {}".format(
                                                 self.ticke_peoples_num))
                                             is_more_ticket_num = self.ticke_peoples_num
                                         print(ticket.QUERY_C)
                                         return {
                                             "secretStr": secretStr,
                                             "train_no": train_no,
                                             "stationTrainCode":
                                             stationTrainCode,
                                             "train_date": station_date,
                                             "query_from_station_name":
                                             query_from_station_name,
                                             "query_to_station_name":
                                             query_to_station_name,
                                             "seat": seat,
                                             "leftTicket": leftTicket,
                                             "train_location":
                                             train_location,
                                             "code": ticket.SUCCESS_CODE,
                                             "is_more_ticket_num":
                                             is_more_ticket_num,
                                             "cdn": self.httpClint.cdn,
                                             "status": True,
                                         }
                             elif is_ticket_pass == '无' and ticket_info[
                                     -2] == "1" and TickerConfig.TICKET_TYPE is 2:
                                 """
                                 is_ticket_pass如果有别的显示,但是可以候补,可以提issues提出来,附上query log,我将添加上
                                 判断车次是否可以候补
                                 目前的候补机制是只要一有候补位置,立马提交候补
                                 """
                                 # 如果最后一位为1,则是可以候补的,不知道这些正确嘛?
                                 nate = list(ticket_info[-1])
                                 for set_type in TickerConfig.SET_TYPE:
                                     if TickerConfig.PASSENGER_TICKER_STR[
                                             set_type] not in nate:
                                         print(
                                             f"当前订单可以候补,候补位置为: {set_type}, 尝试提交候补订单"
                                         )
                                         return {
                                             "secretList": ticket_info[0],
                                             "seat": [set_type],
                                             "status": True,
                                         }
             else:
                 print(u"车次配置信息有误,或者返回数据异常,请检查 {}".format(station_ticket))
     return {
         "code": ticket.FAIL_CODE,
         "status": False,
         "cdn": self.httpClint.cdn,
     }