2017-02-22 99 views
0

我試圖創建一個消費者按照本教程'MyConsumer' 有沒有屬性「clients_connected'`

https://channels.readthedocs.io/en/stable/generics.html

class MyConsumer(WebsocketConsumer): 
def __init__(self,path): 
    WebsocketConsumer.__init__(self,path) 
    self.client_id_seed = 0 
    self.clients_connected = 0 
    # The following are passed on to RosbridgeProtocol 
    self.fragment_timeout = 600     # seconds 
    self.delay_between_messages = 0    # seconds 
    self.max_message_size = None 
    self.protocol = None 

def connection_groups(self): 
    """ 
    Called to return the list of groups to automatically add/remove 
    this connection to/from. 
    """ 
    return ["test"] 

# Connected to websocket.connect 
def connect(self,message): 
    parameters = { 
     "fragment_timeout": self.fragment_timeout, 
     "delay_between_messages": self.delay_between_messages, 
     "max_message_size": self.max_message_size 
    } 
    try: 
     self.protocol.outgoing = self.receive 
     self.client_id_seed += 1 
     self.clients_connected += 1 
    except Exception as exc: 

     print ("Unable to accept incoming connection. Reason: %s" % str(exc)) 
    print "Client connected. %d clients total." % self.clients_connected 
    self.message.reply_channel.send({"accept": True}) 


# Connected to websocket.receive 
def receive(self,text=None, bytes=None): 
    # binary = type(message)==bson.BSON 
    self.send(text=text, bytes=bytes) 

# Connected to websocket.disconnect 
def disconnect(self,message): 
    self.clients_connected -= 1 

我得到了錯誤的稱號,但我已經明確地在我的構造函數中定義了它。從disconnect方法調用該錯誤

回答

0

消費者不應該用這樣的構造函數創建。每次請求進入時都會創建一個新的消費者對象。此外,構造函數將消費者發送到等待狀態,並且從不運行代碼。

解決上述錯誤的最佳方法是將super的構造函數移動到__init__的最後一行,但理想情況下,您希望使用會話來存儲信息。