'Django and channels, expose model data via websockets after save

I am new to websocket and channel with django. In my django project i would to expose saved data after a post_save event occur in a specific model via websocket. I have django 3.2 and i install:

channels==3.0.4
channels-redis==3.3.1

then in my settings.py i add channels to my app list and set:

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'asgi_redis.RedisChannelLayer',
        'CONFIG': {
            'hosts': ["redis://:myredishost:6379/0"],
        },
        'ROUTING': 'backend.routing.channel_routing',
    }
}

chenge my application from WSGI to ASGI:

ASGI_APPLICATION = "backend.asgi.application"

then i try to create the routing.py file like this:

from channels.routing import route
from alarms.consumers import ws_connect, ws_disconnect


channel_routing = [
    route('websocket.connect', ws_connect),
    route('websocket.disconnect', ws_disconnect),
]

and connect and disconnect methods (insert every connected user ubto User group for now):

from channels import Group


def ws_connect(message):
    Group('users').add(message.reply_channel)


def ws_disconnect(message):
    Group('users').discard(message.reply_channel)

now i have an Results_Alarms model:

# Model of Alarms data
class Results_Alarm(models.Model):
    id = models.AutoField(primary_key=True)
    var_id = models.ForeignKey('modbus.ModbusVariable', null=True, on_delete=models.SET_NULL)
    calc_id = models.ForeignKey(CalcGroup, null=True, on_delete=models.SET_NULL)
    templ_id = models.ForeignKey(AlarmsTemplate, null=True, on_delete=models.SET_NULL)
    a_trigger = models.CharField(max_length=200, verbose_name="Alarm trigger")
    dtopen = models.DateTimeField(verbose_name="Date of error")
    e_status = models.ForeignKey(AlarmStatus, null=True, on_delete=models.SET_NULL)
    dtclose = models.DateTimeField(verbose_name="Date of resolution", null=True, blank=True)
    u_involved = models.ForeignKey('accounts.CustomUser', related_name='oumanager', on_delete=models.CASCADE, null=True)
    
    ...

I also create the signals.py file for manage the post_save event:

@receiver(post_save, sender=Results_Alarm)
def ws_alarms_data(sender, instance, created, **kwargs):
    #?? What here for send via websocket?

My problem now is: How can i trigger post_save event and send via websocket the last saved data (maybe in json format)? i have to create a router? but how?

Sorry but i am searching online without find an answer i can understand.

So many thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source