【问题标题】:Django channels : why is channel_layer.gruop_send getting skipped?Django 频道:为什么 channel_layer.gruop_send 被跳过?
【发布时间】:2019-05-08 11:27:51
【问题描述】:

我正在尝试使用 channel-layers 通过 django-channges 中的 websocket 发送消息,但它被跳过了,甚至没有显示任何异常或错误。

我试图让它在没有异步和异步的情况下也能工作,但没有一个工作。

class stock_consumer(AsyncWebsocketConsumer):

   channel_layer = get_channel_layer()

   async def websocket_connect(self, event):
      await self.accept()
      await self.channel_layer.group_add("stock_group", self.channel_name)
      u = stock_market(api_key, access_token)    
      u.subscribe(u.get_instrument_by_symbol('NYSE', 'AAPL'))
      u.start_websocket(True)
      def quote_update(message):
         stock_consumer.send_message(self, message)
      u.set_on_quote_update(quote_update)

   async def websocket_receive(self, event):
      print(event)

   async def websocket_disconnect(self, message):
      await self.channel_layer.group_discard('stock_grogup', self.channel_name)
      await self.close()

   def send_message(self, message):
      print("before") //runs

      ***SKIPPED BLOCK START***
      self.channel_layer.group_send("stock_group", {
         "type": "send_message",
         "text": json.dumps(message)    
      })
      ***SKIPPED BLOCK END***

      print("after") //runs

【问题讨论】:

  • 你试过await self.channel_layer.group_send吗?
  • @BearBrown 我试过了,但是整个函数 send_message 没有运行

标签: python django python-3.x django-channels


【解决方案1】:

在您的示例中 send_message() 是一种同步方法。默认情况下 self.channel_layer.group_send 是异步方法。所以你应该使用 async_to_sync:

from asgiref.sync import async_to_sync

# ....

   def send_message(self, message):
      print("before") //runs

      ***SKIPPED BLOCK START***
      async_to_sync(self.channel_layer.group_send)("stock_group", {
         "type": "send_message",
         "text": json.dumps(message)    
      })
      ***SKIPPED BLOCK END***

      print("after") //runs

更多信息:https://channels.readthedocs.io/en/latest/topics/channel_layers.html#synchronous-functions

【讨论】:

  • 试试这个它说You cannot use AsyncToSync in the same thread as an async event loop
  • 好的,所以也许这不是一条好路。为什么要调用 stock_consumer.send_message(self, message) 而不是 self.send_message(message)?这看起来很奇怪。在类而不是实例上调用方法?
猜你喜欢
  • 2021-11-07
  • 1970-01-01
  • 2021-03-19
  • 2015-05-06
  • 2014-05-28
  • 1970-01-01
  • 2018-09-17
  • 2014-09-24
  • 2016-12-13
相关资源
最近更新 更多