Esempio n. 1
0
class Request(object):
    class Method(Enum):
        '''
            请求动作类型
        '''
        GET = 1
        POST = 2
        PUT = 3
        DELETE = 4

    def __init__(self, session=False, verbose=False):

        # 解决控制台输出 InsecureRequestWarning 的问题
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

        self.log = Logger()

        self.headers = {}

        self.verbose = verbose
        self.info = dict()

        if session:
            self.request = requests.session()
        else:
            self.request = requests

    def send_request(self,
                     request_method,
                     request_type,
                     request_url,
                     request_data=None,
                     auth=None,
                     headers=None,
                     cookies=None):
        '''
        功能:http请求的基础方法,支持不同的请求方法,请求类型
        :param request_method: 请求方法
        :param request_type: 请求内容类型
        :param request_url: 请求URL
        :param request_data: 请求数据
        :return:
        '''

        ssl._create_default_https_context = ssl._create_unverified_context

        if self.verbose:
            self.log.log_info("接口请求地址:{}".format(request_url))
        self.info['request_addrPath'] = "/" + "/".join(
            request_url.split("/")[3:])

        try:
            if self.verbose:
                self.log.log_info("接口请求数据:{}".format(request_data))
            self.info['request_data'] = request_data

            if request_method == "post" and request_type == "urlencoded":
                response = requests.post(url=request_url,
                                         data=request_data,
                                         headers=headers,
                                         auth=auth,
                                         cookies=cookies,
                                         verify=False)

            elif request_method == "post" and request_type == "json":
                response = requests.post(url=request_url,
                                         json=request_data,
                                         headers=headers,
                                         auth=auth,
                                         cookies=cookies,
                                         verify=False)

            elif request_method == "put" and request_type == "json":
                response = requests.put(url=request_url,
                                        json=request_data,
                                        headers=headers,
                                        auth=auth,
                                        cookies=cookies,
                                        verify=False)

            elif request_method == "delete" and request_type == "json":
                response = requests.delete(url=request_url,
                                           json=request_data,
                                           headers=headers,
                                           auth=auth,
                                           cookies=cookies,
                                           verify=False)

            elif request_method == "post" and request_type == "file":

                data = MultipartEncoder(fields=request_data,
                                        boundary="%s" % uuid.uuid4())
                response = self.request.post(url=request_url,
                                             data=data,
                                             headers=headers,
                                             auth=auth,
                                             cookies=cookies,
                                             verify=False)

            elif request_method == "get" and request_type == "urlencoded":
                response = requests.get(url=request_url,
                                        params=request_data,
                                        headers=headers,
                                        auth=auth,
                                        cookies=cookies,
                                        verify=False)

            elif request_method == "get" and request_type == "json":
                response = requests.get(url=request_url,
                                        params=request_data,
                                        headers=headers,
                                        auth=auth,
                                        cookies=cookies,
                                        verify=False)

            else:
                raise exceptions.HttpRequestException(
                    "当前的请求方法:{},请求类型:{}".format(request_method, request_type))

        except Exception as e:
            self.log.log_error("http请求异常:{}".format(e))
            raise exceptions.HttpRequestException("http请求异常")

        self.info['request_header'] = headers
        return self.__setting_response_format(response)

    def __setting_response_format(self, response):

        response_code = response.status_code

        self.info['response_code'] = response_code
        self.info['response_time'] = response.elapsed.total_seconds()
        self.info['local_time'] = TimeHelper.get_time_from_timestamp()
        self.info['response_data'] = response.text
        self.info['response_header'] = dict(response.headers)

        # 进行http的状态码的检测
        '''
            200 请求成功
            401 接口未授权
            404 接口请求地址不存在
            500 接口服务器内部错误
            502 请求失败:接口服务器运行错误:服务是否启动,端口是否可用,网络能否ping通
        '''
        # if response_code == 200 or 201:
        if response_code == 200:

            response_ContentType = response.headers.get("Content-Type")

            if "application/json" in response_ContentType:
                try:
                    self.info['response_data'] = response.json()
                except Exception:
                    self.log.log_error(self.info)
                    raise exceptions.HttpResponseException(
                        "请求类型是json,但接口返回内容却不是json格式")
            elif "image" in response_ContentType:
                self.info['response_data'] = response.content
            else:
                self.log.log_warning("响应内容类型不是json也不是image,是其他类型:{}".format(
                    response_ContentType))
                self.info['response_data'] = response.text

            if self.verbose:
                self.log.log_info("接口响应信息:{}".format(
                    self.info['response_data']))

            return self.info

        self.log.log_warning("请求请求地址:{}".format(self.info['request_addrPath']))
        self.log.log_warning("请求响应的http状态码:{}".format(response_code))
        try:
            self.info['response_data'] = response.json()
        except:
            self.info['response_data'] = response.text

        return self.info
Esempio n. 2
0
class UploadNetty():

    def __init__(self, deviceCode, socket_addr, aes_key):

        self.deviceCode = deviceCode
        self.socket_addr = socket_addr
        self.aes_key = aes_key
        self.log = Logger()

        self.simulate_socket_conn()
        self.simulate_device_login()

        g1 = gevent.spawn(self.simulate_device_beat)
        g1.join()

    # 模拟socket:建立连接
    def simulate_socket_conn(self):
        # 建立socket连接
        self.conn = None
        try:
            self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.conn.connect(self.socket_addr)
            return self.conn
        except Exception as e:
            self.conn.close()
            exit("socket连接建立失败:{}".format(e))

    # 模拟socket:发送消息
    def send_message(self, send_msg):
        try:
            self.conn.sendall(send_msg)
            # res = self.conn.recv(8192)
            # print(res)
        except Exception as e:
            print("发送消息失败:{}".format(e))
            self.conn.close()

    # 模拟业务场景:设备登录
    def simulate_device_login(self):
        info_dict = dict()
        info_dict.setdefault('设备编码', self.deviceCode)
        pb_login_msg = pb_business.login(self.aes_key)
        dev_no_len = len(self.deviceCode)
        msg_aes_len = len(pb_login_msg)
        format = '>BIHIB%ds%ds' % (dev_no_len, msg_aes_len)
        send_msg = struct.pack(format, int('0x1A', 16), msg_aes_len, func_num_map.Login, 0, dev_no_len, self.deviceCode.encode('utf-8'), pb_login_msg)
        self.send_message(send_msg)
        self.log.log_info("设备上报登录信息:{}".format(info_dict))

    # 模拟业务场景:设备心跳
    def simulate_device_beat(self):
        pb_login_beat = pb_business.beat(self.aes_key)
        msg_aes_len = len(pb_login_beat)
        format = '>BIHI%ds' % (msg_aes_len)
        send_msg = struct.pack(format, int('0x1A', 16), msg_aes_len, func_num_map.DeviceStatus , 0, pb_login_beat)
        self.send_message(send_msg)

    # 模拟业务场景:设备上报图片
    def simulate_device_uploadPic(self, img_time=None, score=None, img_path=None, body_img_path=None, userStatus=None, capAngle=None):

        if img_time is None:
            img_time = TimeHelper.get_time(t=TimeHelper.get_time_from_timestamp(), offset=10)
        if score is None:
            score = str(random.randint(80, 190) / 100)
        if img_path is None:
            img_path = gen_bnsData.get_face_picture(index=1)
        face_frame = ImageHelper.pic_to_bytes(img_path)
        if body_img_path is None:
            body_frame = face_frame
        else:
            body_frame = ImageHelper.pic_to_bytes(body_img_path)
        if userStatus is None:
            userStatus = 2  # 默认进店
        if capAngle is None:
            capAngle = 0  # 默认正脸
        alarmId = gen_bnsData.get_alarmId(timestamp=TimeHelper.get_timestamp_from_time(assigned_time=img_time))

        pb_login_msg = pb_business.upload_v4_data(self.aes_key, img_time, face_frame, body_frame, float(score), userStatus, capAngle, alarmId)
        msg_aes_len = len(pb_login_msg)
        format = '>BIHI%ds' % (msg_aes_len)
        send_msg = struct.pack(format, int('0x1A', 16), msg_aes_len, func_num_map.DankiV4ReportData, 0, pb_login_msg)

        # 定义函数需要返回的信息
        info_dict = dict()
        info_dict.setdefault('img_time', img_time)
        info_dict.setdefault('score', score)
        info_dict.setdefault('alarmId', alarmId)
        info_dict.setdefault('userStatus', userStatus)
        info_dict.setdefault('capAngle', capAngle)
        # info_dict.setdefault('face_frame', face_frame)

        self.checkLoginInfo()

        self.send_message(send_msg)
        self.log.log_info("设备上报图片信息:{}".format(info_dict))

        self.checkReplyInfo()

        AllureHelper.attachJson(info_dict, "设备上报的信息")
        AllureHelper.attachPic(face_frame, "设备上报的图片")

        return info_dict

    def checkLoginInfo(self):
        start_time = time.time()
        while True:
            try:
                info_dict = dict()
                end_time = time.time()
                # 等待接收到11个字节
                res = self.conn.recv(11)
                # 获取信息:数据长度、功能号
                data_len = int.from_bytes(res[1:5], byteorder='big')
                func_num = int.from_bytes(res[5:7], byteorder='big')
                self.conn.recv(data_len)
                tmp_res = 'NETTY服务器回复功能号:%s' % func_num_map.functionNo_dict.get(func_num)
                AllureHelper.attachText(tmp_res,"NETTY服务器回复功能号")
                if func_num == 2:
                    info_dict.setdefault('设备登录', func_num_map.functionNo_dict.get(func_num))
                    self.log.log_info("收到设备登录信息回包:{}".format(info_dict))
                    break
                if func_num == 4:
                    info_dict.setdefault('设备心跳', func_num_map.functionNo_dict.get(func_num))
                    self.log.log_info("收到设备心跳信息回包:{}".format(info_dict))
                if end_time - start_time >= 120:
                    raise Exception("NETTY服务器2min超时未回复ReplyLogin")
            except Exception:
                raise Exception("NETTY服务器失败回复ReplyLogin")

    def checkReplyInfo(self):
        start_time = time.time()
        while True:
            try:
                info_dict = dict()
                end_time = time.time()
                # 等待接收到11个字节
                res = self.conn.recv(11)
                # 获取信息:数据长度、功能号
                data_len = int.from_bytes(res[1:5], byteorder='big')
                func_num = int.from_bytes(res[5:7], byteorder='big')
                self.conn.recv(data_len)
                tmp_res = 'NETTY服务器回复功能号:%s' % func_num_map.functionNo_dict.get(func_num)
                AllureHelper.attachText(tmp_res,"NETTY服务器回复功能号")
                if func_num == 12 :
                    info_dict.setdefault('设备上报', func_num_map.functionNo_dict.get(func_num))
                    self.log.log_info("收到设备上报图片回包:{}".format(info_dict))
                    break
                if end_time-start_time >=120:
                    raise Exception("NETTY服务器2min超时未回复ReplyReportData")
            except Exception:
                raise Exception("NETTY服务器失败回复ReplyReportData")