温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

django使用channels如何实现通信

发布时间:2020-10-27 18:08:18 来源:亿速云 阅读:168 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关django使用channels如何实现通信,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

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使用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 最底部加上这条。

django使用channels如何实现通信

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'}
>>>

以上就是django使用channels如何实现通信,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI