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程序的方法
Apr 21 Python
Python yield使用方法示例
Dec 04 Python
Python单链表简单实现代码
Apr 27 Python
深入解析Python中的descriptor描述器的作用及用法
Jun 27 Python
利用Hyperic调用Python实现进程守护
Jan 02 Python
浅谈Python的list中的选取范围
Nov 12 Python
python实现图片转字符小工具
Apr 30 Python
Python中常用的8种字符串操作方法
May 06 Python
python 计算一个字符串中所有数字的和实例
Jun 11 Python
django中SMTP发送邮件配置详解
Jul 19 Python
Python批量处理csv并保存过程解析
May 16 Python
Python web框架(django,flask)实现mysql数据库读写分离的示例
Nov 18 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
德生PL550的电路分析
2021/03/02 无线电
用php简单实现加减乘除计算器
2014/01/06 PHP
基于win2003虚拟机中apache服务器的访问
2017/08/01 PHP
基于JQuery.timer插件实现一个计时器
2010/04/25 Javascript
用apply让javascript函数仅执行一次的代码
2010/06/27 Javascript
JS远程获取网页源代码实例
2013/09/05 Javascript
阻止表单提交按钮多次提交的完美解决方法
2016/05/16 Javascript
javascript封装addLoadEvent实现页面同时加载执行多个函数的方法
2016/07/25 Javascript
浅谈javascript中的Function和Arguments
2016/08/30 Javascript
Vue2递归组件实现树形菜单
2017/04/10 Javascript
纯js实现隔行变色效果
2017/11/29 Javascript
vue短信验证性能优化如何写入localstorage中
2018/04/25 Javascript
element-ui组件中input等的change事件中传递自定义参数
2019/05/22 Javascript
Javascript三种字符串连接方式及性能比较
2019/05/28 Javascript
[02:27]2014DOTA2国际邀请赛 VG赛后采访:更大的挑战在等着我们
2014/07/13 DOTA
[00:32]10月24、25日 辉夜杯外卡赛附加赛开赛!
2015/10/23 DOTA
wxPython框架类和面板类的使用实例
2014/09/28 Python
python动态参数用法实例分析
2015/05/25 Python
Python数据结构之栈、队列的实现代码分享
2017/12/04 Python
Python使用reportlab模块生成PDF格式的文档
2019/03/11 Python
python3转换code128条形码的方法
2019/04/17 Python
Python读写文件基础知识点
2019/06/10 Python
关于python pycharm中输出的内容不全的解决办法
2020/01/10 Python
Python爬取你好李焕英豆瓣短评生成词云的示例代码
2021/02/24 Python
HTML5 video视频字幕的使用和制作方法
2018/05/03 HTML / CSS
美国百年历史早餐食品供应商:Wolferman’s
2017/01/18 全球购物
short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1;有什么错?
2014/09/26 面试题
学期自我鉴定范文
2013/10/01 职场文书
党的群众路线教育实践方案
2014/05/11 职场文书
2014年中学生检讨书大全
2014/10/09 职场文书
《爱的教育》读书心得
2014/11/08 职场文书
2014年计生工作总结
2014/11/21 职场文书
年会邀请函范文
2015/01/30 职场文书
西柏坡观后感
2015/06/08 职场文书
2016年国培研修日志
2015/11/13 职场文书
Pandas||过滤缺失数据||pd.dropna()函数的用法说明
2021/05/14 Python