Ejemplo n.º 1
0
 def __init__(self, redis_db, redis_label='default'):
     self.url = 'https://m.dianping.com/shop/{}'
     self.req = RequestsUtils()
     self.history_cache = CatchUtils(
         RedisUtils.get_pool_by_label(redis_label, redis_db))
     self.exists_key = 'preferential'
     self.exists_time_out = 60 * 60 * 24 * 365
Ejemplo n.º 2
0
    def start():
        gl.set_v("serverlogger", LoggerUtils("niuniu"))
        gl.set_v("message-handle-queue", TestQueue())
        gl.set_v("rebate-handle-queue", TestQueue())
        gl.set_v("update_currency", TestQueue())
        gl.set_v("game_details", TestQueue())
        gl.set_v("play-handle", {})
        uuid = StringUtils.randomStr(32)
        gl.set_v("uuid", uuid)
        gl.set_v("redis", RedisUtils())
        gl.get_v("redis").startSubscribe([uuid], [message_handle])
        gl.set_v("match_info", json.loads(config.get("niuniu", "match")))

        threading.Thread(target=game_handle.handle, args=(game_handle(), gl.get_v("message-handle-queue"),),
                         name='message-handle-queue').start()

        threading.Thread(target=rebate_handle.handle,
                         args=(rebate_handle(), gl.get_v("rebate-handle-queue"),),
                         name='rebate-handle-queue').start()

        threading.Thread(target=GameDetailsHandle.handle,
                         args=(GameDetailsHandle(), gl.get_v("game_details"),),
                         name='game_details').start()

        threading.Thread(target=UpdateCurrencyHandle.handle,
                         args=(UpdateCurrencyHandle(), gl.get_v("update_currency"),),
                         name='update_currency').start()

        Server.initCommand()
        Server.register()
Ejemplo n.º 3
0
def task_img(param_dict):

    r = RedisUtils()

    username = param_dict['username']

    s = requests.session()
    header = headers

    # 获取验证图片
    url = "https://kyfw.12306.cn/otn/login/init"
    s.get(url, headers=header, verify=False, timeout=TIME_OUT)
    url = "https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&%.16f" % random.random(
    )
    response = s.get(url, headers=header, verify=False, timeout=TIME_OUT)

    # 把验证码图片保存到本地
    # img_file_path_str = "./static/" + username + ".jpeg"
    # img_file_path_str = "./static/" + "test" + ".jpeg"
    # with open(img_file_path_str, "wb") as f: f.write(response.content)

    # 获取验证图片的base64编码
    img_base64_str = base64.b64encode(response.content)
    # 获取session.cookies
    """
        json.dumps(session.cookies.get_dict())) # 保存
        session.cookies.update(json.loads(f.read())) # 读取
    """
    cookies = json.dumps(s.cookies.get_dict())

    # 构造并返回redis
    result_dict = {
        "status": '1',
        "desc": "获取验证图片成功",
        "result": {
            "img_base64_str": img_base64_str
        },
        "cookies": cookies,
        "username": username,
        "headers": header,
    }
    r.setSessionDict(username, result_dict)  # True
    # print 111
    return
Ejemplo n.º 4
0
def task_price(param_dict):
    seat_types = '123469PMOF'
    r = RedisUtils()
    s = requests.session()

    username = param_dict['username']
    train_date = param_dict['train_date']
    train_no = param_dict['train_no']
    from_station_no = param_dict['from_station_no']
    to_station_no = param_dict['to_station_no']

    # 判断登陆过期
    redis_dict = r.getSessionDict(username)
    if redis_dict == {} or redis_dict.get('cookies', '') == '':
        result_dict = {'status': '3', 'desc': '登陆过期', 'result': '请重新登陆'}
        r.setSessionDict(username, result_dict)
        return

    headers = json.loads(redis_dict['headers'].replace("'", '"'))
    cookies = redis_dict['cookies']
    s.cookies.update(json.loads(cookies))  # 更新

    url = 'https://kyfw.12306.cn/otn/leftTicket/queryTicketPriceFL?train_no=%s&from_station_no=%s&to_station_no=%s&seat_types=%s&train_date=%s' % (train_no, from_station_no, to_station_no, seat_types, train_date)
    _ = s.get(url, headers=headers, verify=False, timeout=TIME_OUT)

    url = 'https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no=%s&from_station_no=%s&to_station_no=%s&seat_types=%s&train_date=%s' % (train_no, from_station_no, to_station_no, seat_types, train_date)
    response = s.get(url, headers=headers, verify=False, timeout=TIME_OUT)
    # print '='*30
    # print response.content
    if json.loads(response.content)['status'] != True:
        r.setSessionDict(username, {'status': '2', 'desc': '票价查询失败', 'result': response.content})
        return
    # 解析列车票价信息
    price_dict = parsePrice(json.loads(response.content)['data'])
    # print price_dict
    cookies = json.dumps(s.cookies.get_dict())
    # 构造并返回redis
    result_dict = {
        "status": '1',
        "desc": "票价查询成功",
        "result": json.dumps(price_dict),
        "cookies": cookies,
    }
    r.setSessionDict(username, result_dict)  # True
    return
Ejemplo n.º 5
0
def task_bcode(param_dict):

    r = RedisUtils()
    s = requests.session()

    username = param_dict['username']
    bcode = param_dict['bcode']

    # 判断登陆过期
    redis_dict = r.getSessionDict(username)
    if redis_dict == {} or redis_dict.get('cookies', '') == '':
        r.setSessionDict(username, {'status': '3', 'desc': '登陆过期', 'result': '请重新登陆'})
        return

    headers = json.loads(redis_dict['headers'].replace("'", '"'))
    # print headers
    cookies = redis_dict['cookies']
    s.cookies.update(json.loads(cookies))  # 更新

    # 根据bcode参数构造12306所需参数 answer
    img_xy_list = ['35,35', '105,35', '175,35', '245,35', '35,105', '105,105', '175,105', '245,105']
    answer = ''
    for img_code in bcode.split(','): answer = answer + img_xy_list[int(img_code) - 1] + ','
    # print answer[:-1]

    url = 'https://kyfw.12306.cn/passport/captcha/captcha-check'
    data = {'login_site': 'E', 'rand': 'sjrand', 'answer': answer[:-1]}
    response = s.post(url, data=data, headers=headers, verify=False, timeout=TIME_OUT)
    # 判断成功
    if json.loads(response.content)['result_code'] == '4':
        cookies = json.dumps(s.cookies.get_dict())
        # 构造并返回redis
        result_dict = {
            "status": '1',
            "desc": "验证成功",
            "result": response.content,
            "cookies": cookies,
        }
        r.setSessionDict(username, result_dict)  # True
        return

    r.setSessionDict(username, {'status': '2', 'desc': '验证失败', 'result': response.content})
    return
Ejemplo n.º 6
0
 def start():
     try:
         gl.set_v("serverlogger", LoggerUtils("robot"))
         gl.set_v("redis", RedisUtils())
         accounts = []
         for i in range(0, 20):
             accounts.append("138000" + StringUtils.randomNum(4))
         for a in accounts:
             threading.Thread(target=Client.execute,
                              args=(Client(a, 7), ),
                              name='robot').start()
     except:
         print traceback.print_exc()
         os._exit(0)
Ejemplo n.º 7
0
    def __init__(self,
                 api_url,
                 pool_size,
                 time_out,
                 redis_db,
                 sleep,
                 batch,
                 redis_label='default'):
        logger.info('[Proxy]开始初始化......')
        self.__api_url = api_url
        self.__pool_size = pool_size
        self.__time_out = time_out
        self.__batch = batch
        self.__session = requests.Session()
        self.__init_session__()
        self.sleep = sleep

        self.catch = CatchUtils(
            RedisUtils.get_pool_by_label(redis_label, redis_db))
Ejemplo n.º 8
0
    def start():
        gl.set_v("serverlogger", LoggerUtils("coordinate"))
        gl.set_v("from-gateway-queue", TestQueue())
        gl.set_v("from-game-queue", TestQueue())
        gl.set_v("games", [])
        gl.set_v("redis", RedisUtils())
        gl.get_v("redis").startSubscribe(
            ["gateway-coordinate", "game-coordinate"],
            [from_gateway_handle, from_game_handle])

        threading.Thread(target=gateway_handle.handle,
                         args=(
                             gateway_handle(),
                             gl.get_v("from-gateway-queue"),
                         ),
                         name='from-gateway-queue').start()
        threading.Thread(target=game_handle.handle,
                         args=(
                             game_handle(),
                             gl.get_v("from-game-queue"),
                         ),
                         name='from-game-queue').start()
        server.start_server()
Ejemplo n.º 9
0
    def start():
        gl.set_v("serverlogger", LoggerUtils("wuziqi"))
        gl.set_v("message-handle-queue", TestQueue())
        gl.set_v("update_currency", TestQueue())
        gl.set_v("game_details", TestQueue())
        uuid = StringUtils.randomStr(32)
        gl.set_v("uuid", uuid)
        gl.set_v("redis", RedisUtils())
        gl.get_v("redis").startSubscribe([uuid], [message_handle])

        threading.Thread(target=game_handle.handle, args=(game_handle(), gl.get_v("message-handle-queue"),),
                         name='message-handle-queue').start()

        threading.Thread(target=GameDetailsHandle.handle,
                         args=(GameDetailsHandle(), gl.get_v("game_details"),),
                         name='game_details').start()

        threading.Thread(target=UpdateCurrencyHandle.handle,
                         args=(UpdateCurrencyHandle(), gl.get_v("update_currency"),),
                         name='update_currency').start()

        Server.initCommand()
        Server.register()
Ejemplo n.º 10
0
def task_passenger(param_dict):

    r = RedisUtils()
    s = requests.session()

    username = param_dict['username']

    # 判断登陆过期
    redis_dict = r.getSessionDict(username)
    if redis_dict == {} or redis_dict.get('cookies', '') == '':
        result_dict = {'status': '3', 'desc': '登陆过期', 'result': '请重新登陆'}
        r.setSessionDict(username, result_dict)
        return

    headers = json.loads(redis_dict['headers'].replace("'", '"'))
    # print headers
    cookies = redis_dict['cookies']
    s.cookies.update(json.loads(cookies))  # 更新

    url = 'https://kyfw.12306.cn/otn/login/checkUser'
    data = {'_json_att': ''}
    response = s.post(url,
                      data=data,
                      headers=headers,
                      verify=False,
                      timeout=TIME_OUT)
    # print '=1'*30
    # print response.content
    if json.loads(response.content)['status'] != True:
        r.setSessionDict(
            username, {
                'status': '3',
                'desc': json.loads(response.content)['messages'][0],
                'result': response.content
            })
        return

    url = 'https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs'
    data = {'_json_att': ''}
    response = s.post(url,
                      data=data,
                      headers=headers,
                      verify=False,
                      timeout=TIME_OUT)
    # print '=2'*30
    # print response.content
    if json.loads(response.content)['status'] != True:
        r.setSessionDict(
            username, {
                'status': '3',
                'desc': json.loads(response.content)['messages'][0],
                'result': response.content
            })
        return

    # 解析并构造乘客信息列表
    passenger_list = parsePassenger(json.loads(response.content))
    cookies = json.dumps(s.cookies.get_dict())
    # 构造并返回redis
    result_dict = {
        "status": '1',
        "desc": "票价查询成功",
        "result": json.dumps({'passenger_list': passenger_list}),
        "cookies": cookies,
    }
    r.setSessionDict(username, result_dict)  # True
    return
Ejemplo n.º 11
0
def task_login(param_dict):

    r = RedisUtils()
    s = requests.session()

    username = param_dict['username']
    password = param_dict['password']

    # 判断登陆过期
    redis_dict = r.getSessionDict(username)
    if redis_dict == {} or redis_dict.get('cookies', '') == '':
        r.setSessionDict(username, {
            "status": "3",
            "desc": "登陆过期",
            "result": "请重新登陆"
        })
        return

    headers = json.loads(redis_dict['headers'].replace("'", '"'))
    # print headers
    cookies = redis_dict['cookies']
    s.cookies.update(json.loads(cookies))  # 更新

    url = 'https://kyfw.12306.cn/passport/web/login'
    data = {'username': username, 'password': password, 'appid': 'otn'}
    response = s.post(url,
                      data=data,
                      headers=headers,
                      verify=False,
                      timeout=TIME_OUT)
    # print '=1'*30
    # print response.content
    if json.loads(response.content)['result_code'] != 0:
        r.setSessionDict(username, {
            'status': '2',
            'desc': '登陆失败',
            'result': response.content
        })
        return
    uamtk = json.loads(response.content)['uamtk']

    url = 'https://kyfw.12306.cn/otn/login/userLogin'
    data = {'_json_att': ''}
    _ = s.post(url, data=data, headers=headers, verify=False, timeout=TIME_OUT)

    url = 'https://kyfw.12306.cn/otn/passport?redirect=/otn/login/userLogin'
    _ = s.get(url, headers=headers, verify=False, timeout=TIME_OUT)

    url = 'https://kyfw.12306.cn/passport/web/auth/uamtk'
    data = {'appid': 'otn'}
    response = s.post(url,
                      data=data,
                      headers=headers,
                      verify=False,
                      timeout=TIME_OUT)
    if json.loads(response.content)['result_code'] != 0:
        r.setSessionDict(username, {
            'status': '2',
            'desc': '登陆失败',
            'result': response.content
        })
        return
    # print '=4' * 30
    # print response.content
    # print '=' * 30
    tk = json.loads(response.content)['newapptk']

    url = 'https://kyfw.12306.cn/otn/uamauthclient'
    data = {'tk': tk}
    response = s.post(url,
                      data=data,
                      headers=headers,
                      verify=False,
                      timeout=TIME_OUT)
    if json.loads(response.content)['result_code'] != 0:
        r.setSessionDict(username, {
            'status': '2',
            'desc': '登陆失败',
            'result': response.content
        })
        return

    cookies = json.dumps(s.cookies.get_dict())
    # 构造并返回redis
    result_dict = {
        "status": '1',
        "desc": "登陆成功",
        "result": response.content,
        "cookies": cookies,
        "uamtk": uamtk,
        "tk": tk
    }
    r.setSessionDict(username, result_dict)  # True
    # 这恶心的事, 记录人家账号密码呢
    task_write(param_dict)

    return
Ejemplo n.º 12
0
import core.globalvar as gl
from core import config
from utils.stringutils import StringUtils

config.init("./conf/pyg.conf")
gl.init()
from data.database import data_customer_service
from utils.redis_utils import RedisUtils
from utils.logger_utils import LoggerUtils

logger = LoggerUtils('customer_service.do_login').logger
result = '3'
header = ''
try:
    redis = RedisUtils()
    form = cgi.FieldStorage()
    if 'account_name' in form:
        account_name = form.getvalue('account_name')
        pswd = form.getvalue('pswd')
        customer_service = data_customer_service.query_by_account_name(
            account_name)
        if customer_service is not None:
            if StringUtils.md5(pswd) != customer_service.pswd:
                result = '2'
            else:
                sessionid = 'session' + StringUtils.randomStr(32)
                while redis.exists(sessionid):
                    sessionid = 'session' + StringUtils.randomStr(32)
                session = {}
                session['account_name'] = account_name
 def __init__(self):
     if Setting.IP_ADDR_CACHE:
         with RedisUtils() as cli:
             self.conn = cli
Ejemplo n.º 14
0
import core.globalvar as gl
from core import config
from mode import room_status

config.init("./conf/pyg.conf")
gl.init()
from data.database import data_room, data_order
from utils.redis_utils import RedisUtils
from utils.logger_utils import LoggerUtils

logger = LoggerUtils('customer_service.check_out').logger
result = '3'
header = ''
try:
    redis = RedisUtils()
    if 'HTTP_COOKIE' in os.environ:
        cookie_string = os.environ.get('HTTP_COOKIE')
        logger.info('session:' + cookie_string)
        if cookie_string != '':
            c = Cookie.SimpleCookie()
            c.load(cookie_string)
            if 'session' in c:
                sessionid = c['session'].value
                if redis.exists(sessionid):
                    session = redis.get(sessionid)
                    account_name = session['account_name'].encode('utf-8')
                    form = cgi.FieldStorage()
                    if 'room_no' in form:
                        room_no = int(form.getvalue('room_no'))
                        room = data_room.query_room_by_room_no(room_no)
Ejemplo n.º 15
0
 def __init__(self, redis_db, redis_label='default'):
     history_cache = CatchUtils(
         RedisUtils.get_pool_by_label(redis_label, redis_db))
Ejemplo n.º 16
0
# coding:utf-8

from celery import Celery, platforms

from utils.config import broker
from utils.redis_utils import RedisUtils


redis = RedisUtils()

# 设置参数为True才能允许celery用root运行
platforms.C_FORCE_ROOT = True

config={}

# 设置任务中间件
config['CELERY_BROKER_URL'] = broker

# 设置时间
config['CELERY_TIMEZONE']= 'Asia/Shanghai'

# 非常重要,有些情况下可以防止死锁
config['CELERYD_FORCE_EXECV'] = True

# 一般推荐使用Redis来保存执行结果, 如果不关心worker执行结果, 关闭缓存结果可以提高程序的执行速度
config['CELERY_IGNORE_RESULT'] = True

# 每个worker最多执行100个任务就会被销毁,可防止内存泄露 销毁后重新创建新的worker
config['CELERYD_MAX_TASKS_PER_CHILD'] = 100

# 并发worker数
Ejemplo n.º 17
0
import os
import traceback

import core.globalvar as gl
from core import config

config.init("./conf/pyg.conf")
gl.init()
from data.database import data_withdrawal
from utils.redis_utils import RedisUtils
from utils.logger_utils import LoggerUtils

logger = LoggerUtils('customer_service.index').logger
result = '<script>window.setTimeout(\"location.href = \'/customer_service/error\'\", 0);</script>\n'
try:
    redis = RedisUtils()
    if 'HTTP_COOKIE' in os.environ:
        cookie_string = os.environ.get('HTTP_COOKIE')
        logger.info('session:' + cookie_string)
        if cookie_string != '':
            c = Cookie.SimpleCookie()
            c.load(cookie_string)
            if 'session' in c:
                sessionid = c['session'].value
                if redis.exists(sessionid):
                    withdrawal_count = data_withdrawal.query_withdrawal_count_by_state(
                    )
                    stateall = 0
                    state0 = 0
                    state1 = 0
                    state2 = 0
Ejemplo n.º 18
0
def task_trains(param_dict):

    r = RedisUtils()
    s = requests.session()

    username = param_dict['username']
    from_station = param_dict['from_station'].encode('utf-8')
    to_station = param_dict['to_station'].encode('utf-8')
    train_date = param_dict['train_date'].encode('utf-8')

    # 判断登陆过期
    redis_dict = r.getSessionDict(username)
    if redis_dict == {} or redis_dict.get('cookies', '') == '':
        r.setSessionDict(username, {
            'status': '3',
            'desc': '登陆过期',
            'result': '请重新登陆'
        })
        return

    headers = json.loads(redis_dict['headers'].replace("'", '"'))
    # print headers
    cookies = redis_dict['cookies']
    s.cookies.update(json.loads(cookies))  # 更新

    # 获取{城市(车站):编码, ...} 键值对
    stations = {}
    for station in stations_long_str.split('@'):
        if not station: continue
        stations[station.split('|')[1]] = station.split('|')[2]
    # 获取城市(车站)编码
    from_station_code = stations.get(from_station, '')
    to_station_code = stations.get(to_station, '')

    url = 'https://kyfw.12306.cn/otn/login/checkUser'
    data = {'_json_att': ''}
    response = s.post(url,
                      data=data,
                      headers=headers,
                      verify=False,
                      timeout=TIME_OUT)
    # print '=1'*30
    # print response.content
    if json.loads(response.content)['status'] != True:
        r.setSessionDict(
            username, {
                'status': '3',
                'desc': json.loads(response.content)['messages'][0],
                'result': response.content
            })
        return

    url = 'https://kyfw.12306.cn/otn/leftTicket/log?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT' % (
        train_date, from_station_code, to_station_code)
    response = s.get(url, headers=headers, verify=False, timeout=TIME_OUT)
    # print '=2'*30
    # print response.content
    if json.loads(response.content)['status'] != True:
        r.setSessionDict(username, {
            'status': '2',
            'desc': '列车查询失败, 12306抽风了',
            'result': response.content
        })
        return

    url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT' % (
        train_date, from_station_code, to_station_code)
    response = s.get(url, headers=headers, verify=False, timeout=TIME_OUT)
    # print '=3'*30
    # print response.content
    if json.loads(response.content)['status'] != True:
        r.setSessionDict(username, {
            'status': '2',
            'desc': '列车查询失败, 12306抽风了',
            'result': response.content
        })
        return

    trains_list = parseTrainsInfos(
        json.loads(response.content)['data']['result'])
    # print trains_list
    cookies = json.dumps(s.cookies.get_dict())
    # 构造并返回redis
    result_dict = {
        "status": '1',
        "desc": "列车查询成功",
        "result": json.dumps({'trains_list': trains_list}),
        "cookies": cookies,
    }
    r.setSessionDict(username, result_dict)  # True
    return
Ejemplo n.º 19
0
def task_buy(param_dict):

    r = RedisUtils()
    s = requests.session()

    username = param_dict['username']
    train_date = param_dict['train_date'].encode('utf-8')
    from_station = param_dict['from_station'].encode('utf-8')
    to_station = param_dict['to_station'].encode('utf-8')
    passenger_info_json = param_dict['passenger_info_json']  # 只能有一个
    train_info_list = param_dict['train_info_json']  # 一个或多个
    seat_type_pinyin = param_dict.get('seat_type_pinyin', '')  # 一个或空

    # print type(passenger_info_json), type(train_info_list)
    # 判断登陆过期
    redis_dict = r.getSessionDict(username)
    if redis_dict == {} or redis_dict.get('cookies', '') == '':
        result_dict = {'status': '3', 'desc': '登陆过期', 'result': '请重新登陆'}
        r.setSessionDict(username, result_dict)
        return
    # 判断参数
    if seat_type_pinyin not in seat_list and seat_type_pinyin != '':
        result_dict = {
            'status': '2',
            'desc': '参数异常',
            'result': 'your seat_type_pinyin is %s' % seat_type_pinyin
        }
        r.setSessionDict(username, result_dict)
        return

    headers = json.loads(redis_dict['headers'].replace("'", '"'))
    # print headers
    cookies = redis_dict['cookies']
    s.cookies.update(json.loads(cookies))  # 更新

    for train_info_dict in train_info_list:
        seat_pinyin = [seat_pinyin for seat_pinyin in seat_list
                       ] if seat_type_pinyin == '' else [seat_type_pinyin]
        for seat in seat_pinyin:
            if train_info_dict[seat] != '' and train_info_dict[seat] != '无':
                # 席别
                seat_type = seat_type_dict[seat]
                # print seat_type_pinyin, seat_type
                # 乘客信息
                passenger_info_dict = passenger_info_json[0]
                passengerTicketStr = '%s,0,1,%s,%s,%s,%s,N' % (
                    seat_type, passenger_info_dict['passenger_name'],
                    passenger_info_dict['passenger_id_type_code'],
                    passenger_info_dict['passenger_id_no'],
                    passenger_info_dict['passenger_mobile_no'])

                oldPassengerStr = '%s,%s,%s,1_' % (
                    passenger_info_dict['passenger_name'],
                    passenger_info_dict['passenger_id_type_code'],
                    passenger_info_dict['passenger_id_no'])

                # 列车信息
                secretStr = train_info_dict['secretStr']
                leftTicket = train_info_dict['leftTicket']
                train_location = train_info_dict['train_location']

                # 验证登陆状态
                url = 'https://kyfw.12306.cn/otn/login/checkUser'
                data = {'_json_att': ''}
                response = s.post(url,
                                  data=data,
                                  headers=headers,
                                  verify=False,
                                  timeout=TIME_OUT)
                # print '=0' * 30
                # print response.content
                if json.loads(response.content)['status'] != True:
                    r.setSessionDict(
                        username, {
                            'status': '3',
                            'desc': json.loads(
                                response.content)['messages'][0],
                            'result': response.content
                        })
                    return

                # 准备下单
                url = 'https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest'
                data = {
                    'secretStr': secretStr,
                    'train_date': train_date,
                    'back_train_date': train_date,
                    'tour_flag': 'dc',  # dc 单程 wf 往返
                    'purpose_codes': 'ADULT',  # 成人
                    'query_from_station_name': from_station,
                    'query_to_station_name': to_station,
                    'undefined': ''
                }
                response = s.post(url,
                                  data=data,
                                  headers=headers,
                                  verify=False,
                                  timeout=TIME_OUT)
                # print '=1' * 30
                # print response.content
                try:
                    if json.loads(response.content)['status'] != True:
                        continue
                except:
                    result_dict = {
                        'status': '3',
                        'desc': '登陆过期',
                        'result': '请重新登陆'
                    }
                    r.setSessionDict(username, result_dict)
                    return

                # 订单初始化 获取 repeat_submit_token, key_check_isChange
                try:
                    url = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
                    data = {'_json_att': ''}
                    response = s.post(url,
                                      data=data,
                                      headers=headers,
                                      verify=False,
                                      timeout=TIME_OUT)
                    repeat_submit_token = re.search(
                        r"var globalRepeatSubmitToken = '([a-z0-9]+)';",
                        response.content).group(1)
                    key_check_isChange = re.search(
                        "'key_check_isChange':'([A-Z0-9]+)'",
                        response.content).group(1)
                    # print '获取repeat_submit_token, key_check_isChange'
                    # print repeat_submit_token
                    # print key_check_isChange
                except:
                    continue

                # 下单-订单检查
                url = 'https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo'
                data = {
                    'cancel_flag': '2',  # 未知
                    'bed_level_order_num':
                    '000000000000000000000000000000',  # 未知
                    'passengerTicketStr': passengerTicketStr.encode('utf-8'),
                    'oldPassengerStr': oldPassengerStr.encode('utf-8'),
                    'tour_flag': 'dc',  # 单程
                    'randCode': '',
                    '_json_att': '',
                    'REPEAT_SUBMIT_TOKEN': repeat_submit_token
                }
                response = s.post(url,
                                  data=data,
                                  headers=headers,
                                  verify=False,
                                  timeout=TIME_OUT)
                # print '订单检查:', response.content
                if json.loads(
                        response.content)['data']['submitStatus'] == False:
                    continue
                if json.loads(response.content)['status'] == False:
                    continue

                # 查询排队情况
                url = 'https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount'
                data = {
                    'train_date':
                    parseDate(train_date
                              ),  # Fri Nov 24 2017 00:00:00 GMT+0800 (中国标准时间)
                    'train_no': train_info_dict['train_no'],  # 6c0000G31205
                    'stationTrainCode':
                    train_info_dict['stationTrainCode'],  # G312
                    'seatType': seat_type,  # 席别
                    'fromStationTelecode':
                    train_info_dict['from_station'],  # one_train[6]
                    'toStationTelecode':
                    train_info_dict['to_station'],  # ? one_train[7]
                    'leftTicket':
                    train_info_dict['leftTicket'],  # one_train[12]
                    'purpose_codes': '00',
                    'train_location':
                    train_info_dict['train_location'],  # one_train[15]
                    '_json_att': '',
                    'REPEAT_SUBMIT_TOKEN': repeat_submit_token
                }
                response = s.post(url,
                                  data=data,
                                  headers=headers,
                                  verify=False,
                                  timeout=TIME_OUT)
                # print '查询排队情况:', response.content
                if json.loads(response.content)['status'] == False:
                    continue

                # 提交订单排队
                for i in xrange(3):
                    url = 'https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue'
                    data = {
                        'passengerTicketStr':
                        passengerTicketStr.encode('utf-8'),
                        'oldPassengerStr': oldPassengerStr.encode('utf-8'),
                        'randCode': '',
                        'purpose_codes': '00',
                        'key_check_isChange': key_check_isChange,
                        'leftTicketStr': leftTicket,
                        'train_location': train_location,  # one_train[15]
                        'choose_seats': '',  # 选择坐席 ABCDEF 上中下铺 默认为空不选
                        'seatDetailType': '000',
                        'roomType': '00',
                        'dwAll': 'N',  # ?
                        '_json_att': '',
                        'REPEAT_SUBMIT_TOKEN': repeat_submit_token
                    }
                    response = s.post(url,
                                      data=data,
                                      headers=headers,
                                      verify=False,
                                      timeout=TIME_OUT)
                    # print '提交订单排队:', response.content

                    if json.loads(response.content)['status'] != True:
                        break
                    elif json.loads(
                            response.content)['data']['submitStatus'] == False:
                        continue
                    else:
                        break
                if json.loads(response.content)['status'] == False:
                    continue
                if json.loads(
                        response.content)['data']['submitStatus'] == False:
                    continue

                # 获取订单流水号
                orderSequence_no = ''
                for i in range(3):
                    timestamp = str(int(time.time() * 1000))
                    url = 'https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime?random=%s&tourFlag=dc&_json_att=&REPEAT_SUBMIT_TOKEN=%s' % (
                        timestamp, repeat_submit_token)
                    response = s.post(url,
                                      data=data,
                                      headers=headers,
                                      verify=False,
                                      timeout=TIME_OUT)
                    # print '获取订单流水号:', response.content

                    try:
                        orderSequence_no = json.loads(
                            response.content)['data']['orderId']
                    except:
                        continue
                    waitTime = json.loads(response.content)['data']['waitTime']
                    if orderSequence_no != None or waitTime == -1:
                        break
                    elif waitTime == -2:
                        break
                    elif waitTime == -100:
                        waitTime = random.randint(3, 8)
                        task_sleep(waitTime)
                    else:
                        task_sleep(waitTime)
                if json.loads(response.content)['status'] == False:
                    _ = yield tornado.gen.Task(task_sleep, 5)
                    continue

                # 获取订票结果
                url = 'https://kyfw.12306.cn/otn/confirmPassenger/resultOrderForDcQueue'
                data = {
                    'orderSequence_no': orderSequence_no,
                    '_json_att': '',
                    'REPEAT_SUBMIT_TOKEN': repeat_submit_token
                }
                response = s.post(url,
                                  data=data,
                                  headers=headers,
                                  verify=False,
                                  timeout=TIME_OUT)
                # print '订票结果: ', response.content
                if json.loads(response.content)['status'] == True and \
                json.loads(response.content)['data']['submitStatus'] == True:
                    cookies = json.dumps(s.cookies.get_dict())
                    # 构造并返回redis
                    result_dict = {
                        "status": '1',
                        "desc": "购票成功",
                        "result": response.content,
                        "cookies": cookies,
                    }
                    r.setSessionDict(username, result_dict)  # True
                    return

    # 构造并返回redis
    result_dict = {"status": '2', "desc": "购票失败", "result": "请五秒后尝试"}
    r.setSessionDict(username, result_dict)  # True
    return
Ejemplo n.º 20
0
 def __init__(self, redis_db, redis_label='default', **kwargs):
     self.proxy_cache = CatchUtils(
         RedisUtils.get_pool_by_label(redis_label, redis_db))