我有这个curl命令通过pycurl库执行:
curl https://lipn.univ-paris13.fr/framester/en/wfd_json/sentence -d "data=Remember the milk:t" -X PUT
这是我的pycurl转换:
url = "https://lipn.univ-paris13.fr/framester/en/wfd_json/sentence"
buffer = StringIO()
curl = pycurl.Curl()
curl.setopt(pycurl.CAINFO, certifi.where())
curl.setopt(curl.URL, url)
pycurl.HTTPHEADER, ['Content-Type: application/json' ,'Accept: application/json']
curl.setopt(pycurl.CUSTOMREQUEST, "PUT")
curl.setopt(pycurl.POST, 1)
curl.setopt(pycurl.VERBOSE, 1)
data = urllib.urlencode({"data":"Remember the milk:t"})
curl.setopt(pycurl.POSTFIELDS, data)
curl.setopt(curl.WRITEFUNCTION, buffer.write)
curl.perform()
curl.close()
body = buffer.getvalue()
print(buffer.getvalue())
问题是curl命令返回一个json,而当我通过pycurl执行时,详细说明不会停止。有人可以帮我纠正我的代码吗?为什么python代码不会停止?谢谢
答案 0 :(得分:0)
在您的代码段中,未正确设置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)
上面的脚本执行打印数据如下所示:
(info) Invoking PUT on configured target-url...
(info) Response => "There are no similar frames."
Process finished with exit code 0