【问题标题】:django channels message.reply_channel no attribute senddjango 频道 message.reply_channel 无属性发送
【发布时间】:2016-07-24 17:13:20
【问题描述】:

我一直在尝试了解 Django 的频道,但无法将消息发送到我的 websocket。

这是我的consumers.py

import logging
from django.contrib.sites.models import Site
from django.utils import timezone
from channels import Group
from .models import *
import json

def send_free(message):
    try:
        pi = PInformation.objects.get(
            pk=message.content.get('pk'),
        )
    except Parkplatzinformationen.DoesNotExist:
        logging.error("PI not found!")
        return

    try:
        message.reply_channel.send({
        "text": 1,
    })
    except:
        logging.exception('Problem sending %s' % (pi.name))

我的routing.py

from channels.routing import route

from RESTAPI.consumers import send_free

channel_routing = [
    route('send-free',send_free),
]

我收到错误 AttributeError: 'NoneType' object has no attribute 'send'。然而,它确实获得了 PInformation 对象,因此它确实“有点”工作。我在保存对象后立即调用它。

你能给我一些提示吗? The Getting Started guide 使用它就像我尝试的那样。

【问题讨论】:

    标签: python django django-channels


    【解决方案1】:

    我假设你是这样从你的角度调用"send-free"...

    Channel('send-free').send({'message': 'your message'})
    

    那么send_free 没有message.reply_channel...

    换句话说,一旦WebSocket packet is sent to us by a client then 消息从它那里获取reply_channel 属性。这将用于将消息回复给客户端......(可能是前端)

    所以你真的要发送消息...?然后再次使用消费者发送...

    【讨论】:

    • 是的,你是对的,我正在按照你描述的方式调用 send-free。但是我不明白重复这个过程是什么意思。
    • @dowu 重复 Channel("cons").send(dict) 我也编辑了答案..
    • 好的,所以我再次调用Channel("otherchanel").send(dict) 而不是message.reply_channel.send? “其他频道”不应该链接到一个函数,所以我遇到了同样的问题吗?
    • 你想发回什么信息,为什么?您正在从您的视图中调用消费者函数,然后您希望您的消费者将消息发送回视图?
    • 我想在对象更新后向客户端发送一个字典,以便我可以在主页上显示该信息(使用 javascript 检索它)。 (感谢您的耐心等待)
    猜你喜欢
    • 1970-01-01
    • 2017-09-02
    • 2020-09-07
    • 2021-01-03
    • 1970-01-01
    • 2016-09-21
    • 2018-06-19
    • 1970-01-01
    • 2020-07-16
    相关资源
    最近更新 更多