django中的websocket(channels)配置

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

pip install channels

2.在settings.py中注册channels


django中的websocket(channels)配置_第1张图片
settings.py

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


django中的websocket(channels)配置_第2张图片

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'),]

django中的websocket(channels)配置_第3张图片
routing.py

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

6.添加channels的配置

CHANNEL_LAYERS = {

        "default": {

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

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

        },

}

django中的websocket(channels)配置_第4张图片
settings.py

你可能感兴趣的:(django中的websocket(channels)配置)