使用pycurl库转换curl命令

2024-06-30 15:37:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要通过pycurl库执行以下curl命令:

curl https://lipn.univ-paris13.fr/framester/en/wfd_json/sentence -d "data=Remember the milk:t" -X PUT

这是我的pycurl转换:

^{pr2}$

问题是curl命令返回一个json,而当我通过pycurl执行时,精化并没有停止。有人能帮我修改代码吗?为什么python代码没有停止?谢谢你


Tags: 代码https命令jsondatafrcurlsentence
1条回答
网友
1楼 · 发布于 2024-06-30 15:37:27

在代码段中,HTTPHEADER选项设置不正确,以下版本的脚本执行良好。 在

import pycurl
import certifi
import json
import StringIO

TARGET_URL = "https://lipn.univ-paris13.fr/framester/en/wfd_json/sentence"
data = json.dumps({"data": "Remember the milk:t"})

c = pycurl.Curl()
c.setopt(c.URL, TARGET_URL)
c.setopt(pycurl.CAINFO, certifi.where())
c.setopt(pycurl.CUSTOMREQUEST, "PUT")
c.setopt(pycurl.POST, True)
c.setopt(pycurl.POSTFIELDS, data)
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json'])
try:
    # c.setopt(pycurl.VERBOSE, 1)
    buf = StringIO.StringIO()
    c.setopt(c.WRITEFUNCTION, buf.write)
    print("(info) Invoking PUT on configured target-url...")
    c.perform()
    body = buf.getvalue().decode(encoding="utf-8")
    print("(info) Response => \"{}\"".format(body))
    c.close()
except pycurl.error, error:
    errno, errstr = error
    print('An error occurred:', errstr)

上面的脚本执行打印数据如下所示:

^{pr2}$

相关问题 更多 >