将POST卷曲到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)

2 years ago

此脚本模仿您的 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()

2 years ago

你的帖子数据是错误的,根据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()