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地理信息数据可视化
地图 基础铺垫 定义 地图(map):是指按一定的比例运用符号.颜色.文字标记等描绘显示地球表面的自然地理.行政区域.社会经济状况的图形. 地图绘制步骤 绘制需要展示的地图,获取地图对象,获取每个区域 ...
- Java字节码例子解析
举个简单的例子: public class Hello { public static void main(String[] args) { String string1 = ...
- linux磁盘内存满了?删除大文件依然不起作用
好久没有更新博客了,但并不代表自己没有遇到技术问题了.遇到了一大堆,也解决了一大堆.只是没有记下来的欲望了,似乎大脑就这样,忘不掉.啥都忘不掉了,即使忘掉了也知道如何百度了. 查看目录大小命令 du命 ...
- IntelliJ IDEA利用Maven下载所需的JAR包到项目中
直接复制JetBrains/../conf/settings.xml后修改镜像出现问题,然后用了这里的settings.xml配置文件.
- HTML5调用本地摄像头画面,拍照,上传服务器
实现功能和适用业务 采集本地摄像头获取摄像头画面,拍照保存,上传服务器: 前端上传图片处理,展示,缩小,裁剪,上传服务器 实现步骤 调取本地摄像头(getUserMedia)/上传图片,将图片/视频显 ...
- Netfilter 之 钩子函数注册
通过注册流程代码的分析,能够明确钩子函数的注册流程,理解存储钩子函数的数据结构,如下图(点击图片可查看原图): 废话不多说,开始分析: nf_hook_ops是注册的钩子函数的核心结构,字段含义如下所 ...
- CNN中感受野大小的计算
1 感受野的概念 从直观上讲,感受野就是视觉感受区域的大小.在卷积神经网络中,感受野的定义是 卷积神经网络每一层输出的特征图(feature map)上的像素点在原始图像上映射的区域大小. 2 感受野 ...
- pytorch-Resnet网络
残差网络:将输入层与输出层进行连接,保证了经过这层网路结构,网络的运算能力不会出现较大的改变 网络解析: 第一层网络: 输入网络经过一个卷积层,再经过一个batch_normalize, 再经过一个r ...
- C memcpy()用法
https://blog.csdn.net/qq_21792169/article/details/50561570
- easyUI之validatebox验证框
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <hea ...