websocket的配置 Daphne + Channels
常规的视图函数进行的是http请求,Django中使用channels库将websocket请求添加到部分子路由中
1,在项目同名子目录下添加routing,py文件
# mysite/routing.py
from channels.routing import ProtocolTypeRouter
application = ProtocolTypeRouter({
# (http->django views is added by default)
})
2,在settings文件中注册channels(最好在第一位注册,如果有其他的冲突选择性的删除)
在settings最下面的文件中写入
# Channels
ASGI_APPLICATION = 'mysite.routing.application' (这里是自己的项目名称)
此时websocket服务已经开始运行了
但是websocket并不知道怎么处理websocket请求,需要添加路由consumers
# chat/consumers.py
from channels.generic.websocket import WebsocketConsumer
import json
class ChatConsumer(WebsocketConsumer):
def
Django中使用Websocket
最新推荐文章于 2024-03-25 23:59:08 发布