一个需求,需要读取一个 json 文件然后推送给前端
这里选择用的 dwebsocket,相比channels更简单一些
pip install dwebsocket
from dwebsocket.decorators import accept_websocket,require_websocket
import sys,os
import time
import json
from django.http import HttpResponse
def read():
path=os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),'xxx/public.json')
with open("xxx/public.json",'r',encoding='utf8') as f:
return f.read()
@accept_websocket
def demo_api(request):
while 1:
txt=read()
time.sleep(3)
request.websocket.send(json.dumps(txt))
return HttpResponse('ok')
demo_api是主要函数.
@accept_websocket给需要进行 websocket 通信的函数加上装饰器
accept_websocket-—可以接受websocket请求和普通http请求
require_websocket—-只接受websocket请求,拒绝普通http请求
我这里使用的accept_websocket.但是我没有过滤请求.如果有需求可以使用if request.is_websocket()
在循环读取文件时出现一个问题.path 拿到的路径在django 启动之后,这个路径读取不到. 但是我单独去跑这个函数用 path 路径可以读取得到.很奇怪.到最后我写的绝对路径.这并没有发现是哪里的问题.
WEBSOCKET_ACCEPT_ALL=True
created() {
this.initWebSocket();
},
destroyed() {
this.websock.close() //离开路由之后断开websocket连接
},
methods: {
initWebSocket() { //初始化weosocket
const wsuri = "ws://127.0.0.1:8000/v1.0/flight/";//django view 请求地址
this.websock = new WebSocket(wsuri);
this.websock.onopen = this.websocketonopen;
this.websock.onmessage = this.websocketonmessage;
// this.websock.onclose = this.websocketclose;
},
websocketonopen() { //连接建立之后执行send方法发送数据
console.log("链接成功")
// let actions = {"test":"12345"};
// this.websocketsend(JSON.stringify(actions));
},
websocketonmessage(e) { //数据接收
let redata=''
redata = JSON.parse(JSON.parse(e.data))
console.log(redata)
}
},
websocketsend(Data) {//数据发送
this.websock.send(Data);
},
// websocketclose(e){ //关闭
// console.log('断开连接',e);
// },