[英]Django Channels error when trying to create a web-socket connection ValueError: No route found for path ' '
我正在使用 django-channels 和 websockets 开发一个 Django 聊天应用程序。 我一直在关注一个教程,其中讲师正在创建两个用户之间的一对一聊天。 在他的示例中,讲师使用的是 URLRouter,但我使用的是 websocketurlpatterns。 我收到的错误状态是ValueError: No route found for path 'ws/chat/'
并且未建立 websocket 连接。 这是我的 consumers.py:
class ChatConsumer(SyncConsumer):
def websocket_connect(self, event):
me = self.scope\['user'\]
other_username = self.scope\['url_route'\]\['kwargs'\]\['username'\]
other_user = User.objects.get(username=other_username)
self.thread_obj = Thread.objects.get_or_create_personal_thread(me, other_user)
self.room_name = f'presonal_thread\_{self.thread_obj.id}'
async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name)
self.send({
'type': 'websocket.accept'
})
print(f'\[{self.channel_name}\] - You are connected')
def websocket_receive(self, event):
print(f'[{self.channel_name}] - Recieved message - {event["text"]}')
msg = json.dumps({
'text': event.get('text'),
'username': self.scope['user'].username
})
self.store_message(event.get('text'))
async_to_sync(self.channel_layer.group_send)(
self.room_name,
{
'type': 'websocket.message',
'text': msg
}
)
def websocket_message(self, event):
print(f'[{self.channel_name}] - Message sent - {event["text"]}')
self.send({
'type': 'websocket.send',
'text': event.get('text')
})
def websocket_disconnect(self, event):
print(f'[{self.channel_name}] - Disonnected')
async_to_sync(self.channel_layer.group_discard)(self.room_name, self.channel_name)
def store_message(self, text):
Message.objects.create(
thread = self.thread_obj,
sender = self.scope['user'],
text = text
)
class EchoConsumer(SyncConsumer):
def websocket_connect(self, event):
self.room_name = 'broadcast'
self.send({
'type': 'websocket.accept'
})
async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name)
print(f'\[{self.channel_name}\] - You are connected')
def websocket_receive(self, event):
print(f'[{self.channel_name}] - Recieved message - {event["text"]}')
async_to_sync(self.channel_layer.group_send)(
self.room_name,
{
'type': 'websocket.message',
'text': event.get('text')
}
)
def websocket_message(self, event):
print(f'[{self.channel_name}] - Message sent - {event["text"]}')
self.send({
'type': 'websocket.send',
'text': event.get('text')
})
def websocket_disconnect(self, event):
print(f'[{self.channel_name}] - Disonnected')
async_to_sync(self.channel_layer.group_discard)(self.room_name, self.channel_name)
这是 urls.py:
urlpatterns = \[
path('\<str:username\>/', ThreadView.as_view(), name= 'chat'),
\]
然后这是我的 routing.py:
websocket_urlpatterns = [
re_path(r"ws/chat/(?P<username>\w+)/$", consumers.ChatConsumer.as_asgi()),
# re_path(r"ws/chat/$", consumers.EchoConsumer.as_asgi()),
]
在路由中,每当我使用 EchoConsumer 时,就会发生 websocket 连接。 所以我认为问题是由用户名引起的,但我不知道如何解决。 此处还附有包含 websocket 的模板:
<script>
const url = 'ws://localhost:8000/ws/chat/';
// const url = 'ws://' + window.location.host + '/ws/chat/' + username + '/';
// const url = 'ws://localhost:8000/ws' + window.location.pathname;
const ws = new WebSocket(url)
ws.onopen = function(event) {
console.log("Connection is opened");
ws.send("Thanks for connecting");
}
ws.onmessage = function(event) {
console.log(event);
console.log("Message is received");
const ul = document.getElementById('message-list');
var li = document.createElement('li');
// var data = JSON.parse(event.data);
var data = event.data;
li.append(document.createTextNode(
'[' + data.username + ']:' + data
));
ul.append(li);
}
ws.onclose = function(event) {
console.log("Connection is closed");
}
ws.onerror = function(event) {
console.log("Something went wrong");
}
const messageForm = document.getElementById('message-form')
messageForm.addEventListener('submit', sendMessage)
function sendMessage(e) {
if (e.preventDefault) e.preventDefault();
ws.send(document.getElementById('message').value);
messageForm.reset()
return false;
}
</script>
我已尝试按照注释行的指示更改脚本中的 URL。 任何帮助将不胜感激。 谢谢你。
我曾尝试更改 javascript 中的 URL 模式,但它也无济于事。
所以我终于找到了解决这个问题的方法。 事实证明,要使 url 正常工作,我必须使用localhost:8000
而不是在浏览器的 url 中使用127.0.0.1:8000
。 这样,websocket 就完美地变成了 function。 谢谢你们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.