Skip to content

Commit

Permalink
update to fix some bug
Browse files Browse the repository at this point in the history
  • Loading branch information
lzqwebsoft committed Jan 14, 2014
1 parent 37a9381 commit 160b3a1
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 46 deletions.
51 changes: 30 additions & 21 deletions access12306.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# coding: utf8
import time
import tkinter
import copy
import ui.LoginUI, ui.OrderConfirmUI, ui.QueryTrainUI
from core import login,order,query
from common.httpaccess import HttpTester
Expand Down Expand Up @@ -31,6 +32,9 @@ def __init__(self):
# 车票预定时所填的参数数组
self.orderParams = None

# 读取用户设置的是否进行验证码的检查
self.check_rand_status = self.performanceInfo.get('check_rand', 'Y')

def access(self):
if self.userInfo:
login_result = login.getRandImageUrlAndCodeRand(self.ht)
Expand All @@ -49,17 +53,17 @@ def processLoginCallBack(self, event=None):
randCode = self.randImage.randCode.get()
if randCode:
loginResult = login.login(ht=self.ht, username=self.userInfo[0], password=self.userInfo[1],
randCode=randCode, rand=self.login_rand)
randCode=randCode, rand=self.login_rand, check_rand_status=self.check_rand_status)
if loginResult:
# 登录成功,关闭登框
self.randImage.quit()
# 更新城市编码表
query.updateCityCode(self.ht)
# 得到性能配置中设定是否更新车站编码属性,默认是Y,表更新
update_stations = self.performanceInfo.get('update_stations', 'Y')
if update_stations and update_stations=="Y":
# 装载列车站点编码
self.allStationCodes = query.getAllStationCodes()
# 更新城市编码表
query.updateCityCode(self.ht)
# 装载列车站点编码
self.allStationCodes = query.getAllStationCodes()
# 获取默认的列车查询信息
defaultQueryParams = query.getDefaultQueryParams()
# 载入用户设定的所有联系人信息
Expand Down Expand Up @@ -129,9 +133,13 @@ def queryTrainsCallBack(self):
# 处理列车预定按钮回调
def orderTrainsCallBack(self, selectStr='', row=0):
if selectStr:
from_station = self.queryFrame.fromStation.get()
# 对Http请求工具对象进行一次深度拷贝
ht = copy.deepcopy(self.ht)
# ht = HttpTester()
# ht.setCookiejar(self.ht.getCookiejar())

# 提交预定,获取初始化乘客确认页面内容
submitResult = order.submitOrderRequest(self.ht, selectStr, queryParams=self.currentSelectedParams)
submitResult = order.submitOrderRequest(ht, selectStr, queryParams=self.currentSelectedParams)
if submitResult:
# 记录车票预订的HTML解析对象parser
parser = order.ParserConfirmPassengerInitPage(submitResult)
Expand All @@ -151,7 +159,7 @@ def orderTrainsCallBack(self, selectStr='', row=0):
train_info=trainInfo,
passenger_params=passenger_params)
comfirmFrame.backButton.configure(command=lambda comfirmFrame=comfirmFrame: self.backToTrainQueryCallBack(comfirmFrame))
comfirmFrame.submitButton.configure(command=lambda comfirmFrame=comfirmFrame, parser=parser: self.submitOrderCallBack(comfirmFrame, parser))
comfirmFrame.submitButton.configure(command=lambda comfirmFrame=comfirmFrame, httpAccessObj=ht, parser=parser: self.submitOrderCallBack(comfirmFrame, parser, httpAccessObj))
comfirmFrame.show()
else:
print('解析车票预订画面失败,详情查看当前目录下的submitResult.html文件.')
Expand All @@ -170,18 +178,15 @@ def backToTrainQueryCallBack(self, comfirmFrame):
#self.queryFrame.show()

# 订单提交回调
def submitOrderCallBack(self, comfirmFrame, parser):
def submitOrderCallBack(self, comfirmFrame, parser, httpAccessObj):
# 整合POST上传参数
# hidden_params = self.parser.get_hidden_params()
passenger_info = comfirmFrame.getAllPassengerParams()
count = comfirmFrame.getCustomerCount()

# 订单提交页面隐藏参数
order_request_params = parser.get_order_request_params()
ticketInfoForPassengerForm = parser.get_ticketInfoForPassengerForm()

passengerTicketStr = ''
oldPassengersStr = ''
oldPassengers = []
passengerTickets = []
for i in range(count):
Expand Down Expand Up @@ -209,12 +214,16 @@ def submitOrderCallBack(self, comfirmFrame, parser):
# f.write(str(self.orderParams))
# f.close()
# =========================================
# 检查用户输入验证码的合法性
checkResult = order.checkOrderImgCode(self.ht, rand=image_code_rand, img_code=image_code,
# 读取用户配置信息,判断是否进行验证码的检查操作,默认设定为Y表示检查
if self.check_rand_status == 'Y':
# 检查用户输入验证码的合法性
checkResult = order.checkOrderImgCode(httpAccessObj, rand=image_code_rand, img_code=image_code,
token=parser.globalRepeatSubmitToken)
else:
checkResult = True
if checkResult:
# 检证用户提交的乘客信息的合法性
checkResult = order.checkOrderInfo(self.ht, randCode=image_code, passengerTicketStr=passengerTicketStr,
checkResult = order.checkOrderInfo(httpAccessObj, randCode=image_code, passengerTicketStr=passengerTicketStr,
oldPassengersStr=oldPassengersStr, tour_flag='dc',
token=parser.globalRepeatSubmitToken)
if checkResult:
Expand Down Expand Up @@ -244,21 +253,21 @@ def submitOrderCallBack(self, comfirmFrame, parser):
('train_location', ticketInfoForPassengerForm['train_location']),
('REPEAT_SUBMIT_TOKEN', parser.globalRepeatSubmitToken)
]
queue_note = order.getQueueCount(self.ht, queueCounParams, seat_type)
queue_note = order.getQueueCount(httpAccessObj, queueCounParams, seat_type)
ui.OrderConfirmUI.ConfirmOrderDialog(comfirmFrame.root, queue_note, parser.get_train_info(),
comfirmFrame.getPassengerInfo(), self.comfirmOrderSubmitCallBack,
orderParams)
orderParams, httpAccessObj)

# 用户点击提交订单确认对话框的确认按钮时回调
def comfirmOrderSubmitCallBack(self, orderParams=None):
if not orderParams:
def comfirmOrderSubmitCallBack(self, orderParams=None, httpAccessObj=None):
if not orderParams or not httpAccessObj:
print('预定参数不能为空')
return
# 检查单程预定允许排队
checkResult = order.checkQueueOrder(self.ht, 'dc', orderParams)
checkResult = order.checkQueueOrder(httpAccessObj, 'dc', orderParams)
if checkResult:
# 开始排队
timer = order.OrderQueueWaitTime(self.ht, 'dc', order.waitFunc, order.finishMethod)
timer = order.OrderQueueWaitTime(httpAccessObj, 'dc', order.waitFunc, order.finishMethod)
timer.start()


Expand Down
13 changes: 13 additions & 0 deletions common/httpaccess.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,19 @@ def getCookieStr(self):
return ';'.join(cookies)
return ''

def getCookiejar(self):
handers = self.__opener.handlers
for hander in handers:
if type(hander) == urllib.request.HTTPCookieProcessor:
cookiejar = hander.cookiejar
return cookiejar
return http.cookiejar.CookieJar()

def setCookiejar(self, cookiejar=None):
if not cookiejar:
cookiejar = http.cookiejar.CookieJar()
self.__opener.add_handler(urllib.request.HTTPCookieProcessor(cookiejar))

def addProxy(self, host, type='http'):
'''设置代理'''
proxy = urllib.request.ProxyHandler({type: host})
Expand Down
34 changes: 19 additions & 15 deletions core/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import json
import configparser
import html.parser
import urllib, urllib.request,urllib.parse
import urllib, urllib.request, urllib.parse

# 读取URL获得验证码的路径HTML解析类
class LoginRandCodeParser(html.parser.HTMLParser):
Expand Down Expand Up @@ -71,20 +71,21 @@ def getRandImageUrlAndCodeRand(ht):
return result


def login(ht, username, password, randCode, rand):
# 判断用户输入的验证码是否正确
post_datas = {
'randCode': randCode, # 输入验证码
'rand': rand # 验证令牌
}

# 检证输入验证码的合法性
json_str = ht.post(url="https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn", params=post_datas)
json_data = json.loads(json_str)
if (json_data["data"] == 'N'):
print(json_str)
print('输入的验证码有误.')
def login(ht, username, password, randCode, rand, check_rand_status='Y'):
# 判断用户是否进行验证码的检查操作,如果check_rand_status为N则直接跳过进行登录
if check_rand_status == 'Y':
# 判断用户输入的验证码是否正确
post_datas = {
'randCode': randCode, # 输入验证码
'rand': rand # 验证令牌
}
# 检证输入验证码的合法性
json_str = ht.post(url="https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn", params=post_datas)
json_data = json.loads(json_str)
else:
json_data = {'data': 'Y'}

if (json_data["data"] == 'Y'):
post_data = {
"loginUserDTO.user_name": username,
"userDTO.password": password,
Expand Down Expand Up @@ -116,8 +117,11 @@ def login(ht, username, password, randCode, rand):
print("登录失败, 详情查看登录返回的login_result.html页面")
else:
messages = json_data.get('messages', '') if type(json_data) == dict else json_str
if not messages: messages='当前网络繁忙不可登录访问!'
if not messages: messages = '当前网络繁忙不可登录访问!'
print(messages)
else:
print(json_str)
print('输入的验证码有误.')

return False

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
}
setup(
name="trainticket",
version='0.2.0',
version='0.2.2',
description='风险版',
options={'build_exe': build_exe_options},
executables=[Executable("access12306.py", icon='logo.ico')])
24 changes: 15 additions & 9 deletions ui/OrderConfirmUI.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import random
import socket
import urllib.error

try:
# Python2
from Tkinter import *
Expand Down Expand Up @@ -100,10 +101,13 @@ def __init__(self, contacts=None, rand_image_url='', train_info=None, passenger_
self.ticket_types = {}
self.card_types = {}
# 乘客输入框数据
if 'limitBuySeatTicketDTO' in passenger_params and 'seat_type_codes' in passenger_params['limitBuySeatTicketDTO']:
self.seats_types = {seat_type_codes['id']:seat_type_codes['value'] for seat_type_codes in passenger_params['limitBuySeatTicketDTO']['seat_type_codes']}
self.ticket_types = {ticket_type_codes['id']:ticket_type_codes['value'] for ticket_type_codes in passenger_params['limitBuySeatTicketDTO']['ticket_type_codes']}
self.card_types = {cardTypes['id']:cardTypes['value'] for cardTypes in passenger_params['cardTypes']}
if 'limitBuySeatTicketDTO' in passenger_params and 'seat_type_codes' in passenger_params[
'limitBuySeatTicketDTO']:
self.seats_types = {seat_type_codes['id']: seat_type_codes['value'] for seat_type_codes in
passenger_params['limitBuySeatTicketDTO']['seat_type_codes']}
self.ticket_types = {ticket_type_codes['id']: ticket_type_codes['value'] for ticket_type_codes in
passenger_params['limitBuySeatTicketDTO']['ticket_type_codes']}
self.card_types = {cardTypes['id']: cardTypes['value'] for cardTypes in passenger_params['cardTypes']}

self.customerTable = Frame(customerPanel)
self.customerTable.pack(fill=X)
Expand Down Expand Up @@ -442,15 +446,15 @@ def getSetCustomerInfo(self):
if text == seat_type:
params['passenger_%d_seat' % self.index] = value
break
# 得到选中的票类
# 得到选中的票类
params['passenger_%d_ticket' % self.index] = ''
ticket_type = self.customerTypeListBox.get()
ticket_type = ticket_type.strip()
for value, text in self.ticket_types.items():
if ticket_type == text:
params['passenger_%d_ticket' % self.index] = value
break
# 得到设置的用户名
# 得到设置的用户名
params['passenger_%d_name' % self.index] = self.getCustomerName()
# 得到证件类型
params['passenger_%d_cardtype' % self.index] = ''
Expand All @@ -460,7 +464,7 @@ def getSetCustomerInfo(self):
if card_type == text:
params['passenger_%d_cardtype' % self.index] = value
break
# 得到证件号
# 得到证件号
params['passenger_%d_cardno' % self.index] = self.cardNo.get()
# 手机号
params['passenger_%d_mobileno' % self.index] = self.cellphone.get()
Expand Down Expand Up @@ -494,7 +498,8 @@ def getSetCusomerInfoText(self):

# 订单提交对话框
class ConfirmOrderDialog(Toplevel):
def __init__(self, parent, prompt_text='', train_info=None, passenger_info=None, okFunc=None, orderParams=None):
def __init__(self, parent, prompt_text='', train_info=None, passenger_info=None, okFunc=None, orderParams=None,
ht=None):
Toplevel.__init__(self, parent)
self.transient(parent)

Expand All @@ -506,6 +511,7 @@ def __init__(self, parent, prompt_text='', train_info=None, passenger_info=None,
self.passenger_info = passenger_info
self.okFunc = okFunc
self.orderParams = orderParams
self.httpAccessObj = ht

body = Frame(self)
self.initial_focus = self.body(body)
Expand Down Expand Up @@ -622,7 +628,7 @@ def ok(self, event=None):
return
self.withdraw()
self.update_idletasks()
self.okFunc(self.orderParams)
self.okFunc(self.orderParams, self.httpAccessObj)
self.cancel()

def cancel(self, event=None):
Expand Down

0 comments on commit 160b3a1

Please sign in to comment.