项目依赖
# requirements.txt
Django==3.0.2
channels==2.4.0
# 安装channels 其他的包都会自动下载
channels-redis==2.4.1
# 使用channels-redis
python版本==3.6.9
完整项目结构
废话不多说 新建一个项目手把手教
第一步 进入虚拟环境 新建一个app
python manage.py startapp chat
当前项目结构
第二步 虚拟环境下 pip包
pip install channels
pip install channels-redis
第三步 项目根目录下chat_demo
文件中修改settings.py
文件
在
INSTALLED_APPS
中注册'chat' app 和'channels'包
第四步 项目根目录下chat
文件中新建consumers.py
文件
消费者模式
第五步 项目根目录下chat
文件中新建routing.py
文件
# chat/routing.py
from django.urls import re_path
from chat.consumers import ChatConsumer
websocket_urlpatterns = [
re_path(r'ws/room/(?P\w+)/$', ChatConsumer),
]
第六步 templates
目录下新建room.html
文件
room.html
全部内容
Chat Room
第七步 项目根目录下 修改chat/views.py
文件 添加room
视图
# chat/views.py
from django.shortcuts import render
def room(request, room_name):
return render(request, 'room.html', {'room_name': room_name})
# {'room_name': room_name} ==> `room.html` 中的 var roomName = "{{ room_name|escapejs }}";
# 把 room_name 的参数带给前端页面
第八步 项目根目录下 修改chat_demo/urls.py
文件 添加room
路由
from django.contrib import admin
from django.urls import path
from chat.views import room
urlpatterns = [
path('room//', room, name='room'),
]
第九步 项目根目录下 chat_demo
目录下新建routing.py
文件
# chat_demo/routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
第十步 修改settings.py
文件内容 并添加CHANNEL_LAYERS
以及 WSGI_APPLICATION
修改ALLOWED_HOST
并修改访问Hsot
ALLOWED_HOSTS = ["*"]
settings.py文件全部内容
# chat_demo/settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*+#-wxtj$li1)4q$1q1b99=-qz^qs+caidcn*e3+*g7991$e=d'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chat',
'channels',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'chat_demo.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'chat_demo.wsgi.application'
ASGI_APPLICATION = 'chat_demo.routing.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
第十一步 虚拟环境下 执行数据库迁移
python manage.py migrate
第十二步 虚拟环境下 运行项目
python manage.py runserver 192.168.101.100:8000
运行项目后打开两个浏览器 访问同一个IP路径
例:192.168.101.100:8000/room/test/
room
指向chat app中的函数视图 room
test
指向房间号码 可以是任意非汉字值
192.168.101.100
是我修改后的访问地址
左边发送消息 右边更新了同样的消息
补充 如果需要主动推送系统消息到指定的聊天室 (这里写一个案例)
例如定时任务 可以加入chat/views.py
里 woker
视图中 16行至28行 的代码
导包
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.http import JsonResponse
在项目根目录chat/views.py
文件中添加视图worker
# chat/views.py
from asgiref.sync import async_to_sync
# asgiref需要Python 3.5或更高版本。
from channels.layers import get_channel_layer
from django.http import JsonResponse
from django.shortcuts import render
def room(request, room_name):
return render(request, 'room.html', {'room_name': room_name})
# {'room_name': room_name} ==> `room.html` 中的 var roomName = "{{ room_name|escapejs }}";
# 把 room_name 的参数带给前端页面
def worker(request):
channel_layer = get_channel_layer()
# print(type(channel_layer))
room_group_name = 'room_test'
# 这里的 'room_test' 代表 192.168.101.100:800/room/test/ 中的 room/test/路径房间名称
# 如果 访问别的路径 则需要修改 该值
async_to_sync(channel_layer.group_send)(
room_group_name,
{
'type': 'chat_message',
'message': '欢迎大家',
'user_id': '系统的消息',
}
)
data = {
'code': 200,
'message': '消息已经推送',
}
return JsonResponse(data)
在项目根目录chat_demo/urls/py
文件中注册worker
视图
from django.urls import path
from chat.views import room, worker
urlpatterns = [
path('room//', room, name='room'),
path('worker/', worker,),
]
重启项目 重新打开两个浏览器
先访问 http://192.168.101.100:8000/room/test/
再访问 http://192.168.101.100:8000/worker/