【问题标题】:Django channels - unable to subscribe to groupsDjango 频道 - 无法订阅群组
【发布时间】:2022-01-19 22:15:59
【问题描述】:

我正在尝试发送 consumer.py 信息以显示在 consumer.py 之外的客户端上。

我已经引用了Send message using Django Channels from outside Consumer classthis previous question,但子进程.group_send.group_add似乎不存在,所以我觉得我可能错过了一些非常容易的东西。

Consumers.py

from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync

class WSConsumer(WebsocketConsumer):
    def connect(self):
        async_to_sync(self.channel_layer.group_add)("appDel", self.channel_name)
        self.accept()

        self.render()

appAlarm.py

def appFunc(csvUpload):
    #csvUpload=pd.read_csv(request.FILES['filename'])
    csvFile = pd.DataFrame(csvUpload)
    colUsernames = csvFile.usernames
    print(colUsernames)

    channel_layer = get_channel_layer()

    for user in colUsernames:
        req = r.get('https://reqres.in/api/users/2')
        print(req)
        t = req.json()
        data = t['data']['email']
        print(user + " " + data)
        
        message = user + " " + data
        async_to_sync(channel_layer.group_send)(
        'appDel',
        {'type': 'render', 'message': message}
    )

它抛出了这个错误:

    async_to_sync(channel_layer.group_send)(
AttributeError: 'NoneType' object has no attribute 'group_send'

并且在将group_add 剥离更多以弄清楚发生了什么时,会为group_add 抛出相同的错误,但根据HERE 的文档,我觉得这应该可以工作。

【问题讨论】:

    标签: python django django-channels


    【解决方案1】:

    对于将来看到这个的人来说,由于成本原因,我无法在 Windows 操作系统中使用 redis 甚至 memurai。我最终使用了服务器端事件 (SSE),特别是 django-eventstream,到目前为止它工作得很好,因为我不需要客户端与服务器交互,对于聊天应用程序来说,这是行不通的。

    Eventstream 在/events/ 创建一个端点,客户端可以连接并接收流式 http 响应。

    从 externalFunc.py 发送数据:

    send_event('test', 'message', {'text': 'Hello World'})
    

    HTML 页面中的事件监听器:

    var es = new ReconnectingEventSource('/events/');
    
    es.addEventListener('message', function (e) {
        console.log(e.data);
    
        var source = new EventSource("/events/")
    
        var para = document.createElement("P");
        const obj = JSON.parse(event.data)
        para.innerText = obj.text;
        document.body.appendChild(para)
    
    }, false);
    
    es.addEventListener('stream-reset', function (e) {
    }, false);
    

    【讨论】:

      猜你喜欢
      • 2017-03-24
      • 2022-08-09
      • 2022-06-11
      • 2017-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 2022-01-03
      相关资源
      最近更新 更多