通道 - 接收到信号时如何通过 websocket 发送数据?



我想通过websocket从数据库流式传输数据。基本上每秒都会有一条新记录入到 DataModel 中,我想在插入后立即通过 websocket 发送这条新记录。有人建议我在调用模型的 save(( 方法时使用 signal。因此,对于我的 models.py,我只是添加了以下内容:

def save_post(sender, instance, **kwargs):
print('signal')
post_save.connect(save_post, sender=DataModel)

我应该在save_post里面和 consumers.py 上放什么,以便数据通过?

你首先必须使用以下代码连接到你的 django 通道层:

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
channel_layer = get_channel_layer()
data = <your-data> # data you want to send
async_to_sync(channel_layer.group_send(<group_name>, {
"type": "notify",
"message": data
}))

它会将您连接到您在设置文件中定义的默认后端层:

CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost", 6379)],
},
},
}

并将在Consumer类中为具有组<group_name>的所有用户调用名为notify的函数(函数名称由您选择(

async def notify(self, event):
data = event["message"]
# here you can do whatever you want to do with data

有关更多信息,您可以在此处获得工作示例:https://channels.readthedocs.io/en/latest/tutorial/part_2.html#enable-a-channel-layer

最新更新