Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curl --data-binary equivalent in python-requests library

I'm trying to post testing data to a server by using python-requests library in python. I am able to post data successfully with the following command using Curl in the terminal:

curl -i -XPOST 'http://myServerAddress/write?db=some_data' --data-binary 'param1,state=test,param2=1 param3=2.932,param4=3250 1497064544944 '

I'm trying to do the same thing with requests or maybe even pycurl python library. I am having a hard time translating the "--data-binary" part with pycurl or requests. Doing something like this with requests library for example:

import requests    

p = requests.post('http://myServerAddress/write?db=some_data', data={'param1,state=test,param2=1 param3=2.932,param4=3250 1497064544944 '})

print(p)
print(p.status_code)
print(p.text)

Getting "TypeError: a bytes-like object is required, not 'set'" in the shell when I run the code. What am I missing? Any help is appreciated. Thanks.

like image 334
Joel Pou Avatar asked Jun 14 '17 05:06

Joel Pou


People also ask

Does Python requests use curl?

In Python, cURL transfers requests and data to and from servers using PycURL. PycURL functions as an interface for the libcURL library within Python. Almost every programming language can use REST APIs to access an endpoint hosted on a web server.

How do I convert curls to requests in Python?

Curl Converter automatically generates valid Python code using the Python request library for all provided Curl HTTP headers and Curl data. Enter the Curl command, click Run to execute the command online and check the results. Click Generate Code and select Python to convert the Curl command to Python code.

What is data binary in curl?

--data-binary is a curl SPECIFIC flag for curl itself. it has nothing to do with HTTP web services call specifically, but it's how you "POST" data to the call in the HTTP BODY instead of in the header WHEN using curl.

Is requests built into Python?

Requests is one of the most popular Python libraries that is not included with Python.


1 Answers

Try something like this

import requests
data='param1,state=test,param2=1 param3=2.932,param4=3250 1497064544944 '
p = requests.post('http://myServerAddress/write?db=some_data', data.encode())
like image 57
Junyong Yao Avatar answered Sep 30 '22 13:09

Junyong Yao