Search code examples
pythondjangodjango-channels

django channels with redis in WSL2


I have a redis installation running inside the windows subsystem for linux. It is working finde, but I cannot connect to it from django-channels. In my WSL I started redis and when using a normal terminal and python in Windows I can do for example:

import redis
c = redis.Redis("localhost", 6379, 0)
c.keys("hello world")

which leads inside of WSL2 to:

1675861647.991521 [0 [::1]:32934] "KEYS" "hello world"

But when I am trying to do the same thing with the functions from the channels 4 tutorial I get stuck:

$ python3 manage.py shell
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec  6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.  
(InteractiveConsole)

import channels.layers
channel_layer = channels.layers.get_channel_layer()
from asgiref.sync import async_to_sync
async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})
async_to_sync(channel_layer.receive)('test_channel')

the last call results in the following error:

Task exception was never retrieved
future: <Task finished name='Task-5' coro=<Connection.disconnect() done, defined at ...\venv\lib\site-packages\redis\asyncio\connection.py:723> exception=RuntimeError('Event loop is closed')>    
Traceback (most recent call last):
  File ...\venv\lib\site-packages\redis\asyncio\connection.py", line 732, in disconnect
    self._writer.close()  # type: ignore[union-attr]
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\streams.py", line 337, in close
    return self._transport.close()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\selector_events.py", line 706, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 753, in call_soon
    self._check_closed()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
{'type': 'hello'}

I configured my channels in settings.py:

ASGI_APPLICATION = "sst4.asgi.application"
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

Solution

  • It should be RedisPubSubChannelLayer instead of RedisChannelLayer.

    And it is a subclass of pubsub not core as you described later on in the above comment.