django channels
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的更多相关文章
- Django Channels 学习笔记
一.为什么要使用Channels 在Django中,默认使用的是HTTP通信,不过这种通信方式有个很大的缺陷,就是不能很好的支持实时通信.如果硬是要使用HTTP做实时通信的话只能在客户端进行轮询了,不 ...
- 实时 Django 终于来了 —— Django Channels 入门指南
Reference: http://www.oschina.net/translate/in_deep_with_django_channels_the_future_of_real_time_app ...
- Django Channels 入门指南
http://www.oschina.NET/translate/in_deep_with_django_channels_the_future_of_real_time_apps_in_django ...
- 通过Django Channels设计聊天机器人WEB框架
这两个月都在忙着设计针对银联客服业务的智能聊天机器人,上一周已经交完设计报告,这一周还和部门同事一起分享了系统设计及运行效果.因为时间的关系,系统原型我使用了Flask+jQuery的组合,感觉用以原 ...
- 【翻译】Django Channels 官方文档 -- Tutorial
Django Channels 官方文档 https://channels.readthedocs.io/en/latest/index.html 前言: 最近课程设计需要用到 WebSocket,而 ...
- Django Channels简明实践
1.安装,如果你已经安装django1.9+,那就不要用官方文档的安装指令了,把-U去掉,直接用: sudo pip install channels 2.自定义的普通Channel的名称只能包含a- ...
- 【webSokect】基于django Channels的简单实现
# settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.con ...
- django+channels+dephne实现websockrt部署
当你的django项目中使用channels增加了websocket功能的时候,在使用runserver命令启动时,既可以访问http请求,又可以访问websocket请求.但是当你使用uWSGI+n ...
- 第25月第22日 django channels
1. https://github.com/andrewgodwin/channels-examples/ https://channels.readthedocs.io/en/latest/
随机推荐
- Python回归分析五部曲(三)—一元非线性回归
(一)基础铺垫 一元非线性回归分析(Univariate Nonlinear Regression) 在回归分析中,只包括一个自变量和一个因变量,且二者的关系可用一条曲线近似表示,则称为一元非线性回归 ...
- Django基础之response对象
与由DJango自动创建的HttpRequest对象相比, HttpResponse对象是我们的职责范围了. 我们写的每个视图都需要实例化, 填充和返回一个HttpResponse. HttpResp ...
- OpenGL 开发环境配置:Visual Studio 2017 + GLFW + GLEW
Step1:Visual Studio 2017 Why 开发环境,后面编译GLFW 和 GLEW也要用 How 这里使用的是Visual Studio 2017的 Community 版本,直接官网 ...
- Ioc容器与laravel服务容器初探
一.Ioc容器 某天,小J心血来潮,决定建造一艘星舰,这艘星舰要搭载"与众不同最时尚,开火肯定棒"的电磁炮.于是他写了一个星舰类: class ElectromagneticGun ...
- C++11正则表达式初探
C++正则表达式 在此之前都没有了解过C++的正则,不过现在大多数赛事都支持C++11了,因此有必要学习一下,用于快速A签到题. 所在头文件 #include<regex> 正则表达式语法 ...
- Java关键字volatile的实现原理(四)
简述 volatile 是轻量级的synchronized,在多线程开发中保证了共享变量的可见性.可见性就是当一个线程修改一个共享变量时,另一个线程可以读到修改的值.如果volatile变量使用恰当, ...
- Activity中使用PagerAdapter实现切换代码
主活动 public class ViewPagerManager extends AppCompatActivity { private ViewPager viewPager; @Override ...
- Golang使用RabbitMQ消息中间件amqp协议
"github.com/streadway/amqp" Publish发布 // amqp://<user>:<password>@<ip>:& ...
- C++ STL——C++容器的共性和相关概念
目录 一 STL容器共性机制 二 STL容器的使用场合 三 函数对象 四 谓词 五 内建函数对象 六 函数对象适配器 注:原创不易,转载请务必注明原作者和出处,感谢支持! 注:内容来自某培训课程,不一 ...
- hibernate关联映射之多对多
package loaderman.c_many2many; import java.util.HashSet; import java.util.Set; /** * 开发人员 * * */ pub ...