带Redis的Django websockets

时间:2018-06-14 17:30:33

标签: python jquery django websocket redis

我正在使用django-websocket-redis(http://django-websocket-redis.readthedocs.io/en/latest/

我可以向全局频道发送消息,但不向特定用户发送消息。

关注文档:http://django-websocket-redis.readthedocs.io/en/latest/usage.html

致全球频道的消息(工作):

客户代码:

WS4Redis({
    uri: '{{ WEBSOCKET_URI }}foobar?subscribe-broadcast,
    receive_message: function(data){alert(data)},
    heartbeat_msg: {{ WS4REDIS_HEARTBEAT }}
});

服务器代码:

redis_publisher = RedisPublisher(facility='foobar', broadcast=True)
message = RedisMessage('Hello World')
redis_publisher.publish_message(message)

给特定用户的消息(不工作):

客户代码:

WS4Redis({
    uri: '{{ WEBSOCKET_URI }}foobartwo?subscribe-user,
    receive_message: function(data){alert(data)},
    heartbeat_msg: {{ WS4REDIS_HEARTBEAT }}
});

服务器代码:

redis_publisher = RedisPublisher(facility='foobartwo', users=['user1',])
message = RedisMessage('Hello World')
redis_publisher.publish_message(message)

没有错误发生,只是用户的消息从未捕获它。为什么呢?

1 个答案:

答案 0 :(得分:0)

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:

<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.