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
添加回答
舉報