django channels

django channels 是django支持websocket的一个模块。

1. 安装

`pip3 install channels`

2. 快速上手

2.1 在settings中添加配置

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
]
ASGI_APPLICATION = "django_channels_demo.routing.application"

2.2 创建websocket应用和路由

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from chat import consumers application = ProtocolTypeRouter({
'websocket': URLRouter([
url(r'^chat/$', consumers.ChatConsumer),
])
})

2.3 编写处理websocket逻辑业务

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer class ChatConsumer(WebsocketConsumer): def websocket_connect(self, message):
self.accept() def websocket_receive(self, message):
print('接收到消息', message)
self.send(text_data='收到了') def websocket_disconnect(self, message):
print('客户端断开连接了')
raise StopConsumer()
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer class SimpleChatConsumer(WebsocketConsumer):
def connect(self):
self.accept() def receive(self, text_data=None, bytes_data=None):
self.send(text_data) # 主动断开连接
# self.close() def disconnect(self, code):
print('客户端要断开了')
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer CLIENTS = [] class ChatConsumer(WebsocketConsumer): def connect(self):
self.accept()
CLIENTS.append(self) def receive(self, text_data=None, bytes_data=None):
for item in CLIENTS:
item.send(text_data) # 主动断开连接
# self.close() def disconnect(self, code):
CLIENTS.remove(self)

3. channel layer

基于内存的channel layer

CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer",
}
}
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync class ChatConsumer(WebsocketConsumer): def connect(self):
async_to_sync(self.channel_layer.group_add)('x1', self.channel_name)
self.accept() def receive(self, text_data=None, bytes_data=None):
async_to_sync(self.channel_layer.group_send)('x1', {
'type': 'xxx.ooo',
'message': text_data
}) def xxx_ooo(self, event):
message = event['message']
self.send(message) def disconnect(self, code):
async_to_sync(self.channel_layer.group_discard)('x1', self.channel_name)

基于 redis的channel layer

`pip3 install channels``-``redis`
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [('10.211.55.25', 6379)]
},
},
} CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {"hosts": ["redis://10.211.55.25:6379/1"],},
},
} CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {"hosts": [('10.211.55.25', 6379)],},},
} CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": ["redis://:password@10.211.55.25:6379/0"],
"symmetric_encryption_keys": [SECRET_KEY],
},
},
}
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync class ChatConsumer(WebsocketConsumer): def connect(self):
async_to_sync(self.channel_layer.group_add)('x1', self.channel_name)
self.accept() def receive(self, text_data=None, bytes_data=None):
async_to_sync(self.channel_layer.group_send)('x1', {
'type': 'xxx.ooo',
'message': text_data
}) def xxx_ooo(self, event):
message = event['message']
self.send(message) def disconnect(self, code):
async_to_sync(self.channel_layer.group_discard)('x1', self.channel_name)

django channels的更多相关文章

  1. Django Channels 学习笔记

    一.为什么要使用Channels 在Django中,默认使用的是HTTP通信,不过这种通信方式有个很大的缺陷,就是不能很好的支持实时通信.如果硬是要使用HTTP做实时通信的话只能在客户端进行轮询了,不 ...

  2. 实时 Django 终于来了 —— Django Channels 入门指南

    Reference: http://www.oschina.net/translate/in_deep_with_django_channels_the_future_of_real_time_app ...

  3. Django Channels 入门指南

    http://www.oschina.NET/translate/in_deep_with_django_channels_the_future_of_real_time_apps_in_django ...

  4. 通过Django Channels设计聊天机器人WEB框架

    这两个月都在忙着设计针对银联客服业务的智能聊天机器人,上一周已经交完设计报告,这一周还和部门同事一起分享了系统设计及运行效果.因为时间的关系,系统原型我使用了Flask+jQuery的组合,感觉用以原 ...

  5. 【翻译】Django Channels 官方文档 -- Tutorial

    Django Channels 官方文档 https://channels.readthedocs.io/en/latest/index.html 前言: 最近课程设计需要用到 WebSocket,而 ...

  6. Django Channels简明实践

    1.安装,如果你已经安装django1.9+,那就不要用官方文档的安装指令了,把-U去掉,直接用: sudo pip install channels 2.自定义的普通Channel的名称只能包含a- ...

  7. 【webSokect】基于django Channels的简单实现

    # settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.con ...

  8. django+channels+dephne实现websockrt部署

    当你的django项目中使用channels增加了websocket功能的时候,在使用runserver命令启动时,既可以访问http请求,又可以访问websocket请求.但是当你使用uWSGI+n ...

  9. 第25月第22日 django channels

    1. https://github.com/andrewgodwin/channels-examples/ https://channels.readthedocs.io/en/latest/

随机推荐

  1. Navicat Premium 12破解版激活(全新注册机)

    使用打包下载就可以了 打包下载:(注册机有5.0和5.1用哪个看心情,我用的5.1) 连接:https://pan.baidu.com/s/1ARjFa2vEYxe9sljbrZR8fQ 提取码:lx ...

  2. Go http包执行流程

    Go 语言实现的 Web 服务工作方式与其他形式下的 Web 工作方式并没有什么不同,具体流程如下: -- http包执行流程 Request:来自用户的请求信息,包括 post.get.Cookie ...

  3. R语言:实现SQL的join功能的函数

    library(dplyr) ribao <- full_join(ribao,result,by = '渠道',copy = T) ribao <- full_join(ribao,se ...

  4. 笔记:YSmart: Yet Another SQL-to-MapReduce Translator

    http://web.cse.ohio-state.edu/hpcs/WWW/HTML/publications/papers/TR-11-7.pdf  Introduce样例sql语句:" ...

  5. yield and send的使用详细解释

    https://blog.csdn.net/mieleizhi0522/article/details/82142856 虽然并不完全正确,但是能在使用中帮我们拨开迷雾 再结合另外一篇文章理解了htt ...

  6. 用socket.io实现websocket的一个简单例子

    socket.io 是基于 webSocket 构建的跨浏览器的实时应用. 逛博客发现几个比较好的 一.用socket.io实现websocket的一个简单例子 http://biyeah.iteye ...

  7. 实时更新DataGridView 合计值

    public partial class Form1 : Form { public Form1() { InitializeComponent(); dataGridView1.DataSource ...

  8. bind绑定服务的生命周期

    bindService(service, conn, flags); * service :意图 * conn :activity和服务的连接通道 * flags : BIND_AUTO_CREATE ...

  9. ResourceUtils 创建资源目录工具类

    package com.jcf.utilsdemo; import android.content.Context; import android.content.res.Resources; pub ...

  10. ZooKeeper Lead选举

    前段时间学习了zookeeper,对其中比较难理解并且容易忘掉的知识点做一个记录~ 关键词: myId:表示在集群中,自身对应的id zxId:节点状态发生改变时,产生的一个时间戳,并且这个时间戳全局 ...