Menu Close

Playing with Django-Channels

Django-channels is a library touted to bring websockets to django in an incredibly simple / easy-to-implement fashion. I’ve listened to presentations, read some documentation and started exploring the code samples. One of the very first example apps provided by the project maintainers is a chat application – it’s a rudimentary implementation of live chat for authenticated users. It works well, but it’s far from feature-rich. To deep-dive and learn more about django-channels, I wanted to make the app more feature rich by implementing a “user count”. One would think this should be simple – just count the number of open websocket connections associated with a given chat room! And while the premise is simple, the implementation doesn’t really exist yet.

I researched the issue and submitted a ticket on the GitHub project here:

Currently, retrieving this count requires getting the RedisChannelLayer instance and asking for all of the key/value pairs from the Group zset, then getting the length of the returned list:

This also works:

It feels dirty to retrieve all the data when you just need the count. When using redis as a backend, we can issue the zcard command to retrieve row count for a given zset, i.e:

zcard asgi::group:room-1

Redis Screenshot

My knowledge/research falls short at this point. Could we extend Group class this enhancement be generic enough to implement for all backends? The hacky way can be implemented easily:

We can use the native connection in a backend-specific (asgi_redis.core.RedisChannelLayer) fashion:

 3,327 total views,  3 views today

Leave a Reply

Your email address will not be published. Required fields are marked *