问题描述
我正在使用 youtube上的本教程制作一个简单的聊天应用(此处的github链接: LINK ).一个潜在的问题是该教程使用的是Django的2.x版本,但是我有3.1.7,但是我运行得很好并且接近,但是随后开始出现此错误:
I'm working on making a simple chat app using this tutorial from youtube (github link here: LINK). One potential issue is that the tutorial uses 2.x version of django but i have 3.1.7, but I had it working pretty well and was close, but then started getting this error:
ValueError:找不到路径'ws/chat//'
在查看我的终端时,它会不断尝试重新连接,可能是因为我正在使用 ReconnectingWebSocket github javascript代码.当我运行redis-cli并输入'ping'时,我得到的是'PONG',因此我认为它工作正常.
When looking at my terminal, it keeps trying to reconnect over and over, possible becaues I'm using the ReconnectingWebSocket github javascript code. When I run redis-cli and type 'ping', I get 'PONG' in return so I think that is working properly.
以下是我的代码:
routing.py(我认为这很可能是问题所在)
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), #new django
]
wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings')
application = get_wsgi_application()
settings.py:
WSGI_APPLICATION = 'django_project.wsgi.application'
ASGI_APPLICATION = 'django_project.asgi.application' # older version of django: 'django_project.routing.application'
# Channels redis config:
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
views.py:
导入json从django.contrib.auth.decorators导入login_required从django.utils.safestring导入mark_safe
from django.shortcuts import renderimport jsonfrom django.contrib.auth.decorators import login_requiredfrom django.utils.safestring import mark_safe
def索引(请求):返回render(request,'chat/index.html')
def index(request):return render(request, 'chat/index.html')
@login_requireddef room(请求,room_name):返回render(request,'chat/room.html',{'room_name_json':room_name})
@login_requireddef room(request, room_name):return render(request, 'chat/room.html', {'room_name_json': room_name})
urls.py 从django.urls导入路径,包括从 .导入视图
urls.pyfrom django.urls import path, includefrom . import views
app_name = 'chat'
urlpatterns = [
path('chat/', views.index, name='index'),
path('chat/<str:room_name>/', views.room, name='room'),
]
room.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<script src="{% static '/reconnecting_websockets.js' %}"></script>
<textarea id="chat-log" cols="100" rows="20"></textarea><br>
<input id="chat-message-input" type="text" size="100"><br>
<input id="chat-message-submit" type="button" value="Send">
{{ room_name|json_script:"room-name" }}
<script>
const roomName = JSON.parse(document.getElementById('room-name').textContent);
const chatSocket = new ReconnectingWebSocket(
'ws://'
+ window.location.host
+ '/ws/chat/'
+ roomName
+ '/'
);
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
document.querySelector('#chat-log').value += (data.message + '\n'); //grabbing the textarea with id(#) 'chat-log'
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message,
'command': 'fetch_messages'
}));
messageInputDom.value = ''; //reset value to empty string
};
</script>
</body>
</html>
consumers.py:
导入json从asgiref.sync导入async_to_sync从channels.generic.websocket导入WebsocketConsumer来自.models导入消息从django.contrib.auth.models导入用户
import jsonfrom asgiref.sync import async_to_syncfrom channels.generic.websocket import WebsocketConsumerfrom .models import Messagefrom django.contrib.auth.models import User
ChatConsumer(WebsocketConsumer)类:
class ChatConsumer(WebsocketConsumer):
def fetch_messages(self, data):
messages = Message.last_10_messages(self)
content = {
'command': 'messages',
'messages': self.messages_to_json(messages)
}
self.send_message(content)
def new_message(self, data):
author_user = User.objects.filter(username='admin')[0]
message = Message.objects.create(author=author_user, content=data['message'])
content = {
'command': 'new_message',
'message': self.message_to_json(message)
}
return self.send_chat_message(content)
def messages_to_json(self, messages):
result = []
for message in messages:
result.append(self.message_to_json(message))
return result
def message_to_json(self, message):
return {
'author': message.author.username,
'content': message.content,
'timestamp': str(message.timestamp)
}
commands = {
'fetch_messages': fetch_messages,
'new_message': new_message
}
def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, close_code):
# Leave room group
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
def receive(self, text_data):
data = json.loads(text_data)
self.commands[data['command']](self, data) # either fetch_messages or new_message
def send_chat_message(self, message):
print('in send_chat_message')
async_to_sync(self.channel_layer.group_send)( # Send message to room group
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
def send_message(self, message):
print('message: ' + str(message))
self.send(text_data=json.dumps(message))
# Receive message from room group
def chat_message(self, event):
message = event['message']
content1 = message['message']
content2 = content1['content']
#self.send(text_data=json.dumps(content2)) # Send message to WebSocket
self.send(text_data=json.dumps(content2)) # Send message to WebSocket
推荐答案
解决方案:当我将views.py更改为此时,它起作用了:
Solution: When i changed views.py to this, it worked:
@login_required
def room(request, room_name):
print('~~~DEBUG~~~')
return render(request, 'chat/room.html', {
'room_name': room_name
这篇关于Django ValueError:找不到路径"ws/chat//"的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!