2017-03-02 70 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這樣的東西中。 –