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:


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 startapp websocket

Create in project directory 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')
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(

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:
def websocket_receive(self, message):
        //The client sends a message, triggers this method, and returns data
        :param message:
msg = message['text']
def websocket_disconnect(self, message):
        //The client actively disconnects the link, triggering this method
        :param message:
#Server triggers exception StopConsumer
raise StopConsumer

To create a front-end test file:

➜  ~ cat socket.html
        <input type="text" id="txt">
        <input type="button" value="send" onclick="sendMsg();">
        <input type="button" value="close" onclick="closeConn();">
    <h2>Chat record</h2>
    <div id="content">
<script src=""></script>
    var ws = new WebSocket("ws://");
    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
        var tag = $("<div>");
    function sendMsg() {
        //  ws.send(): send message
    function closeConn() {
        //  ws.close(): close Websocket link

A simple chat room is created

Tags: Linux Django JQuery Python socket

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