Ejemplo n.º 1
0
    def submit_order_by_time(self, buy_time, retry=4, interval=5):
        """定时提交商品订单

        重要:该方法只适用于普通商品的提交订单,事先需要先将商品加入购物车并勾选✓。

        :param buy_time: 下单时间,例如:'2018-09-28 22:45:50.000'
        :param retry: 下单重复执行次数,可选参数,默认4次
        :param interval: 下单执行间隔,可选参数,默认5秒
        :return:
        """
        if not self.is_login:
            print(get_current_time(), '请先登录再定时下单!')
            return

        t = Timer(buy_time=buy_time)
        t.start()

        for count in range(1, retry + 1):
            print(get_current_time(),
                  '第[{0}/{1}]次尝试提交订单……'.format(count, retry))
            if self.submit_order():
                break
            print(get_current_time(), '休息{0}s……'.format(interval))
            time.sleep(interval)
        else:
            print(get_current_time(), '执行结束,提交订单失败!')
def process_time_based_output(results_dir, interval, rampup_rampdown, request,
                              temp_log, output_file, memlogfile, instance_id,
                              multiple_instance, no_graph, queue, concurrency):
    """
    # Desc  : Main function which handles all the Output Processing
    #         This function is run by the Child Function
    # Input : Results directory, interval for generating summary, time interval for 
    #         rampup-rampdown phase,time interval for MT phase, output summary file,
    #         memory logfile, instance ID, flag to check multiple instance run
    # Output: None
    """
    print("[%s] Starting process for post processing." %
          (util.get_current_time()))
    process_tempfile(results_dir, interval, rampup_rampdown, request, temp_log,
                     instance_id, multiple_instance, queue)
    if multiple_instance:
        util.create_indicator_file(
            os.path.dirname(os.path.dirname(results_dir)), "done_processing",
            instance_id, "")
    # #Post Processing Function
    post_process(temp_log, output_file, results_dir, interval, memlogfile,
                 no_graph, concurrency)
    print("[%s] Exiting process for post processing." %
          (util.get_current_time()))
    sys.exit(0)
Ejemplo n.º 3
0
    def clear_cart(self):
        """清空购物车

        包括两个请求:
        1.选中购物车中所有的商品
        2.批量删除

        :return: 清空购物车结果 True/False
        """
        # 1.select all items  2.batch remove items
        select_url = 'https://cart.jd.com/selectAllItem.action'
        remove_url = 'https://cart.jd.com/batchRemoveSkusFromCart.action'
        data = {
            't': 0,
            'outSkus': '',
            'random': random.random(),
        }
        try:
            select_resp = self.sess.post(url=select_url, data=data)
            remove_resp = self.sess.post(url=remove_url, data=data)
            if (not response_status(select_resp)) or (
                    not response_status(remove_resp)):
                print(get_current_time(), '购物车清空失败')
                return False
            print(get_current_time(), '购物车清空成功')
            return True
        except Exception as e:
            print(get_current_time(), e)
            return False
Ejemplo n.º 4
0
    def _get_QRcode_ticket(self):
        url = 'https://qr.m.jd.com/check'
        payload = {
            'appid': '133',
            'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)),
            'token': self.sess.cookies.get('wlfstk_smdl'),
            '_': str(int(time.time() * 1000)),
        }
        headers = {
            'User-Agent': USER_AGENT,
            'Referer': 'https://passport.jd.com/new/login.aspx',
        }
        resp = self.sess.get(url=url, headers=headers, params=payload)

        if not response_status(resp):
            print(get_current_time(), '获取二维码扫描结果出错')
            return False

        resp_json = parse_json(resp.text)
        if resp_json['code'] != 200:
            print(
                get_current_time(),
                'Code: {0}, Message: {1}'.format(resp_json['code'],
                                                 resp_json['msg']))
            return None
        else:
            print(get_current_time(), '已完成手机客户端确认')
            return resp_json['ticket']
Ejemplo n.º 5
0
    def get_cart_detail(self):
        """获取购物车商品详情
        :return:
        """
        url = 'https://cart.jd.com/cart.action'
        cart_detail_format = '商品名称:{0}----单价:{1}----数量:{2}----总价:{3}'
        try:
            resp = self.sess.get(url=url)
            if not response_status(resp):
                print(get_current_time(), '获取购物车信息失败')
                return
            soup = BeautifulSoup(resp.text, "html.parser")

            print('************************购物车商品详情************************')
            for item in soup.select('div.item-form'):
                name = get_tag_value(item.select('div.p-name a'))
                price = get_tag_value(item.select('div.p-price strong'))
                quantity = get_tag_value(
                    item.select('div.quantity-form input'), 'value')
                total_price = get_tag_value(item.select('div.p-sum strong'))
                print(
                    cart_detail_format.format(name, price, quantity,
                                              total_price))
        except Exception as e:
            print(get_current_time(), e)
Ejemplo n.º 6
0
    def exec_seckill(self, sku_id, retry=4, interval=4, num=1):
        """立即抢购

        抢购商品的下单流程与普通商品不同,不支持加入购物车,主要执行流程如下:
        1. 访问商品的抢购链接
        2. 访问抢购订单结算页面(好像可以省略这步,待测试)
        3. 提交抢购(秒杀)订单

        :param sku_id: 商品id
        :param retry: 抢购重复执行次数,可选参数,默认4次
        :param interval: 抢购执行间隔,可选参数,默认4秒
        :param num: 购买数量,可选参数,默认1个
        :return: 抢购结果 True/False
        """
        for count in range(1, retry + 1):
            print(get_current_time(),
                  '第[{0}/{1}]次尝试抢购商品:{2}'.format(count, retry, sku_id))
            self.request_seckill_url(sku_id)
            self.request_seckill_checkout_page(sku_id, num)
            if self.submit_seckill_order(sku_id, num):
                return True
            else:
                print(get_current_time(), '休息{0}s……'.format(interval))
                time.sleep(interval)
        else:
            print(get_current_time(), '执行结束,抢购{0}失败!'.format(sku_id))
            return False
Ejemplo n.º 7
0
 def start(self):
     print(get_current_time(), '正在等待到达设定时间:%s' % self.buy_time)
     now_time = datetime.now
     while True:
         if now_time() >= self.buy_time:
             print(get_current_time(), '时间到达,开始执行……')
             break
         else:
             time.sleep(self.sleep_interval)
Ejemplo n.º 8
0
    def get_checkout_page_detail(self):
        """访问订单结算页面

        该方法会打印出订单结算页面的详细信息:商品名称、价格、数量、库存状态等。
        如果只是想下单商品,可以不调用该方法。

        :return:
        """
        url = 'http://trade.jd.com/shopping/order/getOrderInfo.action'
        # url = 'https://cart.jd.com/gotoOrder.action'
        payload = {
            'rid': str(int(time.time() * 1000)),
        }
        try:
            resp = self.sess.get(url=url, params=payload)
            if not response_status(resp):
                print(get_current_time(), '获取订单结算页信息失败')
                return
            soup = BeautifulSoup(resp.text, "html.parser")

            self.risk_control = get_tag_value(soup.select('input#riskControl'),
                                              'value')

            print('************************订单结算页详情************************')
            items = soup.select('div.goods-list div.goods-items')[1:]
            checkout_item_detail = '商品名称:{0}----单价:{1}----数量:{2}----库存状态:{3}'
            for item in items:
                name = get_tag_value(item.select('div.p-name a'))
                div_tag = item.select('div.p-price')[0]
                price = get_tag_value(div_tag.select('strong.jd-price'))[
                    2:]  # remove '¥ ' from the begin of price
                quantity = get_tag_value(div_tag.select('span.p-num'))[
                    1:]  # remove 'x' from the begin of quantity
                state = get_tag_value(
                    div_tag.select('span.p-state'))  # in stock or out of stock
                print(checkout_item_detail.format(name, price, quantity,
                                                  state))

            sum_price = soup.find('span', id='sumPayPriceId').text[
                1:]  # remove '¥' from the begin of sum price
            address = soup.find('span', id='sendAddr').text[
                5:]  # remove '收件人:' from the begin of receiver
            receiver = soup.find('span', id='sendMobile').text[
                4:]  # remove '寄送至: ' from the begin of address
            print('应付总额:{0}'.format(sum_price))
            print('收货地址:{0}----收件人:{1}'.format(address, receiver))
        except Exception as e:
            print(get_current_time(), e)
Ejemplo n.º 9
0
 def load_all_data(self):
     # 将以前标记的数据全部读入,用LSH Forest保存,方便计算距离
     # 使用半身照进行检测和识别(输入图片,得到content,解析content得到feature)
     current_day = get_current_day()
     log_file = open(os.path.join(self.log_dir, current_day + '.txt'), 'a')
     if not os.path.exists(self.all_feature_label_file):
         return
     start = time.time()
     # 从数据库中得到半身照和人名
     half_pic_name_list = get_all_annotate_half()
     for element in half_pic_name_list:
         image, name = element
         im = cv2.imdecode(np.fromstring(base64.decodestring(image), dtype=np.uint8), 1)
         tmp_1 = self.extract_pic_feature(im)
         if tmp_1 == None:
             continue
         face_frame, im_feature = tmp_1
         if im_feature == None or face_frame == None:
             continue
         if np.sum(im_feature) == 0:
             print im.shape, name, 'blur'
             continue
         print im.shape, name
         im_feature = list(im_feature)
         # type(im_feature) < type 'list' > ;  len(im_feature) 256
         this_label = name
         self.all_pic_feature.append(im_feature)
         self.all_labels.append(this_label)
         self.lshf.partial_fit(im_feature, this_label)
     end = time.time()
     self.user_count = Counter(self.all_labels)
     current_time = get_current_time()
     log_file.write('\t'.join(map(str, [current_time, self.user_count, 'fit all data time :', (end - start)])) + '\n')
     log_file.close()
Ejemplo n.º 10
0
def add_question():
    if request.method == 'POST':
        user_question = {
            'submission_time': util.get_current_time(),
            'view_number': 0,
            'vote_number': 0,
            'title': request.form['title'],
            'message': request.form['message'],
            'image': None,
            'user_id': session.get('id')
        }

        # if 'file' not in request.files:
        #     flash('No image part')
        # else:
        #     file = request.files['file']
        #     user_question['image'] = file.filename
        #     file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))

        question_id = data_handler.add_question(user_question)

        if request.form['tag-selector'] != 'None':
            data_handler.set_question_tag(question_id['id'], int(request.form['tag-selector']))

        return redirect('/')

    return render_template('add_question.html', tags=data_handler.get_tags())
Ejemplo n.º 11
0
    def submit_seckill_order(self, sku_id, num=1):
        """提交抢购(秒杀)订单
        :param sku_id: 商品id
        :param num: 购买数量,可选参数,默认1个
        :return: 抢购结果 True/False
        """
        url = 'https://marathon.jd.com/seckillnew/orderService/pc/submitOrder.action'
        payload = {
            'skuId': sku_id,
        }
        if not self.seckill_order_data.get(sku_id):
            self.seckill_order_data[sku_id] = self._gen_seckill_order_data(
                sku_id, num)
        headers = {
            'User-Agent':
            USER_AGENT,
            'Host':
            'marathon.jd.com',
            'Referer':
            'https://marathon.jd.com/seckill/seckill.action?skuId={0}&num={1}&rid={2}'
            .format(sku_id, num, int(time.time())),
        }
        resp = self.sess.post(url=url,
                              params=payload,
                              data=self.seckill_order_data.get(sku_id),
                              headers=headers)
        resp_json = parse_json(resp.text)
        # 返回信息
        # 抢购失败:
        # {'errorMessage': '很遗憾没有抢到,再接再厉哦。', 'orderId': 0, 'resultCode': 60074, 'skuId': 0, 'success': False}
        # {'errorMessage': '抱歉,您提交过快,请稍后再提交订单!', 'orderId': 0, 'resultCode': 60017, 'skuId': 0, 'success': False}
        # {'errorMessage': '系统正在开小差,请重试~~', 'orderId': 0, 'resultCode': 90013, 'skuId': 0, 'success': False}
        # 抢购成功:
        # {"appUrl":"xxxxx","orderId":820227xxxxx,"pcUrl":"xxxxx","resultCode":0,"skuId":0,"success":true,"totalMoney":"xxxxx"}

        if resp_json.get('success'):
            order_id = resp_json.get('orderId')
            total_money = resp_json.get('totalMoney')
            pay_url = 'https:' + resp_json.get('pcUrl')
            print(
                get_current_time(),
                '抢购成功,订单号: {0}, 总价: {1}, 电脑端付款链接: {2}'.format(
                    order_id, total_money, pay_url))
            return True
        else:
            print(get_current_time(), '抢购失败,返回信息: {}'.format(resp_json))
            return False
Ejemplo n.º 12
0
def open_log(log_dir):
  try:
      log = open(os.path.join(log_dir, "tempfile_" + str(file_cnt)), "w")
  except IOError:
      print "[%s] Could not open templog file for writing." % (util.get_current_time())
      sys.exit(1)

  return log
def process_tempfile(results_dir, interval, rampup_rampdown, request, temp_log,
                     instance_id, multiple_instance, queue):
    """
    # Desc  : Function to process each intermediate files.
    #         waits for interval and then calls process_data on the next templog file
    # Input : result directory where all the templog files are present,interval after which 
    #         control moves to the next templog file,total time for rampup and rampdown
    #         total time for the measurement, instance ID, flag to check multiple insatnce run 
    # Output: None
    """

    try:
        temp_log = open(os.path.join(results_dir, temp_log), "a")
    except IOError:
        print "[%s] Could not open templog file for writing." % util.get_current_time(
        )
        sys.exit(1)

    temp_log.flush()

    while True:
        event = queue.get()
        if event[0] == 'EXIT':
            break
        _, tempfile, file_cnt = event
        try:
            temp_file = open(tempfile, "r")
        except IOError:
            print "[%s] Could not open %s file for reading." % (
                util.get_current_time(), tempfile)
            sys.exit(1)

        with temp_file:
            print "[%s] Processing Output File tempfile_[%d]." % (
                util.get_current_time(), file_cnt)
            process_data(temp_file, temp_log, results_dir, file_cnt, interval)

        if file_cnt == 0 and multiple_instance:
            util.create_indicator_file(
                os.path.dirname(os.path.dirname(results_dir)),
                "start_processing", instance_id, temp_log.name)
        os.remove(tempfile)

    print("[%s] Closing main templog file." % (util.get_current_time()))
    temp_log.close()
Ejemplo n.º 14
0
def process_tempfile(results_dir, interval, rampup_rampdown, request, temp_log,
                     instance_id, multiple_instance):
    """
    # Desc  : Function to process each intermediate files.
    #         waits for interval and then calls process_data on the next templog file
    # Input : result directory where all the templog files are present,interval after which 
    #         control moves to the next templog file,total time for rampup and rampdown
    #         total time for the measurement, instance ID, flag to check multiple insatnce run 
    # Output: None
    """

    file_cnt = 0
    try:
        temp_log = open(os.path.join(results_dir, temp_log), "a")
    except IOError:
        print("[%s] Could not open templog file for writing." %
              (util.get_current_time()))
    print >> temp_log, "File#,MinResp,MaxResp,MeanResp,95percentile,99percentile,Startime,Endtime,#RUReq,#MTReq,#RDReq,TotalReq,Throughput"
    temp_log.flush()
    time.sleep(60)
    while True:
        tempfile = os.path.join(results_dir, "tempfile_" + str(file_cnt))
        if (os.path.exists(tempfile)):
            time.sleep(interval)
            try:
                temp_file = open(tempfile, "r")
                print("[%s] Processing Output File tempfile_[%d]." %
                      (util.get_current_time(), file_cnt))
                process_data(temp_file, temp_log, results_dir, file_cnt)
                temp_file.close()
                if (file_cnt == 0 and multiple_instance):
                    util.create_indicator_file(
                        os.path.dirname(os.path.dirname(results_dir)),
                        "start_processing", instance_id, temp_log.name)
                os.remove(tempfile)
                file_cnt += 1
            except IOError:
                print("[%s] Could not open templog file for reading." %
                      (util.get_current_time()))
                sys.exit(1)
        else:
            break

    print("[%s] Closing main templog file." % (util.get_current_time()))
    temp_log.close()
Ejemplo n.º 15
0
    def submit_order_by_stock(self, sku_ids, area, interval=3):
        """当商品有库存时提交订单

        重要:该方法只适用于普通商品的提交订单,事先需要先将商品加入购物车并勾选✓。
        该方法会按照指定的间隔查询库存,当有货时提交订单。

        :param sku_ids: 商品id,多个商品id用逗号进行分割,如"123,456,789"
        :param area: 地区id
        :param interval: 查询库存间隔,可选参数,默认为3秒/次
        :return:
        """
        while True:
            if self.if_item_in_stock(sku_ids=sku_ids, area=area):
                print(get_current_time(), '【%s】有货了,正在提交订单……' % sku_ids)
                if self.submit_order():
                    break
            else:
                print(get_current_time(), '【%s】无货,准备下一次查询' % sku_ids)
                time.sleep(interval)
Ejemplo n.º 16
0
 def make_reserve(self, sku_id):
     """商品预约
     :param sku_id: 商品id
     :return:
     """
     reserve_url = self._get_reserve_url(sku_id)
     if not reserve_url:
         print(get_current_time(), '{} 非预约商品'.format(sku_id))
         return
     headers = {
         'User-Agent': USER_AGENT,
         'Referer': 'https://item.jd.com/{}.html'.format(sku_id),
     }
     resp = self.sess.get(url=reserve_url, headers=headers)
     soup = BeautifulSoup(resp.text, "html.parser")
     reserve_result = soup.find('p', {
         'class': 'bd-right-result'
     }).text.strip(' \t\r\n')
     # 预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约
     print(get_current_time(), reserve_result)
Ejemplo n.º 17
0
def gate_pass(lplate):
    sucess = model.is_registered_plate(lplate)
    if sucess:
        # data = {"name" : "view.display_sucessful_gatepass" ,"param" : ()}
        time = util.get_current_time()
        admin = get_current_admin()
        model.add_gate_pass(time, admin, lplate)
        return True
    else:
        # data = {"name" : "view.display_unsucessful_gatepass" ,"param" : ()}
        return False
Ejemplo n.º 18
0
    def add_item_to_cart(self, sku_ids):
        """添加商品到购物车

        重要:
        1.商品添加到购物车后将会自动被勾选✓中。
        2.在提交订单时会对勾选的商品进行结算。
        3.部分商品(如预售)无法添加到购物车

        :param sku_ids: 商品id,格式:"123" 或 "123,456" 或 "123:1,456:2" 或 {"123":1, "456":2}。若不配置数量,默认为1个。
        :return:
        """
        url = 'https://cart.jd.com/gate.action'
        headers = {
            'User-Agent': USER_AGENT,
        }

        # "123" or "123,456" or "123:1,456:2" or {"123":1, "456":2}
        if isinstance(sku_ids, str):
            if ':' in sku_ids:
                sku_ids = parse_sku_id(sku_ids=sku_ids)
            else:
                sku_ids = {
                    sku_id: 1
                    for sku_id in parse_sku_id(sku_ids=sku_ids)
                }

        for sku_id, count in sku_ids.items():
            payload = {
                'pid': sku_id,
                'pcount': count,
                'ptype': 1,
            }
            resp = self.sess.get(url=url, params=payload, headers=headers)
            soup = BeautifulSoup(resp.text, "html.parser")
            tag = soup.select(
                'h3.ftx-02')  # [<h3 class="ftx-02">商品已成功加入购物车!</h3>]
            if not tag:
                print(get_current_time(), '{0}添加到购物车失败'.format(sku_id))
                return
            print(get_current_time(),
                  '{0} x {1} 已成功加入购物车'.format(sku_id, count))
Ejemplo n.º 19
0
def add_new_answer(question_id):

    new_answer = {
        "id": data_manager.generate_answer_id(),
        "submission_time": util.get_current_time(),
        "vote_number": 0,
        "question_id": question_id,
        "message": request.form.get("message"),
    }

    data_manager.write_answers(new_answer)

    return redirect(url_for("display_question", question_id=question_id))
Ejemplo n.º 20
0
def add_new_question():

    new_question = {
        "id": data_manager.generate_question_id(),
        "submission_time": util.get_current_time(),
        "view_number": 0,
        "vote_number": 0,
        "title": request.form.get("title"),
        "message": request.form.get("message"),
    }

    data_manager.write_questions(new_question)
    return redirect("/")
Ejemplo n.º 21
0
    def _get_QRcode(self):
        url = 'https://qr.m.jd.com/show'
        payload = {
            'appid': 133,
            'size': 147,
            't': str(int(time.time() * 1000)),
        }
        headers = {
            'User-Agent': USER_AGENT,
            'Referer': 'https://passport.jd.com/new/login.aspx',
        }
        resp = self.sess.get(url=url, headers=headers, params=payload)

        if not response_status(resp):
            print(get_current_time(), '获取二维码失败')
            return False

        QRCode_file = 'QRcode.png'
        save_image(resp, QRCode_file)
        print(get_current_time(), '二维码获取成功,请打开京东APP扫描')
        open_image(QRCode_file)
        return True
Ejemplo n.º 22
0
def edit_comment(comment_id):
    edit = True
    comment = data_handler.get_comment_by_id(comment_id)

    if request.method == 'POST':
        edited_comment = {
            'id': comment_id,
            'message': request.form['edit_comment'],
            'submission_time': util.get_current_time()
        }
        data_handler.update_comment(edited_comment)
        return redirect(url_for('question', question_id=comment['question_id']))
    return render_template('comment.html', edit=edit, comment=comment)
Ejemplo n.º 23
0
    def exec_reserve_seckill_by_time(self,
                                     sku_id,
                                     buy_time,
                                     retry=4,
                                     interval=4,
                                     num=1):
        """定时抢购`预约抢购商品`

        预约抢购商品特点:
            1.需要提前点击预约
            2.大部分此类商品在预约后自动加入购物车,但是无法勾选✓,也无法️进入到结算页面
            3.到了抢购的时间点后将商品加入购物车,此时才能勾选并下单

        注意:
            1.请在抢购开始前手动清空购物车中此类无法勾选的商品!(因为脚本在执行清空购物车操作时,无法清空不能勾选的商品)

        :param sku_id: 商品id
        :param buy_time: 下单时间,例如:'2018-09-28 22:45:50.000'
        :param retry: 抢购重复执行次数,可选参数,默认4次
        :param interval: 抢购执行间隔,可选参数,默认4秒
        :param num: 购买数量,可选参数,默认1个
        :return:
        """

        t = Timer(buy_time=buy_time)
        t.start()

        self.add_item_to_cart(sku_ids={sku_id: num})

        for count in range(1, retry + 1):
            print(get_current_time(),
                  '第[{0}/{1}]次尝试提交订单……'.format(count, retry))
            if self.submit_order():
                break
            print(get_current_time(), '休息{0}s……'.format(interval))
            time.sleep(interval)
        else:
            print(get_current_time(), '执行结束,提交订单失败!')
Ejemplo n.º 24
0
def edit_answer(answer_id):
    answer = data_handler.get_selected_answer(answer_id)

    if request.method == 'POST':
        edited_answer = {
            'id': answer_id,
            'submission_time': util.get_current_time(),
            'message': request.form['edit_answer'],
            'image': None
        }
        data_handler.update_answer(edited_answer)
        return redirect(url_for('question', question_id=answer['question_id']))

    return render_template('answer.html', answer=answer)
def modify_comment(cmnt_id, modified_input):
    modified = {
        key: (value if value else None)
        for key, value in modified_input.items()
    }
    modified[CMNT_STIME] = util.get_current_time()
    persistence.update_query(table=CMNT_TABLE,
                             columns=modified.keys(),
                             values=modified.values(),
                             where=(CMNT_ID, '=', (cmnt_id, )))
    persistence.update_increment_query(table=CMNT_TABLE,
                                       column=CMNT_EDIT_COUNT,
                                       value=1,
                                       where=(CMNT_ID, '=', (cmnt_id, )))
Ejemplo n.º 26
0
def edit_question(question_id):

    edited_question = {
        "id": question_id,
        "submission_time": util.get_current_time(),
        "view_number": 0,
        "vote_number": 0,
        "title": request.form.get("title"),
        "message": request.form.get("message"),
    }

    questions = data_manager.update_question(edited_question, question_id)

    return redirect(url_for("display_question", question_id=question_id))
Ejemplo n.º 27
0
    def exec_seckill_by_time(self,
                             sku_ids,
                             buy_time,
                             retry=4,
                             interval=4,
                             num=1):
        """定时抢购
        :param sku_ids: 商品id,多个商品id用逗号进行分割,如"123,456,789"
        :param buy_time: 下单时间,例如:'2018-09-28 22:45:50.000'
        :param retry: 抢购重复执行次数,可选参数,默认4次
        :param interval: 抢购执行间隔,可选参数,默认4秒
        :param num: 购买数量,可选参数,默认1个
        :return:
        """
        sku_ids_list = parse_sku_id(sku_ids=sku_ids, need_shuffle=False)
        print(get_current_time(), '准备抢购商品:%s' % list_to_str(sku_ids_list))

        t = Timer(buy_time=buy_time)
        t.start()

        for sku_id in sku_ids_list:
            print(get_current_time(), '开始抢购商品:%s' % sku_id)
            self.exec_seckill(sku_id, retry, interval, num)
def process_data(temp_file, temp_log, results_dir, file_cnt, interval):
    """
    # Desc  : Function which opens temporary files one by one and process 
    #         them for intermediate results
    # Input : file pointer to the templog file which needs to be processed,the temporary file 
    #         where all the processed data is stored, results directory where 
    #         all the templog files are present
    # Output: Generates a summary output file with all the processed data
    """
    col_st = 3  #column number of start time
    col_et = 4  #column number of end time
    col_rt = 5  #column number of response time
    col_ct = 6  #column number of total data length
    col_type = 7  #column number of url type
    read_time = []
    res_arr = []
    total_length = []
    url_type = []
    abs_start = 0
    RUreq = 0
    MTreq = 0
    RDreq = 0
    csvReader = csv.reader(temp_file)
    sortedlist = sorted(csvReader, key=lambda row: int(row[1]))
    for row in sortedlist:
        read_time.append(float(row[col_et]))
        res_arr.append(float(row[col_rt]))
        total_length.append(int(row[col_ct]))
        url_type.append(int(row[col_type]))
        if "RU" in row[0]:
            RUreq = RUreq + 1
        if "MT" in row[0]:
            MTreq = MTreq + 1
        if "RD" in row[0]:
            RDreq = RDreq + 1
        if abs_start == 0:
            abs_start = float(row[col_st])
    if (len(res_arr) > 0):
        calculate(res_arr)
        calculate_total_bytes(total_length)
        total_length.sort()
        len_arr = np.array(total_length)
        mean_len = np.mean(len_arr)
        url_count = Counter(url_type)
        print >> temp_log,str(file_cnt)+","+str(min_resp)+","+str(mean_resp)+","+str(percent95)+","+str(percent99)+","\
        +str(max_resp)+","+str(abs_start)+","+str(max(read_time))+","+str(RUreq)+","+str(MTreq)+","+str(RDreq)+","+str(len(res_arr))+","+\
        str(len(res_arr)/int(interval))+","+str(mean_len)+","+str(url_count[1])+","+str(url_count[2])+","+str(url_count[3])+","+str(total_bytes)
    print("[%s] Writing tempfile_[%d] data to summary file." %
          (util.get_current_time(), file_cnt))
    temp_log.flush()
Ejemplo n.º 29
0
    def login_by_QRcode(self):
        """二维码登陆
        :return:
        """
        if self.is_login:
            print(get_current_time(), '登录成功')
            return True

        self._get_login_page()

        # download QR code
        if not self._get_QRcode():
            print(get_current_time(), '登录失败')
            return False

        # get QR code ticket
        ticket = None
        retry_times = 90
        for _ in range(retry_times):
            ticket = self._get_QRcode_ticket()
            if ticket:
                break
            time.sleep(2)
        else:
            print(get_current_time(), '二维码扫描出错')
            return False

        # validate QR code ticket
        if not self._validate_QRcode_ticket(ticket):
            print(get_current_time(), '二维码登录失败')
            return False
        else:
            print(get_current_time(), '二维码登录成功')
            self.nick_name = self.get_user_info()
            self._save_cookies()
            self.is_login = True
            return True
Ejemplo n.º 30
0
def emergency_bypass(lplate):
    admin = get_current_admin()
    if admin == '':
        data = {"name": "view.display_not_logged", "param": ()}
        return data
    time = util.get_current_time()
    # call gatepass here
    hw.gatepass()
    sucess = model.emergency_bypass(lplate, time, admin)
    if sucess:
        data = {"name": "view.display_sucessful_bypass", "param": ()}
    else:
        data = {"name": "view.display_unsucessful_bypass", "param": ()}
    # print data
    return data