我正在使用带有装饰器的Django Channels@channel_session_user
(用于访问 Django 的会话数据)。
@channel_session_user_from_http
def ws_connect(message):
# creates group names like "group-1"
group_kw = get_group_id_for_user(message.user)
Group(group_kw).add(message.reply_channel)
@channel_session_user
def ws_receive(message):
group_kw = get_group_id_for_user(message.user)
payload = json.loads(message.content['text'])
Channel(payload['action']).send(message.content)
@channel_session_user
def ws_disconnect(message):
group_kw = get_group_id_for_user(message.user)
Group(group_kw).discard(message.reply_channel)
这工作正常,但在测试时出现问题。
下面的测试应该在websocket.receive
通道上放置一条消息,然后ws_receive
应该获取消息并将其放置在消息action
值中定义的通道上。最后,我测试它是否真的放在那个频道上。
def test_send_chat_message_is_used_by_consumer(self):
# Make sure a user is authenticated
self.assertTrue(auth.get_user(self.client).is_authenticated())
payload = {'action': 'chat.receive',
'msg': 'Test message.',
'receiver': self.user2.id}
message = {'text': json.dumps(payload)}
# Send a chat message
Channel('websocket.receive').send(message)
# Receive it and place it on the right channel
ws_receive(self.get_next_message('websocket.receive', require=True))
# Fetch it from the channel
result = self.get_next_message(payload['action'], require=True)
# That should be the message sent
self.assertEqual(result, message)
相反,我收到以下错误,指向ws_receive()
调用所在的行。
ValueError: No reply_channel 发送给消费者;@channel_session 只能用于包含它的消息。
错误在Channels源中引发。
打印reply_channel
返回None
而不是包含正确的回复通道名称。
tmp = self.get_next_message('websocket.receive', require=True)
print(tmp.reply_channel) # prints: None
我忽略了一些明显的东西?