溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python中如何使用dwebsocket實(shí)現(xiàn)后端數(shù)據(jù)實(shí)時(shí)刷新

發(fā)布時(shí)間:2023-05-11 10:56:56 來源:億速云 閱讀:119 作者:zzz 欄目:編程語(yǔ)言

本文小編為大家詳細(xì)介紹“Python中如何使用dwebsocket實(shí)現(xiàn)后端數(shù)據(jù)實(shí)時(shí)刷新”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Python中如何使用dwebsocket實(shí)現(xiàn)后端數(shù)據(jù)實(shí)時(shí)刷新”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

執(zhí)行定時(shí)任務(wù)的時(shí)候,我們需要了解執(zhí)行百分比或者實(shí)時(shí)數(shù)據(jù)返回,這時(shí)候可以采用的方法

1.ajax請(qǐng)求后端服務(wù)器,然后前端頁(yè)面局部渲染獲取百分比

2.使用webscoket進(jìn)行長(zhǎng)連接交流刷新

ajax使用方法使用interval函數(shù)來實(shí)現(xiàn)定時(shí)請(qǐng)求,本次這里不做說明

views.py文件添加如下內(nèi)容

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,'websocket_client.html',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文件添加相關(guān)鏈接

urlpatterns = [
    path('test_websocket', views.test_websocket, name='test_websocket'),
    path('test_websocket_client', views.test_websocket_client, name='test_websocket_client'),
]

直接上html代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>dwebsocket實(shí)踐</title>
    <script  src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            // $('#send_message').click(
            //     function() {
                var socket = new WebSocket("ws://" + window.location.host + "/test_websocket");
                socket.onopen = function () {
                    console.log('WebSocket open');//成功連接上Websocket
                    // socket.send($('#message').val());//發(fā)送數(shù)據(jù)到服務(wù)端
                };
                socket.onmessage = function (e) {
                    // console.log('message: ' + e.data);//打印服務(wù)端返回的數(shù)據(jù)
                    $('#messagecontainer').text('<p>' + JSON.parse(e.data).client_msg + '</p>'+'<p>' + JSON.parse(e.data).server_msg + '</p>');
                    // $('#messagecontainer').text('<p>' + JSON.parse(e.data).server_msg + '</p>');
                };
                socket.onclose=function () {
                    console.log("連接已關(guān)閉")
                }
            // });
        });
    </script>
</head>
<body>
    <input type="text" id="message" value="請(qǐng)輸入發(fā)送消息!" />
    <button type="button" id="send_message">send message</button>
    <h3>接受到消息</h3>
    <div id="messagecontainer">
    </div>
</body>
</html>

然后我們運(yùn)行程序

Python中如何使用dwebsocket實(shí)現(xiàn)后端數(shù)據(jù)實(shí)時(shí)刷新

十秒之后斷開連接得到了我們想要的結(jié)果

業(yè)務(wù)需求的話,可以在我們的test_websocket 修改我們的邏輯然后根據(jù)返回的結(jié)果進(jìn)行渲染

讀到這里,這篇“Python中如何使用dwebsocket實(shí)現(xiàn)后端數(shù)據(jù)實(shí)時(shí)刷新”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI