Example #1
0
    def test_lazy_load_twice(self):
        # This test is sad and confusing. Need to figure out what's
        # going on with partial reads and socket reuse.

        with HTTPConnectionPool(self.host,
                                self.port,
                                block=True,
                                maxsize=1,
                                timeout=2) as pool:
            payload_size = 1024 * 2
            first_chunk = 512

            boundary = "foo"

            req_data = {"count": "a" * payload_size}
            resp_data = encode_multipart_formdata(req_data,
                                                  boundary=boundary)[0]

            req2_data = {"count": "b" * payload_size}
            resp2_data = encode_multipart_formdata(req2_data,
                                                   boundary=boundary)[0]

            r1 = pool.request(
                "POST",
                "/echo",
                fields=req_data,
                multipart_boundary=boundary,
                preload_content=False,
            )

            first_data = r1.read(first_chunk)
            assert len(first_data) > 0
            assert first_data == resp_data[:len(first_data)]

            try:
                r2 = pool.request(
                    "POST",
                    "/echo",
                    fields=req2_data,
                    multipart_boundary=boundary,
                    preload_content=False,
                    pool_timeout=0.001,
                )

                # This branch should generally bail here, but maybe someday it will
                # work? Perhaps by some sort of magic. Consider it a TODO.

                second_data = r2.read(first_chunk)
                assert len(second_data) > 0
                assert second_data == resp2_data[:len(second_data)]

                assert r1.read() == resp_data[len(first_data):]
                assert r2.read() == resp2_data[len(second_data):]
                assert pool.num_requests == 2

            except EmptyPoolError:
                assert r1.read() == resp_data[len(first_data):]
                assert pool.num_requests == 1

            assert pool.num_connections == 1
Example #2
0
    def test_lazy_load_twice(self):
        # This test is sad and confusing. Need to figure out what's
        # going on with partial reads and socket reuse.

        pool = HTTPConnectionPool(self.host,
                                  self.port,
                                  block=True,
                                  maxsize=1,
                                  timeout=2)

        payload_size = 1024 * 2
        first_chunk = 512

        boundary = 'foo'

        req_data = {'count': 'a' * payload_size}
        resp_data = encode_multipart_formdata(req_data, boundary=boundary)[0]

        req2_data = {'count': 'b' * payload_size}
        resp2_data = encode_multipart_formdata(req2_data, boundary=boundary)[0]

        r1 = pool.request('POST',
                          '/echo',
                          fields=req_data,
                          multipart_boundary=boundary,
                          preload_content=False)

        first_data = r1.read(first_chunk)
        self.assertGreater(len(first_data), 0)
        self.assertEqual(first_data, resp_data[:len(first_data)])

        try:
            r2 = pool.request('POST',
                              '/echo',
                              fields=req2_data,
                              multipart_boundary=boundary,
                              preload_content=False,
                              pool_timeout=0.001)

            # This branch should generally bail here, but maybe someday it will
            # work? Perhaps by some sort of magic. Consider it a TODO.

            second_data = r2.read(first_chunk)
            self.assertGreater(len(second_data), 0)
            self.assertEqual(second_data, resp2_data[:len(second_data)])

            self.assertEqual(r1.read(), resp_data[len(first_data):])
            self.assertEqual(r2.read(), resp2_data[len(second_data):])
            self.assertEqual(pool.num_requests, 2)

        except EmptyPoolError:
            self.assertEqual(r1.read(), resp_data[len(first_data):])
            self.assertEqual(pool.num_requests, 1)

        self.assertEqual(pool.num_connections, 1)
Example #3
0
    def test_scwj(self):
        select_data = DataBase.mysql_select(
            db='ziyun-iot',
            sql='SELECT cnc_brand FROM `t_device` where device_id ="7429";')
        a = 0
        while a < 2:
            if select_data == 'Fanuc':
                with open('./document/FLK_0.nc', mode="r",
                          encoding="utf-8") as f:
                    file = {
                        "file": ('FLK_0.nc', f.read()),
                        "deviceId": deviceId,
                        "remark": "自动化备注"
                    }
                    encode_data = encode_multipart_formdata(file)
                    file_data = encode_data[0]
                    headers_from_data = {
                        "Content-Type": encode_data[1],
                        "token": token_data
                    }

                rp_resp = request.post_request(url=url + '/file/upload',
                                               data=file_data,
                                               headers=headers_from_data)
                assertions.assert_code(rp_resp.status_code, 200)
                login_resp_json = rp_resp.json()
                assertions.assert_in_text(login_resp_json['message'],
                                          'Success')
                a += 1
            elif select_data == 'Siemens':
                with open('./document/XMZ_0.txt', mode="r",
                          encoding="utf-8") as f:
                    file = {
                        "file": ('XMZ_0.txt', f.read()),
                        "deviceId": deviceId,
                        "remark": "自动化备注"
                    }
                    encode_data = encode_multipart_formdata(file)
                    file_data = encode_data[0]
                    headers_from_data = {
                        "Content-Type": encode_data[1],
                        "token": token_data
                    }

                rp_resp = request.post_request(url=url + '/file/upload',
                                               data=file_data,
                                               headers=headers_from_data)
                assertions.assert_code(rp_resp.status_code, 200)
                login_resp_json = rp_resp.json()
                assertions.assert_in_text(login_resp_json['message'],
                                          'Success')
                a += 1
Example #4
0
    def imagedo(self, role):
        '''
        处理图片信息函数
        主要处理图片上传后返回一个key
        role:客户:1 供应商:2
        :return:
        '''
        url = os.path.join(self.baseurl, 'ub/image/cache/upload')
        header = {
            'Authorization': '09091ca4b0534cbfb57ff6d49c115d83',
            'Accept-Encoding': 'gzip, deflate'
        }
        filename = '1.png'
        filepath = r'C:\Users\Think\Desktop\img\1.png'
        header['Authorization'] = self.header['Authorization']
        if role == '1':
            dictkey = {}
            for i in (2, 3, 11):
                data = {}
                data['type'] = i
                data['file'] = (filename, open(filepath, 'rb').read())
                encode_data = encode_multipart_formdata(data)
                data = encode_data[0]
                header['Content-Type'] = encode_data[1]
                try:
                    res = requests.post(url=url, headers=header,
                                        data=data).json()
                    dictkey['%s' % i] = res['resultObject']['key']
                except Exception as e:
                    print('图片上传失败', e)
            return dictkey

        elif role == '2':
            dictkey = {}
            for i in (2, 3, 11, 12, 13):
                data = {}
                data['type'] = i
                data['file'] = (filename, open(filepath, 'rb').read())
                encode_data = encode_multipart_formdata(data)
                data = encode_data[0]
                header['Content-Type'] = encode_data[1]
                try:
                    res = requests.post(url=url, headers=header,
                                        data=data).json()
                    dictkey['%s' % i] = res['resultObject']['key']
                except Exception as e:
                    print('图片上传失败', e)
            return dictkey
        else:
            print('未知的业务模式')
Example #5
0
 def commit_new_notice(self):
     data = dict()
     title = self.title_edit.text().strip()
     file_path = self.file_edit.text()
     if not all([title, file_path]):
         QMessageBox.information(self, "错误", "请填写完整信息")
         return
     data['utoken'] = settings.app_dawn.value('AUTHORIZATION')
     data['title'] = title
     data['category'] = self.category_combobox.currentData()
     # 读取文件
     file = open(file_path, "rb")
     file_content = file.read()
     file.close()
     filename = file_path.rsplit('/', 1)[1]
     # 文件内容字段
     data["notice_file"] = (filename, file_content)
     encode_data = encode_multipart_formdata(data)
     try:
         r = requests.post(url=settings.SERVER_ADDR + 'exnotice/',
                           headers={"Content-Type": encode_data[1]},
                           data=encode_data[0])
         response = json.loads(r.content.decode('utf8'))
         if r.status_code != 201:
             raise ValueError(response['message'])
     except Exception as e:
         QMessageBox.information(self, "错误", str(e))
     else:
         QMessageBox.information(self, "成功", "添加通知成功")
         self.close()
Example #6
0
 def run(self):
     for file_item in self.file_list:
         # 读取文件
         try:
             data_file = dict()
             # 增加其他字段
             data_file['name'] = file_item['file_name']
             data_file['date'] = file_item['file_date']
             data_file['category_id'] = file_item['category_id']
             # 读取文件
             file = open(file_item['file_path'], "rb")
             file_content = file.read()
             file.close()
             # 文件内容字段
             data_file["file"] = (file_item['file_name'], file_content)
             encode_data = encode_multipart_formdata(data_file)
             data_file = encode_data[0]
             # 发起上传请求
             r = requests.post(url=settings.SERVER_ADDR +
                               'home/transaction_notice/?mc=' +
                               self.machine_code,
                               headers={
                                   'AUTHORIZATION': self.token,
                                   'Content-Type': encode_data[1]
                               },
                               data=data_file)
             response = json.loads(r.content.decode('utf-8'))
             if r.status_code != 201:
                 raise ValueError(response['message'])
         except Exception as e:
             with open('debug/home_notice.log', 'w') as f:
                 f.write(str(e) + '\n')
             self.response_signal.emit(file_item['row_index'], False)
         else:
             self.response_signal.emit(file_item['row_index'], True)
 def get_login_smscode(self, phone):
     path = self.domain + "/apicase/user/getCode"
     data = {"tel": phone, "token": ""}
     # 将公共参数合并进来
     data = dict(data, **self.get_common_args())
     # 获取签名后的参数
     data = get_signData(data)
     bd = self.boundary
     # 将参数转换成encode_multipart_formdata对应的格式
     data_res = encode_multipart_formdata(data, boundary=bd)
     response = requests.post(path,
                              data=data_res[0],
                              headers=self.get_headers(bd))
     # 美化返回的json
     info = self.json_format(response.json())
     print("接口{0}的返回结果是\n{1}".format(path, info))
     assert "成功" in response.text
     # 强制等待两秒钟,待数据库生成短信验证码
     time.sleep(2)
     sql = "SELECT s.content FROM hjxpushdb.sms_log_202106 s WHERE s.phone = {0} ORDER BY s.update_time DESC limit 1".format(
         phone)
     text = Pmysql().execute_sql(sql)
     # 从短信内容中获取验证码
     smsCode = text[0][0].split("验证码是")[1][:6]
     # print("获取到的验证码是:{0}".format(smsCode))
     return smsCode
Example #8
0
async def ocr_request_async(ocr_url, file_path):
    async with aiohttp.ClientSession() as session:
        file_name = os.path.split(file_path)[1]
        encode_data = encode_multipart_formdata({
            "file": (file_name, open(file_path, 'rb').read()),
            "data":
            json.dumps({"caller_request_id": str(uuid.uuid1())})
        })
        data = encode_data[0]
        header = {'Content-Type': encode_data[1]}
        try:
            async with session.post(url=ocr_url, data=data,
                                    headers=header) as resp:
                # print(f"{file_path} start request")
                response_text = await resp.text()
                response_json = json.loads(response_text)
                img_data = [
                    i["text_string"]
                    for i in response_json["img_data_list"][0]["text_info"]
                ]
        except Exception as e:
            print(f"{file_path} {e}")
            return False
        else:
            return img_data
Example #9
0
 def upload_file(self):
     self.edit_widget.commit_button.setEnabled(False)
     self.edit_widget.commit_button.setText("处理文件")
     upload_file_path, _ = QFileDialog.getOpenFileName(
         self, '打开表格', '', "Excel file(*.xls *xlsx)")
     if upload_file_path:
         data = dict()
         data['utoken'] = settings.app_dawn.value('AUTHORIZATION')
         f = open(upload_file_path, 'rb')
         file_content = f.read()
         f.close()
         filename = upload_file_path.rsplit('/', 1)[1]
         data['spot_file'] = (filename, file_content)
         encode_data = encode_multipart_formdata(data)
         try:
             r = requests.post(url=settings.SERVER_ADDR + 'spot/',
                               headers={"Content-Type": encode_data[1]},
                               data=encode_data[0])
             response = json.loads(r.content.decode('utf8'))
             if r.status_code != 201:
                 raise ValueError(response['message'])
         except Exception as e:
             QMessageBox.information(self, "错误", str(e))
             self.edit_widget.commit_button.setEnabled(True)
             self.edit_widget.commit_button.setText("确认提交")
         else:
             QMessageBox.information(self, "成功", "上传数据成功")
             self.edit_widget.commit_button.setEnabled(True)
             self.edit_widget.commit_button.setText("确认提交")
             self.close()
Example #10
0
    def upload_file(self, id, file_path):
        url = "http://************/magicflu/service/s/%s/forms/%s/records/%s/txt/attachments?jqUpload" % (
            self.space_id, self.table_id, id)
        filename = file_path.split('\\')[-1]
        file_data = {"files": (filename, open(file_path, 'rb').read())}
        encode_data = encode_multipart_formdata(file_data)
        data = encode_data[0]

        headers = {
            'content-type': encode_data[1],
            'Cookie': cookie,
            'Origin': "http://************",
            'Accept-Encoding': "gzip, deflate",
            'Accept-Language': "zh-CN,zh;q=0.9",
            'User-Agent':
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36",
            'Accept': "application/json, text/javascript, */*; q=0.01",
            'Referer':
            "http://************/magicflu/html/upload/upload.jsp?single=true&upload_url=%2Fmagicflu%2Fservice%2Fs%2F93d0b958-52d3-4858-b6e9-344a23aede67%2Fforms%2F2717074e-7886-4495-9a0e-4733e55098d2%2Frecords%2F12%2Ftxt%2Fattachments%3FjqUpload&file_size_limit=8000000&file_types=*.*&file_types_description=%E6%89%80%E6%9C%89%E6%96%87%E4%BB%B6",
            'X-Requested-With': "XMLHttpRequest",
            'Connection': "keep-alive",
            'X-FirePHP-Version': "0.0.6",
            'Cache-Control': "no-cache",
            'Postman-Token': "e7a8f7b7-3889-5ece-5642-a57b2b01df10"
        }
        response = requests.post(url, headers=headers, data=data)
        print(response.text)
Example #11
0
def sendFile(filename, file_path):
  '''

  :param filename:
  :param file_path:
  :return:
  '''

  #请求的接口地址
  url = "http://192.168.1.6:8666/cloudApi/fileUpload/doUpload"
  with open(file_path, mode="r", encoding="utf-8")as f: # 打开文件
    file = {
    "file": (filename, f.read()),
    "bussCode":"questionBankPic"
    }

  encode_data = encode_multipart_formdata(file)

  file_data = encode_data[0]
  # b'--c0c46a5929c2ce4c935c9cff85bf11d4\r\nContent-Disposition: form-data; name="file"; filename="1.txt"\r\nContent-Type: text/plain\r\n\r\n...........--c0c46a5929c2ce4c935c9cff85bf11d4--\r\n

  headers_from_data = {
  "Content-Type":"application/octet-stream"
  }
  # token是登陆后给的值,如果你的接口中头部不需要上传字段,就不用写,只要前面的就可以
  # 'Content-Type': 'multipart/form-data; boundary=c0c46a5929c2ce4c935c9cff85bf11d4',这里上传文件用的是form-data,不能用json

  response = requests.post(url=url, headers=headers_from_data, data=file_data).json()
  return response
Example #12
0
 def confirm_avatar(self):
     if not self.new_image_path:
         return
     try:
         data = dict()
         image_name = self.new_image_path.rsplit('/', 1)[1]
         image = open(self.new_image_path, 'rb')
         image_content = image.read()
         image.close()
         data['image'] = (image_name, image_content)
         encode_data = encode_multipart_formdata(data)
         # 发起上传请求
         r = requests.post(url=settings.SERVER_ADDR + 'user/' +
                           str(self.user_id) + '/avatar/',
                           headers={
                               'AUTHORIZATION':
                               settings.app_dawn.value('AUTHORIZATION'),
                               'Content-Type':
                               encode_data[1]
                           },
                           data=encode_data[0])
         response = json.loads(r.content.decode('utf-8'))
         if r.status_code != 200:
             raise ValueError(response['message'])
     except Exception as e:
         pass
     else:
         # 关闭弹窗,修改头像
         new_avatar = response['avatar_url']
         self.new_avatar_url.emit(new_avatar)
         self.close()
Example #13
0
def main(config, istream, job, hashtag, desc, login, passwd, report_empty=False):
    file_data = istream.read()
    # check the data
    report_tree = ET.parse(StringIO.StringIO(file_data))
    if not report_tree.getroot().getchildren() and not report_empty:
        # nothing to report and user not interested in reporting empty result
        print "nothing to report..."
        return
    params = {"parameter": [{'name':'report.xml', 'file': 'file0'},{"name": "desc", "value": hashtag}]}
    data, content_type = urllib3.encode_multipart_formdata([
        ("file0", (istream.name, file_data)),
        ("json", json.dumps(params)),
        ("Submit", "Build"),
        ])
    url = job + 'build'
    r = requests.post(url, auth=(login, passwd), data=data, headers={"content-type": content_type})
    if not r.ok:
        print "Authentification failure."
        exit(1)
    print "Waiting 10s for build to be finished."
    time.sleep(10)
    url = job + 'api/xml'
    xpath_str = "//build//*[contains(text(),'"+ hashtag +"')]/../../../url"
    params = {'depth': '1', 'xpath': xpath_str, 'wrapper': 'list'}
    r = requests.get(url, auth=(login, passwd), params=params)
    
    tree = ET.fromstring(r.text.replace('</url>','</url>\n'))
    notags = ET.tostring(tree, encoding='utf8', method='text')
    job_number = notags.splitlines()[0].rsplit('/',2)[1]

    url = job + 'default/' + job_number + '/testReport/submitDescription'
    params = {'description': desc}
    r = requests.get(url, auth=(login,passwd), params=params)

    print "Return code: " + str(r.status_code)
Example #14
0
def post_form_data(url, payload, header={}):
    encode_payload = encode_multipart_formdata(payload)
    form_data = encode_payload[0]
    header['Content-Type'] = encode_payload[1]
    r = requests.post(url, headers=header, data=form_data)
    res = r.content.decode('utf-8')
    return json.loads(res)
Example #15
0
 def send_file(self, file_name, file_content):
     """
     file_name: xxx.xx 如: 123.jpg
     """
     file = {
         "file": (file_name, file_content),  # 引号的file是接口的字段,后面的是文件的名称、文件的内容
         # "key": "value",  # 如果接口中有其他字段也可以加上
     }
     encode_data = encode_multipart_formdata(file)
     file_data = encode_data[0]
     headers_from_data = {
         "Content-Type": encode_data[1]
     }
     response = requests.post(url=self.uploadurl, headers=headers_from_data, data=file_data).json()
     if response:
         if response.get('success', False) is True:
             return response['data']['url']
         elif response.get('msg', False):
             self.logger.info('传输文件错误:%s' % str(response['msg']))
             return None
         else:
             self.logger.info('传输文件错误:%s' % str(response))
             return None
     else:
         self.logger.info('传输文件错误:无返回结果')
         return None
def update_file(local_image_path):
    # image_path = r'C:\Users\Administrator\Desktop\8888.jpg'
    url = "https://mp.toutiao.com/tools/upload_picture/?type=ueditor&pgc_watermark=1&action=uploadimage&encode=utf-8"

    headers = {
        'content-type':
        'multipart/form-data; boundary=----WebKitFormBoundarySPGWzUNHa41APTAb',
        'origin': 'https://www.toutiao.com',
        'referer': 'https://www.toutiao.com/',
        "User-Agent":
        "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
        "cookie": COOKIE,
    }
    data = {}
    data['upfile'] = (local_image_path.rsplit(os.sep)[-1],
                      open(local_image_path, 'rb').read())
    encode_data = encode_multipart_formdata(data)
    data = encode_data[0]
    headers['content-type'] = encode_data[1]

    reponse = requests.post(url=url, data=data, headers=headers)

    dt = json.loads(reponse.text)
    # AddData(data)

    # print(dt)
    return dt
Example #17
0
 def commit_news_bulletin(self):
     self.commit_button.setEnabled(False)
     # 获取上传的类型
     category = self.category_combo.currentData()
     title = re.sub(r'\s+', '', self.news_title_edit.text())
     if not title:
         self.error_message_label.setText('请输入公告名称!')
         return
     data = dict()
     data['title'] = title  # 标题
     if category == 'file':  # 上传文件
         file_path = self.file_path_edit.text()
         if not file_path:
             self.error_message_label.setText('请选择文件!')
             return
         file_name = file_path.rsplit('/', 1)[1]
         file = open(file_path, "rb")  # 获取文件
         file_content = file.read()
         file.close()
         # 文件内容字段
         data["file"] = (file_name, file_content)
     else:
         data['content'] = self.text_edit.toPlainText()
     encode_data = encode_multipart_formdata(data)
     final_data = encode_data[0]
     self.upload_news(data=final_data, content_type=encode_data[1])
Example #18
0
def free_delay_add(filename):
    files = {
        'cmd': (None, "free_delay_add"),
        'ptype': (None, "vps"),
        'url': (None, "http://www.adminxy.com/showidc-4335.asp"),
        'yanqi_img': (filename, open(filepath + "/screenshot/" + filename,
                                     'rb').read(), 'image/png')
    }
    # 自定义表单 boundary 并编码
    boundary = '----WebKitFormBoundarykYZ25McvRHOtaBYE'
    data = encode_multipart_formdata(files, boundary=boundary)

    # 请求头
    SAN_HEADER['path'] = "/www/renew.php"
    SAN_HEADER['accept'] = "*/*"
    SAN_HEADER[
        'content-type'] = "multipart/form-data; boundary=----WebKitFormBoundarykYZ25McvRHOtaBYE"
    try:
        resp = requests.post(url=DELAY_URL, headers=SAN_HEADER,
                             data=data[0]).json()
        logging.info("***延期请求响应成功,%s ***" % resp)
        if resp['response'] != '200':
            logging.info('***延期失败,原因:%s ***' % resp['msg'])
            return False
        logging.info('***%s***' % resp['msg'])
        return True
    except Exception:
        logging.info('***延期时异常,终止延期***')
        return False
Example #19
0
 def imagedo(self):
     '''
     处理图片信息函数
     主要处理图片上传后返回一个key
     role:钉钉申请:1 供应商:2
     :return:
     '''
     url = os.path.join(self.baseurl, 'scf/oss/file/upload')
     header = {
         'Authorization': '09091ca4b0534cbfb57ff6d49c115d83',
         'Accept-Encoding': 'gzip, deflate'
     }
     filename = '1.png'
     filepath = r'C:\Users\Think\Desktop\img\1.png'
     header['Authorization'] = self.header['Authorization']
     data = {}
     data['type'] = '1'
     data['file'] = (filename, open(filepath, 'rb').read())
     encode_data = encode_multipart_formdata(data)
     data = encode_data[0]
     header['Content-Type'] = encode_data[1]
     try:
         res = requests.post(url=url, headers=header, data=data).json()
         key = res['resultObject']['md5']
         print(key)
         return key
     except Exception as e:
         print('图片上传失败', e)
Example #20
0
def post_files(url, header, data, filename, filepath):
    data['file'] = (filename, open(filepath, 'rb').read())
    encode_data = encode_multipart_formdata(data)
    data = encode_data[0]
    header['Content-Type'] = encode_data[1]
    r = requests.post(url, headers=header, data=data)
    return r
Example #21
0
 def blacklist_add(self, identity, gender, remark, shop_id=golbal_shopid):
     """黑名单--新增
     :param identity:身份
     :param gender:性别
     :param remark:备注
     :param avatar:黑名单头像
     """
     url = host + "/api/shops/%s/blacklist" % shop_id
     files = {
         "avatar": ("%s.jpg" % random.randrange(10, 18),
                    open(
                        r"F:\test\interfaceTest\image\%s.jpg" %
                        random.randrange(10, 18), "rb").read(), "jpg/png"),
         "identity":
         identity,
         "gender":
         gender,
         "remark":
         remark
     }
     encode_data = encode_multipart_formdata(
         files)  # encode_multipart_formdata是导入的一个方法,这个方法下面的文件赋值给encode_data
     data = encode_data[0]  # encode的返回结果第一个值是上传的文件
     header_data = \
         {
             "Content-Type": encode_data[1],  # 指要上传文件的方式,输出encode_data的结果,头部变更为第2个值才能上传
             "Authorization": "Bearer "+token,
         }
     r = requests.post(url=url, headers=header_data, data=data).json()
     out_format("黑名单--新增:", r)
def update_file(cookie, image_path):
    url = "https://mp.toutiao.com/tools/upload_picture/?type=ueditor&pgc_watermark=1&action=uploadimage&encode=utf-8"

    # 再把加密后的结果解码
    ck = base64.b64decode(cookie).decode()

    headers = {
        'content-type':
        'multipart/form-data; boundary=----WebKitFormBoundarySPGWzUNHa41APTAb',
        'origin': 'https://www.toutiao.com',
        'referer': 'https://www.toutiao.com/',
        "User-Agent":
        "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
        "cookie": ck,
    }
    data = {}
    data['upfile'] = (image_path.rsplit(os.sep)[-1], open(image_path,
                                                          'rb').read())
    encode_data = encode_multipart_formdata(data)
    data = encode_data[0]
    headers['content-type'] = encode_data[1]

    reponse = requests.post(url=url, data=data, headers=headers)

    # print(reponse.text)
    dt = json.loads(reponse.text)

    print(dt)
Example #23
0
    def test_post_with_multipart(self):
        data = {'banana': 'hammock', 'lol': 'cat'}
        r = self.pool.request('POST',
                              '/echo',
                              fields=data,
                              encode_multipart=True)
        body = r.data.split(b'\r\n')

        encoded_data = encode_multipart_formdata(data)[0]
        expected_body = encoded_data.split(b'\r\n')

        # TODO: Get rid of extra parsing stuff when you can specify
        # a custom boundary to encode_multipart_formdata
        """
        We need to loop the return lines because a timestamp is attached
        from within encode_multipart_formdata. When the server echos back
        the data, it has the timestamp from when the data was encoded, which
        is not equivalent to when we run encode_multipart_formdata on
        the data again.
        """
        for i, line in enumerate(body):
            if line.startswith(b'--'):
                continue

            self.assertEqual(body[i], expected_body[i])
Example #24
0
 def commit_upload_report(self):
     data = dict()
     title = self.title_edit.text()
     file_path = self.report_file_edit.text()
     if not all([title, file_path]):
         QMessageBox.information(self, "错误", "请填写完整信息")
         return
     data['utoken'] = settings.app_dawn.value('AUTHORIZATION')
     data['title'] = title
     data['link_varieties'] = ','.join(
         map(str, self.attach_varieties.variety_ids))
     data["custom_time"] = self.date_edit.text()
     data['category'] = self.category_combo.currentData()
     # 读取文件
     file = open(file_path, "rb")
     file_content = file.read()
     file.close()
     filename = file_path.rsplit('/', 1)[1]
     # 文件内容字段
     data["report_file"] = (filename, file_content)
     encode_data = encode_multipart_formdata(data)
     try:
         r = requests.post(url=settings.SERVER_ADDR + 'report/',
                           headers={"Content-Type": encode_data[1]},
                           data=encode_data[0])
         response = json.loads(r.content.decode('utf8'))
         if r.status_code != 201:
             raise ValueError(response['message'])
     except Exception as e:
         QMessageBox.information(self, "错误", str(e))
     else:
         QMessageBox.information(self, "成功", "添加报告成功")
         self.close()
Example #25
0
    def commit_upload(self):
        name = re.sub(r'\s+', '', self.name_edit.text())
        if not name:
            self.findChild(QLabel, 'nameError').setText('请输入名称!')
            return
        file_path = self.file_edit.text()
        file_name = file_path.rsplit('/', 1)[1]
        data_file = dict()
        # 增加其他字段
        data_file['utoken'] = settings.app_dawn.value('AUTHORIZATION')
        data_file['title'] = name
        # 读取文件
        file = open(file_path, "rb")
        file_content = file.read()
        file.close()
        # 文件内容字段
        data_file["sreport_file"] = (file_name, file_content)
        encode_data = encode_multipart_formdata(data_file)
        data_file = encode_data[0]
        # 发起上传请求
        try:
            r = requests.post(
                url=settings.SERVER_ADDR + 'advise/searchreport/',
                headers={'Content-Type': encode_data[1]},
                data=data_file
            )
            response = json.loads(r.content.decode('utf-8'))
            if r.status_code != 201:
                raise ValueError(response['message'])

        except Exception as e:
            QMessageBox.information(self, '错误', str(e))
        else:
            QMessageBox.information(self, '成功', response['message'])
            self.close()
Example #26
0
 def _prepare_request(self, timeout, attempt) -> Mapping[str, Any]:
     if self.hmac_key:
         auth = HTTPSignatureAuth(key=self._sqs2bin(self.hmac_key),
                                  key_id=self.hmac_key_id)
     else:
         auth = None
     headers = {}
     if attempt is not None:
         headers[attempt_header_name] = str(attempt)
     request = dict(method=self.method,
                    url=self.url,
                    auth=auth,
                    allow_redirects=False,
                    headers=headers,
                    timeout=timeout)
     body = json.loads(self._sqs2bin(self.body))
     if self.encoding == 'application/json':
         request['json'] = body
     elif self.encoding == 'multipart/form-data':
         # The requests.request() method can encode this content type for us (using the files= keyword argument)
         # but it is awkward to use if the field values are strings or bytes and not streams.
         data, content_type = urllib3.encode_multipart_formdata(body)
         request['data'] = data
         request['headers']['Content-Type'] = content_type
     else:
         raise ValueError(f'Encoding {self.encoding} is not supported')
     return request
    def test_post_with_multipart(self):
        data = {"banana": "hammock", "lol": "cat"}
        r = self.pool.request("POST",
                              "/echo",
                              fields=data,
                              encode_multipart=True)
        body = r.data.split(b"\r\n")

        encoded_data = encode_multipart_formdata(data)[0]
        expected_body = encoded_data.split(b"\r\n")

        # TODO: Get rid of extra parsing stuff when you can specify
        # a custom boundary to encode_multipart_formdata
        """
        We need to loop the return lines because a timestamp is attached
        from within encode_multipart_formdata. When the server echos back
        the data, it has the timestamp from when the data was encoded, which
        is not equivalent to when we run encode_multipart_formdata on
        the data again.
        """
        for i, line in enumerate(body):
            if line.startswith(b"--"):
                continue

            assert body[i] == expected_body[i]
Example #28
0
 def commit_upload(self):
     file_path = self.file_edit.text()
     file_name = file_path.rsplit('/', 1)[1]
     data_file = dict()
     # 增加其他字段
     data_file['utoken'] = settings.app_dawn.value('AUTHORIZATION')
     # data_file['name'] = name
     # 读取文件
     file = open(file_path, "rb")
     file_content = file.read()
     file.close()
     # 文件内容字段
     data_file["pt_file"] = (file_name, file_content)
     encode_data = encode_multipart_formdata(data_file)
     data_file = encode_data[0]
     # 发起上传请求
     try:
         r = requests.post(
             url=settings.SERVER_ADDR + 'consult/persontrain/',
             headers={'Content-Type': encode_data[1]},
             data=data_file
         )
         response = json.loads(r.content.decode('utf-8'))
         if r.status_code != 201:
             raise ValueError(response['message'])
     except Exception as e:
         QMessageBox.information(self, '错误', str(e))
     else:
         QMessageBox.information(self, '成功', response['message'])
         self.close()
Example #29
0
 async def ipfs_add(self, tarball, tarball_name):
     client = AsyncHTTPClient()
     file_field = RequestField(filename=tarball_name, name=tarball_name, data=tarball)
     body, content_type = encode_multipart_formdata([file_field])
     resp = await client.fetch(urljoin(IPFS_API_URL, 'add' + '?' + urlencode({'path': tarball_name})), body=body,
             headers={'Content-Type': content_type}, method='POST')
     return ujson.loads(resp.body)['Hash']
Example #30
0
    def Upload(self, url, file_path, arg="arg"):
        """
        :param filename:文件的名称
        :param file_path:文件的绝对路径
        """
        # filename = FileUtil.GetPathNameWithExt(file_path)
        filename = self.GetPathNameWithExt(file_path)

        with open(file_path, "rb") as f:
            # with open(file_path, mode="r", encoding="utf8") as f :
            file = {
                "file": (filename, f.read()),  # 引号的file是接口的字段,后面的是文件的名称、文件的内容
                "arg": arg,  # 如果接口中有其他字段也可以加上
            }

            encode_data = encode_multipart_formdata(file)

            file_data = encode_data[0]
            # b'--c0c46a5929c2ce4c935c9cff85bf11d4\r\nContent-Disposition: form-data; name="file"; filename="1.txt"\r\nContent-Type: text/plain\r\n\r\n...........--c0c46a5929c2ce4c935c9cff85bf11d4--\r\n

            headers_from_data = {
                "Content-Type": encode_data[1]
                # "Authorization": token
            }
            # token是登陆后给的值,如果你的接口中头部不需要上传字段,就不用写,只要前面的就可以
            # 'Content-Type': 'multipart/form-data; boundary=c0c46a5929c2ce4c935c9cff85bf11d4',这里上传文件用的是form-data,不能用json

            # response = requests.post(url=url, headers=headers_from_data, data=file_data).json()
            response = requests.post(url=url,
                                     headers=headers_from_data,
                                     data=file_data)
            return response.content.decode("utf-8")
    def test_lazy_load_twice(self):
        # This test is sad and confusing. Need to figure out what's
        # going on with partial reads and socket reuse.

        pool = HTTPConnectionPool(self.host, self.port, block=True, maxsize=1, timeout=2)

        payload_size = 1024 * 2
        first_chunk = 512

        boundary = "foo"

        req_data = {"count": "a" * payload_size}
        resp_data = encode_multipart_formdata(req_data, boundary=boundary)[0]

        req2_data = {"count": "b" * payload_size}
        resp2_data = encode_multipart_formdata(req2_data, boundary=boundary)[0]

        r1 = pool.request("POST", "/echo", fields=req_data, multipart_boundary=boundary, preload_content=False)

        self.assertEqual(r1.read(first_chunk), resp_data[:first_chunk])

        try:
            r2 = pool.request(
                "POST",
                "/echo",
                fields=req2_data,
                multipart_boundary=boundary,
                preload_content=False,
                pool_timeout=0.001,
            )

            # This branch should generally bail here, but maybe someday it will
            # work? Perhaps by some sort of magic. Consider it a TODO.

            self.assertEqual(r2.read(first_chunk), resp2_data[:first_chunk])

            self.assertEqual(r1.read(), resp_data[first_chunk:])
            self.assertEqual(r2.read(), resp2_data[first_chunk:])
            self.assertEqual(pool.num_requests, 2)

        except EmptyPoolError:
            self.assertEqual(r1.read(), resp_data[first_chunk:])
            self.assertEqual(pool.num_requests, 1)

        self.assertEqual(pool.num_connections, 1)
 def lua(self):
      #headers={'Content-Type':'multipart/form-data', 'Content-Encoding':'gzip', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'}
     files={'file': ("gwlog.zip", open('/software/locust/locustfile/gwlog.zip','rb').read(), "application/zip")}
     d = encode_multipart_formdata(files, boundary='eaaee54a-3b9a-4b60-9d98-0b5f27d9c4ef')
     with self.client.post('/api/uploadlog.json', data=d[0], headers = {"content-type": d[1]}) as response:
         if response.status_code == 200:
             response.success()
         else:	
             print(response.text)
    def test_post_with_multipart(self):
        data = {"banana": "hammock", "lol": "cat"}
        r = self.pool.request("POST", "/echo", fields=data, encode_multipart=True)
        body = r.data.split(b"\r\n")

        encoded_data = encode_multipart_formdata(data)[0]
        expected_body = encoded_data.split(b"\r\n")

        # TODO: Get rid of extra parsing stuff when you can specify
        # a custom boundary to encode_multipart_formdata
        """
        We need to loop the return lines because a timestamp is attached
        from within encode_multipart_formdata. When the server echos back
        the data, it has the timestamp from when the data was encoded, which
        is not equivalent to when we run encode_multipart_formdata on
        the data again.
        """
        for i, line in enumerate(body):
            if line.startswith(b"--"):
                continue

            self.assertEqual(body[i], expected_body[i])