感谢各位网上大佬博客的帮忙,我才写出此篇,文中有摘抄的部分,定会写明出处,侵删!
先上图,效果是这样的,就是个数据展示
就是一堆传感器,放在工厂里,数据是终端虚拟的
进入正题
HelloWorld.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>智慧工业互联</h2>
<el-row>
<el-button type="info" @click="clickfun">显示设备</el-button>
</el-row>
<el-table
:data="tableData"
style="width: 100%"
:row-class-name="tableRowClassName">
<el-table-column
prop="date"
label="上线日期"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="设备名称"
width="300">
</el-table-column>
<el-table-column
prop="sensor1"
label="传感器数值1"
width="180">
</el-table-column>
<el-table-column
prop="sensor2"
label="传感器数值2"
width="180">
</el-table-column>
<el-table-column
prop="address"
label="设备地址"
width="500">
</el-table-column>
</el-table>
</div>
</template>
<style>
.el-table .warning-row {
background: oldlace;
}
.el-table .success-row {
background: #f0f9eb;
}
</style>
<script>
export default {
name: 'HelloWorld',
data() {
return {
msg: '炬远智能科技(上海)有限公司 数据后台',
tableData: [{
date: '2019-05-02',
name: '酸碱度检测仪',
sensor1:'7.1PH',
sensor2:'9.8°C',
address: '某化工设备厂',
}, {
date: '2019-05-04',
name: '二氧化碳检测仪',
sensor1:'8.2PH',
sensor2:'11.7°C',
address: '某材料设备厂'
}, {
date: '2019-05-01',
name: '温湿度检测仪',
sensor1:'6.4PH',
sensor2:'32.6°C',
address: '宿迁某电子材料厂',
}, {
date: '2019-05-01',
name: '酸碱度检测仪',
sensor1:'7.2PH',
sensor2:'23.5°C',
address: '某机械电子设备厂',
}, {
date: '2019-05-03',
name: '温湿度检测仪',
sensor1:'60.2%RH',
sensor2:'42.6°C',
address: '上海市某公司'
}]
}
},
methods:{
tableRowClassName({row, rowIndex}) {
if (rowIndex === 1) {
return 'warning-row';
} else if (rowIndex === 3) {
return 'success-row';
}
return '';
},
clickfun:function(){
var that = this;
this.$axios({
method: 'get',
url: '/api/testapi',
}).then(function (response) {
// handle success
console.log(response.data.Devices);
that.tableData[0].name = response.data.Devices[0].DeviceName;
that.tableData[1].name = response.data.Devices[1].DeviceName;
that.tableData[2].name = response.data.Devices[2].DeviceName;
that.tableData[3].name = response.data.Devices[3].DeviceName;
that.tableData[4].name = response.data.Devices[4].DeviceName;
console.log('axiosa debug resp');
})
.catch(function (error) {
// handle error
console.log(error);
console.log('axiosa debug error');
})
.finally(function () {
// always executed
console.log("axiosa debug exec\n");
});
},
fun:function () {
this.$nstance.get("/").then(function (response) {
// handle success
console.log(response);
console.log('ABT debug resp');
})
.catch(function (error) {
// handle error
console.log(error);
console.log('ABT debug error');
})
.finally(function () {
// always executed
console.log("ABT debug exec\n");
});
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
说几点:
- 使用element-ui中的table组件
- 初始化的数据是我自定义的
- button发起axios请求,从后端获取设备名称数据。唯一想说的是that = this的处理,也是老生常谈的问题了,可参考 https://blog.csdn.net/ysgjiangsu/article/details/88665894 ,之前写过,就不赘述了
后端处理
views .py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
import json
from django.views.decorators.csrf import csrf_exempt
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.iotcloud.v20180614 import iotcloud_client, models
@csrf_exempt
def testapi(request):
print(request)
print(request.method)
if request.method == "GET":
try:
cred = credential.Credential("your-key", "your-secret")
httpProfile = HttpProfile()
httpProfile.endpoint = "iotcloud.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = iotcloud_client.IotcloudClient(cred, "ap-shanghai", clientProfile)
req = models.DescribeDevicesRequest()
params = '{"ProductId":"your-productName","Offset":0,"Limit":10}'
req.from_json_string(params)
resp = client.DescribeDevices(req)
print(resp.to_json_string())
except TencentCloudSDKException as err:
print(err)
return HttpResponse(resp.to_json_string(), content_type="application/json")
else:
print(request.POST)
print(request.body)
str1 = str(request.body,encoding='utf-8')
data = eval(str1)
print(data)
print(data['aa'])
print(type(request.body))
resp = {'errorcode':100,'type':'Post','data':{'main':data['aa']}}
return HttpResponse(json.dumps(resp), content_type="application/json")
实现:前端向后端要设备名称,后端向IOT要数据流,简单处理,response回去。我这里没有实现跨域访问,主要是想对接不同的IOT,我们的服务器后端相当于是个中转站。
如你所料想,点击button后,设备名称全部被更新,如下所示:
IOT返回的数据是这样的,所以现象如上
工程搭建
1.使用pycharm创建django工程,简单不表
2.在django根目录下创建后端
cd yourprjdir
python3 manage.py startapp backend
3.在django根目录下创建前端
vue-init webpack frontend
4.看一下现在的工程文件
5.比你的文件可能多一些,因为加入了自定义API部分
摘自 https://blog.csdn.net/qq_39785489/article/details/82751868
5.1在django的backend目录下新建urls .py
from django.urls import path
from . import views
urlpatterns = [
path('testapi', views.testapi, name='testapi'),
]
5.2修改backend目录下views.py文件
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
import json
# 解决前端post请求 csrf问题
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def testapi(request):
print(request)
print(request.method)
if request.method == "GET":
print(request.GET.get('aa'))
resp = {'errorcode': 100, 'type': 'Get', 'data': {'main': request.GET.get('aa')}}
return HttpResponse(json.dumps(resp), content_type="application/json")
else:
print(request.POST)
print(request.body)
str1=str(request.body, encoding = "utf-8")
data=eval(str1)
print(data)
print(data['aa'])
print(type(request.body))
resp = {'errorcode': 100, 'type': 'Post', 'data': {'main': data['aa']}}
return HttpResponse(json.dumps(resp), content_type="application/json")
5.3配置first/urls.py文件
from django.contrib import admin
from django.urls import include, path // 添加
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', TemplateView.as_view(template_name="index.html")),
path('api/', include('backend.urls')) // 添加
]
知识点
python中json文件处理涉及的四个函数json.dumps()和json.loads()、json.dump()和json.load()的区分,摘自 https://www.cnblogs.com/xiaomingzaixian/p/7286793.html
概念理解
1、json.dumps()和json.loads()是json格式处理函数(两函数为互逆过程)
(1)json.dumps()函数是将一个Python数据类型列表进行json格式的编码(可以这么理解,json.dumps()函数是将字典转化为字符串)
(2)json.loads()函数是将json格式数据转换为字典(可以这么理解,json.loads()函数是将字符串转化为字典)
2、json.dump()和json.load()主要用来读写json文件函数
代码1
import json
# json.dumps()函数的使用,将字典转化为字符串
dict1 = {"age": "12"}
json_info = json.dumps(dict1)
print("dict1的类型:"+str(type(dict1)))//字典dict
print("通过json.dumps()函数处理:")
print("json_info的类型:"+str(type(json_info)))//字串str
代码2
import json
# json.loads函数的使用,将字符串转化为字典
json_info = '{"age": "12"}'
dict1 = json.loads(json_info)
print("json_info的类型:"+str(type(json_info)))//字串str
print("通过json.dumps()函数处理:")
print("dict1的类型:"+str(type(dict1)))//字典dict
代码3
import json
# json.dump()函数的使用,将json信息写进文件
json_info = "{'age': '12'}"
file = open('1.json','w',encoding='utf-8')
json.dump(json_info,file)//json信息将被写入file
代码4
import json
# json.load()函数的使用,将读取json信息
file = open('1.json','r',encoding='utf-8')
info = json.load(file)
print(info)//json信息将被加载到info