我想通过 websocket 从数据库流式传输数据。基本上,每秒钟都会有一条新记录被插入DataModel中,我想在新记录插入后立即通过websocket发送。有人建议我在模型的save()方法被调用时使用信号。所以我在models.py中添加了这个。
def save_post(sender, instance, **kwargs):
print('signal')
post_save.connect(save_post, sender=DataModel)
我在里面加了什么 save_post
并在我的consumer.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)],
},
},
}
并将调用一个名为 notify
(函数名称由您选择)在您的 Consumer
类的所有用户的 <group_name>
async def notify(self, event):
data = event["message"]
# here you can do whatever you want to do with data
更多信息,你可以在这里找到工作实例。https:/channels.readthedocs.ioenlatesttutorialpart_2.html#enable-a-channel-layer。