def sendGetQueueCountAsync(self): """ 请求排队接口 :return: """ urls = self.session.urls["getQueueCountAsync"] data = self.data_par() getQueueCountAsyncResult = self.session.httpClint.send(urls, data) if getQueueCountAsyncResult.get("status", False) and getQueueCountAsyncResult.get("data", False): if "status" in getQueueCountAsyncResult and getQueueCountAsyncResult["status"] is True: if "countT" in getQueueCountAsyncResult["data"]: ticket_data = getQueueCountAsyncResult["data"]["ticket"] ticket_split = sum(map(self.conversion_int, ticket_data.split(","))) if ticket_data.find( ",") != -1 else ticket_data print(u"排队成功, 当前余票还剩余: {0} 张".format(ticket_split)) c = confirmSingleForQueueAsys(session=self.session, passengerTicketStr=self.passengerTicketStr, oldPassengerStr=self.oldPassengerStr, result=self.result,) print(u"验证码提交安全期,等待{}MS".format(self.ifShowPassCodeTime)) time.sleep(self.ifShowPassCodeTime) c.sendConfirmSingleForQueueAsys() else: print(u"排队发现未知错误{0},将此列车 {1}加入小黑屋".format(getQueueCountAsyncResult, self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) elif "messages" in getQueueCountAsyncResult and getQueueCountAsyncResult["messages"]: print(u"排队异常,错误信息:{0}, 将此列车 {1}加入小黑屋".format(getQueueCountAsyncResult["messages"][0], self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) else: if "validateMessages" in getQueueCountAsyncResult and getQueueCountAsyncResult["validateMessages"]: print(str(getQueueCountAsyncResult["validateMessages"]))
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 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 sendGetQueueCountAsync(self): """ 请求排队接口 :return: """ urls = self.session.urls["getQueueCountAsync"] data = self.data_par() getQueueCountAsyncResult = self.session.httpClint.send(urls, data) if getQueueCountAsyncResult.get("status", False) and getQueueCountAsyncResult.get("data", False): if "status" in getQueueCountAsyncResult and getQueueCountAsyncResult["status"] is True: if "countT" in getQueueCountAsyncResult["data"]: ticket_data = getQueueCountAsyncResult["data"]["ticket"] ticket_split = sum(map(self.conversion_int, ticket_data.split(","))) if ticket_data.find( ",") != -1 else ticket_data print(u"排队成功, 当前余票还剩余: {0} 张".format(ticket_split)) c = confirmSingleForQueueAsys(session=self.session, passengerTicketStr=self.passengerTicketStr, oldPassengerStr=self.oldPassengerStr, result=self.result,) print(u"验证码提交安全期,等待{}MS".format(self.ifShowPassCodeTime)) time.sleep(self.ifShowPassCodeTime) c.sendConfirmSingleForQueueAsys() else: print(u"排队发现未知错误{0},将此列车 {1}加入小黑屋".format(getQueueCountAsyncResult, self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=TickerConfig.TICKET_BLACK_LIST_TIME * 60) elif "messages" in getQueueCountAsyncResult and getQueueCountAsyncResult["messages"]: print(u"排队异常,错误信息:{0}, 将此列车 {1}加入小黑屋".format(getQueueCountAsyncResult["messages"][0], self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=TickerConfig.TICKET_BLACK_LIST_TIME * 60) else: if "validateMessages" in getQueueCountAsyncResult and getQueueCountAsyncResult["validateMessages"]: print(str(getQueueCountAsyncResult["validateMessages"]))
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
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, }
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, }
def sendPassengerInitApi(self): passengerInitApiRsp = self.session.httpClint.send(urls.get("passengerInitApi")) if not passengerInitApiRsp.get("status"): print("".join(passengerInitApiRsp.get("messages")) or passengerInitApiRsp.get("validateMessages")) return data = passengerInitApiRsp.get("data", {}) jzdhDateE = data.get("jzdhDateE") if not data.get("jzdhHourE"): wrapcache.set(key=f"hb{self.tickerNo}", value=datetime.datetime.now(), timeout=TickerConfig.TICKET_BLACK_LIST_TIME * 60) print(f"获取当前候补日期失败,原因: {data.get('jzdhHourE')}") return jzdhHourE = data.get("jzdhHourE").replace(":", "#") jzdhDate = f"{jzdhDateE}#{jzdhHourE}" print(f"当前候补日期为:{jzdhDateE} {jzdhHourE}") confirm = confirmHB(self.secretList, self.session, self.tickerNo, jzdhDate) confirm.sendChechFace()
def sendGetQueueCount(self): """ # 模拟查询当前的列车排队人数的方法 # 返回信息组成的提示字符串 :return: """ getQueueCountResult = self.session.httpClient.send( self.session.urls["getQueueCountUrl"], self.data_par()) if "status" in getQueueCountResult and getQueueCountResult[ "status"] is True: if "countT" in getQueueCountResult["data"]: ticket = getQueueCountResult["data"]["ticket"] ticket_split = sum(map( conversion_int, ticket.split(","))) if ticket.find(",") != -1 else ticket countT = getQueueCountResult["data"]["countT"] if int(ticket_split) is 0: wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=TickerConfig.TICKET_BLACK_LIST_TIME * 60) print(f"排队失败,当前余票数还剩: {ticket_split} 张") return print(u"排队成功, 你排在: {1}位, 当前余票还剩余: {0} 张".format( ticket_split, countT)) csf = confirmSingleForQueue( self.session, self.ifShowPassCodeTime, self.is_need_code, self.token, self.set_type, self.ticket_peoples, self.ticketInfoForPassengerForm, self.oldPassengerStr, self.passengerTicketStrList) csf.sendConfirmSingleForQueue() # else: # print(u"当前排队人数: {1} 当前余票还剩余:{0} 张,继续排队中".format(ticket_split, countT)) else: print(u"排队发现未知错误{0},将此列车 {1}加入小黑屋".format( getQueueCountResult, self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=TickerConfig.TICKET_BLACK_LIST_TIME * 60) elif "messages" in getQueueCountResult and getQueueCountResult[ "messages"]: print(u"排队异常,错误信息:{0}, 将此列车 {1}加入小黑屋".format( getQueueCountResult["messages"][0], self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=TickerConfig.TICKET_BLACK_LIST_TIME * 60) else: if "validateMessages" in getQueueCountResult and getQueueCountResult[ "validateMessages"]: print(str(getQueueCountResult["validateMessages"])) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=TickerConfig.TICKET_BLACK_LIST_TIME * 60) else: print(u"未知错误 {0}".format("".join(getQueueCountResult)))
def sendChechFace(self): chechFaceRsp = self.session.httpClint.send(urls.get("chechFace"), self.data_apr()) if not chechFaceRsp.get("status"): print("".join(chechFaceRsp.get("messages")) or chechFaceRsp.get("validateMessages")) wrapcache.set(key=f"hb{self.train_no}", value=datetime.datetime.now(), timeout=TickerConfig.TICKET_BLACK_LIST_TIME * 60) return data = chechFaceRsp["data"] if not data.get("face_flag"): """ 未通过人脸核验 """ raise ticketConfigException( "通过人证一致性核验的用户及激活的“铁路畅行”会员可以提交候补需求,请您按照操作说明在铁路12306app.上完成人证核验") g = getSuccessRate(self.session, self.secretList) g.sendSuccessRate()
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)
def sendGetQueueCount(self): """ # 模拟查询当前的列车排队人数的方法 # 返回信息组成的提示字符串 :return: """ getQueueCountResult = self.session.httpClint.send(self.session.urls["getQueueCountUrl"], self.data_par()) if "status" in getQueueCountResult and getQueueCountResult["status"] is True: if "countT" in getQueueCountResult["data"]: ticket = getQueueCountResult["data"]["ticket"] ticket_split = sum(map(conversion_int, ticket.split(","))) if ticket.find(",") != -1 else ticket countT = getQueueCountResult["data"]["countT"] # if int(countT) is 0: print(u"排队成功, 你排在: {1}位, 当前余票还剩余: {0} 张".format(ticket_split, countT)) csf = confirmSingleForQueue(self.session, self.ifShowPassCodeTime, self.is_need_code, self.token, self.set_type, self.ticket_peoples, self.ticketInfoForPassengerForm, self.oldPassengerStr, self.passengerTicketStrList) csf.sendConfirmSingleForQueue() # else: # print(u"当前排队人数: {1} 当前余票还剩余:{0} 张,继续排队中".format(ticket_split, countT)) else: print(u"排队发现未知错误{0},将此列车 {1}加入小黑屋".format(getQueueCountResult, self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) elif "messages" in getQueueCountResult and getQueueCountResult["messages"]: print(u"排队异常,错误信息:{0}, 将此列车 {1}加入小黑屋".format(getQueueCountResult["messages"][0], self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) else: if "validateMessages" in getQueueCountResult and getQueueCountResult["validateMessages"]: print(str(getQueueCountResult["validateMessages"])) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) else: print(u"未知错误 {0}".format("".join(getQueueCountResult)))
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)
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')
def sendChechFace(self): chechFaceRsp = self.session.httpClint.send(urls.get("chechFace"), self.data_apr()) if not chechFaceRsp.get("status"): print("".join(chechFaceRsp.get("messages")) or chechFaceRsp.get("validateMessages")) wrapcache.set(key=f"hb{self.train_no}", value=datetime.datetime.now(), timeout=TickerConfig.TICKET_BLACK_LIST_TIME * 60) return data = chechFaceRsp["data"] if not data.get("face_flag"): print("".join(chechFaceRsp.get("messages")) or chechFaceRsp.get("validateMessages")) if data.get("face_check_code") == "14": """ 未通过人脸核验 """ raise ticketConfigException( "通过人证一致性核验的用户及激活的“铁路畅行”会员可以提交候补需求,请您按照操作说明在铁路12306app.上完成人证核验" ) elif data.get("face_check_code") in ["12", "02"]: """ 系统忙,请稍后再试! """ print("系统忙,请稍后再试!") wrapcache.set(key=f"hb{self.train_no}", value=datetime.datetime.now(), timeout=TickerConfig.TICKET_BLACK_LIST_TIME * 60) elif data.get("face_check_code") in ["03", "13"]: """ 证件信息审核失败,请检查所填写的身份信息内容与原证件是否一致。 """ raise ticketConfigException("证件信息审核失败,请检查所填写的身份信息内容与原证件是否一致。") elif data.get("face_check_code") in ["01", "11"]: """ 证件信息正在审核中,请您耐心等待,审核通过后可继续完成候补操作。 """ print("证件信息正在审核中,请您耐心等待,审核通过后可继续完成候补操作。") wrapcache.set(key=f"hb{self.train_no}", value=datetime.datetime.now(), timeout=TickerConfig.TICKET_BLACK_LIST_TIME * 60) g = getSuccessRate(self.session, self.secretList) g.sendSuccessRate()
def sendGetQueueCount(self, log_info=[]): """ # 模拟查询当前的列车排队人数的方法 # 返回信息组成的提示字符串 :return: """ getQueueCountResult = self.session.httpClint.send(self.session.urls["getQueueCountUrl"], self.data_par()) if "status" in getQueueCountResult and getQueueCountResult["status"] is True: if "countT" in getQueueCountResult["data"]: ticket = getQueueCountResult["data"]["ticket"] ticket_split = sum(map(conversion_int, ticket.split(","))) if ticket.find(",") != -1 else ticket countT = getQueueCountResult["data"]["countT"] if int(countT) is 0: if int(ticket_split) < len(self.ticket_peoples): print(u"当前余票数小于乘车人数,放弃订票") log_info.append(u"当前余票数小于乘车人数,放弃订票") else: log_info.append(u"排队成功, 当前余票还剩余: {0} 张".format(ticket_split)) print(u"排队成功, 当前余票还剩余: {0} 张".format(ticket_split)) csf = confirmSingleForQueue(self.session, self.ifShowPassCodeTime, self.is_need_code, self.token, self.set_type, self.ticket_peoples, self.ticketInfoForPassengerForm, self.oldPassengerStr, self.passengerTicketStrList) csf.sendConfirmSingleForQueue(log_info) else: log_info.append(u"当前排队人数: {1} 当前余票还剩余:{0} 张,继续排队中".format(ticket_split, countT)) print(u"当前排队人数: {1} 当前余票还剩余:{0} 张,继续排队中".format(ticket_split, countT)) else: log_info.append(u"排队发现未知错误{0},将此列车 {1}加入小黑屋".format(getQueueCountResult, self.train_no)) print(u"排队发现未知错误{0},将此列车 {1}加入小黑屋".format(getQueueCountResult, self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) elif "messages" in getQueueCountResult and getQueueCountResult["messages"]: log_info.append(u"排队异常,错误信息:{0}, 将此列车 {1}加入小黑屋".format(getQueueCountResult["messages"][0], self.train_no)) print(u"排队异常,错误信息:{0}, 将此列车 {1}加入小黑屋".format(getQueueCountResult["messages"][0], self.train_no)) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) else: if "validateMessages" in getQueueCountResult and getQueueCountResult["validateMessages"]: log_info.append(str(getQueueCountResult["validateMessages"])) print(str(getQueueCountResult["validateMessages"])) wrapcache.set(key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) else: log_info.append(u"未知错误 {0}".format("".join(getQueueCountResult))) print(u"未知错误 {0}".format("".join(getQueueCountResult)))
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)
def sendGetQueueCountAsync(self, log_info=[]): """ 请求排队接口 :return: """ urls = self.session.urls["getQueueCountAsync"] data = self.data_par() getQueueCountAsyncResult = self.session.httpClint.send(urls, data) if getQueueCountAsyncResult.get( "status", False) and getQueueCountAsyncResult.get( "data", False): if "status" in getQueueCountAsyncResult and getQueueCountAsyncResult[ "status"] is True: if "countT" in getQueueCountAsyncResult["data"]: ticket_data = getQueueCountAsyncResult["data"]["ticket"] ticket_split = sum( map(self.conversion_int, ticket_data.split(",")) ) if ticket_data.find(",") != -1 else ticket_data countT = getQueueCountAsyncResult["data"]["countT"] if int(countT) is 0: if int(ticket_split) < self.users: log_info.append(u"当前余票数小于乘车人数,放弃订票") print(u"当前余票数小于乘车人数,放弃订票") else: log_info.append( u"排队成功, 当前余票还剩余: {0} 张".format(ticket_split)) print(u"排队成功, 当前余票还剩余: {0} 张".format(ticket_split)) c = confirmSingleForQueueAsys( session=self.session, passengerTicketStr=self.passengerTicketStr, oldPassengerStr=self.oldPassengerStr, result=self.result, ) print(u"验证码提交安全期,等待{}MS".format( self.ifShowPassCodeTime)) log_info.append(u"验证码提交安全期,等待{}MS".format( self.ifShowPassCodeTime)) time.sleep(self.ifShowPassCodeTime) c.sendConfirmSingleForQueueAsys() else: log_info.append(u"排队发现未知错误{0},将此列车 {1}加入小黑屋".format( getQueueCountAsyncResult, self.train_no)) print(u"排队发现未知错误{0},将此列车 {1}加入小黑屋".format( getQueueCountAsyncResult, self.train_no)) # wrapcache.set(key=self.train_no, value=datetime.datetime.now(), # timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) elif "messages" in getQueueCountAsyncResult and getQueueCountAsyncResult[ "messages"]: log_info.append(u"排队异常,错误信息:{0}, 将此列车 {1}加入小黑屋".format( getQueueCountAsyncResult["messages"][0], self.train_no)) print(u"排队异常,错误信息:{0}, 将此列车 {1}加入小黑屋".format( getQueueCountAsyncResult["messages"][0], self.train_no)) wrapcache.set( key=self.train_no, value=datetime.datetime.now(), timeout=int(_get_yaml()["ticket_black_list_time"]) * 60) else: if "validateMessages" in getQueueCountAsyncResult and getQueueCountAsyncResult[ "validateMessages"]: log_info.append( str(getQueueCountAsyncResult["validateMessages"])) print(str(getQueueCountAsyncResult["validateMessages"]))
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)
def set_timeout(self): """设置超时 """ wrapcache.set("user_time", datetime.datetime.now(), timeout=60 * 5)
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)