'Django sending data from outside consumer class
I am trying to get use Django channels to send data over a websocket to my react native application from django. I have read all the available documentation on this subject on Django and have went through numerous stackoverflow posts, but I don't think they are applicable to me because they use redis and I decided not to use redis.
Whenever I try to send data right now, nothing sends.
These are my files.
models.py
from django.db import models
import json
from .consumers import DBUpdateConsumer
from django.db.models.signals import post_save
from django.dispatch import receiver
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
channel_layer = get_channel_layer()
class Connect(models.Model):
id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
neighborhood = models.CharField(max_length=50, choices=neighborhood_choices, default='all')
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.CharField(max_length=100)
phone = models.CharField(max_length=50)
def save(self, *args, **kwargs):
super().save(self, *args, **kwargs)
print("def save")
async_to_sync(channel_layer.send)("hello", {"type": "something", "text": "hellooo"})
class Meta:
managed = False
db_table = 'connect'
settings.py
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer"
}
}
consumers.py
import json
from channels.generic.websocket import AsyncJsonWebsocketConsumer
#used https://blog.logrocket.com/django-channels-and-websockets/
#https://channels.readthedocs.io/en/latest/topics/consumers.html
class DBUpdateConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
self.send_message(self, "UPDATE")
await self.accept()
await self.send(text_data=json.dumps({
"payload": "UPDATE",
}))
print("connect!")
async def disconnect(self, close_code):
print("Disconnected")
async def receive(self, text_data):
"""
Receive message from WebSocket.
Get the event and send the appropriate event
"""
response = json.loads(text_data)
#event = response.get("event", None)
#message = response.get("message", None)
print(response)
@classmethod
async def send_message(cls, self, res):
# Send message to WebSocket
print("send msg")
await self.send(text_data=json.dumps({
"payload": res,
}))
print("send msg")
What I am trying to do is whenever a new value is stored in my database, I am trying to send a message through a websocket that connects my react native app and my django backend. The websocket currently connects fine, but I am having trouble using the send_message function contained within my consumers.py file from outside consumers.py. So what I am trying to do is in my models.py file, send a message to all the channels that are open to eventually update my database. Currently, I am just trying to send test messages through, but no matter what I do, nothing goes through, and being a newbie to Django, I have no idea why.
Thank you!
Solution 1:[1]
Solved, with some help from a friend!
consumers.py
`import json from channels.generic.websocket import AsyncJsonWebsocketConsumer from .models import Client from asgiref.sync import sync_to_async
#used https://blog.logrocket.com/django-channels-and-websockets/ #https://channels.readthedocs.io/en/latest/topics/consumers.html
class DBUpdateConsumer(AsyncJsonWebsocketConsumer): async def connect(self): print("channel name is " + self.channel_name) await sync_to_async(Client.objects.create)(channel_name=self.channel_name) await self.accept() await self.send(text_data=json.dumps({ "payload": "UPDATE", })) print("connect!")
async def disconnect(self, close_code):
print("Disconnected")
# Leave room group
"""await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)"""
async def update(self, message):
print("Sent message " + message["text"])
await self.send(text_data=json.dumps({
"payload": "UPDATE",
}))
async def receive(self, text_data):
"""
Receive message from WebSocket.
Get the event and send the appropriate event
"""
response = json.loads(text_data)
#event = response.get("event", None)
#message = response.get("message", None)
print(response)
"""if event == 'MOVE':
# Send message to room group
await self.channel_layer.group_send(self.room_group_name, {
'type': 'send_message',
'message': message,
"event": "MOVE"
})
if event == 'START':
# Send message to room group
await self.channel_layer.group_send(self.room_group_name, {
'type': 'send_message',
'message': message,
'event': "START"
})
if event == 'END':
# Send message to room group
await self.channel_layer.group_send(self.room_group_name, {
'type': 'send_message',
'message': message,
'event': "END"
})"""
# @classmethod
# async def send_message(cls, self, res):
# # Send message to WebSocket
# print("send msg")
# await self.send(text_data=json.dumps({
# "payload": res,
# }))
# print("send msg")`
models.py
class Connect(models.Model):
id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
neighborhood = models.CharField(max_length=50, choices=neighborhood_choices, default='all')
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.CharField(max_length=100)
phone = models.CharField(max_length=50)
def save(self, *args, **kwargs):
super().save(self, *args, **kwargs)
clients = Client.objects.all()
for client in clients:
async_to_sync(channel_layer.send)(client.channel_name, {"type": "update", "text": "hellooo"})
class Meta:
managed = False
db_table = 'connect'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dumplingexpress |
