1 回答

TA貢獻(xiàn)1943條經(jīng)驗(yàn) 獲得超7個(gè)贊
您首先必須使用以下代碼連接到您的 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
}))
它會(huì)將您連接到您在設(shè)置文件中定義的默認(rèn)后端層:
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost", 6379)],
},
},
}
并將在您的班級(jí)中為擁有該組的所有用戶調(diào)用一個(gè)名為notify(函數(shù)名稱是您的選擇)的函數(shù)Consumer<group_name>
async def notify(self, event):
data = event["message"]
# here you can do whatever you want to do with data
有關(guān)更多信息,您可以在此處獲得工作示例:https ://channels.readthedocs.io/en/latest/tutorial/part_2.html#enable-a-channel-layer
添加回答
舉報(bào)