本文整理汇总了Python中requests_toolbelt.multipart.encoder.MultipartEncoder方法的典型用法代码示例。如果您正苦于以下问题:Python encoder.MultipartEncoder方法的具体用法?Python encoder.MultipartEncoder怎么用?Python encoder.MultipartEncoder使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests_toolbelt.multipart.encoder
的用法示例。
在下文中一共展示了encoder.MultipartEncoder方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __upload_file_gee
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def __upload_file_gee(session, file_path, use_multipart):
with open(file_path, 'rb') as f:
upload_url = __get_upload_url(session)
if use_multipart:
form = encoder.MultipartEncoder({
"documents": (file_path, f, "application/octet-stream"),
"composite": "NONE",
})
headers = {"Prefer": "respond-async", "Content-Type": form.content_type}
resp = session.post(upload_url, headers=headers, data=form)
else:
files = {'file': f}
resp = session.post(upload_url, files=files)
gsid = resp.json()[0]
return gsid
示例2: upload_dataset
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def upload_dataset(self, dataset_path, dataset_name=None, has_header=True):
if dataset_name is None:
head, tail = os.path.split(dataset_path)
dataset_name = tail
# dataset_name = dataset_path.split('/')[-1]
url = self.server_url + self.routes['upload_dataset']
headers = self.get_auth_header()
if headers is None:
return False, "Cannot get Auth token. Please log in."
if not os.path.isfile(dataset_path):
return False, "File not found"
with open(dataset_path, 'rb') as f:
form = encoder.MultipartEncoder({
"dataset": (str(dataset_path), f, 'text/csv/h5'),
'dataset_name': str(dataset_name),
'has_header': str(has_header)
})
headers.update({"Prefer": "respond-async", "Content-Type": form.content_type})
r = self.s.post(url, headers=headers, data=form)
return self.get_return_info(r)
示例3: create_version
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def create_version(image_name, version, workspace_path, monitor_callback):
with open(workspace_path, 'rb') as file:
e = encoder.MultipartEncoder(
fields={'version': version,
'source': ('workspace', file, 'text/plain')}
)
m = encoder.MultipartEncoderMonitor(e, monitor_callback)
response = get_session().post(base_images_url + '/' + image_name + '/versions', data=m,
headers={'Content-Type': m.content_type})
if response.status_code == 404:
raise ResourceNotFoundError(
response=response,
message="There is no image named {}, please check for typo".format(image_name)
)
if response.status_code != 200:
raise get_exception(response)
else:
return response.json()
示例4: upload_source
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def upload_source(workspace_path, manifest, monitor_callback):
with open(workspace_path, 'rb') as file:
e = encoder.MultipartEncoder(
fields={
'source': ('workspace', file, 'text/plain'),
'manifest': manifest
}
)
m = encoder.MultipartEncoderMonitor(e, monitor_callback)
response = get_session().post(base_sources_url, data=m, headers={'Content-Type': m.content_type})
if response.status_code != 200:
if response.status_code == 400:
document = get_manifest_document(list(response.json().keys())[0])
click.echo(format_text(document, TextStyle.WARNING))
raise get_exception(response)
else:
return response.json()
示例5: create
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def create(self, name, schemaFileName, schemaContents, description):
"""
Create a schema for the org.
Returns: schemaId (string), response (object).
Throws APIException on failure
"""
if not isinstance(schemaContents, str):
schemaContents = json.dumps(schemaContents)
fields = {
"schemaFile": (schemaFileName, schemaContents, "application/json"),
"schemaType": "json-schema",
"name": name,
}
if description:
fields["description"] = description
multipart_data = MultipartEncoder(fields=fields)
r = self._apiClient.postMultipart(self._baseUrl, multipart_data)
if r.status_code == 201:
return Schema(apiClient=self._apiClient, **r.json())
else:
raise ApiException(r)
示例6: updateContent
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def updateContent(self, schemaId, schemaFileName, schemaContents):
"""
Updates a schema for the org.
Returns: True on success
Throws APIException on failure
"""
if not isinstance(schemaContents, str):
schemaContents = json.dumps(schemaContents)
fields = {"schemaFile": (schemaFileName, schemaContents, "application/json")}
multipart_data = MultipartEncoder(fields=fields)
r = self._apiClient.putMultipart("%s/%s/content" % (self._baseUrl, schemaId), multipart_data)
if r.status_code == 204:
return True
else:
raise ApiException(r)
示例7: post_localfile
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def post_localfile(at, roomId, filename, text='', toPersonId='', toPersonEmail=''):
openfile = open(filename, 'rb')
filename = ntpath.basename(filename)
payload = {'roomId': roomId, 'files': (filename, openfile, 'image/jpg')}
if text:
payload['text'] = text
if toPersonId:
payload['toPersonId'] = toPersonId
if toPersonEmail:
payload['toPersonEmail'] = toPersonEmail
m = MultipartEncoder(fields=payload)
headers = {'Authorization': _fix_at(at), 'Content-Type': m.content_type}
resp = requests.request("POST",url=_url('/messages'), data=m, headers=headers)
file_dict = json.loads(resp.text)
file_dict['statuscode'] = str(resp.status_code)
return file_dict
示例8: to_multipart_form
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def to_multipart_form(data, boundary=None):
"""Create a multipart form like produced by HTML forms from a dict."""
fields = {}
for k, v in data.items():
if k not in SPECIAL_KEYS:
fields[k] = str(v) if not isinstance(v, bool) else str(v).lower()
if k in JSON_KEYS:
fields[k] = json.dumps(data[k])
if _has_image_file(data):
fields[IMAGE_FILE] = _get_image(data[IMAGE_FILE])
return MultipartEncoder(fields=fields, boundary=boundary)
示例9: _get_image
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def _get_image(path_or_url):
'''
Returns a tuple (filename, file, MIME type) compliant with
requests_toolbelt's MultipartEncoder.
See also: https://toolbelt.readthedocs.io/en/latest/uploading-data.html#uploading-data # noqa
'''
if os.path.exists(path_or_url):
mime_type = mime_type_from_path(path_or_url)
return (_FILENAME, open(path_or_url, 'rb'), mime_type)
elif path_or_url.startswith('http'):
img, mime_type = get_image(path_or_url)
return (_FILENAME, img, mime_type)
else:
raise ValueError('Unknown image: %s' % path_or_url)
示例10: import_image
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def import_image(self, infile, image_id, digest_id, image_name, sync=False):
'''**Description**
Import an image archive
**Arguments**
- infile: An image archive file
- sync: Whether the import should be synchronous or asynchronous
**Success Return Value**
If synchronous, A JSON object representing the image that was imported.
'''
try:
m = MultipartEncoder(
fields={'archive_file': (infile, open(infile, 'rb'), 'text/plain')}
)
if sync:
url = self.url + "/api/scanning/v1/anchore/import/images"
else:
url = self.url + "/api/scanning/v1/import/images"
headers = {'Authorization': 'Bearer ' + self.token, 'Content-Type': m.content_type,
'imageId': image_id, 'digestId': digest_id, 'imageName': image_name}
res = requests.post(url, data=m, headers=headers, verify=self.ssl_verify)
if not self._checkResponse(res):
return [False, self.lasterr]
return [True, res.json() if sync else res.content]
except Exception as err:
print(err)
示例11: __init__
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def __init__(self, fields):
mp_encoder = encoder.MultipartEncoder(fields=fields)
self.monitor = encoder.MultipartEncoderMonitor(mp_encoder, callback=self._create_callback(mp_encoder))
示例12: _upload
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def _upload(self, archive_path, s3_upload_data):
files = self._get_files_dict(archive_path)
fields = OrderedDict(s3_upload_data['fields'])
fields.update(files)
monitor = MultipartEncoder(fields).get_monitor()
s3_response = requests.post(s3_upload_data['url'], data=monitor, headers={'Content-Type': monitor.content_type})
self.logger.debug("S3 upload response: {}".format(s3_response.headers))
if not s3_response.ok:
raise S3UploadFailedError(s3_response)
示例13: post_attachment
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def post_attachment(self, uri, filepath,
filename=None, mimetype=None, data=None, co3_context_token=None, timeout=None):
"""
Upload a file to the specified URI
e.g. "/incidents/<id>/attachments" (for incident attachments)
or, "/tasks/<id>/attachments" (for task attachments)
:param uri: The REST URI for posting
:param filepath: the path of the file to post
:param filename: optional name of the file when posted
:param mimetype: optional override for the guessed MIME type
:param data: optional dict with additional MIME parts (not required for file attachments; used in artifacts)
:param co3_context_token: Action Module context token, if responding to an Action Module event
:param timeout: optional timeout (seconds)
"""
filepath = ensure_unicode(filepath)
if filename:
filename = ensure_unicode(filename)
url = u"{0}/rest/orgs/{1}{2}".format(self.base_url, self.org_id, ensure_unicode(uri))
mime_type = mimetype or mimetypes.guess_type(filename or filepath)[0] or "application/octet-stream"
with open(filepath, 'rb') as filehandle:
attachment_name = filename or os.path.basename(filepath)
multipart_data = {'file': (attachment_name, filehandle, mime_type)}
multipart_data.update(data or {})
encoder = MultipartEncoder(fields=multipart_data)
headers = self.make_headers(co3_context_token,
additional_headers={'content-type': encoder.content_type})
response = self._execute_request(self.session.post,
url,
data=encoder,
proxies=self.proxies,
cookies=self.cookies,
headers=headers,
verify=self.verify,
timeout=timeout)
BasicHTTPException.raise_if_error(response)
return json.loads(response.text)
示例14: request
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def request(self,headers,args,url):
multipart_encoder = MultipartEncoder(
fields={
"token": str(args[2]),
"source": "0",
"source-version": "9999",
# "lat": "39.928845",
"lat": str(args[0]),
# "lng":"116.422077"
"lng":str(args[1])
#file为路径
},
boundary='----ofo-boundary-MC40MjcxMzUw'
)
response = requests.request(
"POST",url,headers=headers,
timeout = self.config.getint("DEFAULT","timeout"),
verify=False,
data=multipart_encoder
)
with self.lock:
with self.connect_db() as c:
try:
decoded = json.loads(response.text)['values']['info']['cars']
self.done += 1
for x in decoded:
self.bikes_count += 1
c.execute("INSERT OR IGNORE INTO ofo VALUES (%d,'%s',%f,%f)" % (
int(time.time()) * 1000, x['carno'], x['lat'], x['lng']))
timespent = datetime.datetime.now() - self.start_time
percent = self.done / self.total
total = timespent / percent
print("位置 %s, 未去重单车数量 %s, 进度 %0.2f%%, 速度 %0.2f个/分钟, 总时间 %s, 剩余时间 %s" % (
args, self.bikes_count, percent * 100, self.done / timespent.total_seconds() * 60, total, total - timespent))
except Exception as ex:
print(ex)
示例15: _post_batch
# 需要导入模块: from requests_toolbelt.multipart import encoder [as 别名]
# 或者: from requests_toolbelt.multipart.encoder import MultipartEncoder [as 别名]
def _post_batch(self, data=None, f=None, **kwargs):
returntype = kwargs.get('returntype', 'geographies')
url = self._geturl('addressbatch', returntype)
if data is not None:
# For Python 3, compile data into a StringIO
f = io.StringIO()
writer = csv.DictWriter(f, fieldnames=['id', 'street', 'city', 'state', 'zip'])
for i, row in enumerate(data):
row.setdefault('id', i)
writer.writerow(row)
f.seek(0)
elif f is None:
raise ValueError('Need either data or a file for CenusGeocode.addressbatch')
try:
form = MultipartEncoder(fields={
'vintage': self.vintage,
'benchmark': self.benchmark,
'addressFile': ('batch.csv', f, 'text/plain')
})
h = {'Content-Type': form.content_type}
with requests.post(url, data=form, timeout=kwargs.get('timeout'), headers=h) as r:
# return as list of dicts
return self._parse_batch_result(r.text, returntype)
except RequestException as e:
raise e
finally:
f.close()