django-websocket 安装及配置
1、安装 dwebsocket
(venv) C:\code_object\websocketTest>pip install dwebsocket -i https://pypi.douban.com/simple
2、当前项目环境
python版本
1 (venv) C:\code_object\websocketTest>python --version
2 Python 3.4.4
django版本
1 (venv) C:\code_object\websocketTest>pip list dwebsocket
2 Django (1.10)
3 dwebsocket (0.5.5)
4 pip (9.0.1)
5 setuptools (28.8.0)
6 six (1.11.0)
3、相关代码
urls.py
1 from django.conf.urls import url, include
2
3 from websocketTest import views
4 urlpatterns = [
5 url(r'^websocket/', views.websocket_test),
6 url(r'^echo/', views.echo),
7 ]
views.py
1 from dwebsocket import require_websocket,accept_websocket
2 import dwebsocket
3
4 from django.http.response import HttpResponse
5 from django.shortcuts import render
6 import json
7
8 import redis
9 rc = redis.StrictRedis(host='redis_host', port=6379, db=8, decode_responses=True)
10
11
12 @require_websocket # 只接受websocket请求,不接受http请求,这是调用了dwebsocket的装饰器
13 def websocket_test(request):
14 message = request.websocket.wait()
15 request.websocket.send(message)
16
17
18 @accept_websocket # 既能接受http也能接受websocket请求
19 def echo(request):
20 if not request.is_websocket():
21 try:
22 prin