def login(self): logger.info('login starting...\n1#.get session id') begin_session_resp = http_handler.login.begin_session( self.partner, self.cc) logger.info('begin session resp:%s' % begin_session_resp) if begin_session_resp['success']: self.account['sessionid'] = begin_session_resp['data']['sessionId'] logger.info('get session id success,the id is %s' % self.account['sessionid']) logger.info('#2.login') login_resp = http_handler.login.login(self.account['sessionid'], self.account['username'], self.account['password'], self.partner, self.cc) logger.debug('login resp:%s' % login_resp) if login_resp['success']: logger.info('login success,the sessionid is %s' % self.account['sessionid']) return self.account['sessionid'] else: err = '2#.login faild' logger.info('account cant use,send to server') resp = requests.put(base_data.put_aacount_cantuse % self.accountid) logger.info(resp.text) logger.error(err) raise ValueError(err) else: err = 'get session id faild' logger.error(err) raise ValueError(err)
def get_couponList(self, cookie, id): headers = { 'Accept-Encoding': 'gzip,deflate', 'jdc-backup': cookie, 'Cookie': cookie, 'Charset': 'UTF-8', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'User-Agent': 'Dalvik/1.6.0 (Linux; U; Android 4.4.2;)' } body = {"pageSize": "100", "page": "1"} sign = auth.sign('configCouponList', self.uuid, json.dumps(body)) resp = requests.post( url= 'http://api.m.jd.com/client.action?functionId=configCouponList&clientVersion=5.8.0&build=42523&client=android&d_brand=nubia&d_model=NX507J&osVersion=4.4.2&screen=1920*1080&partner=jingdong2&uuid=%s&area=1_2802_2821_0&networkType=wifi&st=%s&sign=%s&sv=111' % ( #url = 'http://api.m.jd.com/client.action?functionId=configCouponList&clientVersion=5.8.0&build=42523&client=android&d_brand=&d_model=&osVersion=&screen=1280*720&partner=tencent&uuid=%s&area=1_2802_0_0&networkType=wifi&st=%s&sign=%s&sv=122' % ( self.uuid, sign[1], sign[0]), data='body=' + urllib.quote(json.dumps(body)) + '&', headers=headers) logger.debug(resp.url) logger.debug(resp.text) list = resp.json() if id: return filter(lambda c: c['id'] == id, list['couponList']) else: return list
def get_cookie(username, password): logger.info('pc:login') logoutUrl = "https://passport.jd.com/uc/login?ltype=logout" resp = requests.get(logoutUrl) logger.info('get pc cookie') cookie = resp.headers['Set-Cookie'] text = resp.text payload = {} bsop = BeautifulSoup(text, 'html.parser') verify_code_img = bsop.find('img', {'id': 'JD_Verification1'}) verify_code = '' if verify_code_img: url = verify_code_img['src2'] logger.info('verifycodeurl:' + url) verify_code = get_verifycode(url) else: logger.info('verifycode not need') hidden_ipputs = bsop.findAll('input', {'type': 'hidden'}) for _input in hidden_ipputs: payload[_input['name']] = _input['value'] if payload: payload['loginname'] = username payload['loginpwd'] = password payload['nloginpwd'] = password payload['authcode'] = verify_code else: raise Exception('pc payload get error') logger.debug('login.cookie=>%s,payload=>%s' % (cookie, payload)) login_url = 'https://passport.jd.com/uc/loginService?uuid=%s&type=logout&r=%s&version=2015' \ % (payload['uuid'], int(time.time())) resp = requests.post( login_url, payload, headers={ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4", "Connection": "keep-alive", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36", "Cache-Control": "no-cache", "Referer": "https://passport.jd.com/uc/login?ltype=logout", "Host": "passport.jd.com", "Cookie": cookie }) if '({"success":"http://www.jd.com"})' == resp.text: logger.info('login success') cookies = [] for c in resp.headers['Set-Cookie'].split(';,'): cookies.append(c.split(';')[0].strip()) return ';'.join(cookies) logger.info('login faild') return None
def get_special_coupon(userid, sessionid, mark): headers = { 'content-type': 'application/json; charset=UTF-8', 'User-Agent': base_data.get_user_agent(), 'Origin': 'http://m.tuniu.com', 'Referer': 'http://m.tuniu.com/event/couponCenter/mainCenter/index?utm_source=morecoupon&utm_medium=couponcenter&q=1005', 'X-Requested-With': 'com.tuniu.app.ui', 'Cookie': 'PageSwitch=2,%s; _tacau=MCwzYTY0MTU4Ni1mZDI3LTQyMWUtZDI3NS1kNGI1ZDEzNDU1ODcs; _tacz2=taccsr=(direct)|tacccn=(none)|taccmd=(none)|taccct=(none)|taccrt=(none); _taca=1477397184786.1477397184786.1477397184786.1; _tacc=1; SERVERID=dnionD; app_imei=%s; ov=1; tuniuuser_id=%d; TUNIUmuser=%s; sessionId=MQ==; token=%s; appVersion=9.0.6; tuniu_partner=MTU0NDcsMCwsOWIxMTFkNWY3NGQ1NmQ1NjdhNjEyZDQzYjEzYjVlYjI=; deviceType=1; SsoSession=%s; clientType=20; page_flag=; __utma=1.1665134217.1477397186.1477397186.1477397188.2; __utmb=1.4.10.1477397188; __utmc=1; __utmz=1.1477397188.2.2.utmcsr=morecoupon|utmccn=(not set)|utmcmd=couponcenter; _tact=NTExZDJiZTYtNGUxOS05Y2E2LWJlNjEtMTM0ZDMwYmMwNDRh; _tacb=NTFiZjQ2ZjgtZWZmNi1iYzUzLWFkNmQtZGQwMTZkZGQ4ZmU1' % (str(time.time()).replace( '.', ''), base_data.get_random_number(), userid, sessionid, base64.b64encode(base_data.get_random_letter_number()), sessionid) } req = requests.get( 'http://dynamic.m.tuniu.com/event/couponCenter/MainCenter/getSpecialAjax?tab_id=9&mark=%s&tel=&q=1005' % mark, headers=headers) logger.debug('GET %s \n%s' % (req.url, req.headers)) try: return req.json() except Exception, e: raise HttpRequestException( e, { 'function': 'click_special_coupon', 'method': 'get', 'url': req.url, 'headers': headers, 'resp_content': req.content })
def confirm(parms): headers = {'User-Agent': base_data.get_user_agent(), 'baseParams': base64.b64encode(json.dumps({"fingerPrint": "", "sessionId": parms['sessionId'], "termAppVersion": "1.4.0", "termSysVersion": "4.4.2", "majorAppVersion": "9.0.0", "termModel": "", "appType": 2, "platformId": 1, "network": "WIFI", "termId": parms['termId']})), 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} url = 'https://jr.tuniu.com/fmp-web/pay/confirm' data = {"downPaymentFlag": 0, "encodeTotalAmount": rsa.encode(parms['price']), "orderId": parms['orderId'], "orderType": 1, "payChannel": base_data.payChannel, "payMethod": 11, "sign": "", "userId": parms['userId']} sign_data = 'downPaymentFlag=0&encodeTotalAmount=%s&orderId=%s&orderType=1&payChannel=%d&payMethod=11&userId=%d' % ( data['encodeTotalAmount'], data['orderId'], base_data.payChannel, data['userId']) sign_data = sign_data + '&*()%sd76@#$Dfs^YsfUJKDs' data['sign'] = hashlib.md5(sign_data).hexdigest() base64_data = base64.b64encode(json.dumps(data)) req = requests.post(url, data=base64_data, headers=headers) logger.debug('POST %s\n%s\n%s\n%s' % (req.url, json.dumps(headers), data, base64_data)) try: resp = json.loads(base64.b64decode(req.text)) return resp except Exception, e: raise HttpRequestException(e, {'function': 'pay_confirm', 'method': 'post', 'url': req.url, 'headers': headers, 'data': data, 'resp_content': req.content})
def get_coupon(self, coupon_id): logger.info('looking for coupon %d\n1#.' % coupon_id) get_coupon_list_resp = http_handler.coupon.get_coupon_list() if get_coupon_list_resp['success']: list = filter(lambda c: c['id'] == str(coupon_id), get_coupon_list_resp['data']['list']) if list: mark = list[0]['mark'] logger.info( '''looking for coupon %d success,the mark is %s.\n2#.get coupon %d''' % (coupon_id, mark, coupon_id)) get_special_coupon_resp = http_handler.coupon.get_special_coupon( 1 and self.account['userid'] or self.get_user_id(), self.account['sessionid'], mark) logger.debug('get special coupon resp: %s' % get_special_coupon_resp) if get_special_coupon_resp['success']: logger.info('get coupon %d success' % coupon_id) return True else: logger.warn('get coupon %d falid' % coupon_id) return False else: logger.warn('find coupon %d faild' % coupon_id)
def submit(parms): headers = {'User-Agent': 'TuNiuApp/9.0.6/Dalvik/1.6.0 (Linux; U; Android 4.2.2)', 'baseParams': base64.b64encode(json.dumps({"fingerPrint": "", "sessionId": parms['sessionId'], "termAppVersion": "1.3.9", "termSysVersion": "4.4.2", "termModel": "", "appType": 2, "platformId": 1, "network": "WIFI", "termId": parms['termId']}))} url = 'https://jr.tuniu.com/fmp-web/app/order/submit' data = {"bizId": 38, "bizOrderId": parms['orderId'], "encodeTotalAmount": rsa.encode(parms['price']), "sign": "", "userId": parms['userId']} data['sign'] = hashlib.md5(('bizId=38&bizOrderId=%s&encodeTotalAmount=%s&userId=%d' % ( data['bizOrderId'], data['encodeTotalAmount'], data['userId'])) + '&*()%sd76@#$Dfs^YsfUJKDs').hexdigest() base64_data = base64.b64encode(json.dumps(data)) req = requests.post(url, data=base64_data, headers=headers) logger.debug('POST %s\n%s\n%s\n%s' % (req.url, json.dumps(headers), data, base64_data)) try: resp = json.loads(base64.b64decode(req.text)) return resp except Exception, e: raise HttpRequestException(e, {'function': 'order_submit', 'method': 'post', 'url': req.url, 'headers': headers, 'data': data, 'resp_content': req.content})
def gen_order(self, train, passenger_ids): url = 'http://train.m.jd.com/bookSeat/generateOrder.json' # seatType = str(train['data']['exData1']) # if seatType == '1': # seatType = 'yz' # elif seatType == 'O': # seatType = 'edz' # else: # raise Exception('seat type not support') logger.info('seach ticket') ticket = self.seach_ticket(train) if ticket: start_time = ticket[0]['trainInfo']['startTime'] else: raise Exception('find out ticket faild') data = {'account': '', 'trainDate': train['data']['ticketsInfo'][0]['dptDate'], 'toStationCode': train['data']['ticketsInfo'][0]['arrStation'], 'toStationName': train['data']['ticketsInfo'][0]['destination'].encode("utf-8"), 'seatType': ticket[2], 'realBook': '1', 'acceptNoSeat':0, 'ticketType':1, 'phone': train['data']['contactInfo']['mobileNo'], 'fromStationName': train['data']['ticketsInfo'][0]['departure'].encode("utf-8"), 'contactId': train['data']['contactInfo']['contractId'], 'contact': train['data']['contactInfo']['name'].encode("utf-8"), 'password': '', 'passengerIds': passenger_ids, 'seatPrice': int(train['data']['ticketsInfo'][0]['ticketPrice'] * 100) * len(passenger_ids.split(',')), 'fromStationCode': train['data']['ticketsInfo'][0]['dptStation'], # 'cheCi': train['data']['ticketsInfo'][0]['coachNo'], 'cheCi': ticket[0]['trainInfo']['trainCode'], 'trainTime': start_time, 'hasInsurance': False, 'insuranceCode': 0, 'hasInvoice': False, 'invoiceJson': {}, 'isGrab': False, 'userRank': '', 'deadline': '' } # print data encode_data = urllib.urlencode(data) logger.debug('POST %s \n%s' % (url, encode_data)) # data = 'cheCi=G5&seatType=edz&seatPrice=55300&fromStationCode=VNP&fromStationName=%E5%8C%97%E4%BA%AC%E5%8D%97&toStationCode=AOH&toStationName=%E4%B8%8A%E6%B5%B7%E8%99%B9%E6%A1%A5&trainDate=1480435200000&passengerIds=1204607&contact=%E5%90%B4%E5%8B%87%E5%88%9A&phone=13978632546&realBook=1&account=&password='******'resp %s' % resp.text) resp_body = resp.json() if resp_body and resp_body['success']: orderid = resp_body['orderId'] data['orderid'] = orderid return data else: raise Exception('generate order faild.\n%s' % resp.text)
def account_info(sessionid, partner): req = requests.get('https://m.tuniu.com/iapi/appserver/view/myAccountInfoV400?%s' % base64.b64encode(json.dumps( {"sessionID": sessionid, "r": time.time(), "partner": partner, "clientType": 20, "deviceType": 1, "version": "9.0.6"})), headers={'content-type': 'application/json; charset=UTF-8', 'User-Agent': base_data.get_user_agent()}) # "_currentCityCode": "1502" logger.debug('GET %s \n%s' % (req.url, req.headers)) try: return json.loads(base64.b64decode(req.content)) except Exception, e: raise HttpRequestException(e, {'function': 'account_info', 'method': 'get', 'url': req.url, 'resp_content': req.content})
def add_contract(self, name, phone): url = 'https://train.m.jd.com/contact/add.json' self.headers[ 'Referer'] = 'https://train.m.jd.com/bookSeat/book/s_1482508800000_%E6%96%B0%E4%BD%99_XUG_%E7%BB%8D%E5%85%B4_SOH_G2334_edz' data = 'contactName=%s&contactPhone=%s' % (urllib.quote_plus(name.encode('utf-8')), phone) resp = requests.post(url, data=data, headers=self.headers, verify=False) logger.debug('resp %s' % resp.text) resp_body = resp.json() if resp_body['success']: return resp_body['contactId'] else: raise Exception('add contract error')
def get_user_id(self): logger.info('get user id starting...') resp = http_handler.account.account_info(self.account['sessionid'], self.partner) logger.debug('account info:%s' % resp) if (resp['success']): logger.info('get user id %s' % resp['data']['userProfile']['userId']) self.account['userid'] = int(resp['data']['userProfile']['userId']) return self.account['userid'] else: err = 'get user id faild' logger.error(err) raise ValueError(err)
def callback_partner_and_save_order(data, success, order_id, pc_cookie=''): data['order_handler_complete_time'] = str(datetime.datetime.now()) if success: while True: try: pay_task_data = { "module": { "worker": [ { "assembly": "FBServer.Pay.TrainJD.Pay_RechargePhoneBillJD,FBServer.Pay.TrainJD.dll", "type": 0, "parms": '' } ], "payer": [ "{0}" ] }, "sessionId": '', "data": { "siteNo": "jingdong_phone", "ticketOrderNo": data['jd_order_id'], "sysOrderNo": data['trade_no'], "loginUser": data['account']["username"], "loginPwd": data['account']["password"], "exData": { "Cookie": pc_cookie.replace('"', ''), "userId": '', "mCookie": '', "orderId": "", "payurl": "" }, "creatTime": str(datetime.datetime.now()), "amount": float(data['money']) / 100, "isPay": "false" } } url = 'http://op.ykjd.com/JDTrainOpen/CreatePayTaskByPhone' pay_task_data = json.dumps(pay_task_data) logger.debug('POST %s\n%s' % (url, pay_task_data)) resp = requests.post(url, data={'send_data': pay_task_data}) logger.info(resp.text) data['pay_task_id'] = resp.text break except Exception, e: logger.error('callback pay faild') logger.error(traceback.format_exc()) time.sleep(60) continue
def get_coupon_list(): req = requests.get( 'http://dynamic.m.tuniu.com/event/couponCenter/MainCenter/SpecialListAjax?tab_id=9' ) logger.debug('GET %s \n%s' % (req.url, req.headers)) try: return req.json() except Exception, e: raise HttpRequestException( e, { 'function': 'get_coupon_list', 'method': 'get', 'url': req.url, 'resp_content': req.content })
def get_details(self, orderid): url = 'http://train.m.jd.com/orderDetail/orderDetail?orderId=%s&un_area=1_0_0_0' % orderid logger.debug('GET %s' % url) resp = requests.get(url, headers=self.headers) resp_body = resp.text # logger.debug('resp:%s' % resp_body) erpOrderId = re.findall(r'<input type="hidden" name="erpOrderId" value="(\w+)" />', resp_body) onlinePayFee = re.findall(r'<input type="hidden" name="onlinePayFee" value="(.*)"/>', resp_body) if erpOrderId and onlinePayFee: return {'erpOrderId': erpOrderId[0], 'onlinePayFee': onlinePayFee[0]} else: return None
def get_account(uuid): logger.info('get jd account') url = base_data.JD_ACCOUNT_API_GET try: logger.debug('GET %s' % url) resp = requests.get(url) logger.debug(resp.text) account_json = resp.json() account = json.loads(account_json['_data']) account['account_id'] = account_json['account_id'] return account except Exception, e: logger.error('get jd account faild') return None
def get_token(self, data): url = 'https://train.m.jd.com/bookSeat/book/s_%s_%s_%s_%s_%s_%s_%s' % ( data['trainDate'], urllib.quote_plus(data['fromStationName']), data['fromStationCode'], urllib.quote_plus(data['toStationName']), data['toStationCode'], data['cheCi'], data['seatType']) logger.debug('GET %s' % url) resp = requests.get(url, headers=self.headers, verify=False) resp_body = resp.text # logger.debug('resp:%s' % resp_body) token = re.findall(r'<input type="hidden" name="token" value="(\w+)" />', resp_body) if token: data['token'] = token[0] data['referer'] = url return data else: raise Exception('token not found')
def save_order(data, id=0): while True: try: logger.info('save trade data') _data = {'order_id': id, 'data': data} logger.debug('POST %s\n%s' % (base_data.ORDER_SAVE_API_POST, json.dumps(_data))) resp = requests.post(base_data.ORDER_SAVE_API_POST, json=_data) logger.debug(resp.text) if resp.text == '-1' or resp.text == '0': logger.warn('maybe faild') time.sleep(60) else: logger.info('sucess') return resp.text except Exception: logger.error(traceback.format_exc()) time.sleep(60) continue
def submit(self, data): url = 'https://train.m.jd.com/bookSeat/submitOrder.action' self.headers['Referer'] = data['referer'] + '?ran=%d' % int(time.time()) data = 'token=%s&orderId=%s&totalFee=%d&pwd=%s' % ( data['token'], data['orderid'], data['seatPrice'], data['coupon']) logger.debug('POST %s\n%s' % (url, data)) self.headers['Origin'] = 'https://train.m.jd.com' self.headers['Upgrade-Insecure-Requests'] = '1' req = requests.post(url, data=data, headers=self.headers, verify=False) resp = req.text logger.debug('resp:%s' % resp) if resp.find(u'系统异常') == -1: return True else: return False
def get_account_train_order_can_use_coupon(order, sessionid, partner, cc): headers = {'User-Agent': base_data.get_user_agent()} params = {'d': json.dumps( {"trainNumber": order['trainNumber'], "startStationName": order['startStationName'], "sessionId": sessionid, "arrivalStationName": order['arrivalStationName'], "departureCityCode": order['departureCityCode'], "departDate": order['departDate'], "adultPrice": order['adultPrice'], "insurancePrice": 0, "childCount": 0, "adultCount": 1, "absId": 0}), 'c': json.dumps({"v": "9.0.6", "ct": 20, "dt": 1, "ov": 1, "p": partner, "cc": cc})} # "seatId": order['seatId'], req = requests.get( 'http://m.tuniu.com/api/train/order/getMyCoupons', params=params, headers=headers) logger.debug('GET %s \n%s' % (req.url, req.headers)) try: return req.json() except Exception, e: raise HttpRequestException(e, {'function': 'get_account_coupon', 'method': 'get', 'url': req.url, 'headers': headers, 'resp_content': req.content})
def add_passenger(self, passenger): url = 'https://train.m.jd.com/passenger/add.json' self.headers[ 'Referer'] = 'https://train.m.jd.com/bookSeat/book/s_1482508800000_%E6%96%B0%E4%BD%99_XUG_%E7%BB%8D%E5%85%B4_SOH_G2334_edz' p_ids = [] for p in passenger: data = 'contactName=%s&idCardType=1&idCardInfo=%s' % ( urllib.quote_plus(p['name'].encode('utf-8')), p['IDCard']) logger.debug('POST %s \n%s' % (url, data)) resp = requests.post(url, data=data, headers=self.headers, verify=False) logger.debug('resp %s' % resp.text) resp_body = resp.json() if resp_body['success']: p_ids.append(str(resp_body['passengerId'])) else: raise Exception('add passenger error') return p_ids
def get_train_list(data): headers = {'User-Agent': base_data.get_user_agent(), 'Content-Type': 'application/json; charset=UTF-8'} url = 'http://m.tuniu.com/api/train/product/ticketListWithFresh?c=%7B%22v%22%3A%228.1.6%22%2C%22ct%22%3A20%2C%22dt%22%3A1%2C%22ov%22%3A1%2C%22p%22%3A15447%2C%22cc%22%3A1502%7D' req = requests.post(url, json=data, headers=headers) logger.debug('POST #1 %s\n%s \n%s' % (req.url, req.headers, data)) try: resp = req.json() if resp['success'] and 'rows' in resp['data'] and resp['data']['rows']: return resp else: kyfw_req = requests.get( 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=%s&from_station=%s&to_station=%s' % ( data['departureDate'], base_data.get_station_code_12306(data['departureCityName']), base_data.get_station_code_12306(data['arrivalCityName'])), verify=False) logger.debug('request 12306:GET %s' % kyfw_req.url) data['trainInfo'] = kyfw_req.text req = requests.post(url, json=data, headers=headers) logger.debug('POST #2 %s\n%s \n%s' % (req.url, req.headers, data)) return req.json() except Exception, e: raise HttpRequestException(e, {'function': 'get_train_list', 'method': 'post', 'url': req.url, 'headers': headers, 'data': data, 'resp_content': req.content})
def get_verifycode(verifycode_url): url = 'https://passport.jd.com/uc/showAuthCode?r=' resp = requests.get(url) if '\"verifycode\":true' in resp.text: for i in range(2): resp = requests.get( 'https:%s&yys=%d' % (verifycode_url.replace( '&', '&'), int(round(time.time() * 1000))), headers={ 'Referer': 'https://passport.jd.com/new/login.aspx?ReturnUrl=https%3A%2F%2Fwww.jd.com%2F' }) logger.info('send image to rk') rc = rk.RClient('15974253250', '1qaz2wsx', '78409', 'e024badb361646e1a38a2afca8cf23f6') result = rc.rk_create(resp.content, 3000) logger.debug('rk=>' + json.dumps(result)) if result and result['Result']: logger.info('verify code =>' + result['Result']) return result['Result'] else: return None
def __init__(self, account, acountid): self.partner = base_data.get_partner() self.cc = base_data.get_cc() self.account = account self.accountid = acountid logger.info('check session by get user id %s' % account) if not account.has_key('sessionid') or not account['sessionid']: logger.info('need login') self.login() account['userid'] = self.get_user_id() logger.info('update account data') req = requests.put(base_data.put_account % acountid, data=json.dumps(account), headers={'Content-Type': 'application/json'}) logger.debug('put %s %s' % (req.url, account)) logger.debug('resp:%s' % req.text) if req.text == '1': logger.info('update account success') else: raise ValueError('update account faild')
def get_cookie(self): logger.debug('get-cookie[get_req_data]:%s %s %s' % (self.name, self.pwd, self.uuid)) url = 'http://wlogin.m.jd.com/applogin_v2' data = auth.get_req_data(self.name, self.pwd, self.uuid) headers = {'User-Agent': 'Android WJLoginSDK 2.4.0'} data = auth.get_req_data(self.name, self.pwd, self.uuid) logger.debug('POST %s\n%s\n%s' % (url, data, json.dumps(headers))) resp = requests.post(url, data=data, headers=headers) resp_text = resp.text logger.debug('resp: %s' % (resp_text)) try: cookie = auth.get_cookie(resp_text) return cookie except Exception, e: raise Exception(u'密码错误')
def get_h5_cookie(self, cookie): body = {"action": "to", "to": 'https%3A%2F%2Ftrain.m.jd.com'} sign = auth.sign('genToken', self.uuid, json.dumps(body)) url = 'http://api.m.jd.com/client.action?functionId=genToken&clientVersion=5.8.0&build=42523&client=android&d_brand=&d_model=&osVersion=&screen=1280*720&partner=tencent&uuid=%s&area=1_2802_0_0&networkType=wifi&st=%s&sign=%s&sv=122' % ( self.uuid, sign[1], sign[0]) logger.debug('POST %s' % url) headers = { 'Charset': 'UTF-8', 'Connection': 'close', 'Cookie': cookie, 'User-Agent': self.user_agent, 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } resp = requests.post(url, data='body=' + urllib.quote(json.dumps(body)) + '&', headers=headers) logger.debug('resp:%s' % resp.text) resp_body = resp.json() # {"code":"0","tokenKey":"AAEAMKMEfWAYh1fRAvE0siwbJrEjuCmaht3Of-dkAaMMpGzemdi7WsCeMn3EaUdejhCZvQ0","url":"http://un.m.jd.com/cgi-bin/app/appjmp"} url = 'http://un.m.jd.com/cgi-bin/app/appjmp?tokenKey=' + resp_body[ 'tokenKey'] + '&to=https%3A%2F%2Ftrain.m.jd.com&lbs=' logger.debug('GET:%s' % url) session = requests.session() resp = session.get( url, headers={ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'User-Agent': self.user_agent }, verify=False) return session.cookies.get_dict()
def place_order(): while True: partner_order_id = '' try: currentHour = int(time.strftime('%H', time.localtime(time.time()))) if currentHour > 22 or currentHour < 7: print 'sleep a hour' time.sleep(600) continue logger.info('--------------------------') logger.info('get jingdong train data') try: resp = requests.get( 'http://op.ykjd.com/JDTrainOpen/getTaskForJD?order_src=app' ) train = resp.json() # train = {"data":"{\"module\":{\"worker\":[{\"assembly\":\"FBServer.Order.TrainJD.Order_TrainJD,FBServer.Order.TrainJD.dll,1.0.0.0\",\"type\":0,\"parms\":None}],\"payer\":None},\"sessionId\":None,\"data\":{\"ticketsInfo\":[{\"coachNo\":\"G1278\",\"departure\":\"漯河西\",\"dptStation\":\"LBN\",\"destination\":\"邢台东\",\"arrStation\":\"EDP\",\"dptDate\":\"2017-04-07\",\"dptTime\":\"\",\"ticketPrice\":204.0000,\"optionType\":1}],\"contactInfo\":{\"name\":\"夏邦初\",\"IDCard\":\"130401197407226837\",\"mobileNo\":\"15077618216\"},\"passengersInfo\":[{\"name\":\"邹凡嘉\",\"IDType\":\"1\",\"IDCard\":\"510123197802174259\",\"mobileNo\":\"15077618216\"},{\"name\":\"夏邦初\",\"IDType\":\"1\",\"IDCard\":\"130401197407226837\",\"mobileNo\":\"15077618216\"}],\"count\":1,\"exData1\":\"O\",\"exData2\":{\"user\":\"15347531101\",\"pwd\":\"aa748578\",\"couponid\":\"9894437370\",\"couponPrice\":\"28.0000\",\"UseAmount\":\"399.0000\",\"cookie\":None,\"orderUser\":\"system\",\"taskType\":1,\"priceSection\":\"300\"},\"fee\":0}}","order_id":"fc9668d6d80d404d94825253ef53029f"} partner_order_id = train['order_id'] logger.debug(json.dumps(train)) except Exception, e: if resp: print resp.text print 'get jingdong train data faild' time.sleep(5) continue train = json.loads(train['data']) # train={"module":{"worker":[{"assembly":"FBServer.Order.TrainJD.Order_TrainJD,FBServer.Order.TrainJD.dll,1.0.0.0","type":0,"parms":None}],"payer":None},"sessionId":None,"data":{"ticketsInfo":[{"coachNo":"G1278","departure":"漯河西","dptStation":"LBN","destination":"邢台东","arrStation":"EDP","dptDate":"2017-04-07","dptTime":"","ticketPrice":204.0000,"optionType":1}],"contactInfo":{"name":"夏邦初","IDCard":"130401197407226837","mobileNo":"15077618216"},"passengersInfo":[{"name":"邹凡嘉","IDType":"1","IDCard":"510123197802174259","mobileNo":"15077618216"},{"name":"夏邦初","IDType":"1","IDCard":"130401197407226837","mobileNo":"15077618216"}],"count":1,"exData1":"O","exData2":{"user":"******","pwd":"xaf888","couponid":"9837987575","couponPrice":"10.0000","UseAmount":"399.0000","cookie":None,"orderUser":"******","taskType":1,"priceSection":"300"},"fee":0}} username = train['data']['exData2']['user'].encode('utf-8') password = train['data']['exData2']['pwd'] logger.info('get orderid:%s,username:%s,password:%s,logon...' % (partner_order_id, username, password)) uuid = base_data.get_random_number( ) + '-' + base_data.get_random_letter_number(12).lower() user_agent = base_data.get_user_agent() # while True: # adsl_service.reconnect() # return1 = os.system('ping baidu.com') # if return1: # continue # else: # break pc_cookie = train['data']['exData2']['pc_cookie'] couponType = train['data']['exData2']['couponType'] if not pc_cookie: try: pc_cookie = http_handler.jd_pc_login.get_cookie( username, password) except Exception: if couponType == 4 or couponType == '4': raise Exception("get pc cookie exception") if not pc_cookie: if couponType == 4 or couponType == '4': raise Exception("get pc cookie faild") cookie = train['data']['exData2']['app_cookie'] if not cookie: login = http_handler.login.Login(username, password, uuid, user_agent) cookie = login.get_cookie() logger.info('login success,cookie:%s' % cookie) h5_cookie = login.get_h5_cookie(cookie) logger.info('get h5 cookie:%s' % h5_cookie) couponid = '' couponPrice = '' if train['data']['exData2'].has_key('couponid'): couponid = train['data']['exData2']['couponid'] logger.info('get couponid %s' % couponid) if train['data']['exData2'].has_key('couponPrice'): couponPrice = train['data']['exData2']['couponPrice'] logger.info('get couponPrice %s' % couponPrice) if couponid: logger.info('find out couponid') if not login.get_couponList(cookie, couponid): logger.info('faild') raise Exception(u'没有找到优惠卷,%s' % couponid) order = http_handler.order.Order(uuid, user_agent, h5_cookie) passengers = train['data']['passengersInfo'] logger.info('add passenger %s' % json.dumps(passengers)) passenger_ids = ','.join(order.add_passenger(passengers)) logger.info('add passenger success.ids:%s.' % passenger_ids) logger.info('add contract %s' % json.dumps(train['data']['contactInfo'])) train['data']['contactInfo']['contractId'] = order.add_contract( train['data']['contactInfo']['name'], train['data']['contactInfo']['mobileNo']) logger.info('add contract success.id:%s.' % train['data']['contactInfo']['contractId']) order_data = order.gen_order(train, passenger_ids) logger.info('order generate success,id:%s.get token...' % order_data['orderid']) order_data = order.get_token(order_data) logger.info('order token success,%s' % order_data['token']) if not (couponid and couponPrice): order_data[ 'coupon'] = '&isGrab=false&payTypes=&couponIds=&couponFee=0' else: order_data[ 'coupon'] = '&payTypes=allDCoupon&couponIds=%s&couponFee=%s&isGrab=false&subOrderType=1' % ( str(couponid), str(int(float(couponPrice) * 100))) # order_data['couponid'] = couponid # order_data['couponPrice'] = int(float(couponPrice) * 100) logger.info('submit:%s' % json.dumps(order_data)) if order.submit(order_data): logger.info('get order details') order_details = order.get_details(order_data['orderid']) if order_details: # try: # resp = requests.get( # 'http://115.29.79.63:9000/api/Cookie/Get?username=%s&password=%s' % (username, password), # timeout=10) # data = resp.json() # if data['Status']: # pc_cookie = data['Cookie'] # else: # logger.error(data['Message']) # except requests.exceptions.ReadTimeout: # logger.error('timeout') # except Exception, e: # logger.error(e.message) logger.info('erpOrderId %s,callback start...' % order_details['erpOrderId']) resp = requests.get( 'http://op.ykjd.com/JDTrainOpen/CallBackForMJD?order_id=%s&jdorder_id=' '%s&success=true&order_no=%s&amount=%s&order_src=app&checi=%s&seatTyp=%s&cookie=%s' % (partner_order_id, order_details['erpOrderId'], order_data['orderid'], order_details['onlinePayFee'], order_data['cheCi'], order_data['seatType'], pc_cookie)) logger.info(resp.text) logger.info('ALL SUCCESS') time.sleep(PLACEORDERINTERVAL) else: raise Exception('order place faild') else: raise Exception(u'已经3次预定') except requests.exceptions.ConnectionError, e: print 'adsl faild' print traceback.format_exc() adsl_service.reconnect()
def place_order(): while True: partner_order_id = '' try: currentHour = int(time.strftime('%H', time.localtime(time.time()))) if currentHour > 22 or currentHour < 7: print 'sleep a hour' time.sleep(3600) continue logger.info('--------------------------') logger.info('get jingdong train data') try: resp = requests.get( 'http://op.yikao666.cn/JDTrainOpen/getTaskForJD?order_src=app' ) train = resp.json() partner_order_id = train['order_id'] logger.debug(json.dumps(train)) except Exception, e: if resp: print resp.text print 'get jingdong train data faild' time.sleep(5) continue train = json.loads(train['data']) username = train['data']['exData2']['user'].encode('utf-8') password = train['data']['exData2']['pwd'] logger.info('get orderid:%s,username:%s,password:%s,logon...' % (partner_order_id, username, password)) uuid = base_data.get_random_number( ) + '-' + base_data.get_random_letter_number(12).lower() user_agent = base_data.get_user_agent() # while True: # adsl_service.reconnect() # return1 = os.system('ping baidu.com') # if return1: # continue # else: # break login = http_handler.login.Login(username, password, uuid, user_agent) cookie = login.get_cookie() logger.info('login success,cookie:%s' % cookie) h5_cookie = login.get_h5_cookie(cookie) logger.info('get h5 cookie:%s' % h5_cookie) couponid = '' couponPrice = '' if train['data']['exData2'].has_key('couponid'): couponid = train['data']['exData2']['couponid'] logger.info('get couponid %s' % couponid) if train['data']['exData2'].has_key('couponPrice'): couponPrice = train['data']['exData2']['couponPrice'] logger.info('get couponPrice %s' % couponPrice) if couponid: logger.info('find out couponid') if not login.get_couponList(cookie, couponid): logger.info('faild') raise Exception(u'没有找到优惠卷,%s' % couponid) order = http_handler.order.Order(uuid, user_agent, h5_cookie) passengers = train['data']['passengersInfo'] logger.info('add passenger %s' % json.dumps(passengers)) passenger_ids = ','.join(order.add_passenger(passengers)) logger.info('add passenger success.ids:%s.' % passenger_ids) order_data = order.gen_order(train, passenger_ids) logger.info('order generate success,id:%s.get token...' % order_data['orderid']) order_data = order.get_token(order_data) logger.info('order token success,%s' % order_data['token']) if not (couponid and couponPrice): order_data[ 'coupon'] = '&isGrab=false&payTypes=&couponIds=&couponFee=0' else: order_data[ 'coupon'] = '&payTypes=allDCoupon&couponIds=%s&couponFee=%s' % ( str(couponid), str(int(float(couponPrice) * 100))) # order_data['couponid'] = couponid # order_data['couponPrice'] = int(float(couponPrice) * 100) logger.info('submit:%s' % json.dumps(order_data)) if order.submit(order_data): logger.info('get order details') order_details = order.get_details(order_data['orderid']) if order_details: logger.info('get pc cookie') pc_cookie = '' try: resp = requests.get( 'http://115.29.79.63:9000/api/Cookie/Get?username=%s&password=%s' % (username, password), timeout=10) data = resp.json() if data['Status']: pc_cookie = data['Cookie'] else: logger.error(data['Message']) except requests.exceptions.ReadTimeout: logger.error('timeout') except Exception, e: logger.error(e.message) logger.info('erpOrderId %s,callback start...' % order_details['erpOrderId']) resp = requests.get( 'http://op.yikao666.cn/JDTrainOpen/CallBackForMJD?order_id=%s&jdorder_id=%s&success=true&order_no=%s&amount=%s&order_src=app&checi=%s&seatTyp=%s&cookie=%s' % (partner_order_id, order_details['erpOrderId'], order_data['orderid'], order_details['onlinePayFee'], order_data['cheCi'], order_data['seatType'], pc_cookie)) logger.info(resp.text) # logger.info('get pc cookie') logger.info('ALL SUCCESS') time.sleep(PLACEORDERINTERVAL) else: raise Exception('order place faild') else: raise Exception('submit maybe faild')
def sync_status_from_jd(): pool = redis.ConnectionPool(host='139.199.65.115', port=6379, db=0, password='******') r = redis.Redis(connection_pool=pool) while True: retry = 0 try: print 'redis brpop' result = r.brpop('order_platform:phone_charge:order_pay_success', 5) if result: resp = result[1] logger.info('get order:%s' % resp, program='sync_status_from_jd') # resp = requests.get(base_data.ORDER_API_GET + id) # resp = resp.json() if (resp): order = json.loads(resp) order_sync_jd_status_time = str(datetime.datetime.now()) cookie = order['account']['cookie'] logger.info('get status', order['trade_no'], 'sync_status_from_jd') uuid = base_data.get_random_number() + '-' + base_data.get_random_letter_number(12).lower() headers = { 'Charset': 'UTF-8', 'jdc-backup': cookie, 'Connection': 'close', 'Cookie': cookie, 'User-Agent': 'okhttp/3.2.0', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} body = {"orderId": order['jd_order_id']} sign = auth.sign('queryPczOrderInfo', uuid, json.dumps(body)) url = 'http://api.m.jd.com/client.action?functionId=queryPczOrderInfo&clientVersion=5.8.0&build=42523&client=android&screen=1920*1080&partner=waps007&uuid=%s&area=1_0_0_0&networkType=wifi&st=%s&sign=%s&sv=122' % ( uuid, sign[1], sign[0]) body = 'body=' + urllib.quote_plus(json.dumps(body)) + '&' while True: resp = requests.post(url, data=body, headers=headers) ret = resp.json() logger.debug('get jd response:%s' % resp.text, order['trade_no'], 'sync_status_from_jd') # print ret jd_order_status = ret['rechargeOrder']['orderStatusName'] logger.info(jd_order_status, order['trade_no'], 'sync_status_from_jd') if jd_order_status == u'充值成功': logger.info('send to queue order_platform:phone_charge:order_success', order['trade_no'], 'sync_status_from_jd') order['order_sync_jd_status_time'] = order_sync_jd_status_time r.lpush('order_platform:phone_charge:order_success', json.dumps(order)) break elif jd_order_status == u'等待付款' or u'充值失败' in jd_order_status: logger.info( 'lpush %s to queue order_platform:phone_charge:order_faild' % order['trade_no'], order['trade_no'], 'sync_status_from_jd') r.lpush('order_platform:phone_charge:order_faild', json.dumps( {'trade_no': order['trade_no'], 'order_faild_time': order_sync_jd_status_time})) break else: pay_callback_time = int( time.mktime(time.strptime(order['pay_callback_time'], '%Y-%m-%d %H:%M:%S'))) t = int(time.time()) if t - pay_callback_time < 15 * 60: retry += 1 if retry < 2: time.sleep(5) # time.sleep(2) continue else: logger.info( 'timeout,lpush %s to queue order_platform:phone_charge:order_pay_success' % order['trade_no'], order['trade_no'], 'sync_status_from_jd') r.lpush('order_platform:phone_charge:order_pay_success', order['trade_no']) break else: logger.info('charge timeout and need customer service verifies,set status', order['trade_no'], 'sync_status_from_jd') resp = requests.post(base_data.ORDER_SETSTATUS_API_POST, data={'order_id': order['trade_no'], 'status': '超时待人工核实'}) logger.info(resp.text, order['trade_no'], 'sync_status_from_jd') break else: logger.error('cant find order %s' % id, program='sync_status_from_jd') else: continue except Exception, e: logger.error(e.message, program='sync_status_from_jd') time.sleep(5) continue
def phone_charge(): pool = redis.ConnectionPool(host='139.199.65.115', port=6379, db=0, password='******') r = redis.Redis(connection_pool=pool) while True: order_id = 0 success = 0 try: print 'redis brpop' result = r.brpop('order_platform:phone_charge:order', 5) if result: trade_no = result[1] logger.info('get trade no:%s' % trade_no) data = r.hgetall('order_platform:phone_charge:trade_no:%s' % trade_no) logger.info('get trade data:%s' % data) data['partner'] = json.loads(data['partner']) if not data: # trade data loss save_order({'trade_no': trade_no, 'status': u'数据丢失'}) logger.error('trade_no %s data loss' % trade_no) continue else: continue except Exception, e: logger.error(e.message) time.sleep(5) continue data['order_handler_time'] = str(datetime.datetime.now()) data['status'] = '正在下单' data['partner_price'] = '' data['callback_status'] = '' if data.has_key('order_id'): order_id = data['order_id'] else: order_id = save_order(data) uuid = base_data.get_random_number() + '-' + base_data.get_random_letter_number(12).lower() # data = {'mobile':'15763563256','parterner_id':'123654','amount':100,callback:''} mobile = des_encryption(data['mobile']) account = get_account(uuid) if not account: r.set('order_platform:switch:order_accpet', 0) data['status'] = '下单失败' data['err'] = '账号不足' callback_partner_and_save_order(data, 0, order_id) continue data['account'] = account pc_cookie = account['pc_cookie'] try: headers = { 'Charset': 'UTF-8', 'jdc-backup': account['cookie'], 'Connection': 'close', 'Cookie': account['cookie'], 'User-Agent': 'Dalvik/1.6.0 (Linux; U; Android 4.4.2; Nexus Build/KOT49H)', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} body = {"mobile": mobile} sign = auth.sign('searchPczPriceList', uuid, json.dumps(body)) url = 'http://api.m.jd.com/client.action?functionId=searchPczPriceList&clientVersion=5.8.0&build=42523&client=android&d_brand=nubia&screen=1920*1080&partner=waps007&uuid=%s&area=1_0_0_0&networkType=wifi&st=%s&sign=%s&sv=122' % ( uuid, sign[1], sign[0]) logger.info('get jd price') resp = requests.post(url, data='body=' + urllib.quote_plus(json.dumps(body)) + '&', headers=headers) resp = resp.json() data['providerName'] = resp['providerName'] data['areaName'] = resp['areaName'] data['partner_price'] = data['partner']['price'][resp['providerName']] # if data['providerName'] == u'移动': # data['partner_price'] = 98 # elif data['providerName'] == u'联通': # data['partner_price'] = 98 # else: # data['partner_price'] = 97 sku = filter(lambda s: s['facePrice'] == str(data['amount']), resp['skuList']) if len(sku) == 0: data['status'] = '数据丢失' callback_partner_and_save_order(data, 0, order_id) continue logger.info('get compon') sign = auth.sign('queryPczFavourableInfo', uuid, json.dumps(body)) url = 'http://api.m.jd.com/client.action?functionId=queryPczFavourableInfo&clientVersion=5.8.0&build=42523&client=android&d_brand=nubia&screen=1920*1080&partner=waps007&uuid=%s&area=1_0_0_0&networkType=wifi&st=%s&sign=%s&sv=122' % ( uuid, sign[1], sign[0]) resp = requests.post(url, data='body=' + urllib.quote_plus(json.dumps(body)) + '&', headers=headers) resp = resp.json() logger.debug(resp) if len(resp['dxqInfos']) > 0: data['discount'] = resp['dxqInfos'][0]['discount'] # 优惠金额 data['dxqids'] = resp['dxqInfos'][0]['id'] else: data['status'] = '没有优惠券' while True: try: logger.error('account compon not found,send to server') account['valid_message'] = '没有优惠券' account['valid'] = 0 resp = requests.post(base_data.JD_ACCOUNT_API_POST, json=account) logger.info('resp:%s' % resp.text) if resp.text == '1': logger.info('success') break else: time.sleep(60) continue except Exception, e: time.sleep(60) continue callback_partner_and_save_order(data, 0, order_id) continue data['jd_price'] = float(sku[0]['jdPrice']) / 100 - data['discount'] body = {"dxqids": data['dxqids'], "facePrice": data['amount'], "isBingding": "0", "isNote": "0", "jdPrice": str(data['jd_price']), "payType": "10", "type": "1", "contact": "false", "mobile": mobile} # data['jd_price'] = float(sku[0]['jdPrice']) / 100 # # "dxqids": "7929697981", # body = {"facePrice": data['amount'], "isBingding": "0", "isNote": "0", # "jdPrice": str(data['jd_price']), # "payType": "0", "type": "1", "contact": "false", "mobile": mobile} sign = auth.sign('submitPczOrder', uuid, json.dumps(body)) url = 'http://api.m.jd.com/client.action?functionId=submitPczOrder&client=android&clientVersion=5.8.0&build=42523&osVersion=4.4.2&screen=1280*720&partner=tencent&uuid=%s&area=1_0_0_0&networkType=wifi&st=%s&sign=%s&sv=122' % ( uuid, sign[1], sign[0]) body = 'body=' + urllib.quote_plus(json.dumps(body)) + '&' logger.debug('POST %s\n%s' % (url, body)) resp = requests.post(url, data=body, headers=headers) ret = resp.json() logger.debug(resp.text) if ret.has_key('orderId'): data['jd_order_id'] = ret['orderId'] data['money'] = ret['money'] data['status'] = u'下单成功' success = 1 logger.info('%s charge success,callback' % data['mobile']) else: data['status'] = u'下单失败' logger.error('%s charge faild\n%s' % (data['mobile'], traceback.format_exc()))
def add_order(sessionid, partner, cc, data): from_ = base_data.get_station_code_by_city_name(data['from']) to_ = base_data.get_station_code_by_city_name(data['to']) if from_ is None: raise ValueError('cannot find from station') if to_ is None: raise ValueError('cannot find to station') logger.info('looking for train %s' % data['train_number']) get_train_list_resp = get_train_list( {"arrivalCityCode": to_['cityCode'], "arrivalCityName": data['to'], "departureCityCode": from_['cityCode'], "departureCityName": data['from'], "departureDate": data['depart_date'], "deviceNumber": base_data.get_random_number(), "sortName": 0, "sortType": 0, "start": 0, "showAvailableTickets": 0, "limit": 0}) train = filter(lambda t: t['trainNum'] == data['train_number'], get_train_list_resp['data']['rows']) if train: logger.info('find train %s success,looking for seat %s' % (data['train_number'], data['seatName'])) seat = filter(lambda t: t['seatName'] == data['seatName'], train[0]['seatDesc']) if seat: logger.info('seat lookup %s success,order place starting...' % data['seatName']) params = {'d': json.dumps( {"zipCode": "", "address": "", "verificationCode": "", "travelCouponId": "", "arrivalCityCode": to_['cityCode'], "arrivalCityName": data['to'], "arrivalStationName": to_['stationName'], "arrivalStations": to_['stationId'], "trainNumber": data['train_number'], "contactList": {"appellation": "", "email": "", "name": "", "phone": "", "tel": data['phone']}, "departDate": data['depart_date'], "departureCityCode": from_['cityCode'], "departureCityName": data['from'], "departureStationName": from_['stationName'], "departureStations": from_['stationId'], "deviceNumber": base_data.get_random_number(), "trainId": train[0]['trainId'], "touristList": data['touristList'], "telNum": "", "sessionId": sessionid, "seatId": seat[0]['seatId'], "promotionList": data['promotionList'], "resourceId": seat[0]['resId'], "receiverName": "", "rate": 0, "adultPrice": data['price'], "isTransferToDispatchTicket": 0, "isExcess": 0, "isDispatchTicket": 0, "isCouponValuable": 0, "insuranceResourceId": 0, "insurancePrice": 0, "childCount": 0, "ministryRailwaysId": 0, "travelCouponUseValue": 0, "useTrainUniquePromotion": False, "adultCount": 1, # len(data['promotionList']) > 0 "acceptStandingTicket": False}), 'c': json.dumps({"v": "9.0.6", "ct": 20, "dt": 1, "ov": 1, "p": partner, "cc": cc})} s = requests.session() s.keep_alive = False headers = {'User-Agent': base_data.get_user_agent(), 'Content-Type': 'application/json; charset=UTF-8'} req = requests.get('http://m.tuniu.com/api/train/order/AddOrder', params, headers=headers) logger.debug('GET %s' % req.url) try: resp = req.json() return resp except Exception, e: raise HttpRequestException(e, {'function': 'addorder', 'method': 'get', 'url': req.url, 'resp_content': req.content}) else: raise ValueError('cant find trainNum %s,seat %s' % (data['train_number'], data['seatName']))