簡體   English   中英

Django頻道:為什么要跳過channel_layer.gruop_send?

[英]Django channels : why is channel_layer.gruop_send getting skipped?

我正在嘗試使用channel-layers在django-channgels中通過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

在您的示例中,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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM