1

Starting with this very simple working code sample:

from channels.generic.websocket import JsonWebsocketConsumer

class IsacomptaManagementFeesConsumer(JsonWebsocketConsumer):
    pass

When connecting to this websocket consumer from javascript, this works as expected. The connection is issued properly and I get the following logs:

WebSocket HANDSHAKING /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38108]
WebSocket CONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38108]
WebSocket DISCONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38108]

Now, if I change my code to the following code, to use groups:

from channels.generic.websocket import JsonWebsocketConsumer

class IsacomptaManagementFeesConsumer(JsonWebsocketConsumer):
    groups = ['foobar']

Then, the connection fails. JavaScript console tells me:

Firefox can’t establish a connection to the server at ws://antoine.cocoonr.hq:3001/manager/accounting/isacompta/2020/03/management-fees.ws.
error { target: WebSocket, isTrusted: true, srcElement: WebSocket, currentTarget: WebSocket, eventPhase: 2, bubbles: false, cancelable: false, defaultPrevented: false, composed: false, timeStamp: 7804, … }

And the server logs look like this:

WebSocket HANDSHAKING /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38128]
WebSocket DISCONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38128]

No exception is raised on the server side though.

I can also get a similar behavior without using groups. Let's take a bit bigger working code sample:

from channels.generic.websocket import JsonWebsocketConsumer

class IsacomptaManagementFeesConsumer(JsonWebsocketConsumer):

    def connect(self):
        print("one")
        self.accept()
        print("two")
        self.send_json({'text': "Foobar"})
        print("three")

This code works fine, the connection is issued properly and here are the server logs:

WebSocket HANDSHAKING /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38168]
one
WebSocket CONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38168]
two
three
WebSocket DISCONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38168]

But if I make the following little change to my code:

from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer

class IsacomptaManagementFeesConsumer(JsonWebsocketConsumer):

    def connect(self):
        print("one")
        self.accept()
        print("two")
        async_to_sync(self.channel_layer.send)(self.channel_name, {
            'type': 'foobar.send',
            'text': "Foobar",
        })
        print("three")

    def foobar_send(self, event):
        print("AAA")
        self.send_json({'text': event['text'])
        print("BBB")

Then, the connection is issued properly but is closed straight away and the process is stopped without having a chance to print "three", and the function "foobar_send" is not executed either.

WebSocket HANDSHAKING /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38224]                                                                                                                                                                             
one                                                                                                                                                                                                                                                                             
WebSocket CONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38224]                                                                                                                                                                                 
two                                                                                                                                                                                                                                                                             
WebSocket DISCONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38224]

I don't understand how come "three" is not printed while no exception is raised either. This means an exception is raised by self.channel_layers.send() and caught silently by the caller of IsacomptaManagementFeesConsumer.connect()?

After writing the last paragraph, I decided to give it a try:

import traceback

from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer

class IsacomptaManagementFeesConsumer(JsonWebsocketConsumer):

    def connect(self):
        print("one")
        self.accept()
        print("two")
        try:
            async_to_sync(self.channel_layer.send)(self.channel_name, {
                'type': 'foobar.send',
                'text': "Foobar",
            })
        except Exception as e:
            print(e)
            traceback.print_stack()
        print("three")

    def foobar_send(self, event):
        print("AAA")
        self.send_json({'text': event['text'])
        print("BBB")

And that's it, there is a hidden "file not found" error:

WebSocket HANDSHAKING /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:42562]
one
WebSocket CONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:42562]
two
[Errno 2] No such file or directory
  File "/usr/lib64/python3.6/threading.py", line 884, in _bootstrap
    self._bootstrap_inner()
  File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib64/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/lib64/python3.6/concurrent/futures/thread.py", line 69, in _worker
    work_item.run()
  File "/usr/lib64/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/channels/db.py", line 14, in thread_handler
    return super().thread_handler(loop, *args, **kwargs)
  File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/asgiref/sync.py", line 277, in thread_handler
    return func(*args, **kwargs)
  File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/channels/consumer.py", line 105, in dispatch
    handler(message)
  File "/home/tony/.venvs/cocoonr/lib/python3.6/site-packages/channels/generic/websocket.py", line 39, in websocket_connect
    self.connect()
  File "/home/tony/Workspace/cocoonr/billing/consumers.py", line 32, in connect
    traceback.print_stack()
three
WebSocket DISCONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:42562]

I'm using Django 3.0 with Channels 2.4.0 and channels-redis 2.4.2. Here is my CHANNEL_LAYERS setting:

 CHANNEL_LAYERS = {                                                                                                                                                          
     'default': {                                                                                                                                                                                                                                                         
         'BACKEND': 'channels_redis.core.RedisChannelLayer',                                                                                                                                                                                                                
         'CONFIG': {                                                                                                                                                                                                                                                       
             'hosts': [                                                                                                                                                                                                                                            
                 {                                                                                                                                                                                                                                                 
                     'address': get_env('CHANNELS_REDIS_HOST',                                                                                                                                                                                          
                                        default='localhost:6379'),                                                                                                                                                                             
                     'password': get_env('CHANNELS_REDIS_PASSWORD',                                                                                                                                                                             
                                         default=None),                                                                                                                                                                                          
                     'db': 1,            
                 },                                                                                                                                  
             ],                                                                                                                                   
         },                                                                                                                                                        
     },                                                                                                                                                        
 }                                                                                                                                                                                                                                                                        
Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87
  • Given my last investigations, I assume this might be a bug and thus filed a bug: https://github.com/django/channels/issues/1422 – Antoine Pinsard Mar 04 '20 at 09:17

1 Answers1

0

The fact that the error was hidden is already adressed by issue #1340.

As of the FileNotFoundError itself, it is caused by a wrong address value. It should be passed as 'redis://localhost:6379/', not 'localhost:6379'.

Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87