从 Celery tasks.py 使用 Django Channels 向客户端发送消息
sending message to client using Django Channels from Celery tasks.py
我正在尝试使用 django 中的通道 (v2.1.7) 将消息从服务器发送到客户端。当我执行下面的 celery 任务时,我的消息没有在 consumers.py 中获取(因此没有被发送到客户端)并且令人惊讶的是没有发生错误。
我可以直接从消费者向客户端发送消息。但我无法使用 async_to_sync() 从外部消费者发送。
(我尝试在标准 django views.py 中使用 async_to_sync 方法,但我遇到了同样的问题)
wololo/tasks.py
@app.task(name='wololo.tasks.upgrade_building')
def upgrade_building(user_id):
os.environ['DJANGO_SETTINGS_MODULE'] = 'DjangoFirebaseProject.settings'
from channels.layers import get_channel_layer
channel_layer = get_channel_layer()
print(channel_layer, "wololo")
async_to_sync(channel_layer.send)('chat', {
'type': 'hello.message',
'message': 'hadiInsss',
})
return True
wololo/consumers.py
from channels.generic.websocket import WebsocketConsumer
import json
from asgiref.sync import async_to_sync
class ChatConsumer(WebsocketConsumer):
def connect(self):
async_to_sync(self.channel_layer.group_add)("chat", self.channel_name)
self.accept()
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)("chat", self.channel_name)
def hello_message(self, event):
print("U MUST SEE THAT MSG")
# Send a message down to the client
self.send(text_data=json.dumps(event['message']))
我在 celery 终端的结果
click to see celery terminal
提前致谢
看起来您使用的是 channel_layer.send 方法,但我认为您实际上想使用 channel_layer.group_send 方法。
我正在尝试使用 django 中的通道 (v2.1.7) 将消息从服务器发送到客户端。当我执行下面的 celery 任务时,我的消息没有在 consumers.py 中获取(因此没有被发送到客户端)并且令人惊讶的是没有发生错误。
我可以直接从消费者向客户端发送消息。但我无法使用 async_to_sync() 从外部消费者发送。
(我尝试在标准 django views.py 中使用 async_to_sync 方法,但我遇到了同样的问题)
wololo/tasks.py
@app.task(name='wololo.tasks.upgrade_building')
def upgrade_building(user_id):
os.environ['DJANGO_SETTINGS_MODULE'] = 'DjangoFirebaseProject.settings'
from channels.layers import get_channel_layer
channel_layer = get_channel_layer()
print(channel_layer, "wololo")
async_to_sync(channel_layer.send)('chat', {
'type': 'hello.message',
'message': 'hadiInsss',
})
return True
wololo/consumers.py
from channels.generic.websocket import WebsocketConsumer
import json
from asgiref.sync import async_to_sync
class ChatConsumer(WebsocketConsumer):
def connect(self):
async_to_sync(self.channel_layer.group_add)("chat", self.channel_name)
self.accept()
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)("chat", self.channel_name)
def hello_message(self, event):
print("U MUST SEE THAT MSG")
# Send a message down to the client
self.send(text_data=json.dumps(event['message']))
我在 celery 终端的结果 click to see celery terminal
提前致谢
看起来您使用的是 channel_layer.send 方法,但我认为您实际上想使用 channel_layer.group_send 方法。