Django Channels WebSocketConsumers 是无状态的吗

Are Django Channels WebSocketConsumers stateless

我正在尝试使用 Django 通道创建一个对连接到套接字的每个人都保持持久的对象/

当我尝试创建一个在多次 receive() 运行之间保持持久的对象时,它抛出一个 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

Class 基于消费者未实例化,i。 e.每次将新消息路由到消费者时,它都会创建一个全新的消费者。因此,无法在消费者本身的消息之间持久保存数据。

你可以和工人一起做。工作人员创建一个不会消失的消费者实例。该实例中的对象也会保留。如果你想访问你的对象,你可以发送 requests/messages 给工作人员,工作人员又将他们委托给对象。