【问题标题】:How to send channel_session data from outside the consumer class如何从消费者类外部发送 channel_session 数据
【发布时间】:2018-07-12 05:03:42
【问题描述】:

我在从消费者类之外的 channel_session 发送数据时遇到问题。

我的消费者是这样的:-

class myconsumer(AsyncWebsocketConsumer):
    #all init connect function

    def subscribe(self):
        self.channel_Session = payload['data']

    #some other functions

现在的问题是,我想通过一个称为线程的异步函数发送这个 self.channel_session。

async def sendData():
    while True:
        #send data
        await asyio.sleep(5)

class thread(multiprocess.Process):
     try:
         loop = asyncio.bew_event_loop()
     except Exception as e:
          loop = asyncio.get_event_loop()
     loop.run_until_complete(sendData())

此线程在启动服务器时启动。

问题

我找不到发送通道会话的方法

任何帮助将不胜感激。

【问题讨论】:

    标签: django websocket django-rest-framework django-channels


    【解决方案1】:

    首先使用get_channel_layer()获取与redis通信的活动层,然后调用group_send调用type参数指定的消费者方法。

    from channels.layers import get_channel_layer
    
    async def sendData():
        channel_layer = get_channel_layer()
        while True:
            await channel_layer.group_send(
                << your_group_name_here >>,
                {
                    'type': 'subscribe',
                    'message': 'custom message'
                }
            )
            await asyncio.sleep(5)
    

    【讨论】:

      猜你喜欢
      • 2022-08-09
      • 2022-09-27
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 2020-07-16
      • 2019-05-20
      相关资源
      最近更新 更多