本文整理匯總了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
示例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
示例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
示例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.")
示例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
示例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()
示例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
示例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
示例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)
示例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'
示例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'
示例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')
示例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'])
示例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)
示例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