如何解决Django WebSocket中的daphne模块未找到及连接失败错误
Django WebSocket部署问题解决
一、解决ModuleNotFoundError: No module named 'daphne'
修正安装命令并检查虚拟环境
使用正确的安装命令(无需引号包裹方括号):python -m pip install -U channels[daphne]若使用虚拟环境,必须激活对应环境后执行安装,避免依赖安装到全局Python环境。
验证Python解释器一致性
确认运行项目的Python解释器与安装daphne的解释器为同一版本:- 查看当前项目Python路径:
which python(Linux/macOS)或where python(Windows) - 查看依赖安装路径:
pip -V
若路径不一致,切换到正确环境重新安装。
- 查看当前项目Python路径:
重装依赖
卸载现有版本后重新安装:pip uninstall channels daphne -y pip install channels[daphne]
二、解决WebSocket连接失败问题
1. 修正路由变量拼写错误
room/routing.py中变量名拼写错误,将websoscket_urlpatterns改为websocket_urlpatterns(缺少字母c):
from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()), ]
同时更新asgi.py中的路由引用:
# ... URLRouter( room.routing.websocket_urlpatterns # 修正此处变量名 ) # ...
2. 修正Consumer方法错误
consumers.py中disconnect方法使用了不存在的group_discard,替换为正确的group_remove:
async def disconnect(self): await self.channel_layer.group_remove( self.room_group_name, self.channel_name )
3. 正确启动项目
安装daphne后,通过ASGI服务器启动项目:
daphne WeChat.asgi:application
或继续使用python manage.py runserver(需确保daphne在INSTALLED_APPS首位,你已配置正确)。
4. 验证WebSocket端点
启动项目后,用curl测试端点是否可达:
curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: localhost:8000" -H "Origin: http://localhost:8000" http://localhost:8000/ws/Python/
返回HTTP/1.1 101 Switching Protocols则说明端点配置正常。
内容的提问来源于stack exchange,提问作者vivi
相关产品推荐
相关产品推荐

