执行定时任务的时候,我们需要了解执行百分比或者实时数据返回,这时候可以采用的方法
1.ajax请求后端服务器,然后前端页面局部渲染获取百分比
2.使用webscoket进行长连接交流刷新
ajax使用方法使用interval函数来实现定时请求,本次这里不做说明
views.py文件添加如下内容
立即学习“Python免费学习笔记(深入)”;
from django.shortcuts import render,HttpResponsefrom dwebsocket.decorators import accept_websocketimport time,randomimport uuidimport json@accept_websocketdef 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 cntsettings.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代码
nbsp;html>dwebsocket实践 $(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('' + JSON.parse(e.data).client_msg + ''+'
' + JSON.parse(e.data).server_msg + ''); // $('#messagecontainer').text('
' + JSON.parse(e.data).server_msg + ''); }; socket.onclose=function () { console.log("连接已关闭") } // }); });
接受到消息
登录后复制
然后我们运行程序
十秒之后断开连接得到了我们想要的结果
业务需求的话,可以在我们的test_websocket 修改我们的逻辑然后根据返回的结果进行渲染
以上就是Python中怎么使用dwebsocket实现后端数据实时刷新的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2236706.html