温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中怎么使用dwebsocket实现后端数据实时刷新

发布时间:2023-04-28 11:03:45 来源:亿速云 阅读:83 作者:iii 栏目:开发技术

本篇内容介绍了“Python中怎么使用dwebsocket实现后端数据实时刷新”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

执行定时任务的时候,我们需要了解执行百分比或者实时数据返回,这时候可以采用的方法

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,'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文件添加相关链接

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实践</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());//发送数据到服务端
                };
                socket.onmessage = function (e) {
                    // console.log('message: ' + e.data);//打印服务端返回的数据
                    $('#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("连接已关闭")
                }
            // });
        });
    </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实现后端数据实时刷新

十秒之后断开连接得到了我们想要的结果

业务需求的话,可以在我们的test_websocket 修改我们的逻辑然后根据返回的结果进行渲染

“Python中怎么使用dwebsocket实现后端数据实时刷新”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI