Django 频道还是信号?

Django channels or Signals?

用户通知的渠道或信号。

我目前正在创建这个在线预订 Django 应用程序。我是 django 的新手,我想知道我应该用什么来通知某些用户已经进行了新的预订。一旦 he/she 已登录,用户将收到通知。我使用频道还是信号?

您可以同时使用两者。您可以使用 Django 通道创建 Web 套接字,以便在客户端和服务器之间进行双工通信。然后,您应该创建一个信号来收听新的预订创建事件。

每次创建新预订时,都会触发信号并通过网络套接字将数据发送到客户端。

在名为“Reload”的消费者class的连接方法中,我们定义了一个名为“id”的全局变量。变量的值是消费者 websocket 连接的实例。我们在 class “custom_signal” 之外定义了一个 django 信号,它在创建 Person 对象时触发,并使用 id 变量通过 websocket 发送消息。

class Reload(WebsocketConsumer):

    def connect(self):
      # accept connection
      self.accept()
      
    
      global id # create a global variable so that its accessible outside of the class
      id = self # assign the instance of the consumer class to the global variable
    
    def disconnect(self, close_code):
      pass
    
    # receive message from websocket
    def receive(self, text_data):
      text_data_json = json.loads(text_data)
      print(text_data_json)
      self.send(text_data=json.dumps({'message':'Its working'}))

# django signal that runs custom_signal function when a Person object is created
@receiver(signal=post_save, sender=Person) 
def custom_signal(**kwargs):
   
    # send a message through the websocket connection through the global variable
    id.send(text_data=json.dumps({'message':'updated'}))