django-channels-presence is a Django app which adds “rooms” and presence
notification capability to a Django application using django-channels. If you’re building a chat room
or other site that needs to keep track of “who is connected right now”, this
might be useful to you.
Install with pip:
pip install django-channels-presence
# proj/settings.py INSTALLED_APPS = [ ... "channels_presence", ... ]
For efficiency and flexibility with different backends,
not keep careful track of which sockets are currently connected, nor which of
the sockets that have been added to a
still active. It does provide
websocket.connect hook that fires when a
client first connects, and a
websocket.disconnect that fires if the client
cleanly disconnects. We can use these hooks to maintain a separate list of
which sockets (and associated users, if any) are connected to a room. However,
there are two ways that a socket might disconnect without firing
- The client might drop out without cleanly closing its connection (for example, wifi signal or power drops off).
- The server holding the socket connections might restart, without running
Because of these failure modes, we need both a way to track which clients have
been added to a room, and also a way to periodically prune any connections that
have grown stale.
django-channels-presence provides the first in the form of
Presence models that can be used to track
connections in the
websocket.disconnect handlers, and
the second in the form of a periodic task (usable with celerybeat or
cron) to clean the models up.
This implementation makes database queries on every connection, disconnection,
and message, as well as periodic queries to prune stale connections. As a
result, it will scale differently than
- API Reference