from dwebsocket.decorators import accept_websocket websocketlist = [] @accept_websocket def websocketLink(request): if request.is_websocket: websocketlist.append(request.websocket) for message in request.websocket: break # 发送消息 def send(): sql = "select name,jifen from zusers" res = db1.findall(sql) if websocketlist: for i in websocketlist: mes = [] for j in res: mes.append({'name': j['name'], 'value': j['jifen']}) print(mes) b1 = json.dumps(mes, ensure_ascii=False).encode('utf-8') i.send(b1) return HttpResponse('ok') from apscheduler.schedulers.background import BackgroundScheduler def test1(request): scheduler = BackgroundScheduler() # 添加调度任务 # 调度方法为 timedTask,触发器选择 interval(间隔性),间隔时长为 2 秒 scheduler.add_job(send, 'interval', seconds=5) # 启动调度任务 scheduler.start() return HttpResponse('ok')
这是django的基本代码,配好路由,访问定时器接口,就可以了
setup() { let customerlist = reactive({'data': []}) //初始化websocket const initWebsocket = () => { let socket = new WebSocket('ws://127.0.0.1:8000/websocketLink/') //建立 socket.onopen = function () { console.log('建立连接') } //接收消息 socket.onmessage = function (msg) { customerlist.data = JSON.parse(msg.data) console.log(customerlist) //调用echarts } return { customerlist, initWebsocket } },
这是前端的代码,我这里用的是vue,首先跟后端建立连接,建立完成后接受消息,最后渲染到页面。这样就实现了前后端简单的websocket连接