curl 到 python 请求的转换 [英] Conversion of curl to python Requests
问题描述
我正在尝试将 curl 中的以下工作请求转换为 python 请求(使用请求 http://docs.python-requests.org/en/v0.10.7/).
I'm trying to convert the following working request in curl to a python request (using the Requests http://docs.python-requests.org/en/v0.10.7/).
curl --data 'query={"tags":["test1","test2"]}' http://www.test.com/match
(请注意,我使用了假网址,但该命令确实适用于真实网址)
(please note, I've used a fake url but the command does work with the real url)
接收端(在 Flask 中运行)这样做:
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)
在 curl (7.30) 中,在 Mac OS X (10.9) 上运行,上面的命令正确返回使用标签查询过滤的 json 列表.
In curl (7.30), ran on Mac OS X (10.9) the command above properly returns a json list that filtered using the tag query.
我的python脚本如下,返回400错误请求.
My python script is as follows, it returns a 400 bad request.
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
我觉得我错过了一些小东西,任何帮助将不胜感激.
I feel I'm missing something small and any help would be appreciated.
谢谢
推荐答案
您的服务器需要 JSON,但您没有发送它.试试这个:
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
这篇关于curl 到 python 请求的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!