1 回答

TA贡献1943条经验 获得超7个赞
您首先必须使用以下代码连接到您的 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.io/en/latest/tutorial/part_2.html#enable-a-channel-layer
添加回答
举报