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, AsyncWebsocketConsumer
from channels.layers import get_channel_layer
import time
channel_layer = get_channel_layer()
from apply.models import UpCodeInfo
import json

class ExecConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        print('ws连接')
        # 创建channels group, 命名为:用户名,并使用channel_layer写入到redis
        await self.channel_layer.group_add(self.scope['user'].username, self.channel_name)

        # 返回给receive方法处理
        await self.accept()

    async def receive(self, text_data):
        if len(text_data) == 1:
            id_list = [text_data]
        else:
            id_list = eval(text_data)
        data = {}

        for i in id_list:
            data[i] = UpCodeInfo.objects.get(id=int(i)).progress_bar
        await self.channel_layer.group_send(
            self.scope['user'].username,
            {
                "type": "user.message",
                "text": json.dumps(data),
            },
        )

    async def user_message(self, event):
        # 消费
        await self.send(text_data=event["text"])

    async def disconnect(self, close_code):
        print("关闭ws", close_code)
        await 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),
        ])
    )
})

前端