执行定时任务的时候,我们需要了解执行百分比或者实时数据返回,这时候可以采用的方法
1.ajax请求后端服务器,然后前端页面局部渲染获取百分比
2.使用webscoket进行长连接交流刷新
ajax使用方法使用interval函数来实现定时请求,本次这里不做说明
views.py文件添加如下内容
立即学习“Python免费学习笔记(深入)”;
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代码
Snowy(SnowyAdmin)是国内首个国密前后端分离快速开发平台,集成国密加解密插件, 软件层面完全符合等保测评要求,同时实现国产化机型、中间件、数据库适配,是您的不二之选! 技术框架与密码结合,让更多的人认识密码,使用密码;更是让前后分离“密”不可分。采用SpringBoot+MybatisPlus+AntDesignVue+Vite 等更多组件及前沿技术开发,注释丰富,代码简洁,开箱即用
dwebsocket实践
接受到消息
然后我们运行程序

十秒之后断开连接得到了我们想要的结果
业务需求的话,可以在我们的test_websocket 修改我们的逻辑然后根据返回的结果进行渲染










