Search code examples
djangodjango-channels

Django channels background worker not picking up messages, using InMemoryChannelLayer


I'm trying to implement a background worker that will eventually read a log file and sent it back over websocket to client. Currently the message isn't delivered to the worker.

I'm using the InMemoryChannelLayer, does this work using this default layer or would I have to use Redis instead?

#consumer
channel_layer = get_channel_layer()

class LogFileConsumer(AsyncConsumer):

    async def read_file(self, message):
        print(message)
        await asyncio.sleep(2)
        
class LogConsumer(AsyncWebsocketConsumer):
# group_send code, not shown, is routed back fine to the client browser
    async def connect(self):
        await self.accept()
        await channel_layer.send('read-file',{
            'type': 'read.file',
            'id':'start',
        })
#routing
application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter(
            log_reader.routing.websocket_urlpatterns
        )
    ),
    'channel': ChannelNameRouter({
        'read-file': LogFileConsumer,
    }),
})

I then run the worker like so:

$ python manage.py runworker read-file
Running worker for channels ['read-file']

I'd expect to see a message printed back on the console, but nothing is returned.

The rest of the code, receiving message from browser over websocket, and sending back to client using group_send works fine. I'm sure there is a silly mistake somewhere, just can't spot it.

Thanks


Solution

  • The in memory layer is only intended for testing etc (eg running unit tests on the channel repo).

    You should always be using a Redis (or other, like RabbitMQ) layer.