【问题标题】:REST post using Python-Request使用 Python 请求的 REST 发布
【发布时间】:2012-12-06 04:14:52
【问题描述】:

为什么这个简单的代码不向我的服务发布数据:

import requests
import json

data = {"data" : "24.3"}
data_json = json.dumps(data)
response = requests.post(url, data=data_json)
print response.text

我的服务是这样使用 WCF 开发的:

  [OperationContract]
  [WebInvoke(Method = "POST", UriTemplate = "/test", ResponseFormat =    
      WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json)]
  string test(string data );

注意:如果删除输入参数data 一切正常,可能是什么问题。

【问题讨论】:

  • 当你说它不起作用时,你到底是什么意思?从最后一个“注释”开始,它听起来不仅仅是“忽略我的数据”(因为没有数据“一切正常”),而是确实发生了 ?
  • 好吧,我想我找到了问题所在。它与 {"data" : "24.3"} .. 出于某些原因我需要将它作为一个字符串括起来当我的请求通过时.. 像这样 "{data: 24.3}" .. 任何人都愿意解释原因?
  • 你试过data = {"data": 24.3}(注意:一个浮点数,而不是一个字符串)?我不知道 WCF,但这是另一种解释:string test(string data) 可能意味着您的服务器需要一个字符串作为输入(data_json = '"something"'(注意:它是一个 Python 字符串,其中包含代表 json 字符串的 json 文本)),它不需要一个 json 对象。严格来说,“application/json”必须代表一个 json 对象(例如,data_json = '{"a", 1}')或一个 json 数组(例如,data_json = '[1,2,3]'),因此只接受一个字符串是不正确的。

标签: python python-2.7 python-requests


【解决方案1】:

需要设置内容类型头:

data = {"data" : "24.3"}
data_json = json.dumps(data)
headers = {'Content-type': 'application/json'}

response = requests.post(url, data=data_json, headers=headers)

如果我将 url 设置为 http://httpbin.org/post,该服务器会向我回显发布的内容:

>>> import json
>>> import requests
>>> import pprint
>>> url = 'http://httpbin.org/post'
>>> data = {"data" : "24.3"}
>>> data_json = json.dumps(data)
>>> headers = {'Content-type': 'application/json'}
>>> response = requests.post(url, data=data_json, headers=headers)
>>> pprint.pprint(response.json())
{u'args': {},
 u'data': u'{"data": "24.3"}',
 u'files': {},
 u'form': {},
 u'headers': {u'Accept': u'*/*',
              u'Accept-Encoding': u'gzip, deflate, compress',
              u'Connection': u'keep-alive',
              u'Content-Length': u'16',
              u'Content-Type': u'application/json',
              u'Host': u'httpbin.org',
              u'User-Agent': u'python-requests/1.0.3 CPython/2.6.8 Darwin/11.4.2'},
 u'json': {u'data': u'24.3'},
 u'origin': u'109.247.40.35',
 u'url': u'http://httpbin.org/post'}
>>> pprint.pprint(response.json()['json'])
{u'data': u'24.3'}

如果您使用requests 2.4.2 或更高版本,您可以将JSON 编码留给库;它也会自动为您设置正确的 Content-Type 标头。将要作为 JSON 发送的数据传入 json 关键字参数:

data = {"data" : "24.3"}
response = requests.post(url, json=data)

【讨论】:

  • 之前尝试过Content-type,但没有成功。我的 WCF 有什么问题吗?如果我删除输入参数,我可以调用 URL。我不知道可能是什么问题。
  • 好吧,我想我找到了问题所在。它是{"data" : "24.3"} .. 由于某些原因,我需要将它作为一个字符串括起来,这就是我的请求通过时.. 像这样 "{data : 24.3}" .. 有人愿意解释原因吗?
  • @GJSJ:那么您不再发送 JSON 对象,而是发送 JSON 字符串。那将是服务器端问题,与 Python 或 requests 无关。
  • @GJSJ:用http://httpbin.org/post作为URL试试吧;它以 JSON 结构进行响应,包括一个 json 键,以显示如果您发送 JSON,它会收到什么 JSON。
  • 同意你的评论服务器期待一个 json 字符串,所以我需要传递一个 json 字符串而不是一个对象。谢谢干杯!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-07
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
相关资源
最近更新 更多