django中websocket的具体使用


Posted in Python onJanuary 22, 2022

websocket是一种持久化的协议,HTTP协议是一种无状态的协议,在特定场合我们需要使用长连接,做数据的实时更新,这种情况下我们就可以使用websocket做持久连接。http与websocket二者存在交集。

后端:

from dwebsocket.decorators import accept_websocket
import json
# 存储连接websocket的用户
clist = []
 
@accept_websocket
def websocketLink(request):
    # 获取连接
    if request.is_websocket:
        # 新增 用户  连接信息
        clist.append(request.websocket)
        # 监听接收客户端发送的消息 或者 客户端断开连接
        for message in request.websocket:
            break
 
 # 发送消息
def websocketMsg(client, msg):
    b1 = json.dumps(msg,ensure_ascii=False).encode('utf-8')
    client.send(b1)
 
# 服务端发送消息
def sendmsg():
    sql = "select * from customer"
    res = db1.find_all(sql)
    if len(clist)>0:
        for i in clist:
            i.send(json.dumps({'list': res},ensure_ascii=False).encode('utf-8'))
             # websocketMsg(i, {'list': res})
    return HttpResponse("ok")
 
from apscheduler.schedulers.blocking import BlockingScheduler
 
def getecharts(request):
    scheduler = BlockingScheduler()
    scheduler.add_job(sendmsg,'interval',seconds=1)
    scheduler.start()
    return HttpResponse('ok')

前端:

<template>
  <div class="bgpic">
    <van-row style="padding-top: 10px;padding-bottom: 10px">
      <van-col span="8">
        <div id="weekmain" style="width: 400px;height: 300px"></div>
      </van-col>
      <van-col span="8">http://api.map.baidu.com/marker </van-col>
      <van-col span="8">
        <div id="monthmain" style="width: 400px;height: 300px"></div>
      </van-col>
    </van-row>
    <van-row>
      <van-col span="8"></van-col>
      <van-col span="8"></van-col>
      <van-col span="8">{{infolist1}}</van-col>
    </van-row>
  </div>
</template>
 
<script>
import * as echarts from 'echarts';
// import myaxios from "../../../https/myaxios";
import axios from 'axios';
import {reactive} from 'vue';
export default {
  name: "myweek",
  setup(){
    let infolist1 = reactive({"data":[]})
    // let mydata = reactive([])
    const initdata=()=>{
      var socket = new WebSocket("ws:127.0.0.1:8000/websocketLink");
 
      socket.onopen = function () {
        console.log('连接成功');//成功连接上Websocket
      };
      socket.onmessage = function (e) {
        // alert('消息提醒: ' + e.data);
        //打印服务端返回的数据
        infolist1.data = e.data
        console.log(e.data)
        // mydata = infolist1.list
        // console.log(mydata)
      };
      socket.onclose=function(e){
        console.log(e);
        socket.close(); //关闭TCP连接
      };
    }
    return{
      infolist1,
      initdata
    }
  },
  data(){
    return{
      infolist:[],
    }
  },
  methods:{
    mget(){
      axios.get("http://127.0.0.1:8000/getecharts").then(res=>{
        console.log(res)
      })
    },
    infoshow(){
      axios.get("http://localhost:8000/infoshow","get").then(res=>{
        this.infolist=res.data.list
        this.getmonth()
        this.mget()
      })
    },
    getmonth(){
      var chartDom = document.getElementById('monthmain');
      var myChart = echarts.init(chartDom);
      var option;
 
// prettier-ignore
 
      let dataAxis = [];
// prettier-ignore
      let data = [];
 
      for(let i=0;i<this.infolist.length;i++){
        dataAxis.push(this.infolist[i]["name"])
        data.push(this.infolist[i]["tmoney"])
      }
 
      let yMax = 10000;
      let dataShadow = [];
      for (let i = 0; i < data.length; i++) {
        dataShadow.push(yMax);
      }
      option = {
        title: {
          text: '特性示例:渐变色 阴影 点击缩放',
          subtext: 'Feature Sample: Gradient Color, Shadow, Click Zoom'
        },
        xAxis: {
          data: dataAxis,
          axisLabel: {
            inside: true,
            color: '#fff'
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          },
          z: 10
        },
        yAxis: {
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#999'
          }
        },
        dataZoom: [
          {
            type: 'inside'
          }
        ],
        series: [
          {
            type: 'bar',
            showBackground: true,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            },
            data: data
          }
        ]
      };
// Enable data zoom when user click bar.
      const zoomSize = 6;
      myChart.on('click', function (params) {
        console.log(dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)]);
        myChart.dispatchAction({
          type: 'dataZoom',
          startValue: dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
          endValue:
              dataAxis[Math.min(params.dataIndex + zoomSize / 2, data.length - 1)]
        });
      });
 
      option && myChart.setOption(option);
    },
    getweek(){
      var chartDom = document.getElementById('weekmain');
      var myChart = echarts.init(chartDom);
      var option;
 
      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: 'Direct',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: [320, 332, 301, 334, 390, 330, 320]
          },
          {
            name: 'Email',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            data: [120, 132, 101, 134, 90, 230, 210]
          },
          {
            name: 'Union Ads',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            data: [220, 182, 191, 234, 290, 330, 310]
          },
          {
            name: 'Video Ads',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            data: [150, 232, 201, 154, 190, 330, 410]
          },
          {
            name: 'Search Engine',
            type: 'bar',
            data: [862, 1018, 964, 1026, 1679, 1600, 1570],
            emphasis: {
              focus: 'series'
            },
            markLine: {
              lineStyle: {
                type: 'dashed'
              },
              data: [[{ type: 'min' }, { type: 'max' }]]
            }
          },
          {
            name: 'Baidu',
            type: 'bar',
            barWidth: 5,
            stack: 'Search Engine',
            emphasis: {
              focus: 'series'
            },
            data: [620, 732, 701, 734, 1090, 1130, 1120]
          },
          {
            name: 'Google',
            type: 'bar',
            stack: 'Search Engine',
            emphasis: {
              focus: 'series'
            },
            data: [120, 132, 101, 134, 290, 230, 220]
          },
          {
            name: 'Bing',
            type: 'bar',
            stack: 'Search Engine',
            emphasis: {
              focus: 'series'
            },
            data: [60, 72, 71, 74, 190, 130, 110]
          },
          {
            name: 'Others',
            type: 'bar',
            stack: 'Search Engine',
            emphasis: {
              focus: 'series'
            },
            data: [62, 82, 91, 84, 109, 110, 120]
          }
        ]
      };
 
      option && myChart.setOption(option);
 
    },
  },
  mounted() {
    this.infoshow()
    this.getweek()
    this.initdata()
  }
}
</script>
 
<style scoped>
.bgpic{
  background-image: url("../../../https/4.jpg");
  width: 1269px;
  height: 781px;
}
</style>

到此这篇关于django中websocket的具体使用的文章就介绍到这了,更多相关django websocket内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python+Selenium自动化实现分页(pagination)处理
Mar 31 Python
python如何使用正则表达式的前向、后向搜索及前向搜索否定模式详解
Nov 08 Python
python实现定时自动备份文件到其他主机的实例代码
Feb 23 Python
python利用Opencv实现人脸识别功能
Apr 25 Python
python判断所输入的任意一个正整数是否为素数的两种方法
Jun 27 Python
Python定时任务工具之APScheduler使用方式
Jul 24 Python
Python Django 添加首页尾页上一页下一页代码实例
Aug 21 Python
jupyter notebook 调用环境中的Keras或者pytorch教程
Apr 14 Python
python 对一幅灰度图像进行直方图均衡化
Oct 27 Python
python 下载文件的多种方法汇总
Nov 17 Python
Python中使用subprocess库创建附加进程
May 11 Python
Django与数据库交互的实现
Jun 03 Python
Django+Nginx+uWSGI 定时任务的实现方法
Jan 22 #Python
梳理总结Python开发中需要摒弃的18个坏习惯
Jan 22 #Python
Pandas搭配lambda组合使用详解
Jan 22 #Python
Python中的tkinter库简单案例详解
Jan 22 #Python
解析python中的jsonpath 提取器
Jan 18 #Python
Python中如何处理常见报错
Jan 18 #Python
Python机器学习应用之工业蒸汽数据分析篇详解
You might like
无数据库的详细域名查询程序PHP版(4)
2006/10/09 PHP
隐藏Nginx或Apache以及PHP的版本号的方法
2016/01/03 PHP
PHP中file_exists使用中遇到的问题小结
2016/04/05 PHP
基于jquery实现的类似百度搜索的输入框自动完成功能
2011/08/23 Javascript
JavaScript中的值是按值传递还是按引用传递问题探讨
2015/01/30 Javascript
JavaScript制作简易的微信打飞机
2015/03/31 Javascript
javascript消除window.close()的提示窗口
2015/05/20 Javascript
js实现仿qq消息的弹出窗效果
2016/01/06 Javascript
浅谈jquery的map()和each()方法
2016/06/12 Javascript
基于jQuery代码实现圆形菜单展开收缩效果
2017/02/13 Javascript
layui.js实现的表单验证功能示例
2017/11/15 Javascript
浅谈Angular 中何时取消订阅
2017/11/22 Javascript
node.js将MongoDB数据同步到MySQL的步骤
2017/12/10 Javascript
JS简单实现动态添加HTML标记的方法示例
2018/04/08 Javascript
微信小程序仿美团城市选择
2018/06/06 Javascript
jquery实现二级导航下拉菜单效果实例
2019/05/14 jQuery
JS实现点餐自动选择框(案例分析)
2019/12/10 Javascript
浅谈vue 组件中的setInterval方法和window的不同
2020/07/30 Javascript
python检测服务器是否正常
2014/02/16 Python
python抓取最新博客内容并生成Rss
2015/05/17 Python
python创建列表并给列表赋初始值的方法
2015/07/28 Python
python pandas 对时间序列文件处理的实例
2018/06/22 Python
python实现嵌套列表平铺的两种方法
2018/11/08 Python
python3 打印输出字典中特定的某个key的方法示例
2019/07/06 Python
详解centos7+django+python3+mysql+阿里云部署项目全流程
2019/11/15 Python
tensorflow实现残差网络方式(mnist数据集)
2020/05/26 Python
解决阿里云邮件发送不能使用25端口问题
2020/08/07 Python
html5 分层屏幕适配的方法
2018/03/16 HTML / CSS
傲盾软件面试题
2015/08/17 面试题
公安领导班子四风问题个人整改措施思想汇报
2014/10/09 职场文书
2014年勤工助学工作总结
2014/11/24 职场文书
刑事附带民事代理词
2015/05/25 职场文书
技术转让协议书
2016/03/19 职场文书
python使用XPath解析数据爬取起点小说网数据
2021/04/22 Python
React配置子路由的实现
2021/06/03 Javascript
CSS 实现角标效果的完整代码
2022/06/28 HTML / CSS