Esempio n. 1
0
    def _sendRequest_multipart(self,
                               method,
                               url,
                               headers=None,
                               cookie=None,
                               httpStatusExp=None,
                               statusExp=None,
                               needJson=True,
                               bText=True,
                               multipartEncodedContent=None):
        '''
        Send Multipart request with method post or put
        '''
        if not isinstance(multipartEncodedContent, MultipartEncoder):
            raise RuntimeError("multipartEncodedContent invalid")

        if headers is None:  # 如果header为空,默认header
            headers = self._default_header

        if isinstance(headers, list):
            headers = self.conver_header_list_2_dict(headers)

        headers.update({'Content-Type': multipartEncodedContent.content_type})
        try:
            if method == "POST":
                if "https" in url:
                    resp = requests.post(url,
                                         data=multipartEncodedContent,
                                         headers=headers,
                                         verify=False,
                                         cookies=cookie)
                else:
                    resp = requests.post(url,
                                         data=multipartEncodedContent,
                                         headers=headers,
                                         cookies=cookie)
            elif method == "PUT":
                if "https" in url:
                    resp = requests.put(url,
                                        data=multipartEncodedContent,
                                        headers=headers,
                                        verify=False,
                                        cookies=cookie)
                else:
                    resp = requests.put(url,
                                        data=multipartEncodedContent,
                                        headers=headers,
                                        cookies=cookie)
        except Exception as e:
            print("[Request Exception] {0}: {1}".format(type(e), e))
            msg = "send request {%s] %s failed: %s" % (method, url, str(e))
            logging.error(e)
            logging.error(msg)
            assert False, msg

        if httpStatusExp:
            logging.info("校验httpStatusExp")
            cb.checkResultEqual(
                resp.status_code, httpStatusExp,
                f'actual status_code: {resp.status_code}, expect status_code: {httpStatusExp}'
            )

        # 输出响应头信息
        logging.info('响应headers: {}'.format(resp.headers))

        if needJson:
            if bText:
                resp_text = resp.text
            else:
                resp_text = resp.content
            resp = cb.loadJsonData(resp_text)
            if statusExp:
                cb.checkValueInDict(
                    resp, "status", statusExp,
                    "[Request] resp data['status'] does not match with %s" %
                    str(statusExp))
        return resp
Esempio n. 2
0
    def _sendRequest_requests(self,
                              method,
                              url,
                              data=None,
                              headers=None,
                              cookie=None,
                              files=None,
                              httpStatusExp=None,
                              statusExp=None,
                              needJson=True,
                              bText=True,
                              agent=None,
                              **kwargs):
        '''
        request发送发送API请求,支持application/x-www-form-urlencoded,application/json格式

        '''

        if headers is None:  # 如果header为空,默认header
            headers = self._default_header

        if isinstance(headers, list):
            headers = self.conver_header_list_2_dict(headers)

        new_headers = self.dict_key_to_lower(headers)
        if 'content-type' in new_headers and new_headers[
                'content-type'] == 'application/x-www-form-urlencoded':
            data = data if data else None
        elif 'content-type' in new_headers and new_headers[
                'content-type'] == 'application/json':
            data = json.dumps(data) if data else None
        if 'content_tyep' in new_headers and new_headers[
                'content-type'] == 'multipart/form-data':
            files = files if files else None
            # files = {'file':open('xxx.xls', 'rb')}

        logging.info("请求url: {}".format(url))
        logging.info("请求method: {}".format(method))
        logging.info("请求header: {}".format(headers))
        logging.info("请求header type is: {}".format(type(headers)))
        logging.info("请求data: {}".format(data))

        # 增加容错处理,默认retry_num=3
        for i in range(self._retry_num):
            try:
                self.bContinue = False

                if method == "GET":
                    if "https" in url:
                        resp = requests.get(url,
                                            params=data,
                                            headers=headers,
                                            cookies=cookie,
                                            timeout=self._timeout,
                                            stream=True,
                                            verify=False)
                    else:
                        resp = requests.get(url,
                                            params=data,
                                            headers=headers,
                                            cookies=cookie,
                                            timeout=self._timeout,
                                            stream=True)
                elif method == "PUT":
                    if "https" in url:
                        resp = requests.put(url,
                                            data=data,
                                            headers=headers,
                                            cookies=cookie,
                                            timeout=self._timeout,
                                            stream=True,
                                            verify=False)
                    else:
                        resp = requests.put(url,
                                            data=data,
                                            headers=headers,
                                            cookies=cookie,
                                            timeout=self._timeout,
                                            stream=True)
                elif method == "DELETE":
                    if "https" in url:
                        resp = requests.delete(url,
                                               data=data,
                                               headers=headers,
                                               cookies=cookie,
                                               timeout=self._timeout,
                                               stream=True,
                                               verify=False)
                    else:
                        resp = requests.delete(url,
                                               data=data,
                                               headers=headers,
                                               cookies=cookie,
                                               timeout=self._timeout,
                                               stream=True)
                elif method == "POST":
                    if "https" in url:
                        resp = requests.post(url,
                                             data=data,
                                             files=files,
                                             headers=headers,
                                             cookies=cookie,
                                             timeout=self._timeout,
                                             stream=True,
                                             verify=False)
                    else:
                        resp = requests.post(url,
                                             data=data,
                                             files=files,
                                             headers=headers,
                                             cookies=cookie,
                                             timeout=self._timeout,
                                             stream=True)
                elif method == "PATCH":
                    if "https" in url:
                        resp = requests.patch(url,
                                              data=data,
                                              headers=headers,
                                              cookies=cookie,
                                              timeout=self._timeout,
                                              stream=True,
                                              verify=False)
                    else:
                        resp = requests.patch(url,
                                              data=data,
                                              headers=headers,
                                              cookies=cookie,
                                              timeout=self._timeout,
                                              stream=True)
                else:
                    logging.error(
                        "The request method %s is not in ['post','get','put','delete','patch']"
                    )
                    assert False

                break

            except Exception as e:
                msg = "send request [%s] %s failed: %s" % (method, url, str(e))
                logging.info(e)
                logging.info(msg)
                if (str(e).find('Max retries exceeded') > 0
                        or str(e).find('Read timed out') > 0
                        or str(e).find('Connection aborted') > -1
                    ) and i + 1 < self._retry_num:
                    time.sleep(10)
                    self.bContinueb = True
                    continue
                assert False, msg
            finally:
                if not self.bContinue:
                    pass

        # 校验httpStatusCode
        if httpStatusExp:
            logging.info("校验httpStatusExp")
            cb.checkResultEqual(
                resp.status_code, httpStatusExp,
                f'actual status_code: {resp.status_code}, expect status_code: {httpStatusExp}'
            )

        # 输出响应头和响应内容
        logging.info('响应headers: {}'.format(resp.headers))

        if needJson:
            if bText:
                resp_text = resp.text
            else:
                resp_text = resp.content
            resp = cb.loadJsonData(resp_text)
            logging.info("响应response: {}".format(resp))
            if statusExp:
                cb.checkValueInDict(
                    resp, "status", statusExp,
                    "[Request] resp data['status'] does not match with %s" %
                    str(statusExp))
        return resp