Python Request Post问题

时间:2013-06-14 15:25:00

标签: python python-requests

我正在使用没有文档的API,而且我遇到了绊脚石。我有一个功能:

def add_to_publicaster(self):
    # function that is called in the background whenever a user signs the petition and opts in to the mailing list
    # Makes an API call to publicaster <--- More documentation to follow --->
    username = app.config['PUBLICASTER_USERID']
    userPass = app.config['PUBLICASTER_PASS']
    headers = {'Authorization': {username:userPass}, "Content-type" : "application/json", "Accept":'text/plain'}
    url = 'https://api7.publicaster.com/Rest/Subscribers.svc/1?format=json'
    data = {"Item": {
        "Email": "juliangindi@gmail.com"
        }
    }
    r = requests.post(url, headers = headers, data = data)

这只是假设用这种格式发出POST请求:

POST https://api7.publicaster.com/Rest/Subscribers.svc/1?format=json HTTP/1.1
Content-Type: application/json
Authorization: <AccountID>:<Password>
Host: api7.publicaster.com
Content-Length: 64
Expect: 100-continue
Connection: Keep-Alive
 { "Item" : {
  "Email" : mkucera@whatcounts.com
 }
}

但是,函数中的代码不会产生所需的请求。任何建议都会非常有帮助。

2 个答案:

答案 0 :(得分:0)

您的标头和网址建议您要发布JSON数据。使用json库将您的python结构编码为JSON:

import json

# ...

data = {"Item": {
    "Email": "juliangindi@gmail.com"
    }
}
r = requests.post(url, headers = headers, data = json.dumps(data))

JSON可能看起来像很像Python,但它实际上是一种有限形式的JavaScript源代码。

答案 1 :(得分:0)

您没有正确执行身份验证。您的功能应如下所示:

def add_to_publicaster(self):
    # function that is called in the background whenever a user signs the petition and opts in to the mailing list
    # Makes an API call to publicaster <--- More documentation to follow --->
    username = app.config['PUBLICASTER_USERID']
    userPass = app.config['PUBLICASTER_PASS']
    headers = {"Content-type" : "application/json", "Accept":'text/plain'}
    url = 'https://api7.publicaster.com/Rest/Subscribers.svc/1?format=json'
    data = {"Item": {
        "Email": "juliangindi@gmail.com"
        }
    }
    r = requests.post(url, auth=(username, userPass), headers=headers, data=json.dumps(data))