python组和通道层使进程停止而不引发异常

hmae6n7t  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(469)

从这个非常简单的工作代码示例开始:

from channels.generic.websocket import JsonWebsocketConsumer

class IsacomptaManagementFeesConsumer(JsonWebsocketConsumer):
    pass

当从javascript连接到这个websocket使用者时,它可以正常工作。连接已正确发出,我得到以下日志:

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]

现在,如果我将代码更改为以下代码,使用组:

from channels.generic.websocket import JsonWebsocketConsumer

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

然后,连接失败。javascript控制台告诉我:

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, … }

服务器日志如下所示:

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]

不过,服务器端没有引发任何异常。
我也可以得到一个类似的行为不使用组。让我们用一个更大的工作代码示例:

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")

此代码工作正常,连接已正确发出,以下是服务器日志:

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]

但如果我对我的代码做以下小改动:

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")

然后,连接被正确地发出,但立即关闭,进程停止而没有机会打印“三”,并且函数“foobar\u send”也没有执行。

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]

我不明白为什么不印“三”字,也不例外。这意味着 self.channel_layers.send() 静静地被召唤者抓住 IsacomptaManagementFeesConsumer.connect() ?
写完最后一段,我决定试一试:

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")

就这样,有一个隐藏的“找不到文件”错误:

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]

我正在使用Django3.0和Channels2.4.0以及ChannelsRedis2.4.2。以下是我的频道设置:

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,            
                 },                                                                                                                                  
             ],                                                                                                                                   
         },                                                                                                                                                        
     },                                                                                                                                                        
 }
h9vpoimq

h9vpoimq1#

问题1340已经解决了隐藏错误的事实。
就filenotfounderror本身而言,它是由错误的 address 价值观。它应该作为 'redis://localhost:6379/' ,不是 'localhost:6379' .

相关问题