通过 os.system() 的 Python cURL 命令失败并出现 JSON 解析错误

标签 python json curl fiware-orion

您好,我正在尝试通过 Python 脚本向 Orion Context Broker 发送 cURL 命令。 我在 OpenWRT 上运行脚本,因此由于内存问题,我无法安装 requestsurllib2 库,另外还安装 subprocess 等库编译失败。所以我使用 os.system() 来执行 cURL 命令。这是脚本的代码:

import sys
import os
from urllib import urlencode
sys.path.insert(0, '/usr/lib/python2.7/bridge')
from bridgeclient import BridgeClient as bridgeclient

value = bridgeclient()


header="(curl 10.130.1.228:1026/v1/updateContext -s -S --header 'Content-Type: application/json' \
--header 'Accept: application/json'     -d @- | python -mjson.tool) <<EOF"

json_string="""
{
    "contextElements": [
        {
            "type": "Room",
            "isPattern": "false",
            "id": "R1",
            "attributes": [
                {
                    "name": "temperature",
                    "type": "float",
                    "value": "firstValue"
                },
                {
                    "name": "pressure",
                    "type": "float",
                    "value": "secondValue"
                }
            ]    
        }
    ],
    "updateAction": "UPDATE"
}
EOF""" 


while(True):

    all=value.getall()
    sentValue1=""
    sentValue2=""
    if all['Tmp'] is None:
        sentValue1=all['Tmp']
    else:
        sentValue1="NoValue"
    if all['Prs'] is None:
        sentValue2=all['Prs']
    else:
        sentValue2="NoValue"
    json_string=json_string.replace("firstValue",sentValue1)
    json_string=json_string.replace("secondValue",sentValue2)   
    os.system(header+json_string)

如果我复制并粘贴给 os.system() 的命令,就像在终端窗口中一样,一切都会顺利进行,并且我的 Orion 实例也会更新。但是,如果我通过上述脚本运行相同的命令,我会从服务器收到此响应:

{
    "errorCode": {
        "code": "400",
        "details": "JSON Parse Error",
        "reasonPhrase": "Bad Request"
    }
}

我认为存在一些格式问题,我已尝试一切方法使其正常工作,但没有成功。

更新:

我在 contextBroker 日志中发现了这条消息:

from=10.130.1.1 | srv=pending | subsrv=<defalut> | comp=Orion | 
op=AlarmMenager.cpp[405]:badInput | msg=Releasing alarm BadInput 
10.130.1.1: JSON Parse Error: unspecified file(1):expected end of input

还有这个:

from=10.130.1.1 | srv=pending | subsrv=<defalut> | comp=Orion | 
op=AlarmMenager.cpp[405]:badInput | msg=Releasing alarm BadInput 
10.130.1.1: JSON Parse Error: unspecified file(1):expected object

对于我发出的每个 cURL 请求都重复执行。

更新2:

我设法使 subprocess.call() 工作,但它给出了完全相同的响应。

最佳答案

感谢@Shan-Desai,我解决了这个问题。

我使用 json.dump 构建了 json 字符串并使用了 pycurl。

这是工作代码:

import sys
import os
import subprocess
import json
from urllib import urlencode
from collections import OrderedDict
import StringIO
import pycurl

sys.path.insert(0, '/usr/lib/python2.7/bridge')
from bridgeclient import BridgeClient as bridgeclient


fout = StringIO.StringIO()
value = bridgeclient()
apiurl = '10.130.1.228:1026/v1/updateContext'
headers=['Content-Type: application/json','Accept: application/json']

firstValue = 'firstValue'

secondValue = 'secondValue'

d_attributes = [{'name': 'temperature', 'type': 'float', 'value': firstValue},
            {'name': 'pressure', 'type': 'float', 'value': secondValue}]

d_context = [{'type': 'Room', 'isPattern': 'false', 'id': 'R1', 'attributes': d_attributes}]

d_json = {'contextElements': d_context, 'updateAction': 'UPDATE'}

c = pycurl.Curl()

while (True):

        all = value.getall()

        if all['Tmp'] is not None:
            firstValue = all['Tmp']
        else:
            firstValue = "NoValue"
        if all['Prs'] is not None:
            secondValue = all['Prs']
        else:
            secondValue = "NoValue"
        d_json["contextElements"][0]["attributes"][0]["value"]=firstValue
        d_json['contextElements'][0]['attributes'][1]['value']=secondValue
        c.setopt(pycurl.WRITEFUNCTION, fout.write)
        c.setopt(pycurl.URL, apiurl)
        c.setopt(pycurl.HTTPHEADER, headers)
        c.setopt(pycurl.POST, 1)
    s_json=json.dumps(d_json)
        c.setopt(pycurl.POSTFIELDS,s_json)
        c.perform()
        c.getinfo(pycurl.RESPONSE_CODE)
        print(json.dumps(OrderedDict(d_json)))
        print(fout.getvalue())

关于通过 os.system() 的 Python cURL 命令失败并出现 JSON 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47202065/

相关文章:

java - 如何仅针对给定的单个端点忽略 JsonProperty 并让它适用于其他端点

json - jackson throw 失误

PHP - 使用 cURL 访问 HTTPS (SSL) 保护的站点

python - NoneType-Python 中的 Yield 错误

python - 请求 : Return file object from url (as with open ('' ,'rb' ) )

javascript - 使用react.js从api函数获取json数据

ubuntu - curl 选项 - : is unknown

linux - curl - 在 shell 脚本内运行特殊字符 URL 时出现问题

python - 如何使用 python 或 c 访问我的网络摄像头

python - SciPy:为什么二维插值的输入在内部排序?