Tuesday, April 25, 2017

Multiplex results from (Django-Channels)

Hi,

I've currently setup Django channels to receive all the `messages` from a single `room`. However, I would like to set it up to receive `messages` from several rooms. In DRF, I'd use serializers to achieve this. However, in sockets, I am unsure how I would do it.

What is the correct

EG from chat rooms entitled `Foo` and `Bar` would look like this:

[
   
{
       
"label": "Foo",
       
"pk": 5,
       
"message": [
           
{
               
"handle": "Bruce",
               
"message": "Yo"
           
},
           
{
               
"handle": "Sol",
               
"message": "Hey"
           
}
       
]
   
},
   
{
       
"label": "Bar",
       
"pk": 10,
       
"message": [
           
{
               
"handle": "Sol",
               
"message": "Hi"
           
},
           
{
               
"handle": "Alfred",
               
"message": "Yo"
           
}
       
]
   
}
]

# consumers.py

@channel_session
def ws_connect(message):
    prefix
, label = message['path'].strip('/').split('/')
    room
= Room.objects.get(label=label)
    chathistory
= room.messages.all().order_by('timestamp')
   
Group('chat-' + label).add(message.reply_channel)
    message
.channel_session['room'] = room.label
    message
.reply_channel.send({'text': json.dumps([msg.as_dict() for msg in chathistory.all()])})


# models .py

class Room(models.Model):
    name
= models.TextField()
    label
= models.SlugField(unique=True)

class Message(models.Model):
    room
= models.ForeignKey(Room, related_name='messages')
    handle
= models.TextField()
    message
= models.TextField()
    timestamp
= models.DateTimeField(default=timezone.now, db_index=True)
   
def __unicode__(self):
       
return '[{timestamp}] {handle}: {message}'.format(**self.as_dict())


   
@property
   
def formatted_timestamp(self):
       
return self.timestamp.strftime("%H:%M:%S")
   
   
def as_dict(self):
       
return {'pk':self.pk, 'handle': self.handle, 'message': self.message, 'timestamp': self.formatted_timestamp}




--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/153fb077-46b8-4e13-ab6d-d0a7d4f4dd65%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment