【发布时间】:2018-07-02 14:56:40
【问题描述】:
我想使用 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']
但是不知道怎么写post命令
这个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
谢谢
【问题讨论】:
标签: json python-3.x