I'm trying to use channels(v2.1.7) in django to send messages from server to client. When i execute the celery task below, my message is not being fetched in consumers.py(so not being sent to client) and surprisingly no error occures.
I'm able to send message from consumers to client directly. But i couldn't manage to send from outside of consumers using async_to_sync().
(I tried to use async_to_sync method in standard django views.py and i had same problem)
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']))
the result that i have in celery terminal click to see celery terminal
Thanks in advance
看起来你正在使用channel_layer.send方法,但我认为你实际上想要使用channel_layer.group_send。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.