后台代码:
@accept_websocket # websocket实时传递变更申请至前端
def get_list(request):
while True:
time.sleep(15)
queryset = ChangeApplicationInfoModel.objects.filter(is_remain=0).order_by("-fd_time")
data_list = []
m = 0
if queryset:
for obj in queryset:
try:
m += 1
str1 = datetime.datetime.strftime(obj.fd_time, "%Y/%m/%d %H:%M:%S")
change_str = obj.fd_name + " " + str1 + " 申请单" + obj.fd_oa_number + "变更"
data_list.append(change_str)
except Exception as e:
print('')
print(data_list)
print(datetime.datetime.now())
request.websocket.send(json.dumps({"list1": data_list}))
只需要在视图函数的函数名上加上装饰器即可实现 ,实现了一次前端发送的连接,后台可以一直向前端推送数据
前端代码:
WebSocketTest(){
if ("WebSocket" in window)
{
let vm = this;
// this.lists = [1, 2, 3]
vm.lists = [];
vm.ws = new WebSocket("ws://172.30.244.17:8000/receive/get_list/");
vm.ws.onopen = function () {
console.log('WebSocket open');//成功连接上Websocket
};
vm.ws.onmessage = function (e) {
var res= $.parseJSON(e.data);
vm.lists = res.list1;
console.log(vm.lists); // 此处有值[1,2,3], 但是未能赋值给变量,原因是this指向错误!!
};
}else{
// 浏览器不支持 WebSocket
alert("您的浏览器不支持 WebSocket!");
}
},