Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of curl to python Requests

I'm trying to convert the following working request in curl to a python request (using Requests).

curl --data 'query={"tags":["test1","test2"]}' http://www.test.com/match

(I've used a fake url but the command does work with the real url)

The receiving end (ran in Flask) does this:

@app.route("/match", methods=['POST'])
def tagmatch():
    query = json.loads(request.form['query'])
    tags = query.get('tags')
    # ... does stuff ...
    return json.dump(stuff)

In curl (7.30), ran on Mac OS X (10.9) the command above properly returns a JSON list that's filtered using the tag query.

My Python script is as follows, it returns a 400 Bad Request error.

import requests

payload = {"tags":["test1", "test2"]}
# also tried  payload = 'query={"tags":["test1","test2"]}'
url = 'http://www.test.com/match'

r = requests.post(url, data=payload)

if __name__=='__main__':
     print(r.text)
like image 867
zalc Avatar asked Dec 09 '13 00:12

zalc


2 Answers

There is an open source cURL to Python Requests conversion helper at https://curlconverter.com/. It isn't perfect, but helps out a lot of the time. Especially for converting Chrome "Copy as cURL" commands. There is also a node library if you need to do the conversions programmatically

screenshot of curlconverter.com converting the given command to Python

like image 142
Gourneau Avatar answered Oct 16 '22 23:10

Gourneau


Your server is expecting JSON, but you aren't sending it. Try this:

import requests
import json

payload = {'query': json.dumps({"tags":["test1", "test2"]})}
url = 'http://www.test.com/match'

r = requests.post(url, data=payload)

if __name__=='__main__':
    print r.text
like image 13
Lukasa Avatar answered Oct 17 '22 00:10

Lukasa