Django channels to realize websocket real-time communication

The operation and maintenance platform must have such a scenario, that is, it needs to obtain the back-end data in real time, such as the results of batch execution, or the status of monitoring. If the browser frequently requests the back-end interface to update the data, it seems a little low

So it is easy to learn how django supports websocket long connection so that it can be integrated into the project later

To install channels:

pip3 install channels

First register channels to the app:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'channels',
'app',
'websocket',
'django_celery_beat',
'django_celery_results',
]

Specify the ASIG routing address in the configuration file, because django defaults to wsgi protocol, and channels implements websocket through ASIG and asynchronous gateway protocol

ASGI_APPLICATION = 'captain.routing.application'

Then start django:

Create a separate app:

python manage.py startapp websocket

Create in project directory asgi.py File:

"""
ASGI entrypoint. Configures Django and then runs the application
defined in the ASGI_APPLICATION setting.
"""
import os
import django
from channels.routing import get_default_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'captain.settings')
django.setup()
application = get_default_application()

Create a routing file in the project directory:

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


Create a routing file under the app to bind the path to the function that processes the webssocket request:

from django.urls import path
from websocket.consumers import ChatConsumer
websocket_urlpatterns = [
path('ws/chat/', ChatConsumer),
]


Create a view under the app to process the request function:

from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
class ChatConsumer(WebsocketConsumer):
def websocket_connect(self, message):
"""
        //The client sends the request in, triggering this method
        :param message:
        :return:
        """
self.accept()
def websocket_receive(self, message):
"""
        //The client sends a message, triggers this method, and returns data
        :param message:
        :return:
        """
print(message)
msg = message['text']
self.send(msg)
def websocket_disconnect(self, message):
"""
        //The client actively disconnects the link, triggering this method
        :param message:
        :return:
        """
#Server triggers exception StopConsumer
raise StopConsumer

To create a front-end test file:

➜  ~ cat socket.html
<div>
    <div>
        <input type="text" id="txt">
        <input type="button" value="send" onclick="sendMsg();">
        <input type="button" value="close" onclick="closeConn();">
    </div>
    <h2>Chat record</h2>
    <div id="content">
    </div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script>
    var ws = new WebSocket("ws://127.0.0.1:8088/ws/chat/");
    ws.onopen = function(){
        //After the client verification handshake is completed, the method is automatically executed
        console.log("Link success...")
    };
    ws.onmessage = function (event) {
        //Accept messages sent by the server
        //Trigger this method after client completes handshake verification
        console.log(event.data);
        var tag = $("<div>");
        tag.text(event.data);
        $("#content").append(tag);
        console.log(1)
    };
    function sendMsg() {
        //  ws.send(): send message
      ws.send($("#txt").val());
    };
    function closeConn() {
        //  ws.close(): close Websocket link
        console.log("Disconnect...");
        ws.close();
    };
</script>


A simple chat room is created

Tags: Linux Django JQuery Python socket

Posted on Wed, 20 May 2020 11:17:09 -0400 by Zergman