简体   繁体   中英

Python requests - POST data from a file

I have used curl to send POST requests with data from files.

I am trying to achieve the same using python requests module. Here is my python script

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'

But my script is not POSTing the data from file. Am I missing something here.

In Curl , I used to have a command like below

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

You do not need to use .read() here, simply stream the object directly. You do need to set the Content-Type header explicitly; curl does this when using --data but requests doesn't:

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)

I've used the open file object as a context manager so that it is also auto-closed for you when the block exits (eg an exception occurs or requests.post() successfully returns).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM