[英]Python file upload using request multipartencoder with json bdoy
I have the following python function where im trying to upload a file over to an API that accepts a file as multipart stream.我有以下 python function 我试图将文件上传到 API 接受文件作为多部分 ZF7B44CFAFD5C58A222 The API correctly works with postman, however im struggling to identify the problem here.
API 可以与 postman 一起正常工作,但是我在这里努力找出问题所在。
I have parameters (json body) to post to the API along with the file which I have tried to encode inside my mp_encoder variable.我有参数(json body)要发布到 API 以及我试图在我的 mp_encoder 变量中编码的文件。
def callAPIwithFile(apiData,apiUrl):
file_ids = ''
jsonData = {'type':apiData['type'],'fromId':apiData['fromid'],'toUserIds':apiData['userIds'],'toGroupIds1':apiData['groupIds'],'toDepartmentIds1':apiData['departmentIds'],'subject':apiData['subject'],'body':apiData['body'],'attachment':apiData['attachment'],'report':apiData['report']}
mp_encoder = MultipartEncoder(fields={'type':apiData['type'],'fromId':apiData['fromid'],'toUserIds':apiData['userIds'],'toGroupIds1':apiData['groupIds'],'toDepartmentIds1':apiData['departmentIds'],'subject':apiData['subject'],'body':apiData['body'],'attachment':apiData['attachment'],'report':apiData['report'],'file': (apiData["attachment"], open(apiData["attachment"], 'rb'), 'application/vnd.ms-excel')})
print mp_encoder
headers = {'Authorization': 'Bearer jwt'}
resp = requests.post(apiUrl,headers=headers,data=mp_encoder)
print resp.text
print "status code " + str(resp.status_code)
if resp.status_code == 201:
print ("Success")
data = json.loads(resp.text)
file_ids = data['file_ids']
print file_ids
else:
print ("Failure")
On running the code I get the following errors:在运行代码时,我收到以下错误:
{"statusCode":400,"message":["type must be a valid alpha, beta, Or gamma","body should not be empty"],"error":"Bad Request"}
status code 400
Failure
As per my understanding the JSON Body that im trying to post to the API is not being recognised correctly.据我了解,我试图发布到 API 的 JSON 正文没有被正确识别。 How do I go about this?
我该如何 go 关于这个?
Please note, I have tried using request.post(apiUrl,file=files,data=data,header=header) which results in an error of unexpected field.请注意,我尝试使用 request.post(apiUrl,file=files,data=data,header=header) 导致意外字段错误。
The below answer could solve my problem:以下答案可以解决我的问题:
headers = {'Authorization': 'Bearer '+token}
mydict = dict(type=apiData['type'], fromId=apiData['fromid'], toUserIds1=apiData['userIds'], toGroupIds=apiData['groupIds'], toDepartmentIds1= apiData['departmentIds'], subject= apiData['subject'], body= apiData['body'], attachment= apiData['attachment'], report= apiData['report'])
resp=requests.post(apiUrl, headers = headers, files=dict(attachment=(apiData["attachment"], open(apiData["attachment"], 'rb'), 'application/vnd.ms-excel')),data=mydict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.