[英]sending message to client using Django Channels from Celery tasks.py
我正在嘗試使用django中的頻道(v2.1.7)將消息從服務器發送到客戶端。 當我執行下面的芹菜任務時,我的消息沒有在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']))
我在芹菜終端 點擊查看芹菜終端的結果
提前致謝
看起來你正在使用channel_layer.send方法,但我認為你實際上想要使用channel_layer.group_send。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.