将Curl POST API请求转换为Python3中的子流程调用

问题描述 投票:1回答:1

我有一个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_code 400,显然这里不是这种情况)

Traceback (most recent call last):

  File "/home/joel/.virtualenvs/p3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-35-324f7c5741fc>", line 6, in <module>
    out = eval(out.decode("utf-8"))

  File "<string>", line 1
    NO TEXT INPUT
          ^
SyntaxError: invalid syntax

当我发送带有文本的请求时,它可以正常工作,但这不是我想要的。

proc = subprocess.Popen(["curl", "-d", '{"text":"Some text here.", "title":"some text here"}', '-H', "Content-Type: application/json", "-X", "POST", "http://xx.xx.x.xx/endpoint"], stdout=subprocess.PIPE)
python-3.x curl flask subprocess
1个回答
0
投票

您需要在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)

因此,不要使用str(tmp_dict)(它将您的字典用单引号引起来,这不是有效的JSON),您应该使用json.dumps(tmp_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)
© www.soinside.com 2019 - 2024. All rights reserved.