Django Channels WebSocket error while building the tutorial

roejwanj  于 2023-11-19  发布在  Go
关注(0)|答案(1)|浏览(151)

我正在使用Django通道教程,我做了教程中的任何事情,当我点击我的消息的发送按钮时,我的终端出现错误:“GET /ws/chat/lobby/ HTTP/1.1”404 2232
我的routing.py文件:

from django.urls import re_path

from .consumers import ChatConsumer

websocket_urlpatterns = \[
re_path('ws/chat/\<room_name\>', ChatConsumer.as_asgi()),
\]

字符串
我的consumers.py:

import json
from channels.generic.websocket import WebsocketConsumer

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

    def receive(self, text_data):
        text_data_dict = json.loads(text_data)
        message = text_data_dict['message']

        self.send(text_data=json.dumps({
            'message': message
        }))


views.py:

from django.shortcuts import render

def index(request):
    return render(request, "chat/index.html")

def room(request, room_name):

    context = {

        "room_name": room_name
    }
    return render(request, 'chat/room.html', context)


urls.py:

from django.urls import path
from .views import index, room
urlpatterns = [
    path('', index, name='index'),
    path('<str:room_name>/', room, name='room')

]


asgi.py档案:

import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import Chat.routing

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = ProtocolTypeRouter({
  "http": get_asgi_application(),
  "websocket": AuthMiddlewareStack(
        URLRouter(
            Chat.routing.websocket_urlpatterns
        )
    ),
})


我的room.html文件:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Chat Room</title>
</head>
<body>
    <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 WebSocket(
            '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');
        };

        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
            }));
            messageInputDom.value = '';
        };
    </script>
</body>
</html>


我该如何解决这个问题?
我试了python manage.py runserver,得到了:

Not Found: /ws/chat/lobby/ 
[11/Nov/2022 11:15:36] "GET /ws/chat/lobby/ HTTP/1.1" 404 2232

bzzcjhmw

bzzcjhmw1#

我有类似的问题,在我的情况下,这是一个事实,即请求没有处理的一个aplogic工作。我有它固定与:pip install channels[daphne]
然后将daphne添加为INSTALLED_APPS中的第一个条目。您可以从列表的末尾删除channels。我的工作现在是这样配置的:

INSTALLED_APPS = [
    "daphne",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "chat.apps.ChatConfig",
]

字符串
Daphne控制runserver命令。如果您在INSTALLED_APPS末尾添加channels并单独启动一个worker,则可以不使用它。
有关更多信息,请参阅通道教程here

相关问题