2017-03-02 65 views
1

我试图使用Django渠道创建停留大家连接到插座持久的对象/是Django的渠道WebSocketConsumers无国籍

当我试图创建多个运行之间保持持久的对象,它抛出一个NoneType异常

class MyConsumer(WebsocketConsumer): 


    def __init__(self,path): 
     self.protocol = None 
     WebsocketConsumer.__init__(self, path) 


    def connection_groups(self): 
     return ["test"] 

    # Connected to websocket.connect 
    def connect(self,message): 
     try: 
      self.protocol = "hello" 
     except Exception as exc: 
      print ("Unable to accept incoming connection. Reason: %s" % str(exc)) 
     self.message.reply_channel.send({"accept": True}) 


    # Connected to websocket.receive 
    def receive(self,text=None, bytes=None): 
     text = self.protocol[1] # This throws an error that says protocol is none 
     self.send(text=text, bytes=bytes) 

    # Connected to websocket.disconnect 
    def disconnect(self,message): 
     pass 

回答

2

基于类的消费者是没有证据的,即每当新消息被路由到消费者时,它就创建一个全新的消费者。因此,消费者本身无法在消息之间保存数据。

+0

我已经接受了,但是我会给这个+1,如果你详细说明如何用'channel_session'来做这个事情,而不是请。 – cjds

+0

@cjds channel_session用于存储单个连接的数据,因此您无法使用它将数据公开给每个人。考虑将其存储在像Redis这样的东西中。 –