• Django+VUE使用websocket


    一个需求,需要读取一个 json 文件然后推送给前端

    这里选择用的 dwebsocket,相比channels更简单一些

    安装 dwebsocket

    pip install dwebsocket
    
    • 1

    views.py

    from dwebsocket.decorators import accept_websocket,require_websocket
    import sys,os
    import time
    import json
    from django.http import HttpResponse
    
    def read():
        path=os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),'xxx/public.json')
        with open("xxx/public.json",'r',encoding='utf8') as f:
    
            return f.read()
    
    @accept_websocket
    def demo_api(request):
        while 1:
            txt=read()
            time.sleep(3)
            request.websocket.send(json.dumps(txt))
        return HttpResponse('ok')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    demo_api是主要函数.

    @accept_websocket给需要进行 websocket 通信的函数加上装饰器

    accept_websocket-—可以接受websocket请求和普通http请求
    require_websocket—-只接受websocket请求,拒绝普通http请求

    我这里使用的accept_websocket.但是我没有过滤请求.如果有需求可以使用if request.is_websocket()

    在循环读取文件时出现一个问题.path 拿到的路径在django 启动之后,这个路径读取不到. 但是我单独去跑这个函数用 path 路径可以读取得到.很奇怪.到最后我写的绝对路径.这并没有发现是哪里的问题.

    settings.py

    WEBSOCKET_ACCEPT_ALL=True
    
    • 1

    vue 部分

      created() {
        this.initWebSocket();
      },
      destroyed() {
        this.websock.close() //离开路由之后断开websocket连接
      },
      methods: {
        initWebSocket() { //初始化weosocket
          const wsuri = "ws://127.0.0.1:8000/v1.0/flight/";//django view 请求地址
          this.websock = new WebSocket(wsuri);
          this.websock.onopen = this.websocketonopen;
          this.websock.onmessage = this.websocketonmessage;
          // this.websock.onclose = this.websocketclose;
        },
        websocketonopen() { //连接建立之后执行send方法发送数据
          console.log("链接成功")
          // let actions = {"test":"12345"};
          // this.websocketsend(JSON.stringify(actions));
        },
        websocketonmessage(e) { //数据接收
          let redata=''
          redata = JSON.parse(JSON.parse(e.data))
          console.log(redata)
          }
        },
        websocketsend(Data) {//数据发送
          this.websock.send(Data);
        },
        // websocketclose(e){  //关闭
        //   console.log('断开连接',e);
        // },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
  • 相关阅读:
    回溯法 n皇后
    【个人博客公网访问】使用Cpolar+Emlog在Ubuntu上轻松搭建个人博客公网访问
    剑指offer——JZ24 反转链表 解题思路与具体代码
    全球名校AI课程库(45)| AMMI · 几何深度学习课程『Geometric Deep Learning』
    通天星CMSV6车载监控平台CompanyList信息泄露漏洞
    Volatile和CAS
    Linux邻居协议 学习笔记 之四 通用邻居项创建、查找、删除等相关的函数
    基于51单片机的电子秤LCD1602液晶显示( proteus仿真+程序+设计报告+讲解视频)
    设计模式-抽象工厂模式
    tensorRT简明使用
  • 原文地址:https://blog.csdn.net/qq_40600409/article/details/126300829