consumer.py
#accept websocket连接 def connect(self): self.accept()
#从WebSocket接收消息 def receive(self,text_data): text_data_json = json.loads(…
您无法直接从外部代码调用使用者中的方法,因为您需要将特定的使用者实例连接到客户端。这是通过使用消息传递系统或代理作为reddis实现的通道层的工作。 从我所看到的,你已经走向了正确的方向,除了那个 send_job_notification 是一种需要实例化消费者的实例方法。改为使其成为静态方法,因此您可以直接调用它而无需使用消费者实例
send_job_notification
@staticmethod def send_job_notification(message, job_id): channel_layer = get_channel_layer() group_name = 'job_{0}'.format(job_id) channel_layer.group_send( group_name, { "type": "send.notification", "message": message, }
在您的API视图中,您只需将其称为: ChatConsumer.send_job_notification(message, job_id)
ChatConsumer.send_job_notification(message, job_id)