0

我正在使用一个没有文档的 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
 }
}

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

4

2 回答 2

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))
于 2013-06-15T17:36:13.970 回答
0

您的标头和 URL 表明您想要发布 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 源代码。

于 2013-06-14T15:32:16.043 回答