5đź‘Ť
You need the group to collect all the Channels that should receive your info. Each connected device gets one Channel.
A device’s channel identifier is in the message.reply_channel
. A Group is just a way to collect all the message.reply_channel
s.
So, let’s say any user who opens your /dashboard/
page will receive any new “info” item that is posted. First, you need to remember the new client’s Channel. That’s what your ws_add
is for
def ws_add(message):
Group("all-my-clients").add(message.reply_channel)
Now the client who just connected is part of the all-my-clients
Group, and whatever message you send via all-my-clients
, will be send automatically to that client as well.
Of course you want to clean up after yourself, so that’s what ws_disconnect
is for. Remove the client once they do a WebSocket.close() or they close their browser, etc.
def ws_disconnect(message):
Group("all-my-clients").discard(message.reply_channel)
And finally, there is your ws_message()
. It receives any incoming messages.
def ws_message(message):
# Nothing to do here, because you only push, never receive.
pass
That’s all. Now you can just send messages to the Group you defined above from anywhere in Django. Just make sure you send the response in the correct format. Group().send()
takes a dict
with a key text
that has a string value (see below). The reason is that you could also send other data types, like blobs. But “text” is best for this purpose.
def post(self, request, format=None):
lines = Line.objects.all()
...
print info
response_data = {'info': info, 'status': True}
Group("all-my-clients").send({
'text': json.dumps(response_data)
})
return Response(serializer.data, status=status.HTTP_201_CREATED)
That should be all.