将POST卷曲到pycurl代码中

时间:2016-03-14 15:48:14

标签: python curl pycurl

我正在尝试将以下curl请求转换为pycurl:

curl -v \
--user username:passwd \
-H X-Requested-By:MyClient \
-H Accept:application/json \
-X POST \
http://localhost:7001/some_context

它有效。以下不起作用:

import pycurl, json

url = "http://localhost:7001/some_context"
c = pycurl.Curl()
data = json.dumps(None)
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.setopt(pycurl.URL, url)
c.setopt(pycurl.HTTPHEADER, ['Accept: application/json', 'X-Requested-By:MyClient'])
c.setopt(pycurl.VERBOSE, 1)
c.setopt(pycurl.USERPWD, "username:passwd")
c.perform()

但执行此操作时出现错误415:媒体类型不受支持。你有什么主意吗?我宁愿留下pycurl-我知道请求库...

2 个答案:

答案 0 :(得分:1)

此脚本模仿您的curl命令行:

import pycurl, json

url = "http://localhost:7001/some_url"
url= 'http://httpbin.org/post'
c = pycurl.Curl()
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDSIZE, 0)
c.setopt(pycurl.URL, url)
c.setopt(pycurl.HTTPHEADER, ['Accept: application/json',
                             'X-Requested-By:MyClient',
                             'Content-Type:',
                             'Content-Length:'])
c.setopt(pycurl.VERBOSE, 1)
c.setopt(pycurl.USERPWD, "username:passwd")
c.perform()

答案 1 :(得分:0)

你的帖子数据是错误的,根据http://pycurl.io/docs/latest/quickstart.html#sending-form-data它期待一个字典,而不是一个字符串。 (json.dumps(None) == 'null'

您从网络服务器获得的错误很可能与此相关。

import pycurl, json

url = "http://localhost:7001/some_url"
c = pycurl.Curl()
data = {'whatever_field': None}
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.setopt(pycurl.URL, url)
c.setopt(pycurl.HTTPHEADER, ['Accept: application/json', 'X-Requested-By:MyClient'])
c.setopt(pycurl.VERBOSE, 1)
c.setopt(pycurl.USERPWD, "username:passwd")
c.perform()