我试图让一个WebSocket为我正在工作的Django项目运行,但我不能让WebSocket连接,这很奇怪,因为我复制了示例聊天应用程序。
settings.py
INSTALLED_APPS = [
'daphne',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
'core',
'room',
]
ASGI_APPLICATION = 'WeChat.asgi.application'
HTML部分
{% block scripts %}
{{ room.slug|json_script:"json-roomname" }}
<script>
const roomName = JSON.parse(document.getElementById('json-roomname').textContent);
const chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/'
+ roomName
+ '/'
);
chatSocket.onmessage = function(e){
console.log('onmessage')
}
chatSocket.onclose = function(e){
console.log('onclose')
}
</script>
{% endblock %}
routing.py
from django.urls import path
from .import consumers
websoscket_urlpatterns =[
path('ws/<str:room_name>/',consumers.ChatConsumer.as_asgi()),
]
asgi.py
import os
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter,URLRouter
import room.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WeChat.settings')
application = ProtocolTypeRouter({
"http" : get_asgi_application(),
"websocket" : AuthMiddlewareStack(
URLRouter(
room.routing.websoscket_urlpatterns
)
)
})
consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import sync_to_async
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
我第一次使用WebSocket。我运行Python文件并检查浏览器,但我得到了一个意外的错误,如
Python:64 WebSocket连接到“ws://localhost:8000/ws/Python/”失败:(匿名)@ Python:64
它显示了(新的WebSocket)下的红线
const chatSocket = new WebSocket('ws://'
+ window.location.host
+ '/ws/'
+ roomName
+ '/'
);
首先,我得到了这样的错误,然后我运行命令python -m pip install -U channels[“daphne”],然后我将daphne添加到安装的应用程序。但在那之后,我得到了一个意想不到的错误**ModuleNotFoundError:没有模块名为'daphne'**任何人,请帮助我修复这个错误?
1条答案
按热度按时间zazmityj1#
运行命令
从**
INSTALLED_APPS
**中删除'channels'