2

We would like to upload a string with python. I found here some examples and created the following script.

import requests
url = 'https://URL/fileupload?FileName=file.csv'
headers = {'content-type': 'octet-stream'}
files = {'file': ('ID,Name\n1,test')}
r = requests.post(url, files=files, headers=headers, auth=('user', 'password'))

The upload is working but the output contains some unexpected lines.

--ec7b507f800f48ab85b7b36ef40cfc44
Content-Disposition: form-data; name="file"; filename="file"

ID,Name
1,test
--ec7b507f800f48ab85b7b36ef40cfc44--

The goal is to only upload the following from files = {'file': ('ID,Name\n1,test')}:

ID,Name
1,test

How is this possible?

Patrick
  • 1,400
  • 8
  • 15

1 Answers1

0

When using the files parameter, requests creates the headers and body required to post files.
If you don't want your request formated like that you can use the data parameter.

url = 'http://httpbin.org/anything'
headers = {'content-type': 'application/octet-stream'}
files = {'file': 'ID,Name\n1,test'}
r = requests.post(url, data=files, headers=headers, auth=('user', 'password'))
print(r.request.body)
file=ID%2CName%0A1%2Ctest

Note that when passing a dictionary to data it gets url-encoded. If you want to submit your data without any encoding you can use a string.

url = 'http://httpbin.org/anything'
headers = {'content-type': 'application/octet-stream'}
files = 'ID,Name\n1,test'
r = requests.post(url, data=files, headers=headers, auth=('user', 'password'))
print(r.request.body)
ID,Name
1,test
t.m.adam
  • 14,050
  • 3
  • 25
  • 46