django使用channels實(shí)現(xiàn)通信的示例
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',]

首先需要建立一個(gè)django項(xiàng)目。其中在你自己的app下面 生成consumers.py和routing.py配置文件。
consumers.py:相當(dāng)于django的視圖,也就是說所有的websocket路由過來的執(zhí)行的函數(shù)都在consumers.py類似于django的視圖views.py
routing.py:是websocket中的url和執(zhí)行函數(shù)的對(duì)應(yīng)關(guān)系。相當(dāng)于django的urls.py,根據(jù)映射關(guān)系,當(dāng)websocket的請(qǐng)求進(jìn)來的時(shí)候,根據(jù)用戶的請(qǐng)求來觸發(fā)我們的consumers.py里的方法。
3.安裝redis
redis 安裝配置默認(rèn)密碼yum install -y redis[root@localhost ~]# vim /etc/redis.conf 開啟遠(yuǎn)程bind 0.0.0.0 protected-mode noredis-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 ProtocolTypeRouterapplication = ProtocolTypeRouter({ # Empty for now (http->django views is added by default)})
進(jìn)入django shell 測(cè)試是否能連接到數(shù)據(jù)庫
(venv) C:UsersLySharkPycharmProjectsMyProject>manage.py shellPython 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32Type '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實(shí)現(xiàn)通信的示例的詳細(xì)內(nèi)容,更多關(guān)于channels實(shí)現(xiàn)通信的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. JSP動(dòng)態(tài)網(wǎng)頁開發(fā)原理詳解2. Python使用Excel將數(shù)據(jù)寫入多個(gè)sheet3. PHP驗(yàn)證碼工具-Securimage4. HTML iframe標(biāo)簽用法案例詳解5. php基于DOMDocument操作頁面元素實(shí)例 原創(chuàng)6. jsp中sitemesh修改tagRule技術(shù)分享7. HTML-Canvas的優(yōu)越性能以及實(shí)際應(yīng)用8. 如何用JS實(shí)現(xiàn)簡單的數(shù)據(jù)監(jiān)聽9. 在CentOS上成功安裝Smarty10. 使用本機(jī)IIS?Express開發(fā)Asp.Net?Core應(yīng)用圖文教程

網(wǎng)公網(wǎng)安備