如何实现Django Channel的实时聊天功能示例代码?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1266个文字,预计阅读时间需要6分钟。
首先查看最终的效果,然后开始聊天。输入消息并点击发送消息按钮即可开始对话。点击获取后端数据启动实时推送。先简单了解一下,Django Channel 和 Channels 是利用 Django 并扩展其功能的工具。
先来看一下最终的效果吧
开始聊天,输入消息并点击发送消息就可以开始聊天了
点击 “获取后端数据”开启实时推送
先来简单了解一下 Django Channel
Channels是一个采用Django并将其功能扩展到HTTP以外的项目,以处理WebSocket,聊天协议,IoT协议等。它基于称为ASGI的Python规范构建。
它以Django的核心为基础,并在其下面分层了一个完全异步的层,以同步模式运行Django本身,但异步处理了连接和套接字,并提供了以两种方式编写的选择,从而实现了这一点。
详情请参考官方文档:channels.readthedocs.io/en/latest/introduction.html
再简单说下ASGI是什么东东吧
ASGI 由 Django 团队提出,为了解决在一个网络框架里(如 Django)同时处理 HTTP、HTTP2、WebSocket 协议。为此,Django 团队开发了 Django Channels 插件,为 Django 带来了 ASGI 能力。
在 ASGI 中,将一个网络请求划分成三个处理层面,最前面的一层,interface server(协议处理服务器),负责对请求协议进行解析,并将不同的协议分发到不同的 Channel(频道);频道属于第二层,通常可以是一个队列系统。频道绑定了第三层的 Consumer(消费者)。
详情请参考官方文档:channels.readthedocs.io/en/latest/asgi.html
下边来说一下具体的实现步骤
一、安装channel
pip3 install channels pip3 install channels_redis
二、新建Django项目
1.新建项目
django-admin startproject mysite
2.新建应用
python3 manage.py startapp chat
3.编辑mysite/settings.py文件
#注册应用 INSTALLED_APPS = [ .... 'chat.apps.ChatConfig', "channels", ] # 在文件尾部新增如下配置 #将ASGI_APPLICATION设置设置为指向该路由对象作为您的根应用程序: ASGI_APPLICATION = 'mysite.routing.application' #配置Redis CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('10.0.6.29', 6379)], }, }, }
三、详细代码与配置
1. 添加索引视图的模板
在chat目录中创建一个templates目录。在您刚刚创建的templates目录中,创建另一个名为的目录chat,并在其中创建一个名为的文件index.html以保存索引视图的模板
将以下代码放入chat/templates/chat/index.html
<!-- chat/templates/chat/index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Rooms</title> </head> <body> What chat room would you like to enter?<br> <input id="room-name-input" type="text" size="100"><br> <input id="room-name-submit" type="button" value="Enter"> <script> document.querySelector('#room-name-input').focus(); document.querySelector('#room-name-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#room-name-submit').click(); } }; document.querySelector('#room-name-submit').onclick = function(e) { var roomName = document.querySelector('#room-name-input').value; window.location.pathname = '/chat/' + roomName + '/'; }; </script> </body> </html>
2.创建聊天与消息推送模板
chat/templates/chat/room.html
<!DOCTYPE html> <html> <head> <script src="img.558idc.com/uploadfile/allimg/210409/1235595636-3.jpg" type="text/javascript"></script> <link rel="stylesheet" href="cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="external nofollow" > <script src="img.558idc.com/uploadfile/allimg/210409/1235591A9-4.jpg"></script> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="150" rows="30" class="text"></textarea><br> <input id="chat-message-input" type="text" size="150"><br> <input id="chat-message-submit" type="button" value="发送消息" class="input-sm"> <button id="get_data" class="btn btn-success">获取后端数据</button> {{ room_name|json_script:"room-name" }} <script> $("#get_data").click(function () { $.ajax({ url: "{% url 'push' %}", type: "GET", data: { "room": "{{ room_name }}", "csrfmiddlewaretoken": "{{ csrf_token }}" }, }) }); const roomName = JSON.parse(document.getElementById('room-name').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); let chatSocketa = new WebSocket( "ws://" + window.location.host + "/ws/push/" + roomName ); chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); // data 为收到后端发来的数据 //console.log(data); document.querySelector('#chat-log').value += (data.message + '\n'); }; chatSocketa.onmessage = function (e) { let data = JSON.parse(e.data); //let message = data["message"]; document.querySelector("#chat-log").value += (data.message + "\n"); }; chatSocket.onclose = function (e) { console.error('Chat socket closed unexpectedly'); }; chatSocketa.onclose = function (e) { console.error("Chat socket closed unexpectedly"); }; 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) { const messageInputDom = document.querySelector('#chat-message-input'); const message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'message': message })); messageInputDom.value = ''; }; </script> </body> </html>
3.创建房间的视图
将以下代码放入chat/views.py
# chat/views.py from django.shortcuts import render from django.channels.readthedocs.io/en/latest/tutorial/index.html
blog.ernest.me/post/asgi-demonstration-realtime-blogging
到此这篇关于Django Channel实时推送与聊天的示例代码的文章就介绍到这了,更多相关Django Channel实时推送与聊天内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!
本文共计1266个文字,预计阅读时间需要6分钟。
首先查看最终的效果,然后开始聊天。输入消息并点击发送消息按钮即可开始对话。点击获取后端数据启动实时推送。先简单了解一下,Django Channel 和 Channels 是利用 Django 并扩展其功能的工具。
先来看一下最终的效果吧
开始聊天,输入消息并点击发送消息就可以开始聊天了
点击 “获取后端数据”开启实时推送
先来简单了解一下 Django Channel
Channels是一个采用Django并将其功能扩展到HTTP以外的项目,以处理WebSocket,聊天协议,IoT协议等。它基于称为ASGI的Python规范构建。
它以Django的核心为基础,并在其下面分层了一个完全异步的层,以同步模式运行Django本身,但异步处理了连接和套接字,并提供了以两种方式编写的选择,从而实现了这一点。
详情请参考官方文档:channels.readthedocs.io/en/latest/introduction.html
再简单说下ASGI是什么东东吧
ASGI 由 Django 团队提出,为了解决在一个网络框架里(如 Django)同时处理 HTTP、HTTP2、WebSocket 协议。为此,Django 团队开发了 Django Channels 插件,为 Django 带来了 ASGI 能力。
在 ASGI 中,将一个网络请求划分成三个处理层面,最前面的一层,interface server(协议处理服务器),负责对请求协议进行解析,并将不同的协议分发到不同的 Channel(频道);频道属于第二层,通常可以是一个队列系统。频道绑定了第三层的 Consumer(消费者)。
详情请参考官方文档:channels.readthedocs.io/en/latest/asgi.html
下边来说一下具体的实现步骤
一、安装channel
pip3 install channels pip3 install channels_redis
二、新建Django项目
1.新建项目
django-admin startproject mysite
2.新建应用
python3 manage.py startapp chat
3.编辑mysite/settings.py文件
#注册应用 INSTALLED_APPS = [ .... 'chat.apps.ChatConfig', "channels", ] # 在文件尾部新增如下配置 #将ASGI_APPLICATION设置设置为指向该路由对象作为您的根应用程序: ASGI_APPLICATION = 'mysite.routing.application' #配置Redis CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('10.0.6.29', 6379)], }, }, }
三、详细代码与配置
1. 添加索引视图的模板
在chat目录中创建一个templates目录。在您刚刚创建的templates目录中,创建另一个名为的目录chat,并在其中创建一个名为的文件index.html以保存索引视图的模板
将以下代码放入chat/templates/chat/index.html
<!-- chat/templates/chat/index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Rooms</title> </head> <body> What chat room would you like to enter?<br> <input id="room-name-input" type="text" size="100"><br> <input id="room-name-submit" type="button" value="Enter"> <script> document.querySelector('#room-name-input').focus(); document.querySelector('#room-name-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#room-name-submit').click(); } }; document.querySelector('#room-name-submit').onclick = function(e) { var roomName = document.querySelector('#room-name-input').value; window.location.pathname = '/chat/' + roomName + '/'; }; </script> </body> </html>
2.创建聊天与消息推送模板
chat/templates/chat/room.html
<!DOCTYPE html> <html> <head> <script src="img.558idc.com/uploadfile/allimg/210409/1235595636-3.jpg" type="text/javascript"></script> <link rel="stylesheet" href="cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="external nofollow" > <script src="img.558idc.com/uploadfile/allimg/210409/1235591A9-4.jpg"></script> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="150" rows="30" class="text"></textarea><br> <input id="chat-message-input" type="text" size="150"><br> <input id="chat-message-submit" type="button" value="发送消息" class="input-sm"> <button id="get_data" class="btn btn-success">获取后端数据</button> {{ room_name|json_script:"room-name" }} <script> $("#get_data").click(function () { $.ajax({ url: "{% url 'push' %}", type: "GET", data: { "room": "{{ room_name }}", "csrfmiddlewaretoken": "{{ csrf_token }}" }, }) }); const roomName = JSON.parse(document.getElementById('room-name').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); let chatSocketa = new WebSocket( "ws://" + window.location.host + "/ws/push/" + roomName ); chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); // data 为收到后端发来的数据 //console.log(data); document.querySelector('#chat-log').value += (data.message + '\n'); }; chatSocketa.onmessage = function (e) { let data = JSON.parse(e.data); //let message = data["message"]; document.querySelector("#chat-log").value += (data.message + "\n"); }; chatSocket.onclose = function (e) { console.error('Chat socket closed unexpectedly'); }; chatSocketa.onclose = function (e) { console.error("Chat socket closed unexpectedly"); }; 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) { const messageInputDom = document.querySelector('#chat-message-input'); const message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'message': message })); messageInputDom.value = ''; }; </script> </body> </html>
3.创建房间的视图
将以下代码放入chat/views.py
# chat/views.py from django.shortcuts import render from django.channels.readthedocs.io/en/latest/tutorial/index.html
blog.ernest.me/post/asgi-demonstration-realtime-blogging
到此这篇关于Django Channel实时推送与聊天的示例代码的文章就介绍到这了,更多相关Django Channel实时推送与聊天内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

