Python 3 节假日使用

Python 3 urlopen usage

我正在开发一个 python 脚本,它将与我现在正在部署的 CRM 系统的 API 进行通信。我可以从 CRM 服务器获取数据,但我似乎无法添加(写入)新条目。我怀疑我在做一些愚蠢的事情,因为我对 Python 和一般编程还很陌生,有人可以指出我正确的方向吗?服务器不会拒绝数据,但它的行为就好像我是从 /api/v1.0/payments 请求数据,而不是发布新数据。

from urllib.request import Request, urlopen

headers = {
  'Content-Type': 'application/json',
  'X-Auth-App-Key': '[API key]'
}

values = b"""
  {
"clientId": 104,
"method": 3,
"checkNumber": "",
"createdDate": "2016-09-12T00:00:00+0000",
"amount": 40,
"note": "",
  }
"""

request = Request('http://[SERVER_URL]/api/v1.0/payments', data=values, headers=headers)

response_body = urlopen(request).read()
print(response_body)

我的工作基于此处 API 文档中的示例代码: http://docs.ucrm.apiary.io/#reference/payments/payments/post

我在底部正确使用了 urlopen 吗?

This question/answer 可能是您的问题。基本上你的 POST 请求被重定向到 /api/v1.0/payments/ (注意尾部斜杠),当发生这种情况时你的 POST 被重定向到 GET 请求,这就是服务器的原因正在响应,就好像您正在尝试检索所有付款信息一样。

其他需要注意的事情是您的 json 数据实际上是无效的,因为它在 'note' 值之后包含尾随 ,,因此这也可能是一个问题。我认为您可能还遗漏了 header 中的 Content-Length header。我建议使用 json 模块来创建 json 数据:

values = json.dumps({
    "clientId": 104,
     "method": 3,
     "checkNumber": "",
     "createdDate": "2016-09-12T00:00:00+0000",
     "amount": 40,
     "note": ""
})

headers = {
  'Content-Type': 'application/json',
  'Content-Length': len(values),
  'X-Auth-App-Key': '[API key]'
}

request = Request('http://[SERVER_URL]/api/v1.0/payments/', data=values, headers=headers)