gpt4 book ai didi

python - Django Channels WebSocketConsumers 是无状态的吗

转载 作者:行者123 更新时间:2023-12-01 03:14:50 25 4
gpt4 key购买 nike

我正在尝试使用 Django channel 创建一个对象,该对象对于连接到套接字的每个人都保持持久性/

当我尝试创建一个在多次 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

最佳答案

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

关于python - Django Channels WebSocketConsumers 是无状态的吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42564524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com