最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Django Channel實(shí)時(shí)推送與聊天的示例代碼

 更新時(shí)間:2020年04月30日 09:22:05   作者:Sunzz  
這篇文章主要介紹了Django Channel實(shí)時(shí)推送與聊天的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

先來看一下最終的效果吧

開始聊天,輸入消息并點(diǎn)擊發(fā)送消息就可以開始聊天了

點(diǎn)擊 “獲取后端數(shù)據(jù)”開啟實(shí)時(shí)推送

先來簡單了解一下 Django Channel

Channels是一個(gè)采用Django并將其功能擴(kuò)展到HTTP以外的項(xiàng)目,以處理WebSocket,聊天協(xié)議,IoT協(xié)議等。它基于稱為ASGI的Python規(guī)范構(gòu)建。

它以Django的核心為基礎(chǔ),并在其下面分層了一個(gè)完全異步的層,以同步模式運(yùn)行Django本身,但異步處理了連接和套接字,并提供了以兩種方式編寫的選擇,從而實(shí)現(xiàn)了這一點(diǎn)。

詳情請參考官方文檔:https://channels.readthedocs.io/en/latest/introduction.html

再簡單說下ASGI是什么東東吧

ASGI 由 Django 團(tuán)隊(duì)提出,為了解決在一個(gè)網(wǎng)絡(luò)框架里(如 Django)同時(shí)處理 HTTP、HTTP2、WebSocket 協(xié)議。為此,Django 團(tuán)隊(duì)開發(fā)了 Django Channels 插件,為 Django 帶來了 ASGI 能力。
在 ASGI 中,將一個(gè)網(wǎng)絡(luò)請求劃分成三個(gè)處理層面,最前面的一層,interface server(協(xié)議處理服務(wù)器),負(fù)責(zé)對請求協(xié)議進(jìn)行解析,并將不同的協(xié)議分發(fā)到不同的 Channel(頻道);頻道屬于第二層,通??梢允且粋€(gè)隊(duì)列系統(tǒng)。頻道綁定了第三層的 Consumer(消費(fèi)者)。

詳情請參考官方文檔:https://channels.readthedocs.io/en/latest/asgi.html

下邊來說一下具體的實(shí)現(xiàn)步驟

一、安裝channel

pip3 install channels 
pip3 install channels_redis

二、新建Django項(xiàng)目

1.新建項(xiàng)目

django-admin startproject mysite

2.新建應(yīng)用

python3 manage.py startapp chat

3.編輯mysite/settings.py文件

#注冊應(yīng)用
INSTALLED_APPS = [
  ....
  'chat.apps.ChatConfig',
  "channels",
]

# 在文件尾部新增如下配置

#將ASGI_APPLICATION設(shè)置設(shè)置為指向該路由對象作為您的根應(yīng)用程序:
ASGI_APPLICATION = 'mysite.routing.application'

#配置Redis
CHANNEL_LAYERS = {
  'default': {
    'BACKEND': 'channels_redis.core.RedisChannelLayer',
    'CONFIG': {
      "hosts": [('10.0.6.29', 6379)],
    },
  },
}

三、詳細(xì)代碼與配置

1. 添加索引視圖的模板

chat目錄中創(chuàng)建一個(gè)templates目錄。在您剛剛創(chuàng)建的templates目錄中,創(chuàng)建另一個(gè)名為的目錄chat,并在其中創(chuàng)建一個(gè)名為的文件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.創(chuàng)建聊天與消息推送模板

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"  rel="external nofollow" >
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/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="發(fā)送消息" class="input-sm">
<button id="get_data" class="btn btn-success">獲取后端數(shù)據(jù)</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 為收到后端發(fā)來的數(shù)據(jù)
    //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.創(chuàng)建房間的視圖

將以下代碼放入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. 創(chuàng)建項(xiàng)目二級路由

在chat目錄下創(chuàng)建一個(gè)名為的文件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.創(chuàng)建一個(gè)消費(fèi)者

文件chat/consumers.py

當(dāng)Django接受HTTP請求時(shí),它會(huì)查詢根URLconf來查找視圖函數(shù),然后調(diào)用該視圖函數(shù)來處理該請求。同樣,當(dāng)Channels接受WebSocket連接時(shí),它會(huì)查詢根路由配置以查找使用者,然后在使用者上調(diào)用各種功能來處理來自連接的事件。

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):
    """
    主動(dòng)推送
    :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.為項(xiàng)目添加websocket的路由配置

在chat目錄下創(chuàng)建一個(gè)名為的文件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.最終的文件關(guān)系如下圖

10.啟動(dòng)服務(wù)

python3 manage.py runserver 10.0.6.2:80

注意看,這和django是不一樣的

還有另一種更穩(wěn)健的啟動(dòng)方式

和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()

啟動(dòng)方式為:

daphne -b 10.0.6.2 -p 80 mysite.asgi:application

daphne 在安裝channel時(shí)已經(jīng)自動(dòng)安裝好了

參考:

  https://channels.readthedocs.io/en/latest/tutorial/index.html

  https://blog.ernest.me/post/asgi-demonstration-realtime-blogging

到此這篇關(guān)于Django Channel實(shí)時(shí)推送與聊天的示例代碼的文章就介紹到這了,更多相關(guān)Django Channel實(shí)時(shí)推送與聊天內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python數(shù)據(jù)分析基礎(chǔ)之pandas中l(wèi)oc()與iloc()的介紹與區(qū)別介紹

    python數(shù)據(jù)分析基礎(chǔ)之pandas中l(wèi)oc()與iloc()的介紹與區(qū)別介紹

    我們經(jīng)常在尋找數(shù)據(jù)的某行或者某列的時(shí)常用到Pandas中的兩種方法iloc和loc,兩種方法都接收兩個(gè)參數(shù),第一個(gè)參數(shù)是行的范圍,第二個(gè)參數(shù)是列的范圍,這篇文章主要介紹了python數(shù)據(jù)分析基礎(chǔ)之pandas中l(wèi)oc()與iloc()的介紹與區(qū)別,需要的朋友可以參考下
    2024-07-07
  • Python中如何實(shí)現(xiàn)真正的按位取反運(yùn)算

    Python中如何實(shí)現(xiàn)真正的按位取反運(yùn)算

    按位取反是位運(yùn)算符,而位運(yùn)算符是應(yīng)用在兩個(gè)數(shù)的運(yùn)算上,會(huì)對數(shù)字的二進(jìn)制所有位數(shù)進(jìn)行從低到高的運(yùn)算,下面這篇文章主要給大家介紹了關(guān)于Python中如何實(shí)現(xiàn)真正的按位取反運(yùn)算的相關(guān)資料,需要的朋友可以參考下
    2023-02-02
  • python爬蟲之線程池和進(jìn)程池功能與用法詳解

    python爬蟲之線程池和進(jìn)程池功能與用法詳解

    這篇文章主要介紹了python爬蟲之線程池和進(jìn)程池功能與用法,結(jié)合實(shí)例形式分析了Python基于線程池與進(jìn)程池的爬蟲功能相關(guān)操作技巧與使用注意事項(xiàng),需要的朋友可以參考下
    2018-08-08
  • Python使用socket實(shí)現(xiàn)組播與發(fā)送二進(jìn)制數(shù)據(jù)

    Python使用socket實(shí)現(xiàn)組播與發(fā)送二進(jìn)制數(shù)據(jù)

    在工作中經(jīng)常會(huì)用到socket傳輸數(shù)據(jù),例如客戶端給服務(wù)器發(fā)送數(shù)據(jù)(雙方約定了數(shù)據(jù)格式),本文主要介紹了Python使用socket實(shí)現(xiàn)組播與發(fā)送二進(jìn)制數(shù)據(jù),感興趣的可以了解一下
    2021-06-06
  • Python延時(shí)操作實(shí)現(xiàn)方法示例

    Python延時(shí)操作實(shí)現(xiàn)方法示例

    這篇文章主要介紹了Python延時(shí)操作實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Python基于sched庫與time庫實(shí)現(xiàn)延時(shí)操作的方法,需要的朋友可以參考下
    2018-08-08
  • python中超簡單的字符分割算法記錄(車牌識別、儀表識別等)

    python中超簡單的字符分割算法記錄(車牌識別、儀表識別等)

    這篇文章主要給大家介紹了關(guān)于python中超簡單的字符分割算法記錄,如車牌識別、儀表識別等,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2021-09-09
  • python刪掉重復(fù)行之drop_duplicates()用法示例

    python刪掉重復(fù)行之drop_duplicates()用法示例

    Pandas的drop_duplicates()方法用于從DataFrame中刪除重復(fù)的行,這篇文章主要給大家介紹了關(guān)于python刪掉重復(fù)行之drop_duplicates()用法的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-08-08
  • Django中ORM的基本使用教程

    Django中ORM的基本使用教程

    這篇文章主要給大家介紹了關(guān)于Django中ORM基本使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • Python中反射和描述器總結(jié)

    Python中反射和描述器總結(jié)

    這篇文章主要介紹了Python中的反射和描述器一些知識的匯總,非常的詳細(xì),有需要的小伙伴可以參考下
    2018-09-09
  • Python多進(jìn)程寫入同一文件的方法

    Python多進(jìn)程寫入同一文件的方法

    今天小編就為大家分享一篇Python多進(jìn)程寫入同一文件的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01

最新評論

光山县| 潮安县| 蓝山县| 济南市| 信宜市| 漳平市| 延吉市| 广德县| 阿城市| 衡水市| 社会| 富锦市| 榆社县| 越西县| 孟津县| 汽车| 渭源县| 太仆寺旗| 农安县| 渝北区| 庆云县| 湟源县| 修水县| 定西市| 宁蒗| 会同县| 区。| 炎陵县| 合川市| 宽城| 沈阳市| 万载县| 荆门市| 望江县| 抚远县| 珠海市| 梅州市| 博爱县| 屯留县| 荣昌县| 湛江市|