繁体   English   中英

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

[英]Convert Curl POST API request to Subprocess call in Python3

我有一个 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)

您需要在 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) (它将您的 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM