django实现websocket大致上有两种方式,一种channels,一种是dwebsocket。channels依赖于redis,twisted等
一 dwebsocket#
1 Django实现Websocket#
django实现websocket大致上有两种方式,一种channels,一种是dwebsocket。channels依赖于redis,twisted等,相比之下使用dwebsocket要更为方便一些
2 dwebsocket安装#
pip3 install dwebsocket
3 dwebsocket配置#
setting 设置#
INSTALLED_APPS = 【
...
...
'dwebsocket'
】
import dwebsocket
MIDDLEWARE_CLASSES = 【
'dwebsocket.middleware.WebSocketMiddleware' # 为所有的URL提供websocket,如果只是单独的视图需要可以不选
】
WEBSOCKET_ACCEPT_ALL=True # 可以允许每一个单独的视图实用websockets
urls.py#
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = 【
url(r'^admin/', admin.site.urls),
url(r'^login/', views.login),
url(r'^path/', views.path),
】
views.py#
from django.shortcuts import render
def login(request):
return render(request, 'index.html')
from dwebsocket.decorators import accept_websocket
@accept_websocket
def path(request):
if request.is_websocket():
print(1)
request.websocket.send('下载完成'.encode('utf-8'))
html#