Sending POST requests with data from a file using Python requests

The page’s source code offers two solutions.
Solution 1 advises to submit the request to the correct URL, using the ‘action’ form, and to include the file name in ‘parameter’ (optional). Additionally, it suggests using the ‘dir’ and ‘submit’ parameters to submit other form fields.
Solution 2 starts by defining the upload directory path and the allowed file extension. It then provides an example code to process the uploaded file and store it in the folder.
The question asks for assistance in creating a Python post request to upload an XML file, using a URL and an Authentication-Token. A text file was tested with Python 3.4.2 and requests 2.11.1.

Question:

Utilizing curl, I have transmitted multiple
post request
s containing information sourced from files.

My goal is to accomplish the task with the help of Python programming language, for which I have shared my approach.

import requests
payload=open('data','rb').read()
r = requests.post('https://IP_ADDRESS/rest/rest/2', auth=('userid', 'password'), data=payload , verify=False)
print r.text

Data file
looks like below

'ID' : 'ISM03'

Is there something that I’m overlooking? My script fails to POST the information from the file.

Previously in Curl, a command similar to the one below was utilized.

Curl --data @filename -ik -X POST 'https://IP_ADDRESS/rest/rest/2' 



Solution:

Directly streaming the object is enough and there’s no need for

.read()

usage. However, setting
Content-Type header
explicitly is essential.

curl

automatically takes care of that when utilizing

--data

, but

requests

does not.

with open('data','rb') as payload:
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    r = requests.post('https://IP_ADDRESS/rest/rest/2', auth=('userid', 'password'),
                      data=payload, verify=False, headers=headers)

To ensure the automatic closing of the open file object, I have implemented it as a context manager. This means that, regardless of whether an exception occurs or the

requests.post()

function is successfully executed, the file object will be closed when the block exits.

Frequently Asked Questions