ホームページ  >  記事  >  バックエンド開発  >  Python で dwebsocket を使用してバックエンド データのリアルタイム更新を実現する方法

Python で dwebsocket を使用してバックエンド データのリアルタイム更新を実現する方法

王林
王林転載
2023-05-10 15:34:06932ブラウズ

スケジュールされたタスクを実行するとき、実行率またはリアルタイム データの返還を知る必要があります。このときに使用できる方法は

1 です。Ajax がバックエンド サーバーに要求し、その後、フロントエンド ページが部分的にレンダリングされてパーセンテージを取得します

2. 長時間の接続通信には webscoket を使用し、更新します

Ajax の使用法では、interval 関数を使用してタイミング リクエストを実装します。

次の内容を views.py ファイルに追加します

from django.shortcuts import render,HttpResponse
from dwebsocket.decorators import accept_websocket
import time,random
import uuid
import json
@accept_websocket
def test_websocket(request):
    cnt=1
    if request.is_websocket():
        while True:
            messages = {
                'time': time.strftime('%Y.%m.%d %H:%M:%S', time.localtime(time.time())),
                'server_msg': 'hello%s'%time.time(),
                'client_msg': 'msg%s'%time.time()
            }
            time.sleep(1)
            cnt+=1
            if cnt<=10:
                request.websocket.send(json.dumps(messages))
            else:
                break

def test_websocket_client(request):
    return  render(request,&#39;websocket_client.html&#39;,locals())

Settings.py ファイルに dwebsocket を追加します

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages ',
'django.contrib.staticfiles',
'dwebsocket'
]

関連リンクを urls.py ファイルに追加します

urlpatterns = [
    path(&#39;test_websocket&#39;, views.test_websocket, name=&#39;test_websocket&#39;),
    path(&#39;test_websocket_client&#39;, views.test_websocket_client, name=&#39;test_websocket_client&#39;),
]

直接アップロードHTML コード

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>dwebsocket实践</title>
    <script  src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            // $(&#39;#send_message&#39;).click(
            //     function() {
                var socket = new WebSocket("ws://" + window.location.host + "/test_websocket");
                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;).text(&#39;<p>&#39; + JSON.parse(e.data).client_msg + &#39;</p>&#39;+&#39;<p>&#39; + JSON.parse(e.data).server_msg + &#39;</p>&#39;);
                    // $(&#39;#messagecontainer&#39;).text(&#39;<p>&#39; + JSON.parse(e.data).server_msg + &#39;</p>&#39;);
                };
                socket.onclose=function () {
                    console.log("连接已关闭")
                }
            // });
        });
    </script>
</head>
<body>
    <input type="text" id="message" value="请输入发送消息!" />
    <button type="button" id="send_message">send message</button>
    <h2>接受到消息</h2>
    <div id="messagecontainer">
    </div>
</body>
</html>

次にプログラムを実行します

Python で dwebsocket を使用してバックエンド データのリアルタイム更新を実現する方法

10 秒後に切断すると、望む結果が得られます

用事がある場合必要に応じて、test_websocket のロジックを変更し、返された結果に基づいてレンダリングできます

以上がPython で dwebsocket を使用してバックエンド データのリアルタイム更新を実現する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。