0

The below code is basically generated by Postman. I have removed 'Content-Type' from the header as I understand that is not needed. I've also generalised the URL path etc. However I receive an error message: b'{"Message":"An error has occured. Details: Error writing MIME multipart body part to output stream."}'

The request however does work when I run it from Postman. What am I doing wrong?

import requests

url = "https://website.com/api/inputs/file/upload/Test/12/"

payload = {}
files = [
  ('', open('C:/Users/jmas/Documents/Demo/test.csv','rb'))
]
headers = {
  'Authorization': 'Bearer 0eE6r7DWAIriN6gBR1-5WJI- 
9ZsfgE13JEthzuSXKQ9A05sbt5xdn8cAcV3Sz16D4thYNBcr6dQGdIcivSOpo- 
0dz7tAVP19trL2bwQtQez6FyzZqJFqPQrHm7fLee9eEr5GSpth0JfeqV5Gt7z_juqB3dHDBINu1oxh9G- 
pF8VuSRpUkAOujSMS0RysE1aptVqU1wAXLTXnKxUlDJLpTuQMCQGnFwqNvUWx3mDQ9xh4pw-ZaKw8TMvWaYgtmd1Z- 
oAp2IgvP9bwV5pv5izyuUWIfaZyP0mqYlZu2'
}

response = requests.request("POST", url, headers=headers, data = payload, files = files)

print(response.text.encode('utf8'))
print(response.status_code)
B.Tullero
  • 95
  • 6
  • What happens if you re-add the content type? – Klaus D. Feb 05 '20 at 21:17
  • If I add 'Content-Type': 'application/x-www-form-urlencoded' to headers then I get back b'' and status code 415 (unsupported media type) – B.Tullero Feb 05 '20 at 21:19
  • Does this help https://stackoverflow.com/questions/24196280/error-writing-mime-multipart-body-part-to-output-stream? – Ahmet Feb 05 '20 at 22:17

3 Answers3

0

Your payload is just an empty dictionary. Remove data = payload

AlgoRythm
  • 1,196
  • 10
  • 31
0

You are passing the payload with the request, but this dictionary is empty.

I guess you need something like this:

url = 'https://website.com/api/inputs/file/upload/Test/12/'

files = {'': open('C:/Users/jmas/Documents/Demo/test.csv', 'rb')}

headers = {
    'Authorization': 'Bearer 0eE6r7DWAIriN6gBR1-5WJI-9ZsfgE13JEthzuSXKQ9A05sbt5xdn8cAcV3Sz16D4thYNBcr6dQGdIcivSOpo -0dz7tAVP19trL2bwQtQez6FyzZqJFqPQrHm7fLee9eEr5GSpth0JfeqV5Gt7z_juqB3dHDBINu1oxh9G -pF8VuSRpUkAOujSMS0RysE1aptVqU1wAXLTXnKxUlDJLpTuQMCQGnFwqNvUWx3mDQ9xh4pw - ZaKw8TMvWaYgtmd1Z - oAp2IgvP9bwV5pv5izyuUWIfaZyP0mqYlZu2'
}

response = requests.post(url, headers=headers, files=files)
print(response)

Your headers formatting seemed not following pep8 rules, try to change it to have it formatted well.

JaFizz
  • 328
  • 2
  • 20
0

Success! I added 'text/csv' to the files parameter (dictionary) and the file successfully uploaded.

files = {"file": ("PremSet_2UB_0LB_NoRenewalInfo", 
open('C:/Users/jmas/Documents/Demo/test.csv', 'rb'), 'text/csv')}
B.Tullero
  • 95
  • 6