Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python requests - POST data from a file

Tags:

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'  
like image 757
skanagasabap Avatar asked Apr 22 '13 10:04

skanagasabap


People also ask

How do I get post data in Python?

Python is only a language, to get GET and POST data, you need a web framework or toolkit written in Python. Django is one, as Charlie points out, the cgi and urllib standard modules are others. Also available are Turbogears, Pylons, CherryPy, web.py, mod_python, fastcgi, etc, etc.

How do you pass a body in a POST request in Python?

You'll want to adapt the data you send in the body of your request to the specified URL. Syntax: requests. post(url, data={key: value}, json={key: value}, headers={key:value}, args) *(data, json, headers parameters are optional.)

What does requests post return in Python?

post() Python's requests module comes with a method for making a “post” request to a web server; it returns a response object.


1 Answers

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 (e.g. an exception occurs or requests.post() successfully returns).

like image 59
Martijn Pieters Avatar answered Oct 25 '22 23:10

Martijn Pieters