Python 3.x 在Python3中将Curl POST API请求转换为子流程调用

Python 3.x 在Python3中将Curl POST API请求转换为子流程调用,python-3.x,curl,flask,subprocess,Python 3.x,Curl,Flask,Subprocess,我有一个curl请求,它可以在python3的命令行中正常工作。API是在flask rest框架中编写的 curl -d '{"text":"Some text here.", "category":"some text here"}' -H "Content-Type: application/json" -X POST http://xx.xx.x.xx/endpoint 我将此请求转换为子流程请求 txt = 'Some text here' tmp_dict = {"text":tx

我有一个curl请求,它可以在python3的命令行中正常工作。API是在flask rest框架中编写的

curl -d '{"text":"Some text here.", "category":"some text here"}' -H "Content-Type: application/json" -X POST http://xx.xx.x.xx/endpoint
我将此请求转换为子流程请求

txt = 'Some text here'
tmp_dict = {"text":txt, "category":"text"}
proc = subprocess.Popen(["curl", "-d", str(tmp_dict), '-H', "Content-Type: application/json", "-X", "POST", "http://xx.xx.x.xx/endpoint"], stdout=subprocess.PIPE)
(out, err) = proc.communicate()
out = eval(out.decode("utf-8"))
错误(当请求中没有传递文本时,我返回一个响应
status\u code
400,这里显然不是这种情况)


您需要在curl请求中发送一个有效的json正文。现在,您正在json正文中发送一个无效的字符串

proc = subprocess.Popen(["curl", "-d", str(tmp_dict), '-H', "Content-Type: application/json", "-X", "POST", "http://xx.xx.x.xx/endpoint"], stdout=subprocess.PIPE)
因此,您应该使用
JSON.dumps(tmp\u dict)
(它将您的dict用单引号括起来,这不是一个有效的JSON),而不是使用
str(tmp\u dict)
(它生成一个符合JSON格式的字符串)。因此,将上述行更改为:

proc = subprocess.Popen(["curl", "-d", json.dumps(tmp_dict), '-H', "Content-Type: application/json", "-X", "POST", "http://xx.xx.x.xx/endpoint"], stdout=subprocess.PIPE)

您需要在curl请求中发送一个有效的json正文。现在,您正在json正文中发送一个无效的字符串

proc = subprocess.Popen(["curl", "-d", str(tmp_dict), '-H', "Content-Type: application/json", "-X", "POST", "http://xx.xx.x.xx/endpoint"], stdout=subprocess.PIPE)
因此,您应该使用
JSON.dumps(tmp\u dict)
(它将您的dict用单引号括起来,这不是一个有效的JSON),而不是使用
str(tmp\u dict)
(它生成一个符合JSON格式的字符串)。因此,将上述行更改为:

proc = subprocess.Popen(["curl", "-d", json.dumps(tmp_dict), '-H', "Content-Type: application/json", "-X", "POST", "http://xx.xx.x.xx/endpoint"], stdout=subprocess.PIPE)

从Python程序调用curl有什么意义?Python可以执行HTTP请求,您不必为此调用外部进程。从Python程序调用curl有什么意义?Python可以执行HTTP请求,您不必为此调用外部进程。