详解Django-channels 实现WebSocket实例


Posted in Python onAugust 22, 2019

引入

先安装三个模块

pip install channels

pip install channels_redis

pip install pywin32

创建一个Django项目和一个app

项目名随意,app名随意。这里项目名为 django_websocket_demo ,app名 chat

把app文件夹下除了 views.py 和 __init__.py 的文件都删了,最终项目目录结构如下:

django_websocket_demo/
  manage.py
  django_websocket_demo/
    __init__.py
    settings.py
    urls.py
    wsgi.py
  chat/
    __init__.py
    views.py

在app下新建一个templates文件夹用来存放HTML页面:

chat/
  __init__.py
  templates/
    chat/
      index.html
  views.py

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>

在 chat/views.py 中添加视图函数:

from django.shortcuts import render

def index(request):
  return render(request, 'chat/index.html', {})

添加 chat/urls.py 文件并设置路由信息:

from django.urls import re_path

from . import views

urlpatterns = [
  re_path(r'^$', views.index, name='index'),
]

在项目路由 django_websocket_demo/urls.py 中配置路由信息:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
  url(r'^chat/', include('chat.urls')),
  url(r'^admin/', admin.site.urls),
]

在 settings.py 文件同级目录下新建 routing.py 文件,内容如下:

from channels.routing import ProtocolTypeRouter

application = ProtocolTypeRouter({
  # (http->django views is added by default)
})

把 channels 注册在 settings.py 里:

INSTALLED_APPS = [
  'channels',
  'chat',
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
]

在   settings.py 文件中,添加如下配置项:

# django_websocket_demo/settings.py
# Channels
# Channels
ASGI_APPLICATION = 'django_websocket_demo.routing.application'

创建聊天页面

创建一个 chat/templates/chat/room.html 文件,添加如下内容:

<!-- chat/templates/chat/room.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"/>
  <title>Chat Room</title>
</head>
<body>
  <textarea id="chat-log" cols="100" rows="20"></textarea><br/>
  <input id="chat-message-input" type="text" size="100"/><br/>
  <input id="chat-message-submit" type="button" value="Send"/>
</body>
<script>
  var roomName = {{ room_name_json }};

  var chatSocket = new WebSocket(
    'ws://' + window.location.host +
    '/ws/chat/' + roomName + '/');

  chatSocket.onmessage = function(e) {
    var data = JSON.parse(e.data);
    var message = data['message'];
    document.querySelector('#chat-log').value += (message + '\n');
  };

  chatSocket.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) {
    var messageInputDom = document.querySelector('#chat-message-input');
    var message = messageInputDom.value;
    chatSocket.send(JSON.stringify({
      'message': message
    }));

    messageInputDom.value = '';
  };
</script>
</html>

在 chat/views.py 中添加一个处理 room的视图函数:

from django.shortcuts import render
from django.utils.safestring import mark_safe
import json

def index(request):
  return render(request, 'chat/index.html', {})

def room(request, room_name):
  return render(request, 'chat/room.html', {
    'room_name_json': mark_safe(json.dumps(room_name))
  })

在 chat/urls.py 中注册路由

from django.urls import re_path

from . import views

urlpatterns = [
  re_path(r'^$', views.index, name='index'),
  re_path(r'^(?P<room_name>[^/]+)/$', views.room, name='room'),
]

新建 chat/consumers.py 文件,添加如下内容:

from channels.generic.websocket import AsyncWebsocketConsumer
import json

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

    # Join room group
    await self.channel_layer.group_add(
      self.room_group_name,
      self.channel_name
    )

    await self.accept()

  async def disconnect(self, close_code):
    # Leave room group
    await self.channel_layer.group_discard(
      self.room_group_name,
      self.channel_name
    )

  # Receive message from WebSocket
  async def receive(self, text_data):
    text_data_json = json.loads(text_data)
    message = text_data_json['message']

    # Send message to room group
    await self.channel_layer.group_send(
      self.room_group_name,
      {
        'type': 'chat_message',
        'message': message
      }
    )

  # Receive message from room group
  async def chat_message(self, event):
    message = event['message']

    # Send message to WebSocket
    await self.send(text_data=json.dumps({
      'message': message
    }))

新建一个 chat/routing.py 文件,添加以下内容:

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
  re_path(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
]

将 django_websocket_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
    )
  ),
})

配置redis

在本地6379端口启动redis : redis-server

在 settings.py 中添加如下配置:

CHANNEL_LAYERS = {
  'default': {
    'BACKEND': 'channels_redis.core.RedisChannelLayer',
    'CONFIG': {
      "hosts": [('127.0.0.1', 6379)],
    },
  },
}

最后启动Django项目

使用多个浏览器打开http://127.0.0.1:8000/chat/lobby/ ,开始实时聊天吧。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
用python + hadoop streaming 分布式编程(一) -- 原理介绍,样例程序与本地调试
Jul 14 Python
Python中的装饰器用法详解
Jan 14 Python
Python的类实例属性访问规则探讨
Jan 30 Python
在Python程序中进行文件读取和写入操作的教程
Apr 28 Python
浅谈pyhton学习中出现的各种问题(新手必看)
May 17 Python
解决python selenium3启动不了firefox的问题
Oct 13 Python
手把手教你如何安装Pycharm(详细图文教程)
Nov 28 Python
Appium+Python自动化测试之运行App程序示例
Jan 23 Python
python 判断字符串中是否含有汉字或非汉字的实例
Jul 15 Python
Python实现Word表格转成Excel表格的示例代码
Apr 16 Python
详解pytorch tensor和ndarray转换相关总结
Sep 03 Python
使用pandas读取表格数据并进行单行数据拼接的详细教程
Mar 03 Python
解决python3 requests headers参数不能有中文的问题
Aug 21 #Python
python通过robert、sobel、Laplace算子实现图像边缘提取详解
Aug 21 #Python
Python爬虫:url中带字典列表参数的编码转换方法
Aug 21 #Python
Python GUI学习之登录系统界面篇
Aug 21 #Python
Python爬虫:将headers请求头字符串转为字典的方法
Aug 21 #Python
利用python在大量数据文件下删除某一行的例子
Aug 21 #Python
Python 仅获取响应头, 不获取实体的实例
Aug 21 #Python
You might like
使用YUI+Ant 实现JS CSS压缩
2014/09/02 PHP
php实现给图片加灰色半透明效果的方法
2014/10/20 PHP
php调用shell的方法
2014/11/05 PHP
浅谈PHP中try{}catch{}的使用方法
2016/12/09 PHP
PHP mysqli事务操作常用方法分析
2017/07/22 PHP
PHP常用header头定义代码示例汇总
2020/08/29 PHP
JavaScript的Module模式编程深入分析
2013/08/13 Javascript
javascript跨域的4种方法和原理详解
2014/04/08 Javascript
JavaScript返回当前会话cookie全部键值对照的方法
2015/04/03 Javascript
Bootstrap+jfinal退出系统弹出确认框的实现方法
2016/05/30 Javascript
JS 对java返回的json格式的数据处理方法
2016/12/05 Javascript
Bootstrap超大屏幕的实现代码
2017/03/22 Javascript
webpack构建react多页面应用详解
2017/09/15 Javascript
nodejs async异步常用函数总结(推荐)
2017/11/17 NodeJs
Vue.js 点击按钮显示/隐藏内容的实例代码
2018/02/08 Javascript
vue.js表单验证插件(vee-validate)的使用教程详解
2019/05/23 Javascript
Angular6使用forRoot() 注册单一实例服务问题
2019/08/27 Javascript
Python高效编程技巧
2013/01/07 Python
将Python代码嵌入C++程序进行编写的实例
2015/07/31 Python
Python列表删除的三种方法代码分享
2017/10/31 Python
Tensorflow读取并输出已保存模型的权重数值方式
2020/01/04 Python
解决python执行较大excel文件openpyxl慢问题
2020/05/15 Python
pytorch 常用函数 max ,eq说明
2020/06/28 Python
Django+Django-Celery+Celery的整合实战
2021/01/20 Python
青年创业培训欢迎词
2014/01/10 职场文书
父亲生日宴会答谢词
2014/01/10 职场文书
骨干教师培训感言
2014/01/16 职场文书
社区精神文明建设汇报材料
2014/08/17 职场文书
个人融资协议书范本两则
2014/10/15 职场文书
通报表扬范文
2015/01/17 职场文书
2016年春季运动会广播稿
2015/08/19 职场文书
爱护环境建议书
2015/09/14 职场文书
假如给我三天光明:舟逆水而行,人遇挫而达 
2019/10/29 职场文书
详解CSS开发过程中的20个快速提升技巧
2021/05/21 HTML / CSS
python的变量和简单数字类型详解
2021/09/15 Python
MYSQL如何查看进程和kill进程
2022/03/13 MySQL