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/
随机推荐
- [bat]只更新svn部分文件夹
游戏工程里的sdk文件夹,经常被svn认定为有毒文件. 后来关了权限之后,已拉取过的sdk文件夹还是会拉下来. 网上找了个方法,bat文件只更新部分文件. TortoiseProc /command: ...
- UVA 1393 Highways,UVA 12075 Counting Triangles —— (组合数,dp)
先看第一题,有n*m个点,求在这些点中,有多少条直线,经过了至少两点,且不是水平的也不是竖直的. 分析:由于对称性,我们只要求一个方向的线即可.该题分成两个过程,第一个过程是求出n*m的矩形中,dp[ ...
- redis延时监控
一. slow log慢查询日志 Redis监控工具,命令和调优 slowlog是 Redis 用来记录查询执行时间的日志系统.slowlog-log-slower-than设置慢操作的阈值,单位是微 ...
- 刘汝佳dicnic模板
#include<iostream> #include<cstdio> #include<algorithm> #include<vector> #in ...
- Qt多线程应用--QRunnable
http://blog.csdn.net/lefttime/article/details/5717349 作为Qt类中少有的基类, QRunnable提供了简洁有效的可运行对象的创建. 用QRun ...
- MySQL-插入更新 ON DUPLICATE KEY UPDATE
向数据库中插入一条记录,若该数据的主键值(UNIQUE KEY)已经在表中存在,则执行后面的 UPDATE 操作.否则执行前面的 INSERT 操作. 测试表结构 CREATE TABLE `flum ...
- Flutter移动电商实战 --(8)dio基础_伪造请求头获取数据
在很多时候,后端为了安全都会有一些请求头的限制,只有请求头对了,才能正确返回数据.这虽然限制了一些人恶意请求数据,但是对于我们聪明的程序员来说,就是形同虚设.这篇文章就以极客时间 为例,讲一下通过伪造 ...
- 3.ibatis4种事务类型浅析
ibatis中Transaction有四个实现类 其中spring的SqlMapClientFactoryBean类中 private Class transactionConfigClass = E ...
- Django连接MySQL出错
错误一:No module named 'MySQLdb' 原因:python3连接MySQL不能再使用mysqldb,取而代之的是pymysql. 解决方法:在python的MySQL包中,即路径: ...
- 控制器Controller
1) org.springframework.web.servlet.mvc.ParameterizableViewController 如果请求是/hello.action的请求路径,则直接跳转到 ...