[不完全转载]Django+VUE+Axios实现IOT小demo

6 篇文章 0 订阅
1 篇文章 0 订阅

感谢各位网上大佬博客的帮忙,我才写出此篇,文中有摘抄的部分,定会写明出处,侵删!

先上图,效果是这样的,就是个数据展示
在这里插入图片描述
就是一堆传感器,放在工厂里,数据是终端虚拟的
在这里插入图片描述

进入正题

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>

说几点:

  1. 使用element-ui中的table组件
  2. 初始化的数据是我自定义的
  3. 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
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
djangovue是两种不同的编程框架,它们可以结合使用来开发风险控制系统。在这个系统中,django可以用于后端开发,处理数据存储、业务逻辑和用户认证等;而vue可以用于前端开发,负责用户界面的展示和交互。 为了实现风险控制系统,首先需要建立数据库模型来存储风险相关的数据,例如风险类型、风险等级、风险责任人等。在django中,可以使用ORM来定义这些数据模型,并且实现对数据的增删改查操作。同时,还需要编写业务逻辑来处理风险控制的流程,例如风险评估、风险分析和风险报告等。这部分可以在django的视图函数中实现,并且可以使用django rest framework来提供API接口。 在前端方面,可以使用vue来构建风险控制系统的用户界面。可以使用Vue Router来管理页面路由,使用Vuex来管理状态,以及使用组件化的方式来构建各个功能模块。通过与后端API的交互,实现数据的展示和用户交互功能。 在整个系统开发过程中,还需要考虑安全性和性能优化的问题。在django中可以使用各种中间件和装饰器来增强系统的安全性,例如CSRF保护和JWT认证等。另外,还可以使用缓存和异步任务队列来优化系统的性能。 综上所述,django vue风险控制系统的代码实现需要后端和前端的协同配合,充分利用两种框架的特点来实现系统的数据管理和用户界面展示,同时也需要关注系统的安全性和性能优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值