将Curl命令行转换为python

2024-05-16 13:33:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是Fiware Orion Context Broker,我想使用python脚本发布一些数据。命令行(运行良好)如下所示:

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脚本:

^{pr2}$

这是什么响应.json()退货:

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

有什么办法解决这个问题吗?在

谢谢你!在


Tags: 数据text命令行脚本jsonapplicationvaluetype
2条回答

您可能不应将数据作为字符串传递,如下所示:

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

按正常口述传递:

^{pr2}$

请求库将自动为您转换此词典。{{cd2>也不要使用参数。下面请专家从文档中找出原因。在

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程序更新值,因此在我的方法中补丁请求:

    #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。如我所见,您没有为您的属性定义任何新类型,因此在使用keyValues时,默认情况下它将是“Text”。在

请求中可以省略属性/元数据类型。当在属性/元数据创建或更新操作中忽略时,将根据值对类型使用默认值:

  • 如果值是字符串,则使用文本类型
  • 如果值是数字,则使用类型number。在
  • 如果value是boolean,则使用boolean类型。在
  • 如果value是一个对象或数组,则使用StructuredValue。在
  • 如果值为null,则不使用任何值。在

关于这些东西的更多信息你可以找到here。在

相关问题 更多 >