search
HomeBackend DevelopmentPython TutorialDetailed explanation of using Websockets in Django

1. Introduction to Websockets

With the development of the Internet, the traditional HTTP protocol has been difficult to meet the increasingly complex needs of Web applications. In recent years, with the birth of HTML5, the WebSocket protocol was proposed, which realizes full-duplex communication between the browser and the server, expands the communication functions between the browser and the server, and enables the server to actively send data to the client.
We know that the traditional HTTP protocol is stateless. Each request (request) must be actively initiated by the client (such as a browser). The server returns the response result after processing, and it is difficult for the server to actively request The client sends data; this traditional Web model in which the client is the active party and the server is the passive party causes less trouble for Web applications where information changes infrequently, but it brings problems to Web applications involving real-time information. A big inconvenience, such as applications with instant messaging, real-time data, subscription push and other functions. Before the WebSocket specification was proposed, developers often used compromise solutions to implement these real-time functions: polling and Comet technologies. In fact, the latter is essentially a kind of polling, but it has been improved.
Polling is the original solution for implementing real-time web applications. Polling technology requires the client to periodically send requests to the server at set intervals and frequently query whether there are new data changes. Obviously, this approach will result in too many unnecessary requests, wasting traffic and server resources.
Comet technology can be divided into long polling and streaming technology. Long polling improves the above polling technology and reduces useless requests. It sets an expiration time for certain data, and sends a request to the server only when the data expires; this mechanism is suitable for situations where data changes are not particularly frequent. Streaming technology usually means that the client uses a hidden window to establish a long HTTP connection with the server. The server will continuously update the connection status to keep the HTTP long connection alive; in this case, the server can actively transfer data through this long connection. Sent to the client; streaming technology may test the performance of the server in a large concurrency environment.
These two technologies are based on the request-response model, and they are not real-time technologies in the true sense; each of their requests and responses wastes a certain amount of traffic on the same header information, and the development complexity Also larger.
Along with the launch of HTML5, WebSocket truly realizes real-time communication on the Web, enabling the B/S mode to have the real-time communication capabilities of the C/S mode. The workflow of WebSocket is as follows: the browser sends a request to the server to establish a WebSocket connection through JavaScript. After the WebSocket connection is successfully established, the client and server can transmit data through the TCP connection. Because the WebSocket connection is essentially a TCP connection, it does not need to carry repeated header data with each transmission, so its data transmission volume is much smaller than polling and Comet technologies.

2. Install dwebsocket

Installation method:

1. Through pip

pip install  dwebsocket2

2. By downloading to local

Execute python setup.py install

Attachment: If the installation fails and prompts about the ASCII code, just delete the content in the readme

3. How to use

If If you want to handle a websocket connection for a separate view you can use the accept_websocket decorator, which will route standard HTTP requests to the view. Using the require_websocke decorator only allows WebSocket connections and will reject normal HTTP requests.

Add the setting MIDDLEWARE_CLASSES=dwebsocket.middleware.WebSocketMiddlewareThis will deny the use of separate views websocket, you must add accept_websocket decoration device.

SettingWEBSOCKET_ACCEPT_ALL=TrueAllows each individual view to be usefulwebsockets

Some methods and properties

1.request.is_websocket()

#If it is a websocket request, it returns True, if it is an ordinary http request, it returns False. You can use this method to distinguish them. .

2.request.websocket

在一个websocket请求建立之后,这个请求将会有一个websocket属性,用来给客户端提供一个简单的api通讯,如果request.is_websocket()是False,这个属性将是None。

3.WebSocket.wait()

返回一个客户端发送的信息,在客户端关闭连接之前他不会返回任何值,这种情况下,方法将返回None

4.WebSocket.read()

 如果没有从客户端接收到新的消息,read方法会返回一个新的消息,如果没有,就不返回。这是一个替代wait的非阻塞方法

5.WebSocket.count_messages()

 返回消息队列数量

6.WebSocket.has_messages()

 如果有新消息返回True,否则返回False

7.WebSocket.send(message)

 向客户端发送消息

8.WebSocket.__iter__()

 websocket迭代器

四、干货

功能:让我们从客户端接收一条消息,将该消息发送回客户端并关闭连接。

1.新建一个django项目

Detailed explanation of using Websockets in Django

2.新建index.html在templates文件夹下,编写我们的客户端

<!DOCTYPE html>
<html>
<head>
    <title>django-websocket</title>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">//<![CDATA[
    $(function () {
        $(&#39;#send_message&#39;).click(function () {
            var socket = new WebSocket("ws://" + window.location.host + "/echo_once");
            socket.onopen = function () {
                console.log(&#39;WebSocket open&#39;);//成功连接上Websocket
                socket.send($(&#39;#message&#39;).val());//发送数据到服务端
            };
            socket.onmessage = function (e) {
                console.log(&#39;message: &#39; + e.data);//打印服务端返回的数据
                $(&#39;#messagecontainer&#39;).prepend(&#39;<p>&#39; + e.data + &#39;</p>&#39;);
            };
        });
    });
    //]]></script>
</head>
<body>
<br>
<input type="text" id="message" value="Hello, World!"/>
<button type="button" id="send_message">发送 message</button>
<h1 id="Received-nbsp-Messages">Received Messages</h1>
<div id="messagecontainer">

</div>
</body>
</html>

3.app的views.py编写我们的服务端

from dwebsocket import require_websocket
@require_websocketdef echo_once(request):
    message = request.websocket.wait()
    request.websocket.send(message)

4.url路由设置

from demo import views as v
urlpatterns = [
    url(r'^index/', v.index),
    url(r'^echo_once', v.echo_once),
]

5.runserver运行,效果展示

Detailed explanation of using Websockets in Django

可以看到,当我们点击按钮之后,服务端发送消息到客户端之后,就自动关闭了连接。

当然,我们也可以让服务端不自动关闭连接,接下来利用websocket和http Get写一个一样的功能的函数,

6.新建一个html,写一个新的客户端

<!DOCTYPE html>
<html>
<head>
    <title>django-websocket</title>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">//<![CDATA[
    $(function () {
        $(&#39;#connect_websocket&#39;).click(function () {
            if (window.s) {
                window.s.close()
            }
            /*创建socket连接*/
            var socket = new WebSocket("ws://" + window.location.host + "/echo");
            socket.onopen = function () {
                console.log(&#39;WebSocket open&#39;);//成功连接上Websocket
            };
            socket.onmessage = function (e) {
                console.log(&#39;message: &#39; + e.data);//打印出服务端返回过来的数据
                $(&#39;#messagecontainer&#39;).prepend(&#39;<p>&#39; + e.data + &#39;</p>&#39;);
            };
            // Call onopen directly if socket is already open
            if (socket.readyState == WebSocket.OPEN) socket.onopen();
            window.s = socket;
        });
        $(&#39;#send_message&#39;).click(function () {
            //如果未连接到websocket
            if (!window.s) {
                alert("websocket未连接.");
            } else {
                window.s.send($(&#39;#message&#39;).val());//通过websocket发送数据
            }
        });
        $(&#39;#close_websocket&#39;).click(function () {
            if (window.s) {
                window.s.close();//关闭websocket
                console.log(&#39;websocket已关闭&#39;);
            }
        });

    });
    //]]></script>
</head>
<body>
<br>
<input type="text" id="message" value="Hello, World!"/>
<button type="button" id="connect_websocket">连接 websocket</button>
<button type="button" id="send_message">发送 message</button>
<button type="button" id="close_websocket">关闭 websocket</button>
<h1 id="Received-nbsp-Messages">Received Messages</h1>
<div id="messagecontainer">

</div>
</body>
</html>

7.在viws.py中加入新的方法

from django.shortcuts import render
from dwebsocket.decorators import accept_websocket,require_websocket
from django.http import HttpResponse


@accept_websocket
def echo(request):
    if not request.is_websocket():#判断是不是websocket连接
        try:#如果是普通的http方法
            message = request.GET[&#39;message&#39;]
            return HttpResponse(message)
        except:
            return render(request,&#39;index.html&#39;)
    else:
        for message in request.websocket:
            request.websocket.send(message)#发送消息到客户端

8.url.py

from demo import views as v
urlpatterns = [
    url(r&#39;^index2/&#39;, v.index2),
    url(r&#39;^echo$&#39;, v.echo),
]

9.runserver运行,看看效果

Detailed explanation of using Websockets in Django

可以看到,只有当我们手动关闭连接时候,websocket才会关闭。

The above is the detailed content of Detailed explanation of using Websockets in Django. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.