【发布时间】:2018-02-26 19:51:37
【问题描述】:
我一直在按照本教程在我的 Django 项目中实现实时聊天系统。到目前为止一切顺利,我已经解决了所有出现的问题,但这个问题难倒了我。
2018-02-26 19:45:34,241 - ERROR - worker - Error processing message with consumer TestApp.consumers.ws_receive:
Traceback (most recent call last):
File "/home/.virtualenvs/blog/lib/python3.5/site-packages/channels/worker.py", line 46, in run
consumer(message)
File "/home/.virtualenvs/blog/lib/python3.5/site-packages/channels/sessions.py", line 57, in inner
return func(message, *args, **kwargs)
File "/home/blog_dev/TutorsTalk/TestApp/consumers.py", line 23, in ws_receive
Group('chat-'+label).send({'text': json.dumps([m.as_dict()])})
AttributeError: 'Message' object has no attribute 'as_dict'
这个错误似乎只在接收到 websocket 数据时出现,这就是为什么当我尝试发送数据时它被保存到数据库中的原因。这意味着如果我在另一个浏览器上打开它或刷新页面,我可以阅读这些消息。我还可以说我的断开代码也可以工作,因为在 Django 开发控制台中,它会告诉我 IP 何时与 websocket 断开连接。
您可能会说我对此很陌生。这是我在 consumer.py 中的代码
@channel_session
def ws_receive(message):
label = message.channel_session['room']
room = Room.objects.get(label=label)
data = json.loads(message['text'])
m = room.messages.create(handle=data['handle'], message=data['message'])
Group('chat-'+label).send({'text': json.dumps([m.as_dict()])})
我尝试了一些我认为可能有效但无济于事的方法。请告诉我是否应该提供更多信息。
【问题讨论】:
标签: python django websocket django-channels