通过Celery任务使用Django通道向客户端发送消息。

时间:2019-03-15 17:19:11

标签: python django websocket celery django-channels

我正在尝试使用Django中的channel(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']))

我在芹菜终端中得到的结果  click to see celery terminal

预先感谢

1 个答案:

答案 0 :(得分:0)

It looks like you are using the channel_layer.send method, but I think you actually want to use channel_layer.group_send instead.