【问题标题】:django channels not working how does it work i have read docsdjango 频道不工作它是如何工作的我已经阅读了文档
【发布时间】:2016-10-18 18:18:44
【问题描述】:

我正在尝试使用频道但无法正常工作 这是consumer.py

def ws_connect(message, cat_id):
    try:
        cat = Categories.objects.get(pk=cat_id)
    except Categories.DoesNotExist:
        pass
    Group('cat-1').add(message.reply_channel)


def ws_diconnect(message, cat_id):
    try:
        cat = Categories.objects.get(pk=cat_id)

    except Categories.DoesNotExist:
        pass
    Group('cat-1').discard(message.reply_channel)

这是 routing.py :

channel_routing = [
    route('websocket.receive', ws_connect, path=r'^/liveupdate/(?P<cat_id>\d+)/'),
    route("websocket.disconnect", ws_diconnect, path=r'^/liveupdate/(?P<cat_id>\d+)/'),
]

这是信号.py:

@receiver(post_save, sender=Tender)
def send_update(sender, instance, created, raw, using, **kwargs):
    print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>', instance, '2', raw, '3', using, '4', kwargs
    data = json.dumps(
        {'ministry': 'hisham',})
    Group('cat-1').send({'tender': data,})
    print 'Done'

这里是javascript:

<script type="application/javascript">
    var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
    alert(ws_scheme +"://" + window.location.host + "/liveupdate/1/");
    var socket = new WebSocket(ws_scheme +"://" + window.location.host + "/liveupdate/1/");
    socket.onmessage = function(e) {
    alert(e.data);
};
    socket.onopen = function() {
        console.log("Connected to  socket");
    };
    socket.onclose = function() { console.log("Disconnected to  socket"); }

</script>

当我试图保存招标信号时,浏览器中什么也没有 即没有数据警报 我的代码有什么问题 任何想法

这是我的文件夹:

【问题讨论】:

  • 您是否在已安装的应用中添加了频道应用和asgi?
  • @Anurag INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib。 messages', 'django.contrib.staticfiles', 'Customeauth', 'Register', 'channels', 'django_countries', ]
  • 我在项目中添加了文件夹的照片,看看@Anurag
  • 我把 consumer.py 移到了 Register 但还是一样

标签: javascript python django django-models websocket


【解决方案1】:

使用 websocket.connect 代替 websocket.receive。当客户端向服务器发送数据时使用接收。

route('websocket.connect', ws_connect, path=r'^/liveupdate/(?P<cat_id>\d+)/'),

您何时发送数据而不是使用 text 作为 Key。

Group('cat-1').send({'text': data,})

【讨论】:

  • 请尝试 1 分钟
  • 非常感谢你让我开心了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
相关资源
最近更新 更多