Django websockets with Redis
I'm using django-websocket-redis (http://django-websocket-redis.readthedocs.io/en/latest/)
I can send messages to the global channel but not to a specific user.
Message to the global channel (WORKING):
Client code:
WS4Redis({
uri: '{{ WEBSOCKET_URI }}foobar?subscribe-broadcast,
receive_message: function(data){alert(data)},
heartbeat_msg: {{ WS4REDIS_HEARTBEAT }}
});
Server code:
redis_publisher = RedisPublisher(facility='foobar', broadcast=True)
message = RedisMessage('Hello World')
redis_publisher.publish_message(message)
Message to a specific user (NOT WORKING):
Client code:
WS4Redis({
uri: '{{ WEBSOCKET_URI }}foobartwo?subscribe-user,
receive_message: function(data){alert(data)},
heartbeat_msg: {{ WS4REDIS_HEARTBEAT }}
});
Server code:
redis_publisher = RedisPublisher(facility='foobartwo', users=['user1',])
message = RedisMessage('Hello World')
redis_publisher.publish_message(message)
No error occurs, simply the user's message never captures it. Why?
1 Answer
1
redis_publisher = RedisPublisher(facility='foobartwo', users=['user1',])
This line of code is incorrect.
On your template you must specify some element with attribute value
and you should be able to change it dynamically. For example take select
tag:
value
select
<select id=user>
{% for user in users %}
<option value={{ user.username }}>{{ user.username }}
{% endfor %}
</select>
In your JS code create ajax post request, taking both values of user and message ids:
$.post("{% url 'yourApp:relatedUrl' %}", {
user: $("#user").val(),
message: $("#message").val()
})
Both keys user
and message
will be available in request.POST.get('user')
and request.POST.get('message')
respectively. request.POST.get('user')
this you will put into users
list in RedisPublisher
. BTW, you won't able see you messages. As documentation suggests using SELF
"magic entity", it doesn't work. To see your own messages and others, put users = [request.POST.get('user'), request.user]
into RedisPublisher.
user
message
request.POST.get('user')
request.POST.get('message')
request.POST.get('user')
users
RedisPublisher
SELF
users = [request.POST.get('user'), request.user]
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.