django 实现前端 进度条
后端
安装模块
channels==2.1.5
channels-redis==2.3.1
anyjson==0.3.3
asgi-redis==1.4.3
asgiref==2.3.0
asn1crypto==0.24.0
async-timeout==2.0.1
Twisted==18.9.0
启动一个redis
新建django程序 quan
目录结构
quan
quan
asgi.py
consumers.py
routing.py
settings.py
settings.py
INSTALLED_APPS = [
‘channels‘,
]
# django-channels配置
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("127.0.0.1", 6379)],
},
},
}
# 配置ASGI
ASGI_APPLICATION = "quan.routing.application"
asgi.py
import os
import django
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "quan.settings")
django.setup()
application = get_default_application()
consumers.py
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from channels.layers import get_channel_layer
channel_layer = get_channel_layer()
import json
import time
class ExecConsumer(WebsocketConsumer):
def connect(self):
print(‘ws连接‘)
# 创建channels group, 命名为:用户名,并使用channel_layer写入到redis
async_to_sync(self.channel_layer.group_add)(self.scope[‘user‘].username, self.channel_name)
# 返回给receive方法处理
self.accept()
def receive(self, text_data):
id_list = eval(text_data)
data = {‘1‘:99}
async_to_sync(self.channel_layer.group_send)(
self.scope[‘user‘].username,
{
"type": "user.message",
"text": json.dumps(data),
},
)
def user_message(self, event):
# 消费
self.send(text_data=event["text"])
def disconnect(self, close_code):
print("关闭ws")
async_to_sync(self.channel_layer.group_discard)(self.scope[‘user‘].username, self.channel_name)
routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import URLRouter, ProtocolTypeRouter
from django.urls import path
from .consumers import ExecConsumer
application = ProtocolTypeRouter({
"websocket": AuthMiddlewareStack(
URLRouter([
path(r"progress/", ExecConsumer),
])
)
})
前端
<script>
var socket = new WebSocket(‘ws://‘ + window.location.host + ‘/progress/‘);
var id_list = [];
$(".dataTables").find("tr").each(function () {
var tdArr = $(this).children();
var id = tdArr.eq(0).text();
id_list.push(id)
});
id_list.splice(0, 1);
var to = function () {
socket.send(id_list);
};
socket.onopen = function () {
setInterval(to, 1000);
};
//获得消息事件
socket.onmessage = function (msg) {
console.log(msg.data);
var data = msg.data;
var obj = JSON.parse(data);
$.each(obj, function (key, val) {
$(‘#‘ + key).children(‘td‘).eq(7).html(val + ‘%‘)
});
};
//关闭事件
socket.onclose = function () {
{#alert("Socket已关闭");#}
};
//发生了错误事件
socket.onerror = function () {
{#alert("发生了错误");#}
}
</script>
原文地址:http://blog.51cto.com/hequan/2322751
时间: 2024-10-02 00:21:13