django实现websocket大致上有两种方式,一种channels,一种是dwebsocket。channels依赖于redis,twisted等,相比之下使用dwebsocket要更为方便一些。
安装:
pip install dwebsocket
配置:
# setting.py
INSTALLED_APPS = [
.....
.....
'dwebsocket',
]
MIDDLEWARE_CLASSES = [
......
......
'dwebsocket.middleware.WebSocketMiddleware' # 为所有的URL提供websocket,如果只是单独的视图需要可以不选
]
WEBSOCKET_ACCEPT_ALL=True # 可以允许每一个单独的视图实用websockets
简单使用:
模拟文件下载的简单示例
from dwebsocket.decorators import accept_websocket
@accept_websocket
def test(request):
if not request.is_websocket(): # 判断是不是websocket连接
return render(request, 'websocket.html')
else:
download = Haproxy()
t = threading.Thread(target=download.run)
t.start()
sent = []
while download.status:
if len(download.res_dict) >