安裝依賴包 pip install channels channels-redis .
2.settings.py 修改加上支持.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MyWeb.apps.MywebConfig',
"channels",
]

首先需要建立一個django項目。其中在你自己的app下面 生成consumers.py和routing.py配置文件。
consumers.py:相當於django的視圖,也就是說所有的websocket路由過來的執行的函數都在consumers.py類似於django的視圖views.py
routing.py:是websocket中的url和執行函數的對應關系。相當於django的urls.py,根據映射關系,當websocket的請求進來的時候,根據用戶的請求來觸發我們的consumers.py里的方法。
2.安裝redis
redis 安裝配置默認密碼
yum install -y redis
[root@localhost ~]# vim /etc/redis.conf 開啟遠程
bind 0.0.0.0
protected-mode no
redis-cli -h 192.168.1.20 -p 6379
3.接着配置settings.py 最底部加上這條。

CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('192.168.1.20', 6379)],
},
},
}
ASGI_APPLICATION = "MyWeb.routing.application"
接着簡單的寫一下,routing.py 里面
from channels.routing import ProtocolTypeRouter
application = ProtocolTypeRouter({
# Empty for now (http->django views is added by default)
})
進入django shell 測試是否能連接到數據庫
(venv) C:\Users\LyShark\PycharmProjects\MyProject>manage.py shell
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import channels.layers
>>> channel_layer = channels.layers.get_channel_layer()
>>> from asgiref.sync import async_to_sync
>>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})
>>> async_to_sync(channel_layer.receive)('test_channel')
{'type': 'hello'}
>>>
