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>
    <h1>接受到消息</h1>
    <div id="messagecontainer">

    </div>

</body>
</html>

然后我们运行程序
在这里插入图片描述
十秒之后断开连接得到了我们想要的结果
业务需求的话,可以在我们的test_websocket 修改我们的逻辑然后根据返回的结果进行渲染

  • 技术无止境
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值