将POST请求卷入pycurl代码

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

curl -v
-H Accept:application/json \
-H Content-Type:application/json \
-d "{
    name: 'abc',
    path: 'def',
    target: [ 'ghi' ]
}" \
-X POST http://some-url

我有以下python代码:

import pycurl, json

c = pycurl.Curl()
c.setopt(pycurl.URL, 'http://some-url')
c.setopt(pycurl.HTTPHEADER, ['Accept: application/json'])
data = json.dumps({"name": "abc", "path": "def", "target": "ghi"})
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.setopt(pycurl.VERBOSE, 1)
c.perform()
print curl_agent.getinfo(pycurl.RESPONSE_CODE)
c.close()

执行此操作我有一个错误415:不支持的媒体类型,所以我改变了:

c.setopt(pycurl.HTTPHEADER, ['Accept: application/json'])

成:

c.setopt(pycurl.HTTPHEADER, [ 'Content-Type: application/json' , 'Accept: application/json'])

这次我有400:不好的请求 . 但是使用curl的bash代码可行 . 你知道我应该在python代码中修复什么吗?

回答(3)

2 years ago

在你的bash示例中,属性 target 是一个数组,在Python示例中它是一个字符串 .

试试这个:

data = json.dumps({"name": "abc", "path": "def", "target": ["ghi"]})

我还强烈建议您查看具有更好API的requests库:

import requests
data = {"name": "abc", "path": "def", "target": ["ghi"]}
response = requests.post('http://some-url', json=data)
print response.status_code

2 years ago

我知道这已经超过一年了,但请尝试删除 Headers 值中的空格 .

c.setopt(pycurl.HTTPHEADER, ['Accept:application/json'])

我也更喜欢使用请求模块,因为API /方法干净且易于使用 .

2 years ago

使用请求库更简单 . (http://docs.python-requests.org/en/latest

我为你原来的curl自定义 Headers 添加了python代码 .

import json
import requests

url = 'http://some-url'
headers = {'Content-Type': "application/json; charset=xxxe", 'Accept': "application/json"}
data = {"name": "abc", "path": "def", "target":  ["ghi"]}
res = requests.post(url, json=data, headers=headers)
print (res.status_code)
print (res.raise_for_status())