Redis and django-socketio

516 Views Asked by At

I built a chat with django-socketio and I'm trying to use redis with it.

I have a very simple event.py:

      @events.on_message(channel='^channel-')
      def messages(request, socket, context, message):
            socket.send_and_broadcast_channel(message)

The chat works perfectly.

Now I'm trying to implement redis:

        @events.on_message(channel='^channel-')
        def messages(request, socket, context, message):
        r = redis.StrictRedis()
        r = r.pubsub()
        r.subscribe('chat')
        s = redis.Redis()
        s.publish('chat', message)
        for m in r.listen():
           data = m['data']
           print data

The message is published on the redis channel, but once I call .listen(), nothing works anymore. It looks like .listen() is 'blocking' everything. I can't even escape the server using ctr+C

Any idea on how I can solve that? Thank you!

EDIT:

Here is what I have now:

       def listener(self):
         r = redis.StrictRedis()
         r = r.pubsub()

         r.subscribe('chat')

         for m in r.listen():
             message = m['data']
             socket.send_and_broadcast_channel(message)

      @events.on_message()
      def messages(request, socket, context, message):
          r = redis.Redis()
          r.publish('chat', message)

Still doesn't work.

In order redis to work with gevent(used by django-socketio), we have to start a Greenlet when the user subscribes. So we need to add something like that:

      def on_subscribe(self, *args, **kwargs):
           self.spawn(self.listener)

But I didn't figure how to do that with django-socketio given that we have to use an event

       @event.on_connect()
       def connect(request, socket, context)

But I can't pass an argument 'self'. So I can't use 'self.spawn(self.listener)', and I don't know how I could do differently

0

There are 0 best solutions below