Django频道:为什么是频道_layer.gruop\u发送被跳过了?

2024-04-19 20:59:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过使用通道层的django Changels中的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

Tags: selfeventsendlayermessageasyncdefstock
1条回答
网友
1楼 · 发布于 2024-04-19 20:59:20

在您的示例中,send_message()是一个同步方法。默认情况下self.channel\u层.group\u send是异步方法。所以您应该使用异步\u到\u同步:

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

相关问题 更多 >