【发布时间】:2012-09-28 03:42:00
【问题描述】:
我是 Python 新手,我需要构建一个 Python 库来连接到我们的 API 服务发送一些 json 数据,一切正常,但有一件事,我需要发送一些执行 POST 请求的字典:
def create_project(self, project):
print project
params = simplejson.dumps(project)
print params
req = requests.post(self.url+'/projects/addSpeedy.json',
data=params,
auth=HTTPBasicAuth(self.api_id, self.api_key),verify=False)
data = simplejson.loads(req.text)
return data
我传递给该函数的项目参数包含以下结构:
script = {
'part001': 'HI',
'part002': 'WORLD'
}
project = {
'title': 'Project posted from Python Carrot',
'script': script,
'remarks': "I want the voice be similar to Bugs Bunny.",
'test': '1'
}
但是,在执行请求时,API 告诉我缺少所需的“标题”字段,但是在函数中打印数据时一切似乎都很好,我在请求站点中看到了 dict json 编码这种情况: http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests
我尝试了其他方法,结果好坏参半,但它并没有按应有的方式工作,问题也不是 API,因为我们有其他语言的库,而且工作正常。
【问题讨论】:
-
这是使用 urllib2 的 python 2.x 吗?您不必在收到回复之前发送请求吗?此外,您可能希望确保包含内容类型标头。也许:req.add_header('Content-Type', 'application/json')
-
当您添加“.json”时,API 检测到它必须回答 json 中的请求,而且我还有其他可以正常工作的发布请求功能,请求的问题是当我使用字典的字典。 API 也回答错误。我发送的数据不是连接问题。
-
您是否考虑过使用诸如github.com/VoiceBunny/python-carrot 之类的库?
-
Korylprince 那是我正在扩展的库 :)
标签: python json simplejson python-requests