[英]Is this a good way to stream data through django channels?
I have a database where new data is being inserted every second.我有一个数据库,每秒都会插入新数据。 When the websockets connection is first established, I want to send all the data using django channels.
首次建立 websockets 连接时,我想使用 django 通道发送所有数据。 Then, I want the new data data that goes every second into the database to be sent through the same websocket.
然后,我希望每秒进入数据库的新数据数据通过相同的 websocket 发送。 I have the following consumers.py
我有以下consumers.py
class DataConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("connected", event)
await self.send({
"type": "websocket.accept"
})
obj = ... send the whole db
await self.send({
'type': 'websocket.send',
'text': obj
})
while True:
await asyncio.sleep(1)
obj = ... send only new records
await self.send({
'type': 'websocket.send',
'text': obj
})
async def websocket_receive(self, event):
print("receive", event)
async def websocket_disconnect(self, event):
print("disconnected", event)
Here Django Channels - constantly send data to client from server they mention that the loop will never exit if the user disconnects.此处Django 通道 - 不断从服务器向客户端发送数据,他们提到如果用户断开连接,循环将永远不会退出。 They present a potential fix, but I don't understand it well.
他们提出了一个潜在的解决方案,但我不太了解。 How could I fix it?
我该如何解决?
Basically what you have to do is rather than writing, while True:
.基本上你要做的不是写作,
while True:
. Rather, you should define a global variable say is_connected
and on connection set it to True
and on disconnected make is False
and while
condition must use this variable as follow:相反,您应该定义一个全局变量,比如
is_connected
并在连接时将其设置为True
并且在断开连接时将其设置为False
并且while
条件必须使用此变量,如下所示:
class DataConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("connected", event)
await self.send({
"type": "websocket.accept"
})
obj = ... send the whole db
await self.send({
'type': 'websocket.send',
'text': obj
})
# here set is_connected to True
self.is_connected = True
while is_connected:
await asyncio.sleep(1)
obj = ... send only new records
await self.send({
'type': 'websocket.send',
'text': obj
})
async def websocket_receive(self, event):
print("receive", event)
async def websocket_disconnect(self, event):
# set is_connected to false
is_connected = False
print("disconnected", event)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.