django-websocket-redis icon indicating copy to clipboard operation
django-websocket-redis copied to clipboard

How to receive inbound messages sent to the Django server

Open ghassett opened this issue 10 years ago • 3 comments

Hi, I am using Django and Django Rest Framework to implement a RESTful back end for a mobile client. This client also needs to be able to communicate along a web socket; the server will "push" events to the mobile client. So far, so good: the client calls a REST method, the server responds with a websocket URL, the client opens up a client side websocket to that URL, and the server can subsequently send messages to the client via RedisPublisher().publish_message().

But, what about when the client wants to send messages back to the server? ws4redis puts these messages into redis, under a key named (for example) broadcast:foobar. But how can I proactively respond to the receipt of this event? Do I need a loop somewhere (e.g. a celery task) that continuously looks for these keys? I sort of went down this path experimentally, but quickly realized that if I send "Message 1" to facility foobar, ws4redis stores "Message 1" in redis under the key "broadcast:foobar", but if I then send "Message 2", ws4redis uses the same key, thereby clobbering the first message in redis.

I am wondering what is the preferred method for responding to incoming messages that are sent to the web socket controlled by ws4redis - thanks for any help or guidance!

ghassett avatar Jun 21 '15 15:06 ghassett

But how can I proactively respond to the receipt of this event? Do I need a loop somewhere (e.g. a celery task) that continuously looks for these keys?

Yes, if you use the WS for upstream communication, then you have to poll the Redis server. But think about it, Django then does not have any running task in responsible to handle that request.

As written in the docs, it rarely makes sense to use WS upstream. For these kind of events, use normal Ajax requests.

jrief avatar Jun 22 '15 08:06 jrief

Thanks Jacob, that confirms what I was thinking. It would still be nice if ws4redis could store multiple messages in redis, instead of clobbering the contents of message 1 with the contents of message 2 (since they're both on the same facility). Is this something ti can do today if I configure/use ws4redis differently?

ghassett avatar Jun 22 '15 14:06 ghassett

That would be possible, but quite dangerous. In addition to key-value-pairs, Redis also offers key-list-of-values. However, such a list could become very big, if a client continuously sends some data. Wouldn't it make sense for you to use session based buckets?

jrief avatar Jun 22 '15 15:06 jrief