国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

django使用channels實現(xiàn)通信的示例

瀏覽:3日期:2024-09-20 11:41:31

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實現(xiàn)通信的示例

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

consumers.py:相當于django的視圖,也就是說所有的websocket路由過來的執(zhí)行的函數(shù)都在consumers.py類似于django的視圖views.py

routing.py:是websocket中的url和執(zhí)行函數(shù)的對應(yīng)關(guān)系。相當于django的urls.py,根據(jù)映射關(guān)系,當websocket的請求進來的時候,根據(jù)用戶的請求來觸發(fā)我們的consumers.py里的方法。

3.安裝redis

redis 安裝配置默認密碼yum install -y redis[root@localhost ~]# vim /etc/redis.conf 開啟遠程bind 0.0.0.0 protected-mode noredis-cli -h 192.168.1.20 -p 6379

4.接著配置settings.py 最底部加上這條。

django使用channels實現(xiàn)通信的示例

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

進入django shell 測試是否能連接到數(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實現(xiàn)通信的示例的詳細內(nèi)容,更多關(guān)于channels實現(xiàn)通信的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標簽: Django
相關(guān)文章:
主站蜘蛛池模板: 泰州市| 桐庐县| 玉门市| 大兴区| 许昌县| 枣阳市| 信阳市| 府谷县| 峨边| 织金县| 永登县| 嘉善县| 芦溪县| 揭阳市| 本溪| 阿坝| 德钦县| 溆浦县| 宾阳县| 深泽县| 克什克腾旗| 密山市| 达孜县| 锡林郭勒盟| 红安县| 清水河县| 大同市| 府谷县| 纳雍县| 富顺县| 胶南市| 万安县| 永丰县| 牙克石市| 大姚县| 海口市| 库车县| 安岳县| 任丘市| 宜春市| 夹江县|