Django Channel實時推送與聊天的示例程式碼
先來看一下最終的效果吧
開始聊天,輸入訊息並點擊發送訊息就可以開始聊天了
點選 “獲取後端資料”開啟實時推送
先來簡單瞭解一下 Django Channel
Channels是一個採用Django並將其功能擴充套件到HTTP以外的專案,以處理WebSocket,聊天協議,IoT協議等。它基於稱為ASGI的Python規範構建。
它以Django的核心為基礎,並在其下面分層了一個完全非同步的層,以同步模式執行Django本身,但非同步處理了連線和套接字,並提供了以兩種方式編寫的選擇,從而實現了這一點。
詳情請參考官方文件:https://channels.readthedocs.io/en/latest/introduction.html
再簡單說下ASGI是什麼東東吧
ASGI 由 Django 團隊提出,為了解決在一個網路框架裡(如 Django)同時處理 HTTP、HTTP2、WebSocket 協議。為此,Django 團隊開發了 Django Channels 外掛,為 Django 帶來了 ASGI 能力。
在 ASGI 中,將一個網路請求劃分成三個處理層面,最前面的一層,interface server(協議處理伺服器),負責對請求協議進行解析,並將不同的協議分發到不同的 Channel(頻道);頻道屬於第二層,通常可以是一個佇列系統。頻道綁定了第三層的 Consumer(消費者)。
詳情請參考官方文件:https://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="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.min.js" type="text/javascript"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="external nofollow" > <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></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.http import JsonResponse from channels.layers import get_channel_layer from asgiref.sync import async_to_sync def index(request): return render(request,"chat/index.html") def room(request,room_name): return render(request,"chat/room.html",{"room_name": room_name}) def pushRedis(request): room = request.GET.get("room") print(room) def push(msg): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( room,{"type": "push.message","message": msg,"room_name": room} ) push("推送測試",) return JsonResponse({"1": 1})
4. 建立專案二級路由
在chat目錄下建立一個名為的檔案urls.py
# mysite/chat/urls.py from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), path('<str:room_name>/',views.room,name='room'),]
5. 修改根路由
# mysite/urls.py from django.contrib import admin from django.urls import path,include from chat.views import pushRedis urlpatterns = [ path('admin/',admin.site.urls),path("chat/",include("chat.urls")),path("push",pushRedis,name="push"),]
6.建立一個消費者
檔案chat/consumers.py
當Django接受HTTP請求時,它會查詢根URLconf來查詢檢視函式,然後呼叫該檢視函式來處理該請求。同樣,當Channels接受WebSocket連線時,它會查詢根路由配置以查詢使用者,然後在使用者上呼叫各種功能來處理來自連線的事件。
import time import json from channels.generic.websocket import WebsocketConsumer,AsyncWebsocketConsumer from asgiref.sync import async_to_sync import redis pool = redis.ConnectionPool( host="10.0.6.29",port=6379,max_connections=10,decode_response=True,) conn = redis.Redis(connection_pool=pool,decode_responses=True) class ChatConsumer(AsyncWebsocketConsumer): async def connect(self,): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = "chat_%s" % self.room_name await self.channel_layer.group_add( self.room_group_name,self.channel_name,) await self.accept() async def disconnect(self,close_code): print("close_code: ",close_code) await self.channel_layer.group_discard( self.room_group_name,self.channel_name ) async def receive(self,text_data=None,bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json["message"] print("receive_message:",message) await self.channel_layer.group_send( self.room_group_name,{ "type": "chat_message","message": message } ) async def chat_message(self,event): receive_message = event["message"] response_message = "You message is :" + receive_message await self.send(text_data=json.dumps({ "message": response_message })) class PushMessage(WebsocketConsumer): def connect(self): self.room_group_name = self.scope["url_route"]["kwargs"]["room_name"] async_to_sync(self.channel_layer.group_add)( self.room_group_name,self.channel_name ) self.accept() def disconnect(self,code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name,self.channel_name ) def push_message(self,event): """ 主動推送 :param event: :return: """ print(event,type(event)) while True: time.sleep(2) msg = time.strftime("%Y-%m-%d %H:%M:%S") + "--- room_name: %s" % event["room_name"] self.send(text_data=json.dumps( {"message": msg} ))
7.為專案新增websocket的路由配置
在chat目錄下建立一個名為的檔案routing.py
# mysite/chat/routing.py from django.urls import re_path,path from . import consumers websocket_urlpatterns = [ re_path(r"ws/chat/(?P<room_name>\w+)/$",consumers.ChatConsumer),path("ws/push/<room_name>",consumers.PushMessage),]
8.配置websocket根路由
與setting同級目錄新建ws根路由檔案 routing.py
from channels.routing import ProtocolTypeRouter,URLRouter from channels.auth import AuthMiddlewareStack import chat.routing application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ),})
9.最終的檔案關係如下圖
10.啟動服務
python3 manage.py runserver 10.0.6.2:80
注意看,這和django是不一樣的
還有另一種更穩健的啟動方式
和setting同級新增檔案 asgi.py
import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE","mysite.settings") django.setup() application = get_default_application()
啟動方式為:
daphne -b 10.0.6.2 -p 80 mysite.asgi:application
daphne 在安裝channel時已經自動安裝好了
參考:
https://channels.readthedocs.io/en/latest/tutorial/index.html
https://blog.ernest.me/post/asgi-demonstration-realtime-blogging
到此這篇關於Django Channel實時推送與聊天的示例程式碼的文章就介紹到這了,更多相關Django Channel實時推送與聊天內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!