构建教程时 Django Channels websocket 错误

问题描述 投票:0回答:1

我正在使用 django 通道教程,并且我执行了教程中的任何操作,当我单击消息的发送按钮时,我从终端收到错误: “获取/ws/聊天/大厅/ 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()),
\]

我的消费者.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
django websocket django-channels
1个回答
0
投票

我遇到了类似的问题,就我而言,事实是请求没有由异步工作人员处理。我用以下方法修复了它:

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
命令。如果你愿意的话,你可以不用它,如果你在最后添加
channels
并单独启动一个worker。
有关更多信息,请关注频道教程

此处

© www.soinside.com 2019 - 2024. All rights reserved.