Django 频道中的消费者
Posted
技术标签:
【中文标题】Django 频道中的消费者【英文标题】:Consumers in Django Channels 【发布时间】:2017-03-22 04:35:58 【问题描述】:我正在尝试在 Django 中创建聊天室。我使用 Redis 服务器和 Django 频道。我也有 models Project 和 Room。每个项目都有自己的聊天室。当我尝试通过下面的这个 url 打开聊天室页面时出现错误。在我看来,我的 consumer.py 文件不正确。如何修复此错误。需要帮助!
网址:
url(r'^(?P<project_code>[0-9a-f-]+)/chat_room/$', chat_room, name='chat_room'),
错误:
[2017/03/22 12:44:42] WebSocket HANDSHAKING /chat/ru/account/dashboard/projects/1744d0bc-e439-4562-9c29-4e7b2451f39c/chat_room/ [127.0.0.1:63104]
2017-03-22 12:44:42,236 - ERROR - worker - Error processing message with consumer project.consumers.ws_connect:
Traceback (most recent call last):
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\worker.py", line 119, in run
consumer(message, **kwargs)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\sessions.py", line 78, in inner
return func(*args, **kwargs)
File "C:\Users\Nurzhan\PycharmProjects\RMS\project\consumers.py", line 27, in ws_disconnect
project_code = message.channel_session['room']
TypeError: ws_connect() missing 1 required positional argument: 'project_code'
[2017/03/22 12:44:47] WebSocket DISCONNECT /chat/ru/account/dashboard/projects/1744d0bc-e439-4562-9c29-4e7b2451f39c/chat_room/ [127.0.0.1:63104]
models.py:
class Room(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False)
def __str__(self):
return self.code
def get_absolute_url(self):
return reverse('project:chat_room', args=[self.project_code])
class Message(models.Model):
room = models.ForeignKey(Room, related_name='messages')
handle = models.TextField()
message = models.TextField()
timestamp = models.DateTimeField(default=timezone.now, db_index=True)
def __unicode__(self):
return '[timestamp] handle: message'.format(**self.as_dict())
def __str__(self):
return self.__unicode__()
@property
def formatted_timestamp(self):
return self.timestamp.strftime('%b %-d %-I:%M %p')
def as_dict(self):
return 'handle': self.handle, 'message': self.message, 'timestamp': self.formatted_timestamp
views.py:
@login_required
def chat_room(request, project_code):
# If the room with the given project_code doesn't exist, automatically create it upon first visit.
room, created = Room.objects.get_or_create(project=project_code)
# We want to show the last 50 messages, ordered most-recent-last
messages = reversed(room.messages.order_by('-timestamp')[:50])
return render(request, "project/chat/room.html", 'room': room, 'messages': messages,)
consumers.py:
@channel_session
def ws_connect(message, project_code):
room = Room.objects.get(project_id=project_code)
message.reply_channel.send("accept": True)
Group('chat-' + project_code).add(message.reply_channel)
message.channel_session['room'] = room.project
@channel_session
def ws_receive(message):
project_code = message.channel_session['room']
room = Room.objects.get(project_id=project_code)
data = json.loads(message['text'])
m = room.messages.create(handle=data['handle'], message=data['message'])
Group('chat-' + project_code).send('text': json.dumps(m.as_dict()))
@channel_session
def ws_disconnect(message):
project_code = message.channel_session['room']
Group('chat-' + project_code).discard(message.reply_channel)
【问题讨论】:
实际代码是什么意思?在这里您可以看到我尝试使用的代码,并且此代码引发了该错误...我没有添加到 post routing.py 文件和设置中,因为我认为它们没有必要。 查看 views.py 文件。我使用 get_or_create 方法。 请显示您的项目模型类。 您的错误出现在room = Room(project=project_code)
第 178 行。请使用变量 project_code
发布那段代码
【参考方案1】:
room, created = Room.objects.get_or_create(project_code=project_code)
project_code
的 Insted 使用您在 Project
模型类中提到的您自己的属性。
【讨论】:
谢谢!现在我的consumers.py 有问题。WebSocket DISCONNECT
。你怎么看?我做错了什么?
我更新我的帖子有错误。在我看来,我的消费者错了。你怎么看?【参考方案2】:
我觉得你正在将 id
传递给 Model。试试
room = Room(project_id=project_code)
【讨论】:
谢谢,但现在我的 consumer.py 有问题。我更新了帖子的错误部分。我有WebSocket DISCONNECT
。你怎么看?以上是关于Django 频道中的消费者的主要内容,如果未能解决你的问题,请参考以下文章