最近做了一个项目,需要后端主动与前端进行通信,官方推荐使用的是channels(channels官方文档). 把我的使用经历以及部署过程,记录一下,这篇文章主要记录使用 uwsgi, nginx, supervisor,daphne部署过程,有时间的会把我用docker 部署的经历也写一下.
安装channels,使用websocket
- 下载channels
pip install channels
- 项目中配置channels ,在
settings
文件的INSTALLED_APPS
加入channels
- 在项目中新建
routing.py
文件,用来生成websocket的路由,这里我的文件和官方的不太一样,但是最终的效果是一样的,就像我们平时写urls.py
的路由一样,一个在应用目录下,一个在项目下.我把routing.py
建在应用目录下.
(1) 这是我的项目的目录结构,以及我的routing.py
文件的位置
(2) 这是routing.py
文件的内容,具体写什么,先空着,一步一步来完善
from django.urls import path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from struction.consumers import SendConsumer
application = ProtocolTypeRouter({
# WebSocket chat handler
"websocket": AuthMiddlewareStack(
URLRouter([
])
),
})
(3) routing.py
文件创建完成之后,在settings.py
进行配置
#websocket
ASGI_APPLICATION = "struction.routing.application" # 上面新建的 asgi 应用
- 然后在
struction
应用下新建一个consumers.py
文件用来写websocket通信的业务逻辑
官方文档中的案例是做一个聊天室,我实际的项目需求只需要给前端发消息,不需要做到官方文档中那样,所以在websocket的通信这部分做了修改.
import json
import time
from channels.generic.websocket import WebsocketConsumer
class SendConsumer(WebsocketConsumer):
def connect(self):
self.accept()
# # 断开连接
def disconnect(self, close_code):
# Leave room group
pass
# # 接受消息
def receive(self, text_data=None, bytes_data=None):
# 和前端通信接收前端的消息
text_data_json = json.loads(text_data)
message = text_data_json['message']
print(text_data_json, 'websocket-----------')
# 这个代码测试用,给前端发消息,我这里的是测试的demo,前端给我发什么,我回什么
self.send(text_data=json.dumps({
# 'message': json.dumps(msg)
'time': time.time(),
'message': message
}))
- 完成之后,在
routing.py
配置路由
from django.urls import path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from struction.consumers import SendConsumer
application = ProtocolTypeRouter({
# WebSocket chat handler
"websocket": AuthMiddlewareStack(
URLRouter([
# 这个就是前端与websocket通信时访问的路由
path("ws/channel/websocket/"