1

I'm porting code from NodeJS to python3. I want to post image binary data and text. I red urllib3 User Guide but I can't do it. How can I do it ? Thank you.

NodeJS

filePath = "xxx.jpeg"
text = "xxx"
return chakram.request("POST", "http://xxx",
     { "multipart" : [
           { "body" : fs.createReadStream(filePath),
             "Content-Type" : "image/jpeg",
             "Content-Disposition" : "name='file'; filename='" + filePath + "'"
           },
           { "body" : JSON.stringify(this.RequestData(text)),
             "Content-Type" : "text"
           }
       ],
       "headers" : {
           "Authorization" : "xxx"
       }
     })

My Wrong Python Code with requests:

filePath = "xxx.jpeg"
text = "xxx"
headers = {
    "Authorization" : "xxx"
}

binary_data = None
with open(file_path, 'rb') as fp:
    binary_data = fp.read()

request_body = self.create_request_body(text)

files = {
    "file": (filePath, binary_data, 'image/jpeg'),
    "": ("", request_body, "xxx")
}
resp = requests.post("http://xxx", files=files, headers=headers)

I got 500 error.

Maiko Ohkawa
  • 853
  • 2
  • 11
  • 28

0 Answers0