channels2.X 学习笔记
阅读原文时间:2023年10月09日阅读:5

- No module named 'asgiref.sync' 报错解决:

# 报错原因:
"""
django版本过低, 卸载最新版本的 channels 使用2.x 版本的
"""
pip3 uninstall channels

- 安装:

"""
Django 1.11.15 版本不支持最新的 channels
"""

pip3 install channels==2.1.4

- 在django中的配置:

  - 配置settings.py文件:

# 添加APP
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
"app01.apps.App01Config",
]

其他配置文件 …

ASGI 的路由设置

ASGI_APPLICATION = 'ChannelDemo.routing.application'
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgiref.inmemory.ChannelLayer",
"ROUTING": "ChannelDemo.routing.channel_routing",
},
}

  - channels的路由配置:

# 在项目settings文件同级目录中新增routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import app01.routing

application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter(
app01.routing.websocket_urlpatterns # 指明路由文件是app01.routing.py
)
),
})

  - app01中的routing.py 文件:

from django.conf.urls import url

from . import consumers

websocket_urlpatterns = [
url(r'^ws/deploy/(?P[^/]+)/$', consumers.DeployResult),
url(r'^ws/$', consumers.ws),
]

  - 视图文件 consumers.py :

  待续。。。