項(xiàng)目依賴
# requirements.txt
Django==3.0.2
channels==2.4.0
# 安裝channels 其他的包都會自動下載
channels-redis==2.4.1
# 使用channels-redis
python版本==3.6.9
完整項(xiàng)目結(jié)構(gòu)
廢話不多說 新建一個項(xiàng)目手把手教
第一步 進(jìn)入虛擬環(huán)境 新建一個app
python manage.py startapp chat
當(dāng)前項(xiàng)目結(jié)構(gòu)
第二步 虛擬環(huán)境下 pip包
pip install channels
pip install channels-redis
第三步 項(xiàng)目根目錄下chat_demo
文件中修改settings.py
文件
在
INSTALLED_APPS
中注冊'chat' app 和'channels'包
第四步 項(xiàng)目根目錄下chat
文件中新建consumers.py
文件
消費(fèi)者模式
第五步 項(xiàng)目根目錄下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<room_name>\w+)/$', ChatConsumer),
]
第六步 templates
目錄下新建room.html
文件
room.html
全部內(nèi)容
<!-- chat_demo/templates/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<ul id="chat-box" style="width: 300px;height: 500px;background: burlywood ;overflow-y:scroll ">
</ul>
<input id="chat-message-input" type="text" placeholder="請輸入您要發(fā)送的消息" size="60"/><br/>
<input id="chat-message-submit" type="button" value="發(fā)送消息"/>
</body>
<script>
var roomName = "{{ room_name|escapejs }}";
var chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/room/' + roomName + '/');
chatSocket.onmessage = function send_msg(e) {
var data = JSON.parse(e.data);
var ul_box = document.getElementById('chat-box');
var li = document.createElement('li');
var span = document.createElement('span');
var p = document.createElement('p');
console.log(data);
var user_id = data['user_id'];
var message = data['message'];
if (message) {
span.innerText = (
'用戶名:' + user_id + '\n' +
'消息內(nèi)容:' + message
);
li.appendChild(span);
ul_box.appendChild(li);
ul_box.appendChild(p); // 就是為了空一行而已
ul_box.scrollTo(0, ul_box.scrollHeight) //滑動到最下方(讓最新消息顯示出來)
}
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function (e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function (e) {
var messageInputDom = document.querySelector('#chat-message-input');
var message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'user_id': 12,
'message': message,
}));
messageInputDom.value = '';
};
</script>
</html>
第七步 項(xiàng)目根目錄下 修改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 的參數(shù)帶給前端頁面
第八步 項(xiàng)目根目錄下 修改chat_demo/urls.py
文件 添加room
路由
from django.contrib import admin
from django.urls import path
from chat.views import room
urlpatterns = [
path('room/<str:room_name>/', room, name='room'),
]
第九步 項(xiàng)目根目錄下 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
文件內(nèi)容 并添加CHANNEL_LAYERS
以及 WSGI_APPLICATION
修改ALLOWED_HOST
并修改訪問Hsot
ALLOWED_HOSTS = ["*"]
settings.py文件全部內(nèi)容
# 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/'
第十一步 虛擬環(huán)境下 執(zhí)行數(shù)據(jù)庫遷移
python manage.py migrate
第十二步 虛擬環(huán)境下 運(yùn)行項(xiàng)目
python manage.py runserver 192.168.101.100:8000
運(yùn)行項(xiàng)目后打開兩個瀏覽器 訪問同一個IP路徑
例:192.168.101.100:8000/room/test/
room
指向chat app中的函數(shù)視圖 room
test
指向房間號碼 可以是任意非漢字值
192.168.101.100
是我修改后的訪問地址
左邊發(fā)送消息 右邊更新了同樣的消息
補(bǔ)充 如果需要主動推送系統(tǒng)消息到指定的聊天室 (這里寫一個案例)
例如定時任務(wù) 可以加入chat/views.py
里 woker
視圖中 16行至28行 的代碼
導(dǎo)包
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.http import JsonResponse
在項(xiàng)目根目錄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 的參數(shù)帶給前端頁面
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': '系統(tǒng)的消息',
}
)
data = {
'code': 200,
'message': '消息已經(jīng)推送',
}
return JsonResponse(data)
在項(xiàng)目根目錄chat_demo/urls/py
文件中注冊worker
視圖
from django.urls import path
from chat.views import room, worker
urlpatterns = [
path('room/<str:room_name>/', room, name='room'),
path('worker/', worker,),
]
重啟項(xiàng)目 重新打開兩個瀏覽器
先訪問 http://192.168.101.100:8000/room/test/
再訪問 http://192.168.101.100:8000/worker/