Django 通道 JsonWebsocketConsumer self.send_json() 错误

Posted

技术标签:

【中文标题】Django 通道 JsonWebsocketConsumer self.send_json() 错误【英文标题】:Django channels JsonWebsocketConsumer self.send_json() error 【发布时间】:2019-09-02 05:43:01 【问题描述】:

我正在编写一个发送对话列表和个人资料的消费者 对象(联系人)通过 self.send_json() 发送后出现此错误 我真的不知道发生了什么想知道您是否可以提供帮助

错误:

Exception inside application: 'name'
  File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\sessions.py", 
  line 183, in __call__
    return await self.inner(receive, self.send)
  File "C:\Users\DELL\ENVS\async\lib\site- 
   packages\channels\middleware.py", line 41, in coroutine_call
    await inner_instance(receive, send)
  File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\consumer.py", 
  line 62, in __call__
    await await_many_dispatch([receive], self.dispatch)
  File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\utils.py", 
  line 52, in await_many_dispatch
    await dispatch(result)
  File "C:\Users\DELL\ENVS\async\lib\site-packages\asgiref\sync.py", line 
  238, in __call__
    return await asyncio.wait_for(future, timeout=None)
  File 
"C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib
 \asyncio\tasks.py", 
 line 4 14, in wait_for
    return await fut
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib
 \concurrent\futures\thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\db.py", line     


14, in thread_handler
 return super().thread_handler(loop, *args, **kwargs)
File "C:\Users\DELL\ENVS\async\lib\site-packages\asgiref\sync.py", line 
271, in thread_handler
return func(*args, **kwargs)
File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\consumer.py", 
line 105, in dispatch
handler(message)
File "C:\Users\DELL\ENVS\async\lib\site- 
packages\channels\generic\websocket.py", line 60, in websocket_receive
 self.receive(text_data=message["text"])
File "C:\Users\DELL\ENVS\async\lib\site- 
packages\channels\generic\websocket.py", line 125, in receive
self.receive_json(self.decode_json(text_data), **kwargs)
File "E:\Personal Projects\Tolk\chat\consumers.py", line 41, in 
receive_json
name = content['name']
'name'

Consumers.py:

```python
    class LoadConsumer(JsonWebsocketConsumer):

        def connect(self):
            if self.scope['user'].is_authenticated:
                self.accept()
            else:
                self.close()

        def receive_json(self, content, **kwargs):
            if content['command'] == "CHAT":
                name = content['name']
                data = self.load_conversation_contact(name)
            else:
                data = "success": False, "errors": "no such command"
            self.send_json(data) # the error happens here

        def load_conversation_contact(self, name):
            conversation = self.load_conversation(name)
            contact = self.load_contact()
            return 
                "success": True,
                "conversation": conversation['conversation'],
                "contact": contact['contact'],
            

    def load_conversation(self, name):
        conversation = Conversation.objects.filter(name=name).first()
        if conversation:
            serializer = ConversationSerializer(conversation)
            data = serializer.data
            return "success": True, "conversation": data
        return "success": False
```

数据:

```python
    'success': True, 'conversation': 'type': 'couple', 'name': 
    'conversation_8', 'contacts': [OrderedDict([('first_name', 'limbi'), 
    ('last_name', 'salah'), ('location', 'London, UK'), ('contact_pic', 
    '/media/users/1/profile/92a87524defac4511e17_avatar-male-2.jpg'), 
    ('user', 
    'limbi@main.com')]), OrderedDict([('first_name', 'cool'), ('last_name', 
    'dude'), ('location', 'London, UK'), ('contact_pic', 
    '/media/users/22/profile/f210d59103d63dd2ffa2_avatar-male-4.jpg'), 
    ('user', 'wow@gmail.com')])], 'last_message_content': 'Lorem Ipsum is 
    simply dummy text of the printing and typesetting industry.', 
    'last_message_date': 'Yesterday', 'message_set': 
    [OrderedDict([('content', 
   'Lorem Ipsum is simply dummy text of the printing and typesetting 
    industry.'), ('sender', 4), ('conversation', 8), ('sent', True), 
    ('date_sent', '2019-09-01'), ('time_sent', '08:42:42.079479')])], 
    'contact': 'first_name': 'limbi', 'last_name': 'salah', 'location': 
    'London, UK', 'contact_pic': 
    '/media/users/1/profile/92a87524defac4511e17_avatar-male-2.jpg', 
    'user': 
    'limbi@main.com'
```

我试过了: 1.调试看看有什么问题 2.改变name的值

【问题讨论】:

错误很明显。它在 dict 内容中找不到键名。在消费者中显示您的 receive_json 方法。错误发生在该方法的第 41 行 没错,它现在可以工作了 【参考方案1】:

所以 JSON 对象中缺少一个键

【讨论】:

以上是关于Django 通道 JsonWebsocketConsumer self.send_json() 错误的主要内容,如果未能解决你的问题,请参考以下文章

django 3和django通道中的SynchronousOnlyOperation错误

Django jwt 通道无法验证

使用 Django 通道进行会话身份验证

如何通过 Django 通道 WebSocket 传递请求并调用 Django 视图

断开连接后django通道无效状态错误

Django 通道 websocket 连接和断开连接(Nginx + Daphne + Django + Channels)