我正在尝试使用 channel-layers 通过django通道中的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
答案 0 :(得分:0)
在您的示例中,send_message()是一种同步方法。默认情况下,self.channel_layer.group_send是异步方法。因此,您应该使用async_to_sync:
import numpy as np
import matplotlib.pyplot as plt
img_o = plt.imread('1.jpg')
img = plt.imread('2.jpg')
img_o = np.dstack((img_o,img_o,img_o))
img = np.dstack((img,img,img))
fig, (ax, ax2) = plt.subplots(ncols=2)
im1 = ax.imshow(img)
im2 = ax2.imshow(img_o)
plt.show()
更多信息:https://channels.readthedocs.io/en/latest/topics/channel_layers.html#synchronous-functions