我正在使用Python请求向Web服务API提交文件和相关的元数据。如何使用单个POST一起提交元数据和文件?
我遵循了示例How to send JSON as part of multipart POST-request
# data to be sent to api
payload = {
"name": "sample1",
"fragment": "Yes",
"localProgramCode": "test"
}
gbfile = "sample1.gb"
files = {
'json': (None, json.dumps(payload), 'application/json'),
'file': (os.path.basename(gbfile), open(gbfile, 'rb'),'application/octet-stream')
}
# sending post request and saving response as response object
r=requests.post(
API_ENDPOINT,
auth=HTTPBasicAuth('user', 'pass'),
verify=False,
files=files,
)
如果我没有用Content-type: multi-part
指定标题,我会得到这个
错误:
[“请求未指定JSON内容类型”]
如果我在帖子中添加标题条目以指定多部分内容
headers = {'Content-type': 'multipart/form-data'}
我收到此错误
FileUploadException:由于未找到多部分边界,因此请求被拒绝