欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

django使用channels实现通信的示例

时间:2021-06-28 08:22:10|栏目:Python代码|点击:

1.安装依赖包

pip install channels channels-redis

2.settings.py 修改加上支持

INSTALLED_APPS = [
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'MyWeb.apps.MywebConfig',
  "channels",
]

首先需要建立一个django项目。其中在你自己的app下面 生成consumers.py和routing.py配置文件。

consumers.py:相当于django的视图,也就是说所有的websocket路由过来的执行的函数都在consumers.py类似于django的视图views.py

routing.py:是websocket中的url和执行函数的对应关系。相当于django的urls.py,根据映射关系,当websocket的请求进来的时候,根据用户的请求来触发我们的consumers.py里的方法。

3.安装redis

redis 安装配置默认密码

yum install -y redis

[root@localhost ~]# vim /etc/redis.conf 开启远程
bind 0.0.0.0 
protected-mode no

redis-cli -h 192.168.1.20 -p 6379

4.接着配置settings.py 最底部加上这条。

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

ASGI_APPLICATION = "MyWeb.routing.application"

接着简单的写一下,routing.py 里面

from channels.routing import ProtocolTypeRouter

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

进入django shell 测试是否能连接到数据库

(venv) C:\Users\LyShark\PycharmProjects\MyProject>manage.py shell
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import channels.layers
>>> channel_layer = channels.layers.get_channel_layer()
>>> from asgiref.sync import async_to_sync
>>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})
>>> async_to_sync(channel_layer.receive)('test_channel')
{'type': 'hello'}
>>>

上一篇:深入解析Python设计模式编程中建造者模式的使用

栏    目:Python代码

下一篇:Python-openCV读RGB通道图实例

本文标题:django使用channels实现通信的示例

本文地址:http://www.codeinn.net/misctech/149097.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有