Django Channels group send (exclude the data sender)

Viewed 1132

I'm using Django channels as an intermediate agent, which passes data from one browser(parent/sender) to other connected browsers(children/receivers). And in my consumers, I do a channel_layer.group_send(data) once data are received from the parent browser, so that children browsers can get the data from redis channel later.

However, what I really want is the data passed to the channel should be received by all the children, except the parent browser. My question is, how to exclude the data sender in the group?

2 Answers

Unfortunately, django channels does not offer a filtering like that. I have solved the problem by checking in the chat_message function whether the current connection is the sender.

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        # Send message to room group

        await self.channel_layer.group_send(
            self.GROUP_NAME,
            {
                'type': 'chat_message',
                'data': text_data_json,
                'sender_channel_name': self.channel_name
            }
        )

    # Receive message from room group
    async def chat_message(self, event):

        # send to everyone else than the sender
        if self.channel_name != event['sender_channel_name']:
            await self.send(text_data=json.dumps(event))

I'm end up using session id to exclude sender in consumer (group send outside the consumer):

in application:

def emit_websocket_update_info():
    sender_sessionid = info.context.COOKIES["sessionid"]
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        GraphQLUpdatesConsumer.group_name,
        {   
            "type": GraphQLUpdatesConsumer.mutation_handler,
            "text": json.dumps({"conditions": time.time()}),
            "sender_sessionid": sender_sessionid,
        },  
    )

in consumer:

async def mutation_event(self, event):
    # send to all except sender itself...
    if self.scope["cookies"]["sessionid"] != event["sender_sessionid"]:
        await self.send(text_data=event["text"])
Related