ChatConsumer() 缺少 2 个必需的位置参数:“接收”和“发送”,有什么错误?

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

我不明白为什么会出现错误。我尝试了不同的方法,但仍然遇到consumers.py 的问题。有什么问题,我做错了什么?

messaging_users/routing.py

from django.urls import path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from messaging_users import consumers

websocket_urlpatterns = [
    path('ws/messaging_users/', consumers.ChatConsumer.as_asgi()),
]

application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter(
            websocket_urlpatterns
        )
    ),
})

messaging_users/consumers.py

from channels.generic.websocket import AsyncWebsocketConsumer
import json

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()

    async def disconnect(self, close_code):
        pass

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

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

js:

<script>
const socket = new WebSocket('ws://localhost:8000/ws/messaging_users/');

socket.onopen = function() {
    console.log('WebSocket connection established.');
};

socket.onmessage = function(event) {
    const data = JSON.parse(event.data);
    console.log('Received message:', data.message);
};

function sendMessage(message) {
    if (socket.readyState === WebSocket.OPEN) {
        // WebSocket is ready to send a message
        socket.send(JSON.stringify({
            'message': message
        }));
    } else {
        console.error('WebSocket is not ready to send a message. Please wait until the connection is established.');
        // You can add code here for retrying message sending or other error handling
    }
}

// Call sendMessage when clicking the send message button
function handleSendMessageButtonClick() {
    const messageText = document.getElementById('id_body').value;
    sendMessage(messageText);
}

</script>

TypeError:ChatConsumer() 缺少 2 个必需的位置参数: ‘接收’和‘发送’

“获取/ws/messaging_users/HTTP/1.1”500 66917

python django
1个回答
0
投票

我在这里看到的最简单的修复方法就是这样做,在

routing.py
:

websocket_urlpatterns = [
    path('ws/messaging_users/', consumers.ChatConsumer), # without .as_asgi()
]

不传递类本身可能会导致你的函数出现意外行为

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