美文网首页程序员
django中的websocket(channels)配置

django中的websocket(channels)配置

作者: 梟遙書眚 | 来源:发表于2019-03-08 19:48 被阅读0次

1.安装channels,安装版本高于1.1.8,安装channels会附带安装许多依赖包,其中twisted可能存在兼容问题

pip install channels

2.在settings.py中注册channels

settings.py

3.在项目目录中添加websocket文件routing.py和asgi.py与settings.py同级

4.asgi.py中的内容为

import os

import channels.asgi

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "canteen.settings") #这里填的是你的配置文件settings.py的位置

channel_layer = channels.asgi.get_channel_layer()

asgi.py

5.routing.py中的内容为

from channels.routing import route,include

from apps.user import views

channel_routing = [ route('websocket.connect',views.connect),

        route('websocket.receive',views.recive),

        route('websocket.disconnect',views.disconnect),

]

routing = [ include(channel_routing,path=r'^/distribute_task'),]

routing.py

    这里是websocket的路由配置,channel_routing中是websocket的回调试图函数

6.添加channels的配置

CHANNEL_LAYERS = {

        "default": {

                "BACKEND": "asgiref.inmemory.ChannelLayer",

                "ROUTING": "canteen.routing.routing",

        },

}

settings.py

相关文章

网友评论

    本文标题:django中的websocket(channels)配置

    本文链接:https://www.haomeiwen.com/subject/gvsdpqtx.html