使用websockets,后台实时发数据,前台实时接受数据,并集成到Django
生活随笔
收集整理的這篇文章主要介紹了
使用websockets,后台实时发数据,前台实时接受数据,并集成到Django
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
后端代碼
#!/usr/bin/env python# WS server that sends messages at random intervalsimport asyncio import websockets import time import random import json from datetime import datetimeasync def my_test(websocket, path):while True:camera_ip = '10.192.49.1'server_ip = '10.193.33.139'server_port = '8000'a = random.randint(1000, 10000)b = random.randint(10, 200)c = random.randint(20, 40)numlist = [a, b, int(a/b), c]worklist = []for i in range(10):id = itime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")count = random.randint(20, 40)path = "./html/results/test.jpg"worklist.append([id, time, count, path])daycount = random.randint(30, 200)nightcount = random.randint(30, 200)dayratio = int((daycount / (daycount + nightcount)) * 100)nightratio = 100 - dayratiodaynight = [[dayratio, daycount], [nightratio, nightcount]]real_time_img = "static/results/test11.jpg"recognize_result_img = "static/results/test22.jpg"save_origine_img = "static/results/test33.jpg"return_dict = dict(server_ip=server_ip,server_port=server_port,camera_ip = camera_ip,numlist=numlist,worklist=worklist,real_time_img=real_time_img,recognize_result_img=recognize_result_img,save_origine_img=save_origine_img,daynight = daynight)return_dict = json.dumps(return_dict)await websocket.send(return_dict)await asyncio.sleep(1)async def main():async with websockets.serve(my_test, "10.193.33.139", 1234):await asyncio.Future()asyncio.get_event_loop().run_until_complete(main())前端代碼:
<script type="text/javascript">var websocket = new WebSocket("ws://10.193.33.139:1234");//連接成功建立的回調方法// websocket.onopen = function () {// window.alert('連接成功')// };// 前端接收后端傳來的消息websocket.onmessage = function(event) {var infodic = JSON.parse(event.data);document.getElementById('server_IP').innerText = "服務器IP: " + infodic.server_ip;document.getElementById('server_port').innerText = "服務器端口:" + infodic.server_port;document.getElementById('camera_IP').innerText = "攝像頭IP:" + infodic.camera_ip;// 設置數字document.getElementById('num1').innerText = infodic.numlist[0];document.getElementById('num2').innerText = infodic.numlist[1];document.getElementById('num3').innerText = infodic.numlist[2];document.getElementById('num4').innerText = infodic.numlist[3];// 設置圖片document.getElementById('real_time_img').setAttribute("src", infodic.real_time_img) document.getElementById('real_time_img_light').setAttribute("src", infodic.real_time_img) document.getElementById('recognize_result_img').setAttribute("src", infodic.recognize_result_img) document.getElementById('recognize_result_img_light').setAttribute("src", infodic.recognize_result_img) document.getElementById('save_origine_img').setAttribute("src", infodic.save_origine_img) document.getElementById('save_origine_img_light').setAttribute("src", infodic.save_origine_img)// 設置表格for (var i = 0; i < 9; i++) {document.getElementById('work_id_' + (i + 1)).innerText = infodic.worklist[i][0];document.getElementById('work_time_' + (i + 1)).innerText = infodic.worklist[i][1];document.getElementById('work_count_' + (i + 1)).innerText = infodic.worklist[i][2];document.getElementById('work_save_' + (i + 1)).innerText = infodic.worklist[i][3];}// 設置扇形圖jQuery(document).ready(function($) {var donut_chart_demo = $("#donut-chart-demo");donut_chart_demo.empty() donut_chart_demo.parent().show();var donut_chart = Morris.Donut({element: 'donut-chart-demo',data: [{label: "白天紙漿總量(" + infodic.daynight[0][0] + "%)",value: infodic.daynight[0][1]},{label: "夜晚紙漿總量(" + infodic.daynight[1][0] + "%)",value: infodic.daynight[1][1]}],colors: ['#707f9b', '#242d3c']});donut_chart_demo.parent().attr('style', '');});};//連接關閉的回調方法websocket.onclose = function() {websocket.close();// window.alert('連接已斷開或未連接')};//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。window.onbeforeunload = function() {websocket.close();};//關閉連接function closeWebSocket() {websocket.close();// window.clearInterval(intervalId);} </script>?
集成到Django的manage.py 文件時,后端代碼:
#!/usr/bin/env python# WS server that sends messages at random intervalsimport asyncio import websockets import random import json import threading from datetime import datetimeasync def runner(websocket, path):while True:camera_ip = '10.192.49.1'server_ip = '10.193.33.139'server_port = '8000'a = random.randint(1000, 10000)b = random.randint(10, 200)c = random.randint(20, 40)numlist = [a, b, int(a/b), c]worklist = []for i in range(10):id = itime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")count = random.randint(20, 40)path = "./html/results/test.jpg"worklist.append([id, time, count, path])daycount = random.randint(30, 200)nightcount = random.randint(30, 200)dayratio = int((daycount / (daycount + nightcount)) * 100)nightratio = 100 - dayratiodaynight = [[dayratio, daycount], [nightratio, nightcount]]real_time_img = "static/results/test11.jpg"recognize_result_img = "static/results/test22.jpg"save_origine_img = "static/results/test33.jpg"return_dict = dict(server_ip=server_ip,server_port=server_port,camera_ip = camera_ip,numlist=numlist,worklist=worklist,real_time_img=real_time_img,recognize_result_img=recognize_result_img,save_origine_img=save_origine_img,daynight = daynight)return_dict = json.dumps(return_dict)await websocket.send(return_dict)await asyncio.sleep(1)async def main():async with websockets.serve(runner, "10.193.33.139", 1234):await asyncio.Future()class MyThread (threading.Thread):def __init__(self, threadID, name):threading.Thread.__init__(self)self.threadID = threadIDself.name = namedef run(self):print("開始線程:" + self.name)# loop = asyncio.get_event_loop().run_until_complete(main())# asyncio.set_event_loop(loop)asyncio.set_event_loop(asyncio.new_event_loop())loop = asyncio.get_event_loop()loop.run_until_complete(main())print("退出線程:" + self.name)def myApplication():thread = MyThread(1, "Thread-1")thread.start()?
當出現以下錯誤時:
RuntimeError: There is no current event loop in thread 'Thread-1'.在調用協程語句前加入下述語句即可解決:
asyncio.set_event_loop(asyncio.new_event_loop())參考:Tornado5 執行線程時報錯:RuntimeError: There is no current event loop in thread 'Thread-1'._jusang486的專欄-CSDN博客https://blog.csdn.net/jusang486/article/details/82382358?(1條消息) python協程系列(六)——asyncio的EventLoop以及Future詳解_MIss-Y的博客-CSDN博客https://blog.csdn.net/qq_27825451/article/details/86292513
總結
以上是生活随笔為你收集整理的使用websockets,后台实时发数据,前台实时接受数据,并集成到Django的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Django 一些 简单 配置
- 下一篇: 可视化COCO分割标注文件,以及单个js