我想使用Python 3通过Rest API在JSON中写入值
这是我的代码,我可以连接并读取值,但不能更改值
import os
import requests
import pycurl
import json
import urllib
from urllib.request import urlopen
### Connection to interface ###
headers = {
'X-Requested-With': 'XMLHttpRequest',
}
data = [
('user[name]', 'admin'),
('user[password]', 'hellocpt'),
]
response = requests.post('http://192.168.0.230/sdcard/cpt/app/signin.php', headers=headers, data=data)
#print("Code Status du POST: ",response.status_code)
#print(response.content)
cookies = response.cookies
### Read firmware version ###
params = (
('url', '/app/objects/service/plat.Version'),
)
try:
responseget = requests.get('http://192.168.0.230/sdcard/cpt/app/data_api.php', headers=headers, params=params, cookies=cookies)
#print("\n\nCode Status du GET: ",responseget.status_code)
data = responseget.json()
print (data) # Display JSON return
print ("Firmware version: ",data['response']['data'][0]['slots'][0]['value'],"\n")
except ValueError:
print ("Json Error")
### Try to change value of sedona object ###
params = (
('url', '/app/objects/EasyIO/int.in'),
)
data = {
'path': '/app/objects/EasyIO/int.in',
'type': 'int',
'value': '100',
'slotType': 'property',}
writeValue = requests.post('http://192.168.0.230/sdcard/cpt/app/data_api.php', headers=headers, params=params, cookies=cookies, data=data)
print(writeValue) # Actually return 200
### Read sedona objects to check if post is working######
params = (
('url', '/app/objects/EasyIO/int.out'),
)
readvalue = requests.get('http://192.168.0.230/sdcard/cpt/app/data_api.php', headers=headers, params=params, cookies=cookies,)
dataInt = readvalue.json()
print(dataInt)
print(dataInt['response']['data'][0]['slots'][0]['value'])
os.system("pause")
输出
{'response': {'resultCode': 0, 'data': [{'path': '/service/plat', 'type': 'easyioFW::EasyIOPlatform', 'childNum': '0', 'slots': [{'name': 'Version', 'slotType': 'property', 'type': 'Buf', 'value': 'v1.0b1s'}]}]}}
Firmware version: v1.0b1s
<Response [200]>
{'response': {'resultCode': 0, 'data': [{'path': '/EasyIO/int', 'type': 'control::WriteInt', 'childNum': '0', 'slots': [{'name': 'out', 'slotType': 'property', 'type': 'int', 'value': '600'}]}]}}
600
要读取json中的特定值,我需要编写类似的内容
data['response']['data'][0]['slots'][0]['value']
但是不知道如何编写发布命令
此ajax命令写入值
var url = 'http://192.168.10.11/sdcard/cpt/app/data_api.php';
$.ajax({url: url,
type: 'POST',
dataType: 'json',
data: {
path: '/app/objects/EasyIO/WriteIn.in',
type: 'int',
value: '100',
slotType: 'property'
}
此API文档:http://gofile.me/32wEs/Tvt9NOMt5
谢谢
答案 0 :(得分:0)
在我看来,您所需要的就是这样:
import requests
uri='http://192.168.10.11/sdcard/cpt/app/data_api.php'
data={'path' : '/app/objects/EasyIO/WriteIn.in', 'type' : 'int', 'value': 100, 'slotType': 'property'}
resp=requests.post(uri,
json=data,
headers = headers,
params = params,
cookies = cookies)
虽然我没有要测试的设备,但是在请求中发送json = data将转换并以json格式发送字典。