Esempio n. 1
0
 def test_encodes_with_readable_data(self):
     s = io.BytesIO(b'value')
     m = MultipartEncoder([('field', s)], boundary=self.boundary)
     assert m.read() == (
         '--this-is-a-boundary\r\n'
         'Content-Disposition: form-data; name="field"\r\n\r\n'
         'value\r\n'
         '--this-is-a-boundary--\r\n'
     ).encode()
Esempio n. 2
0
    def test_streams_its_data(self):
        large_file = LargeFileMock()
        parts = {'some field': 'value',
                 'some file': large_file,
                 }
        encoder = MultipartEncoder(parts)
        read_size = 1024 * 1024 * 128
        while True:
            read = encoder.read(read_size)
            if not read:
                break

        assert encoder._buffer.tell() <= read_size
class TestMultipartEncoder(unittest.TestCase):
    def setUp(self):
        self.parts = [('field', 'value'), ('other_field', 'other_value')]
        self.boundary = 'this-is-a-boundary'
        self.instance = MultipartEncoder(self.parts, boundary=self.boundary)

    def test_to_string(self):
        assert self.instance.to_string() == (
            '--this-is-a-boundary\r\n'
            'Content-Disposition: form-data; name="field"\r\n\r\n'
            'value\r\n'
            '--this-is-a-boundary\r\n'
            'Content-Disposition: form-data; name="other_field"\r\n\r\n'
            'other_value\r\n'
            '--this-is-a-boundary--\r\n'
        ).encode()

    def test_content_type(self):
        expected = 'multipart/form-data; boundary=this-is-a-boundary'
        assert self.instance.content_type == expected

    def test_encodes_data_the_same(self):
        assert self.instance.to_string() == self.instance.read()

    def test_streams_its_data(self):
        large_file = LargeFileMock()
        parts = {'some field': 'value',
                 'some file': large_file,
                 }
        encoder = MultipartEncoder(parts)
        read_size = 1024 * 1024 * 128
        while True:
            read = encoder.read(read_size)
            if not read:
                break

        assert encoder._buffer.tell() <= read_size

    def test_length_is_correct(self):
        assert len(self.instance.to_string()) == len(self.instance)

    def test_encodes_with_readable_data(self):
        s = io.BytesIO(b'value')
        m = MultipartEncoder([('field', s)], boundary=self.boundary)
        assert m.read() == (
            '--this-is-a-boundary\r\n'
            'Content-Disposition: form-data; name="field"\r\n\r\n'
            'value\r\n'
            '--this-is-a-boundary--\r\n'
        ).encode()
 def test_pici_shanchu(self):
     a = self.setUp()
     url = "http://123.57.140.190/manage/del_fwm_all.php?act=pici"
     data4 = MultipartEncoder({'riqi': '13213213653515'})
     header4 = {'Content-Type': data4.content_type, 'Cookie': a}
     r = requests.post(url, data=data4, headers=header4)
     print(r.text)
Esempio n. 5
0
    def _register(self, session,
                  url):  # type: (requests.Session, str) -> requests.Response
        """
        Register a package to a repository.
        """
        dist = self._poetry.file.parent / "dist"
        file = dist / "{}-{}.tar.gz".format(
            self._package.name, normalize_version(self._package.version.text))

        if not file.exists():
            raise RuntimeError('"{0}" does not exist.'.format(file.name))

        data = self.post_data(file)
        data.update({":action": "submit", "protocol_version": "1"})

        data_to_send = self._prepare_data(data)
        encoder = MultipartEncoder(data_to_send)
        resp = session.post(
            url,
            data=encoder,
            allow_redirects=False,
            headers={"Content-Type": encoder.content_type},
        )

        resp.raise_for_status()

        return resp
Esempio n. 6
0
    def _register(self, session: requests.Session,
                  url: str) -> requests.Response:
        """
        Register a package to a repository.
        """
        dist = self._poetry.file.parent / "dist"
        file = (
            dist /
            f"{self._package.name}-{normalize_version(self._package.version.text)}.tar.gz"  # noqa: E501
        )

        if not file.exists():
            raise RuntimeError(f'"{file.name}" does not exist.')

        data = self.post_data(file)
        data.update({":action": "submit", "protocol_version": "1"})

        data_to_send = self._prepare_data(data)
        encoder = MultipartEncoder(data_to_send)
        resp = session.post(
            url,
            data=encoder,
            allow_redirects=False,
            headers={"Content-Type": encoder.content_type},
            timeout=REQUESTS_TIMEOUT,
        )

        resp.raise_for_status()

        return resp
Esempio n. 7
0
    def data_handle(self, test):
        """请求数据处理"""
        # ------------如果用例没有设置url,method,headers则获取类属性中的------------------
        if not self.host:
            host = getattr(test, 'host', None) or ENV.get('host')
            if host:
                setattr(self, 'host', host)
            else:
                raise ValueError('用例参数host不能为空')
        if not self.interface:
            interface = getattr(test, 'interface',
                                None) or ENV.get('interface')
            if interface:
                setattr(self, 'interface', interface)
            else:
                raise ValueError('用例参数interface不能为空')

        self.url = self.host + self.interface

        if not getattr(self, 'method', None):
            method = getattr(test, 'method', None) or ENV.get('method')
            if method:
                setattr(self, 'method', method)
            else:
                raise ValueError('用例参数method不能为空')

        if not getattr(self, 'headers', None):
            headers = getattr(test, 'headers', None) or ENV.get('headers')
            if headers:
                setattr(self, 'headers', headers)

        # =======处理文件上传===============
        files = self.datas.get('files')
        if self.files:
            if isinstance(self.files, dict):
                file_data = self.files.items()
            else:
                file_data = self.files
            field = []
            for name, file_info in file_data:
                # 判断是否时文件上传
                if len(file_info) == 3 and os.path.isfile(file_info[1]):
                    field.append([
                        name,
                        (file_info[0], open(file_info[1], 'rb'), file_info[2])
                    ])
                else:
                    field.append([name, file_info])

            form_data = MultipartEncoder(fields=field)
            self.headers["Content-Type"] = form_data.content_type
            self.data = form_data
            self.files = None
        else:
            if self.headers.get("Content-Type"):
                del self.headers["Content-Type"]

        for k, v in self.__dict__.items():
            if k in self.__attrs:
                self.datas[k] = v
Esempio n. 8
0
    def _register(self, session, url):
        """
        Register a package to a repository.
        """
        dist = self._poetry.file.parent / 'dist'
        file = dist / '{}-{}.tar.gz'.format(self._package.name,
                                            self._package.version)

        if not file.exists():
            raise RuntimeError('"{0}" does not exist.'.format(file.name))

        data = self.post_data(file)
        data.update({
            ":action": "submit",
            "protocol_version": "1",
        })

        data_to_send = self._prepare_data(data)
        encoder = MultipartEncoder(data_to_send)
        resp = session.post(
            url,
            data=encoder,
            allow_redirects=False,
            headers={'Content-Type': encoder.content_type},
        )

        return resp
Esempio n. 9
0
    def _upload(self, package):
        data = package.metadata_dictionary()
        data.update({
            # action
            ":action": "file_upload",
            "protcol_version": "1",
        })

        data_to_send = self._convert_data_to_list_of_tuples(data)

        print("Uploading {0}".format(package.basefilename))

        with open(package.filename, "rb") as fp:
            data_to_send.append((
                "content",
                (package.basefilename, fp, "application/octet-stream"),
            ))
            encoder = MultipartEncoder(data_to_send)
            bar = ProgressBar(expected_size=encoder.len, filled_char='=')
            monitor = MultipartEncoderMonitor(
                encoder, lambda monitor: bar.show(monitor.bytes_read))

            resp = self.session.post(
                self.url,
                data=monitor,
                allow_redirects=False,
                headers={'Content-Type': monitor.content_type},
            )
            bar.done()

        return resp
Esempio n. 10
0
def getMultipartSpeechResponse(file):

    now = int(round(time.time() * 1000))
    uid = getUID("mac")
    verify = digest(appsecret + str(uid) + str(now))
    codec = file.split('.')[1]

    addr = server+'api/speech/chat?' + "appkey=" + appkey + "&timestamp=" + str(now) + "&uid=" + str(uid) + "&verify=" + verify + "&codec=" + codec + "&rate=8000" + "&nickname=" + nickname

    print(addr)

    files = open(file, 'rb')
    m = MultipartEncoder({'speech':(file,files)})
    headers = {"content-type":m.content_type}
    print(m.content_type)
    r = requests.post(url=addr, headers=headers, data = m)

    json_obj = r.json()

    print(json_obj)

    if 0 == json_obj["retcode"] :
        print("Success")
    else:
        print("Fail")
        res = json_obj["msg"]
        print(res)


    s = str(json_obj)
    s = s.replace(', ',', \n ')
    print(s)

    return s
Esempio n. 11
0
    def _upload(self, package):
        data = package.metadata_dictionary()
        data.update({
            # action
            ":action": "file_upload",
            "protocol_version": "1",
        })

        data_to_send = self._convert_data_to_list_of_tuples(data)

        print("Uploading {0}".format(package.basefilename))

        with open(package.filename, "rb") as fp:
            data_to_send.append((
                "content",
                (package.basefilename, fp, "application/octet-stream"),
            ))
            encoder = MultipartEncoder(data_to_send)
            with ProgressBar(total=encoder.len,
                             unit='B',
                             unit_scale=True,
                             unit_divisor=1024,
                             miniters=1,
                             file=sys.stdout) as bar:
                monitor = MultipartEncoderMonitor(
                    encoder, lambda monitor: bar.update_to(monitor.bytes_read))

                resp = self.session.post(
                    self.url,
                    data=monitor,
                    allow_redirects=False,
                    headers={'Content-Type': monitor.content_type},
                )

        return resp
Esempio n. 12
0
    def test_addShortBlog002(self):
        '''发布单张图片+文字的短微博'''
        #先上传图片
        # m={'pic': ('image.gif', open("../../file/image.gif", 'rb'), 'image/gif')}    #这样上传文件post中用files,但是文件太大,选择用数据流传送MultipartEncoder
        m = MultipartEncoder(fields={
            "pic": ("image.jpg", open("../../file/image.jpg", "rb"),
                    "image/jpeg")
        })
        self.headers['Content-Type'] = m.content_type
        imageRes = requests.post(userData['hostName'] +
                                 socialData['singleFileUpload_url'],
                                 data=m,
                                 headers=self.headers)
        # imageRes=newSocial.singleFileUpload(userData['hostName']+socialData['singleFileUpload_url'],datas = m,headers = self.headers)
        print(imageRes.text)
        #断言返回200,上传图片成功,返回code=0,上传图片成功
        self.assertEqual(imageRes.status_code, userData['status_code_200'])
        self.assertEqual(json.loads(imageRes.text)['code'], 0)
        #获取上传图片的url,用于发短微博
        imageUrl = json.loads(imageRes.text)['data']
        # print("",)
        imageUrl['Url'] = imageUrl['url']
        print("imageUrl", imageUrl)
        del imageUrl['url']
        imageUrl['ContentType'] = 'jpg'
        listImage = []
        listImage.append(imageUrl)
        print("imageUrl", imageUrl)
        print("listImage", listImage)

        blogParams = {
            "isLongBlog": False,  # boolean  true表示长微博,false表示短微博
            "body": "test",  # 短微博内容
            "files": listImage,  #files图片文件为数组
            "blogType": 0,  # 微博类型:0:普通微博;1:公告;2:品种资讯;3:交易动态
            "symbol": "",
            "postType":
            0  # 发布类型: 0-用户微博,1-推广,2-认证用户微博,3-名人大咖,4-分析师,5-媒体号,6-经纪商
        }

        self.headers['Content-Type'] = "application/json; charset=utf-8"
        addShortBlogRes = newSocial.addBlog(userData['hostName'] +
                                            socialData['addBlog_url'],
                                            headers=self.headers,
                                            datas=blogParams)
        #断言返回200,发微博成功,code=0发微博成功
        self.assertEqual(addShortBlogRes.status_code,
                         userData['status_code_200'])
        self.assertEqual(json.loads(addShortBlogRes.text)['code'], 0)
        #获取微博id,用于删除微博
        blogId = json.loads(addShortBlogRes.text)['data']['ObjectId']

        #检查我的微博列表

        #删除微博
        delBlogRes = newSocial.delBlogById(
            userData['hostName'] + socialData['delBlogById_url'] + str(blogId),
            headers=self.headers)
        self.assertEqual(delBlogRes.status_code, userData['status_code_200'])
        self.assertEqual(json.loads(delBlogRes.text)['code'], 0)
Esempio n. 13
0
    def upload(self, package):
        data = package.metadata_dictionary()
        data.update({
            # action
            ":action": "file_upload",
            "protcol_version": "1",
        })

        data_to_send = self._convert_data_to_list_of_tuples(data)

        print("Uploading {0}".format(package.basefilename))

        with open(package.filename, "rb") as fp:
            data_to_send.append((
                "content",
                (package.basefilename, fp, "application/octet-stream"),
            ))
            encoder = MultipartEncoder(data_to_send)

            resp = self.session.post(
                self.url,
                data=encoder,
                allow_redirects=False,
                headers={'Content-Type': encoder.content_type},
            )

        return resp
Esempio n. 14
0
    def _upload_file(
        self,
        session,
        url,
        file,
        dry_run=False
    ):  # type: (requests.Session, str, Path, Optional[bool]) -> requests.Response
        data = self.post_data(file)
        data.update({
            # action
            ":action": "file_upload",
            "protocol_version": "1",
        })

        data_to_send = self._prepare_data(data)

        with file.open("rb") as fp:
            data_to_send.append(
                ("content", (file.name, fp, "application/octet-stream")))
            encoder = MultipartEncoder(data_to_send)
            bar = self._io.progress_bar(encoder.len)
            bar.set_format(
                " - Uploading <c1>{0}</c1> <b>%percent%%</b>".format(
                    file.name))
            monitor = MultipartEncoderMonitor(
                encoder, lambda monitor: bar.set_progress(monitor.bytes_read))

            bar.start()

            resp = None

            try:
                if not dry_run:
                    resp = session.post(
                        url,
                        data=monitor,
                        allow_redirects=False,
                        headers={"Content-Type": monitor.content_type},
                    )
                if dry_run or resp.ok:
                    bar.set_format(
                        " - Uploading <c1>{0}</c1> <fg=green>%percent%%</>".
                        format(file.name))
                    bar.finish()
            except (requests.ConnectionError, requests.HTTPError) as e:
                if self._io.output.supports_ansi():
                    self._io.overwrite(
                        " - Uploading <c1>{0}</c1> <error>{1}</>".format(
                            file.name, "FAILED"))
                raise UploadError(e)
            finally:
                self._io.write_line("")

        return resp
Esempio n. 15
0
 def send_image_message(self, problem_id, file_path):
     data_send_image = MultipartEncoder(
         fields={
             'file': ('file.png', open(file_path, 'rb'), 'image/png'),
             'explanation_id': str(problem_id),
             'message': ''
         })
     self.headers.update({'Content-Type': data_send_image.content_type})
     requests.post(url=Config.base_url_asker +
                   '/askers/me/explanation_messages',
                   headers=self.headers,
                   data=data_send_image)
Esempio n. 16
0
 def xinzeng(self):
     a = self.denglu()
     url1 = "http://123.57.140.190/manage/add_cp.php?act=save_cp"
     data2 = MultipartEncoder({
         'pro_name': '拉链10',
         'cpbh': '465468985',
         'cptxm': '412164351',
         'cpms': '倚天屠龙记'
     })
     head2 = {'Content-Type': data2.content_type, 'Cookie': a}
     r2 = requests.post(url1, data=data2, headers=head2)
     print(r2.text)
 def test_name_bianji(self):
     url = "http://123.57.140.190/manage/edit_cp.php?act=save_edit_pro"
     data5 = MultipartEncoder({
         'id': '395',
         'pro_name': '飞来峰',
         'cpbh': '888666',
         'cptxm': '666888',
         'cpms': '此山非彼山'
     })
     headers5 = {'Content-Type': data5.content_type, 'Cookie': self.setUp()}
     r = requests.post(url, data=data5, headers=headers5)
     print(r.text)
 def test_zdd(self):
     a = self.setUp()
     url1 = "http://123.57.140.190/manage/add_cp.php?act=save_cp"
     data = MultipartEncoder({
         'pro_name': '拉链8',
         'cpbh': '4654689',
         'cptxm': '4164351',
         'cpms': '降记号三年级'
     })
     headers1 = {"Content-Type": data.content_type, "Cookie": a}
     r1 = requests.post(url=url1, data=data, headers=headers1)
     print(r1.text)
Esempio n. 19
0
 def test_add(self):
     a = self.setUpClass()
     url1 = "http://123.57.140.190/manage/add_cp.php?act=save_cp"
     data = MultipartEncoder({
         "pro_name": "大放厥词",
         "cpbh": "154152",
         "cptxm": "tfgew15465415",
         "cpms": "车号虐范围"
     })
     headers1 = {"Content-Type": data.content_type, "Cookie": a}
     r1 = requests.post(url=url1, data=data, headers=headers1)
     print(r1.text)
Esempio n. 20
0
def upload_img(img_data):
    """upload the img given image data, return the complete url"""

    data = MultipartEncoder({'img': ('abc.jpg', img_data)})
    headers = {
        "Content-Type": data.content_type,
        "Cookie": "PHPSESSID=2oek5ov42u3vj8lnsblkn6srj2"
    }
    response = requests.post(url=UPLOAD_IMG_API, data=data, headers=headers)
    res = json.loads(response.text.encode('utf-8').decode('utf-8-sig'))
    if res["status_code"] == "0":
        print("Cannot recognize the image data!")
        exit(0)
    return DOMAIN + res["link"]
class TestMultipartEncoder(unittest.TestCase):
    def setUp(self):
        self.parts = [('field', 'value'), ('other_field', 'other_value')]
        self.boundary = 'this-is-a-boundary'
        self.instance = MultipartEncoder(self.parts, boundary=self.boundary)

    def test_to_string(self):
        assert self.instance.to_string() == (
            '--this-is-a-boundary\r\n'
            'Content-Disposition: form-data; name="field"\r\n\r\n'
            'value\r\n'
            '--this-is-a-boundary\r\n'
            'Content-Disposition: form-data; name="other_field"\r\n\r\n'
            'other_value\r\n'
            '--this-is-a-boundary--\r\n'
        )

    def test_content_type(self):
        expected = 'multipart/form-data; boundary=this-is-a-boundary'
        assert self.instance.content_type == expected

    def test_encodes_data_the_same(self):
        assert self.instance.to_string() == self.instance.read()
Esempio n. 22
0
    def _upload_file(self, session, url, file):
        data = self.post_data(file)
        data.update(
            {
                # action
                ":action": "file_upload",
                "protocol_version": "1",
            }
        )

        data_to_send = self._prepare_data(data)

        with file.open("rb") as fp:
            data_to_send.append(
                ("content", (file.name, fp, "application/octet-stream"))
            )
            encoder = MultipartEncoder(data_to_send)
            bar = self._io.progress_bar(encoder.len)
            bar.set_format(
                " - Uploading <info>{0}</> <comment>%percent%%</>".format(file.name)
            )
            monitor = MultipartEncoderMonitor(
                encoder, lambda monitor: bar.set_progress(monitor.bytes_read)
            )

            bar.start()

            resp = session.post(
                url,
                data=monitor,
                allow_redirects=False,
                headers={"Content-Type": monitor.content_type},
            )

            if resp.ok:
                bar.finish()

                self._io.write_line("")
            else:
                if self._io.output.supports_ansi():
                    self._io.overwrite(
                        " - Uploading <info>{0}</> <error>{1}%</>".format(
                            file.name, int(math.floor(bar._percent * 100))
                        )
                    )

                self._io.write_line("")

        return resp
Esempio n. 23
0
def req3():
    headers = {
        "X-CSRF-TOKEN":
        "fRQiJBkLt9Wri0LKmyp7hqaQB8XqhOzkmL71lBeL",
        "User-Agent":
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
        "Content-Type":
        "application/x-www-form-urlencoded; charset=UTF-8",
        "X-Requested-With":
        "XMLHttpRequest",
        "Accept-Encoding":
        "gzip, deflate",
        "Accept-Language":
        "zh-CN,zh;q=0.8,en;q=0.6",
        "Cookie":
        "XSRF-TOKEN=eyJpdiI6IlpZYTVsUlVTbE9Bc21IXC9wNHhFQWFRPT0iLCJ2YWx1ZSI6ImRpOUkrQUNiSW50aTR5WVpIQk5iUW1OUnZlbmkyZHZCTVVcL2VveTZZWlQzVFV6RjhTVUE3czRyYkhwTlI0Z1hTakNKdDJQT0hKS1BueTNJZk15RmxJZz09IiwibWFjIjoiMzFjZjdiZWMyNTBiMWJkNDg3YzhjZDlmYjFiODQ0MzdkOWY2YjQyZjg2OWQ5MjIzZThiNGYwYzg4OTRhNjBlNCJ9; laravel_session=b21Rz9SsdQkCUqANwYpZejKhQ5HbU073uTIhzfvR"
    }
    m = MultipartEncoder(fields=[
        ('exampaper_id', '1441'),
        ("excel",
         ('1.xlsx',
          open("D:\workspace\project\pyqt\\biguo2\wantiku\\1.xlsx", 'rb'),
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
    ],
                         boundary='----WebKitFormBoundaryetr1Sq6VzYVCK9H5')
    headers1 = {
        #"X-CSRF-TOKEN": "vZjHj7mzQ2HSCZT43OowXBp6HaQodNmg6khkifjF",
        "User-Agent":
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
        "Content-Type":
        "multipart/form-data;charset=UTF-8;boundary=----WebKitFormBoundaryetr1Sq6VzYVCK9H5",
        #"boundary":"----WebKitFormBoundaryetr1Sq6VzYVCK9H5",
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6",
        #"Cookie":"XSRF-TOKEN=eyJpdiI6IndDbEVsem1ZeGgzZm53VE5qbUxydkE9PSIsInZhbHVlIjoiV05ta05KZDViN2hmTXpyZ1R0NzJBVWowK2ZLblk0ellibWhxTXVabTYzSTRXQmY5dGgreGdlNmZsNm04UlRTNEFSWGF6SVZ1VFNTdHVBXC9EUVhNa2x3PT0iLCJtYWMiOiI2YmM1YzkwZTE2YzA3NDlmMWQwYTM5MGJjZGQ0NGJkMzI4MTViNGZkNDNiMjFhNGMzZjFjMWVkNmJhOTQ4Zjc1In0%3D;laravel_session=fH8AD4X67jQM2XFMSEKzvoFgLez16hPd9geX4s11"
    }
    reqs = requests.Session()
    url = 'http://bg.dengming.pro/admin/exam_real'
    with open("D:\workspace\project\pyqt\\biguo2\wantiku\\1.xlsx", 'rb') as f:
        con = f.read()
    #m = {'exampaper_id':'1441','excel':("1.xlxs",con)}
    #res_major = reqs.get('http://bg.dengming.pro/api/test',files=file,headers=headers1)
    res = reqs.post('http://bg.dengming.pro/api/test',
                    data=m,
                    headers=headers1)
    print(res.text)
Esempio n. 24
0
def req1():
    headers = {
        "X-CSRF-TOKEN":
        "fRQiJBkLt9Wri0LKmyp7hqaQB8XqhOzkmL71lBeL",
        "User-Agent":
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
        "Content-Type":
        "application/x-www-form-urlencoded; charset=UTF-8",
        "X-Requested-With":
        "XMLHttpRequest",
        "Accept-Encoding":
        "gzip, deflate",
        "Accept-Language":
        "zh-CN,zh;q=0.8,en;q=0.6",
        "Cookie":
        "XSRF-TOKEN=eyJpdiI6IlpZYTVsUlVTbE9Bc21IXC9wNHhFQWFRPT0iLCJ2YWx1ZSI6ImRpOUkrQUNiSW50aTR5WVpIQk5iUW1OUnZlbmkyZHZCTVVcL2VveTZZWlQzVFV6RjhTVUE3czRyYkhwTlI0Z1hTakNKdDJQT0hKS1BueTNJZk15RmxJZz09IiwibWFjIjoiMzFjZjdiZWMyNTBiMWJkNDg3YzhjZDlmYjFiODQ0MzdkOWY2YjQyZjg2OWQ5MjIzZThiNGYwYzg4OTRhNjBlNCJ9; laravel_session=b21Rz9SsdQkCUqANwYpZejKhQ5HbU073uTIhzfvR"
    }

    url = "http://www.biguotk.com/admin/login/20186663312"
    res = requests.get(url, headers=headers)
    print(res.text)
    m = MultipartEncoder(fields=[('_token',
                                  'fRQiJBkLt9Wri0LKmyp7hqaQB8XqhOzkmL71lBeL'),
                                 ("exampaper_id", '1443')],
                         boundary='----WebKitFormBoundaryn6sq91D3XNAYKd9D')
    files = [
        ('excel',
         ('2014年10月《中国近现代史纲要》真题.xlsx', 'xx',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
    ]
    #with open(r"D:\workspace\project\pyqt\biguo2\wantiku\2014年10月《中国近现代史纲要》真题.xlsx",'rb') as f:
    #    con = f.read()

    #data = {'------WebKitFormBoundarysjHbIbuyVHS6H0x1 Content-Disposition: form-data; name="_token"':'fRQiJBkLt9Wri0LKmyp7hqaQB8XqhOzkmL71lBeL',
    #        '------WebKitFormBoundarysjHbIbuyVHS6H0x1 Content-Disposition: form-data; name="exampaper_id"':'1442',
    #        '------WebKitFormBoundarysjHbIbuyVHS6H0x1 Content-Disposition: form-data; name="excel"; filename="2014年10月《中国近现代史纲要》真题.xlsx" Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet	':con
    #        }

    res2 = requests.post(
        'http://www.biguotk.com/admin/exam_real',
        data=m,
        headers=headers,
    )
    print(res2.text)
Esempio n. 25
0
	def videoUpload(self):
		# get the video path
		session_id = self.bind_bank()
		path = os.path.join(VIDEO_PATH, "test_video.mp4")
		multipart_encoder = MultipartEncoder(
			fields={
				"Filename": "test_video.mp4",
				# "code": choice(list(upload_file_code.values())),
				"ASPSESSIONID": session_id,
				"Filedata": ("test_vedio.mp4", open(path, 'rb'), 'application/octet-stream')
			},
			boundary="------------------------" + str(random.randint(1e28, 1e29 - 1)),
			encoding='utf-8'
		)
		self.s.headers["Content-Type"] = multipart_encoder.content_type
		r = self.s.post(BASE_URL + "/Video/VideoUploadService", data=multipart_encoder, )
		assert "ok" in r.text
		self.dump_customerinfo()
		return True
Esempio n. 26
0
    def send_excel_file_message(self, problem_id, file_path):
        data_send_excel_file = MultipartEncoder(
            fields={
                'file':
                ('file.xlsx', open(file_path, 'rb'),
                 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                 ),
                'explanation_id':
                str(problem_id),
                'message':
                '',
            })
        self.headers.update(
            {'Content-Type': data_send_excel_file.content_type})

        requests.post(Config.base_url_asker +
                      '/askers/me/explanation_messages',
                      headers=self.headers,
                      data=data_send_excel_file)
Esempio n. 27
0
    def _upload_file(self, session, url, file):
        data = self.post_data(file)
        data.update({
            # action
            ":action": "file_upload",
            "protocol_version": "1",
        })

        data_to_send = self._convert_data_to_list_of_tuples(data)

        with file.open('rb') as fp:
            data_to_send.append((
                "content",
                (file.name, fp, "application/octet-stream"),
            ))
            encoder = MultipartEncoder(data_to_send)
            bar = self._io.create_progress_bar(encoder.len)
            bar.set_format(
                " - Uploading <info>{0}</> <comment>%percent%%</>".format(
                    file.name
                )
            )
            monitor = MultipartEncoderMonitor(
                encoder, lambda monitor: bar.set_progress(monitor.bytes_read)
            )

            bar.start()

            resp = session.post(
                url,
                data=monitor,
                allow_redirects=False,
                headers={'Content-Type': monitor.content_type}
            )

            if resp.ok:
                bar.finish()

                self._io.writeln('')
            else:
                self._io.overwrite('')

        return resp
Esempio n. 28
0
    def upload_tpl_file(self, file_name):
        """
        上传模版文件
        :param file_name:
        :return:
        """
        cmd = 'uploadFile'

        m_data = MultipartEncoder(
            fields={
                'cmd': cmd,
                'value': self.value_wrapper('74ce89b4a5f17575604e91a906fb0e5e', ""),
                'file': (file_name, open(file_name, 'rb'), 'application/octet-stream')
            },
        )
        headers = {
            'Content-Type': m_data.content_type,
        }
        r = requests.post(self._url, data=m_data, headers=headers)
        print(r.text)
Esempio n. 29
0
    def register(self, package):
        data = package.metadata_dictionary()
        data.update({
            ":action": "submit",
            "protocol_version": "1",
        })

        print("Registering {}".format(package.basefilename))

        data_to_send = self._convert_data_to_list_of_tuples(data)
        encoder = MultipartEncoder(data_to_send)
        resp = self.session.post(
            self.url,
            data=encoder,
            allow_redirects=False,
            headers={'Content-Type': encoder.content_type},
        )
        # Bug 28. Try to silence a ResourceWarning by releasing the socket.
        resp.close()
        return resp
 def upload_files(self):
     """
     # >>> url = 'http://httpbin.org/post'
     # >>> multiple_files = [
     # ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
     # ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]
     # >>> r = requests.post(url, files=multiple_files)
     :return:
     """
     """
     1)找出所有需要上传的资料项
     2)循环上传所有的资料
     """
     url = BASE_URL + "/Service/AddFile"
     data = {}
     # get the file of path
     files = os.listdir(PICTURE_PATH)
     filename = choice(files)
     file_path = os.path.join(PICTURE_PATH, filename)
     ret = self.UploadDialog()
     for code in list(ret["items"].values()):
         multipart_encoder = MultipartEncoder(
             fields={
                 "Filename": filename,
                 # "code": choice(list(upload_file_code.values())),
                 "code": code,
                 "ASPSESSIONID": ret["session"],
                 "Filedata": (filename, open(file_path, 'rb'), 'application/octet-stream')
             },
             boundary="------------------------" + str(random.randint(1e28, 1e29 - 1)),
             encoding='utf-8'
         )
         # the content type is:multipart/form-data; boundary={0}
         self.s.headers["Content-Type"] = multipart_encoder.content_type
         r = self.s.post(url, data=multipart_encoder, )
         results = r.json()
         if results["ResponseDetails"] == "ok":
             continue
         else:
             raise AssertionError("上传图片出现异常")
     return ret
Esempio n. 31
0
 def sendfile(self, filenameex, examid, filepath):  # 试卷上传功能
     m = MultipartEncoder(fields=[
         ("_token", csrfli[0]), ('exampaper_id', str(examid)),
         ("excel",
          ("1.xlsx", open(filepath, 'rb'),
           'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
           ))
     ],
                          boundary=boundary)
     hd = headers2.copy()
     hd["Content-Type"] = "multipart/form-data;charset=UTF-8;" + "boundary={}".format(
         boundary)
     try:
         res = requests.post("http://www.biguotk.com/admin/exam_real",
                             data=m,
                             headers=hd,
                             verify=False)
         print("返回内容:", "返回状态:", res.status_code)
         return res.content, res.status_code
     except Exception as e:
         print("网络异常,重新上传。。。")
         self.sendfile(filenameex, examid, filepath)
Esempio n. 32
0
    def _upload(self, package):
        data = package.metadata_dictionary()
        data.update({
            # action
            ":action": "file_upload",
            "protocol_version": "1",
        })

        data_to_send = self._convert_data_to_list_of_tuples(data)

        with open(package.filename, "rb") as fp:
            data_to_send.append((
                "content",
                (package.basefilename, fp, "application/octet-stream"),
            ))
            encoder = MultipartEncoder(data_to_send)
            bar = self._output.create_progress_bar(encoder.len)
            bar.set_format(
                " - Uploading <info>{0}</> <comment>%percent%%</>".format(
                    package.basefilename))
            monitor = MultipartEncoderMonitor(
                encoder, lambda monitor: bar.set_progress(monitor.bytes_read /
                                                          encoder.len))

            resp = self.session.post(
                self.url,
                data=monitor,
                allow_redirects=False,
                headers={'Content-Type': monitor.content_type},
            )

            if resp.ok:
                bar.finish()

                self._output.writeln('')
            else:
                self._output.overwrite('')

        return resp
Esempio n. 33
0
 def setUp(self):
     self.parts = [('field', 'value'), ('other_field', 'other_value')]
     self.boundary = 'this-is-a-boundary'
     self.instance = MultipartEncoder(self.parts, boundary=self.boundary)
Esempio n. 34
0
 def test_reads_open_file_objects_with_a_specified_filename(self):
     with open('setup.py', 'rb') as fd:
         m = MultipartEncoder(
             [('field', 'foo'), ('file', ('filename', fd, 'text/plain'))]
             )
         assert m.read() is not None
Esempio n. 35
0
 def test_reads_open_file_objects(self):
     with open('setup.py', 'rb') as fd:
         m = MultipartEncoder([('field', 'foo'), ('file', fd)])
         assert m.read() is not None
Esempio n. 36
0
def get_expertinfo(unit, author):
    # 总文献量
    literature_num_post = MultipartEncoder({
        'selectType': 'totalLiterature',
        'unitName': unit,
        'scholarName': author
    })
    literature_num = requests.post(
        'http://miner.wanfangdata.com.cn/scholarsBootPage/getRelevantQuota.do',
        data=literature_num_post,
        headers={
            'Content-Type': literature_num_post.content_type,
            "User-Agent": UserAgent().random
        })
    literature_num = json.loads(literature_num.text)
    # 核心发文量
    core_num_post = MultipartEncoder({
        'selectType': 'coreNum',
        'unitName': unit,
        'scholarName': author
    })
    core_num = requests.post(
        'http://miner.wanfangdata.com.cn/scholarsBootPage/getRelevantQuota.do',
        data=core_num_post,
        headers={
            'Content-Type': core_num_post.content_type,
            "User-Agent": UserAgent().random
        })
    core_num = json.loads(core_num.text)
    # 总被引量
    quoted_num_post = MultipartEncoder({
        'selectType': 'sumCiteNum',
        'unitName': unit,
        'scholarName': author
    })
    quoted_num = requests.post(
        'http://miner.wanfangdata.com.cn/scholarsBootPage/getRelevantQuota.do',
        data=quoted_num_post,
        headers={
            'Content-Type': quoted_num_post.content_type,
            "User-Agent": UserAgent().random
        })
    quoted_num = json.loads(quoted_num.text)

    # 篇均被引量
    avg_quoted_post = MultipartEncoder({
        'selectType': 'eachCiteNum',
        'unitName': unit,
        'scholarName': author
    })
    avg_quoted = requests.post(
        'http://miner.wanfangdata.com.cn/scholarsBootPage/getRelevantQuota.do',
        data=avg_quoted_post,
        headers={
            'Content-Type': avg_quoted_post.content_type,
            "User-Agent": UserAgent().random
        })
    avg_quoted = json.loads(avg_quoted.text)

    # 研究兴趣
    research_interest_post = MultipartEncoder({
        'number': '30',
        'unitName': unit,
        'scholarName': author
    })
    research_interest = requests.post(
        'http://miner.wanfangdata.com.cn/scholarsBootPage/researchInterest.do',
        data=research_interest_post,
        headers={
            'Content-Type': research_interest_post.content_type,
            "User-Agent": UserAgent().random
        })
    research_interest = json.loads(research_interest.text)

    # 发文趋势
    line_data_post = MultipartEncoder({
        'unitName': unit,
        'scholarName': author
    })
    line_data = requests.post(
        'http://miner.wanfangdata.com.cn/scholarsBootPage/lineData.do',
        data=line_data_post,
        headers={
            'Content-Type': line_data_post.content_type,
            "User-Agent": UserAgent().random
        })
    line_data = json.loads(line_data.text)

    # 相关学者
    related_scholars_post = MultipartEncoder({
        'unitName': unit,
        'scholarName': author
    })
    related_scholars = requests.post(
        'http://miner.wanfangdata.com.cn/scholarsBootPage/relatedScholarsData.do',
        data=related_scholars_post,
        headers={
            'Content-Type': related_scholars_post.content_type,
            "User-Agent": UserAgent().random
        })
    related_scholars = json.loads(related_scholars.text)

    # 合作学者
    cooperation_scholar_post = MultipartEncoder({
        'unitName': unit,
        'scholarName': author
    })
    cooperation_scholar = requests.post(
        'http://miner.wanfangdata.com.cn/scholarsBootPage/cooperationScholarData.do',
        data=cooperation_scholar_post,
        headers={
            'Content-Type': cooperation_scholar_post.content_type,
            "User-Agent": UserAgent().random
        })
    cooperation_scholar = json.loads(cooperation_scholar.text)

    return JsonResponse(
        {'literature_num': literature_num, 'core_num': core_num, 'quoted_num': quoted_num, 'avg_quoted': avg_quoted, \
         'research_interest': research_interest, 'line_data': line_data, 'related_scholars': related_scholars,
         'cooperation_scholar': cooperation_scholar})
Esempio n. 37
0
    def _upload_file(
        self,
        session: requests.Session,
        url: str,
        file: Path,
        dry_run: Optional[bool] = False,
    ) -> requests.Response:
        from cleo.ui.progress_bar import ProgressBar

        data = self.post_data(file)
        data.update({
            # action
            ":action": "file_upload",
            "protocol_version": "1",
        })

        data_to_send = self._prepare_data(data)

        with file.open("rb") as fp:
            data_to_send.append(
                ("content", (file.name, fp, "application/octet-stream")))
            encoder = MultipartEncoder(data_to_send)
            bar = ProgressBar(self._io, max=encoder.len)
            bar.set_format(
                f" - Uploading <c1>{file.name}</c1> <b>%percent%%</b>")
            monitor = MultipartEncoderMonitor(
                encoder, lambda monitor: bar.set_progress(monitor.bytes_read))

            bar.start()

            resp = None

            try:
                if not dry_run:
                    resp = session.post(
                        url,
                        data=monitor,
                        allow_redirects=False,
                        headers={"Content-Type": monitor.content_type},
                    )
                if dry_run or 200 <= resp.status_code < 300:
                    bar.set_format(
                        f" - Uploading <c1>{file.name}</c1> <fg=green>%percent%%</>"
                    )
                    bar.finish()
                elif resp.status_code == 301:
                    if self._io.output.is_decorated():
                        self._io.overwrite(
                            f" - Uploading <c1>{file.name}</c1> <error>FAILED</>"
                        )
                    raise UploadError("Redirects are not supported. "
                                      "Is the URL missing a trailing slash?")
            except (requests.ConnectionError, requests.HTTPError) as e:
                if self._io.output.is_decorated():
                    self._io.overwrite(
                        f" - Uploading <c1>{file.name}</c1> <error>FAILED</>")
                raise UploadError(e)
            finally:
                self._io.write_line("")

        return resp