• 【Python/前端】Django创建ws/websocket接口 并供前端(vue)消费


    一、后端

    python、django(channels)

    1.1、安装channels

    pip install channels
    pip install channels_redis

    1.2、配置项目settings.py文件中的INSTALLED_APPS

    新增channels项目主站名称

    1.3、配置项目settings.py文件中新增ASGI_APPLICATION

    1.4、在APP(子站)中新建routing.py文件

    from django.conf.urls import url
    
    from myChat.conView import ChatService
    
    websocket_urlpatterns = [
        url(r"ws/", ChatService()),
    ]

    1.5、在APP(子站)中新建conView.py文件

    import json
    import time
    
    from channels.generic.websocket import WebsocketConsumer
    
    
    class ChatService(WebsocketConsumer):
        # 当Websocket创建连接时
        def connect(self):
            print("已连接")
            self.accept()
            # 每隔2秒给前端发送数据
            for i in range(10):
                time.sleep(2)
                self.send(text_data=json.dumps({
                    'code': 200,
                    'message': "djhafkja"
                }))
    
        # 当Websocket接收到消息时
        def receive(self, text_data=None, bytes_data=None):
            print("已收到消息")
    
        # 当Websocket发生断开连接时
        def disconnect(self, code):
            print("已断开")

    1.6、在项目(主站)中新建routing.py文件 

    from channels.auth import AuthMiddlewareStack
    from channels.routing import ProtocolTypeRouter, URLRouter
    
    import myChat.routing
    
    application = ProtocolTypeRouter({
        "websocket": AuthMiddlewareStack(
            URLRouter(
                myChat.routing.websocket_urlpatterns
            )
        ),
    })

    1.7、启动

    python .\manage.py runserver

    二、前端

    vue

        initWebSocket() {
          this.websock = new WebSocket("ws://127.0.0.1:8000/ws/");
          this.websock.onmessage = this.WebSocketOnMessage;
          this.websock.onopen = this.WebSocketOnOpen;
          this.websock.onerror = this.WebSocketOnError;
          this.websock.onclose = this.WebSocketOnClose;
        },
    
        WebSocketOnMessage(e) {
          this.msg.push(JSON.parse(e.data).message);
          console.log("WebSocketOnMessage");
          console.log(e);
          console.log(JSON.parse(e.data).message);
        },
    
        WebSocketOnOpen(e) {
          console.log("WebSocketOnOpen");
          console.log(e);
        },
    
        WebSocketOnError(e) {
          console.log("WebSocketOnError");
          console.log(e);
        },
    
        WebSocketOnClose(e) {
          console.log("WebSocketOnClose");
          console.log(e);
          console.log(e.code);
        },

    三、效果

    如果忍耐算是坚强 我选择抵抗 如果妥协算是努力 我选择争取
  • 相关阅读:
    jQuery UI炫酷雨滴落在水面上的波纹涟漪特效
    mysql_jdbc
    数据库设计---合适的就是最好的
    谈谈 .NET Reflector
    整型反序
    iOS给Model排序
    php安装zendDebug
    zTree实现地市县三级级联封装类
    rnnlm源代码分析(八)
    CSS制作响应式正方形及其应用
  • 原文地址:https://www.cnblogs.com/danhuai/p/15774318.html
Copyright © 2020-2023  润新知