當前位置: 首頁>>代碼示例>>Python>>正文


Python requests_toolbelt.MultipartEncoder方法代碼示例

本文整理匯總了Python中requests_toolbelt.MultipartEncoder方法的典型用法代碼示例。如果您正苦於以下問題:Python requests_toolbelt.MultipartEncoder方法的具體用法?Python requests_toolbelt.MultipartEncoder怎麽用?Python requests_toolbelt.MultipartEncoder使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在requests_toolbelt的用法示例。


在下文中一共展示了requests_toolbelt.MultipartEncoder方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: uploadPhoto

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def uploadPhoto(self, photo, caption=None, upload_id=None, is_sidecar=None):
        if upload_id is None:
            upload_id = str(int(time.time() * 1000))
        data = {'upload_id': upload_id,
                '_uuid': self.uuid,
                '_csrftoken': self.token,
                'image_compression': '{"lib_name":"jt","lib_version":"1.3.0","quality":"87"}',
                'photo': ('pending_media_%s.jpg' % upload_id, open(photo, 'rb'), 'application/octet-stream', {'Content-Transfer-Encoding': 'binary'})}
        if is_sidecar:
            data['is_sidecar'] = '1'
        m = MultipartEncoder(data, boundary=self.uuid)
        self.s.headers.update({'X-IG-Capabilities': '3Q4=',
                               'X-IG-Connection-Type': 'WIFI',
                               'Cookie2': '$Version=1',
                               'Accept-Language': 'en-US',
                               'Accept-Encoding': 'gzip, deflate',
                               'Content-type': m.content_type,
                               'Connection': 'close',
                               'User-Agent': self.USER_AGENT})
        response = self.s.post(self.API_URL + "upload/photo/", data=m.to_string())
        if response.status_code == 200:
            if self.configure(upload_id, photo, caption):
                self.expose()
        return False 
開發者ID:Datalux,項目名稱:Osintgram,代碼行數:26,代碼來源:InstagramAPI.py

示例2: uploadImageFile

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def uploadImageFile(self, print_id, imageBuf):
		try:
			m = MultipartEncoder(fields=[('file',('snapshot.jpg', imageBuf))])
			r = requests.post(
				"%s/prints/%s/image" % (self.apiHost, print_id),
				data= m,
				headers= {'Content-Type': m.content_type},
				auth= self.hmacAuth
			)
			m = None #Free the memory?
			status_code = r.status_code
		except:
			status_code = 500

		if status_code == 201:
			data = r.json()
			return data

		else:
			return None 
開發者ID:AstroPrint,項目名稱:AstroBox,代碼行數:22,代碼來源:cloud.py

示例3: upload

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def upload(self, url, filepath, content_type, **kwargs):
        counter = 0
        while True:
            counter += 1
            try:
                abs_fp = os.path.realpath(os.path.expanduser(filepath))
                m = MultipartEncoder(fields={'file': (os.path.basename(filepath), open(abs_fp, 'rb'), content_type)})
                r = super(APISession, self).post(url, data=m, headers={'Content-Type': m.content_type}, timeout=self.timeout, **kwargs)
                r.raise_for_status()
                time.sleep(self.request_interval)
            except (HTTPError, ConnectionError, ReadTimeout) as e:
                if self.__recoverable(e, url, 'GET', counter):
                    continue
                else:
                    self.logger.debug(f'Unrecoverable error: {e}')
                    raise e
            return r 
開發者ID:OasisLMF,項目名稱:OasisLMF,代碼行數:19,代碼來源:session.py

示例4: upload_record_without_photo

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def upload_record_without_photo(self, record):
        """ 不帶自拍,上傳跑步記錄
        """
        m = MultipartEncoder(
                fields={
                    'userId': str(self.studentID),
                    'duration': str(record.duration),
                    'date': str(record.date),                        # 後端好像會根據日期來判斷是否重複發包
                    'detail': json.dumps(record.detail),             # 路徑似乎並不會用來查重
                    'misc': json.dumps({"agent": "Android v1.2+"}),
                    'step': str(record.step),
                }
            )
        # self.logger.debug(record.__dict__)
        # self.logger.debug(m.to_string()) # 注意! m.to_string() 隻能輸出一次,第二次將會輸出空字節,因此不要用這個方法來調試!
        # return
        respJson = self.post("record/{userId}".format(userId=self.studentID),
            data = m.to_string(), headers = {
                'Content-Type': m.content_type
            }, auth=self.auth)

        if not respJson["data"]["verified"]:
            raise PKURunnerNotVerifiedError("record is not verified, check your running params setting.") 
開發者ID:fieryd,項目名稱:PKURunningHelper,代碼行數:25,代碼來源:client.py

示例5: upload_file

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def upload_file(self, model, filename, query_parameters=None, uri=None):
        if not uri:
            uri = model.uri()

        # urllib3 still uses RFC2231, not compliant with our server
        # https://github.com/shazow/urllib3/issues/303
        # https://github.com/shazow/urllib3/pull/856
        filename_ascii = bytes(filename, 'utf-8').decode('ascii', 'ignore')
        m = MultipartEncoder(fields={"files[]": (filename_ascii, open(filename, 'rb'))})
        response = self._session.post("{}{}".format(self._base_url(), uri),
                                      auth=CytomineAuth(
                                          self._public_key, self._private_key,
                                          self._base_url(), self._base_path),
                                      headers=self._headers(content_type=m.content_type),
                                      params=query_parameters,
                                      data=m)

        if response.status_code == requests.codes.ok:
            model = model.populate(response.json())  # [model.callback_identifier.lower()])
            self._logger.info("File uploaded successfully to {}".format(uri))
        else:
            model = False
            self._logger.error("Error during file uploading to {}".format(uri))

        return model 
開發者ID:cytomine,項目名稱:Cytomine-python-client,代碼行數:27,代碼來源:cytomine.py

示例6: make_api_request

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def make_api_request(method, files=None, **kwargs):
    from requests_toolbelt import MultipartEncoder
    if files is None:
        files = {}
    url = "http://" + str(host) + ":" + str(connection_port) + "/" + method

    kwargs = {k: v for k, v in kwargs.items() if v is not None}

    if len(files) > 0:
        fields = {}
        fields.update(kwargs)
        fields.update(files)
        m = MultipartEncoder(fields=fields)
        response = requests.post(url, data=m, headers={'Content-Type': m.content_type})
    else:
        response = requests.post(url, data=kwargs)
    if response.status_code != 200:
        return {
            'error': response.status_code,
            'message': response.text
        }
    else:
        return response.json() 
開發者ID:halilozercan,項目名稱:halocoin,代碼行數:25,代碼來源:cli.py

示例7: login

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def login(self, username, password):
        url = "https://leetcode.com/accounts/login"
        
        params_data = {
            'csrfmiddlewaretoken': self.csrftoken,
            'login': username,
            'password':password,
            'next': 'problems'
        }
        headers = {'User-Agent': user_agent, 'Connection': 'keep-alive', 'Referer': 'https://leetcode.com/accounts/login/',
        "origin": "https://leetcode.com"}
        m = MultipartEncoder(params_data)   

        headers['Content-Type'] = m.content_type
        self.session.post(url, headers = headers, data = m, timeout = 10, allow_redirects = False)
        self.is_login = self.session.cookies.get('LEETCODE_SESSION') != None
        return self.is_login 
開發者ID:gcyml,項目名稱:leetcode-crawler,代碼行數:19,代碼來源:leetcode-crawler.py

示例8: upload_child_file

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def upload_child_file(self, name, local_path, existing_node=None):
        logging.info("Uploading %s to %s", local_path, self.node["name"])
        mime_type = _get_mimetype(name)
        m = requests_toolbelt.MultipartEncoder([
            ("metadata", json.dumps({
                "name": name,
                "kind": "FILE",
                "parents": [self.node["id"]],
            })),
            ("content", (name, open(local_path, "rb"), mime_type))])
        if existing_node:
            """
            # TODO: this is under-documented and currently 500s on Amazon's side
            node = CloudNode(DriveSink.instance().request_content(
                "%%snodes/%s/content" % existing_node.node["id"],
                method="put", data=m, headers={"Content-Type": m.content_type}))
            """
            old_info = DriveSink.instance().request_metadata(
                "%%s/trash/%s" % existing_node.node["id"], method="put")
        ds = DriveSink.instance()
        resp = ds.request_content("%snodes", method="post", data=m,
            headers={"Content-Type": m.content_type})
        if resp != None:
            node = CloudNode(resp)
            self._children[name] = node 
開發者ID:caseymrm,項目名稱:drivesink,代碼行數:27,代碼來源:drivesink.py

示例9: main

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def main():
    args = parse_args()

    with open(args.filename, 'rb') as file_:
        content_type = mimetypes.guess_type(args.filename)[0]

        fields = {
            'name': 'hello world',
            'lines': 'first line\r\n\r\nsecond line',
            'file': (args.filename, file_, content_type),
        }

        body = MultipartEncoder(fields=fields).to_string()

        if args.decode:
            print(body.decode('utf-8'))
        else:
            print(body) 
開發者ID:siddhantgoel,項目名稱:streaming-form-data,代碼行數:20,代碼來源:multipart_encoder.py

示例10: test_case_insensitive_content_type

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def test_case_insensitive_content_type():
    content_type_header = 'Content-Type'

    for header_key in (
        content_type_header,
        content_type_header.lower(),
        content_type_header.upper(),
        'cOnTeNt-tYPe',
    ):
        target = ValueTarget()

        encoder = MultipartEncoder(fields={'value': 'hello world'})

        parser = StreamingFormDataParser(
            headers={header_key: encoder.content_type}
        )
        parser.register('value', target)

        parser.data_received(encoder.to_string())

        assert target.value == b'hello world' 
開發者ID:siddhantgoel,項目名稱:streaming-form-data,代碼行數:23,代碼來源:test_parser.py

示例11: test_basic_multiple

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def test_basic_multiple():
    first = ValueTarget()
    second = ValueTarget()
    third = ValueTarget()

    encoder = MultipartEncoder(
        fields={'first': 'foo', 'second': 'bar', 'third': 'baz'}
    )

    parser = StreamingFormDataParser(
        headers={'Content-Type': encoder.content_type}
    )

    parser.register('first', first)
    parser.register('second', second)
    parser.register('third', third)

    parser.data_received(encoder.to_string())

    assert first.value == b'foo'
    assert second.value == b'bar'
    assert third.value == b'baz' 
開發者ID:siddhantgoel,項目名稱:streaming-form-data,代碼行數:24,代碼來源:test_parser.py

示例12: test_chunked_single

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def test_chunked_single():
    expected_value = 'hello world'

    target = ValueTarget()

    encoder = MultipartEncoder(fields={'value': expected_value})

    body = encoder.to_string()

    parser = StreamingFormDataParser(
        headers={'Content-Type': encoder.content_type}
    )
    parser.register('value', target)

    index = body.index(b'world')

    parser.data_received(body[:index])
    parser.data_received(body[index:])

    assert target.value == expected_value.encode('utf-8') 
開發者ID:siddhantgoel,項目名稱:streaming-form-data,代碼行數:22,代碼來源:test_parser.py

示例13: create

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def create(
            cls, client, image_data, metadata=None, public=False, wait=True):
        """Create an image.

        If metadata is provided, a multipart form data request is formed to
        push metadata and image together in a single request. The metadata must
        be a tar achive.

        `wait` parameter is now ignored, as the image fingerprint cannot be
        reliably determined consistently until after the image is indexed.
        """

        if wait is False:  # pragma: no cover
            warnings.warn(
                'Image.create wait parameter ignored and will be removed in '
                '2.3', DeprecationWarning)

        headers = {}
        if public:
            headers['X-LXD-Public'] = '1'

        if metadata is not None:
            # Image uploaded as chunked/stream (metadata, rootfs)
            # multipart message.
            # Order of parts is important metadata should be passed first
            files = collections.OrderedDict(
                metadata=('metadata', metadata, 'application/octet-stream'),
                rootfs=('rootfs', image_data, 'application/octet-stream'))
            data = MultipartEncoder(files)
            headers.update({"Content-Type": data.content_type})
        else:
            data = image_data

        response = client.api.images.post(data=data, headers=headers)
        operation = client.operations.wait_for_operation(
            response.json()['operation'])
        return cls(client, fingerprint=operation.metadata['fingerprint']) 
開發者ID:lxc,項目名稱:pylxd,代碼行數:39,代碼來源:image.py

示例14: upload

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def upload(args, upload_url, file_info):
    '''
    The long-running upload request. This runs in a separate process for
    concurrency reasons.
    '''
    with open(file_info[0], 'rb') as image_file:
        files = [
            ('file', (file_info[1], image_file, 'application/x-tar')),
        ]
        transloadit_auth_info = {
            'auth': {
                'key': args.transloadit_account_id,
            },
            'template_id': args.transloadit_template,
        }
        params = json.dumps(transloadit_auth_info)
        logging.debug('About to start the upload.')
        m = requests_toolbelt.MultipartEncoder({
            'params': params,
            'file': files[0][1],
        })

        response = requests.post(upload_url,
                                 data=m,
                                 headers={'Content-Type': m.content_type})
        logging.debug('Upload complete... code: %s %s', response.status_code,
                      response.text) 
開發者ID:coursera,項目名稱:courseraprogramming,代碼行數:29,代碼來源:upload.py

示例15: _multipart_post

# 需要導入模塊: import requests_toolbelt [as 別名]
# 或者: from requests_toolbelt import MultipartEncoder [as 別名]
def _multipart_post(self, data):
        encoder = MultipartEncoder(fields=data)
        monitor = MultipartEncoderMonitor(encoder, callback=self._progress_bar)
        r = requests.post(self.file_host_url,
                          data=monitor,
                          headers={'Content-Type': monitor.content_type})
        return r 
開發者ID:NullArray,項目名稱:Archivist,代碼行數:9,代碼來源:base.py


注:本文中的requests_toolbelt.MultipartEncoder方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。