我正在基于此示例(https://github.com/andrewgodwin/channels-examples/blob/master/multichat/chat/routing.py)构建一个聊天应用程序。当 javascript 运行时(套接字已经打开,ws_connect已经执行),它通过 websocket 将 JSON 发送到。此“消息”被路由到ws_receive,然后将 JSON 加载到“有效负载”变量中。“消息” reply_channel被添加到有效负载变量 (dict) 中。使用 Channels 命令,有效负载然后被发送并路由到chat_join,它应该简单地执行硬编码的 message.reply_channel.send。
所有步骤直到
payload['reply_channel'] = message.content['reply_channel']
工作正常。但是随后有效负载没有被路由到chat_join消费者。如果路由正确,则没有正确读取 reply_channel 值,因此没有将消息发送回客户端。
似乎无法在这里找到断点。需要帮助修复此代码。
.js
//Join Room
socket.send(JSON.stringify({
"command": "join",
"room": "102"
}));
路由.py
from channels.routing import route
from MyProject.consumers import ws_connect, ws_receive, chat_join
websocket_routing = [
route("websocket.connect", ws_connect),
route("websocket.receive", ws_receive),
]
custom_routing = [
route("chat.receive", chat_join, command=r'^join$'),
]
消费者.py
from channels import Channel
def ws_receive(message):
payload = json.loads(message['text'])
payload['reply_channel'] = message.content['reply_channel']
Channel("chat.receive").send(payload)
def chat_join(message):
message.reply_channel.send({
"text": json.dumps({
"alpha": "1",
"beta": "2",
}),
})