将 Curl 命令行转换为 python

Converting Curl command line to python

我正在使用 Fiware Orion Context Broker,我想使用 python 脚本 POST 一些数据。命令行(工作正常)如下所示:

curl -X POST -H "Accept: application/json" -H "Fiware-ServicePath: /orion" -H "Fiware-Service: orion" -H "Content-Type: application/json" -d '{"id": "JetsonTX1", "type": "sensor",  "title": {"type": "Text","value": "Init"}, "percentage": { "type": "Text", "value": "0%"}}' "http://141.39.159.63:1026/v2/entities/"

我的 Python 脚本:

import requests
import json


url = 'http://141.39.159.63:1026/v2/entities/'
data = '''{
      "title": {
        "value": "demo",
        "type": "Text"
      },
          "percentage": {
        "type": "Text",
        "value": "0%"            
       }'''
data_json = json.dumps(data)
headers = {"Accept": "application/json", "Fiware-ServicePath": "/bonseyes", "Fiware-Service": "bonseyes", "Content-Type": "application/json"}

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

print(response.json())

这就是 response.json() returns:

{u'description': u'Errors found in incoming JSON buffer', u'error': u'ParseError'}

有什么解决办法吗?

谢谢!

您可能不应该像这样将数据作为字符串传递:

data = '''{
      "title": {
        "value": "demo",
        "type": "Text"
      },
          "percentage": {
        "type": "Text",
        "value": "0%"            
       }'''

将其作为普通字典传递:

data = {
      "title": {
        "value": "demo",
        "type": "Text"
      },
          "percentage": {
        "type": "Text",
        "value": "0%"            
       }}

请求库会自动为您转换本词典。还要确保您要使用 data 参数而不是 json。文档中的以下专家应该清楚原因。

def post(url, data=None, json=None, **kwargs):
   r"""Sends a POST request.

   :param url: URL for the new :class:`Request` object.
   :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
   :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
"""

根据您的评论,您似乎应该像这样传递数据:

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

因为您的端点需要 json 而不是表单编码字节

最后还缺少花括号。

我认为您应该尝试对 OCB 使用 keyValues 选项。它将使您的有效载荷更短。我使用类似的 python 程序来更新值,因此在我的方法中 PATCH 请求:

    #Sorting out url and payload for request
    data = '{"' + attribute + '":' + value + '}'
    headers = {'Content-type': 'application/json'}

    url = urlOfOCB + '/v2/entities/' + entityId + '/attrs?options=keyValues'
    r = requests.patch(url, (data), headers=headers)

您可以阅读有关此选项的信息 here。如我所见,您没有为属性定义任何新类型,因此默认情况下它将是 "Text",同时使用 keyValues。

Attribute/metadata 类型可以在请求中省略。在 attribute/metadata 创建或更新操作中省略时,根据值使用默认值类型:

  • 如果值为字符串,则使用文本类型
  • 如果值为数字,则使用 Number 类型。
  • 如果值为布尔值,则使用布尔类型。
  • 如果值是对象或数组,则使用 StructuredValue。
  • 如果值为空,则使用 None。

有关这些内容的更多信息,您可以找到 here