先用pip install websocket安装;
1.配置路由url.py
2在views中的操作:
新增
from dwebsocket.decorators import accept_websocket,require_websocket
@accept_websocket
def mywebsocket(request):
judgelis = ['judge1','judge2','judge3','judge4','judge5','judge6','judge7','judge8','min_score','max_score','mean_score']
judgelist= []
if request.is_websocket():
while 1:
time.sleep(1) ## 向前端发送时间
judgelistem = []
groups = Groups.objects.all()
for group in groups:
dictem = {}
for sco in judgelis:
if getattr(group,sco) == 0:
dictem[sco] = ''
else:
dictem[sco] = getattr(group,sco)
judgelistem.append(dictem)
if judgelistem != judgelist:
judgelist = copy.deepcopy(judgelistem)
request.websocket.send(json.dumps({'content':judgelist}))
在前端的操作:
function mywebsocket(){
console.log(1);
ws = new WebSocket('ws://127.0.0.1:8000/display/mark/websocket');
ws.onopen = function(){
ws.send('发送数据中....')
};
ws.onmessage = function (e){
let received_meg =$.parseJSON(e.data).content;
console.log('接收数据.....');
console.log(received_meg);
};
ws.onclose = function(){
console.log('链接已断开.....');
};
};