【问题标题】:Python file upload using request multipartencoder with json bdoy使用带有json正文的请求多部分编码器的Python文件上传
【发布时间】:2020-10-15 19:04:06
【问题描述】:

我有以下 python 函数,我试图将文件上传到接受文件作为多部分流的 API。 API 可以与邮递员一起正常工作,但我很难在这里找出问题。

我有参数(json 正文)与我尝试在我的 mp_encoder 变量中编码的文件一起发布到 API。

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")

运行代码时出现以下错误:

{"statusCode":400,"message":["type must be a valid alpha, beta, Or gamma","body should not be empty"],"error":"Bad Request"}
status code 400
Failure

据我了解,我试图发布到 API 的 JSON 正文没有被正确识别。我该怎么办?

请注意,我已尝试使用 request.post(apiUrl,file=files,data=data,header=header) 导致出现意外字段错误。

【问题讨论】:

    标签: python rest file-upload python-requests python-requests-toolbelt


    【解决方案1】:

    下面的答案可以解决我的问题:

    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)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 2015-06-28
      • 1970-01-01
      相关资源
      最近更新 更多