如何在Azure Web App的Django项目中配置WSS连接
Django Channels Azure Web App WSS 连接问题解决指南
核心结论
必须使用Daphne或Uvicorn这类ASGI服务器,Azure Oryx不会自动处理Channels的WebSocket路由逻辑,Gunicorn(即使搭配UvicornWorker)在Azure Web App环境下对WebSocket的支持存在兼容性问题,无法替代原生ASGI服务器。
具体修复步骤
1. 替换启动命令
放弃Gunicorn的启动方式,改用以下任意一种ASGI服务器命令:
- 使用Channels官方配套的Daphne(推荐):
daphne -b 0.0.0.0 -p 8000 pharmasend.asgi:application - 使用Uvicorn:
uvicorn pharmasend.asgi:application --host 0.0.0.0 --port 8000
将上述命令配置到Azure应用服务的启动命令中(门户路径:应用服务 -> 配置 -> 常规设置 -> 启动命令)。
2. 开启Azure Web App的WebSocket支持
Azure Web App默认关闭WebSocket功能,必须手动开启:
- 进入Azure门户的应用服务后台
- 导航到「配置」->「通用设置」
- 找到「Web sockets」选项,设置为On并保存
3. 验证ASGI与Channels配置
确保你的asgi.py和路由配置正确集成WebSocket:
asgi.py示例:import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import your_app.routing # 替换为你的应用路由模块 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pharmasend.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( your_app.routing.websocket_urlpatterns ) ), })- 路由配置(
routing.py)需匹配前端连接的根路径:from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'^$', consumers.ChatConsumer.as_asgi()), ]
4. 前端代码优化(可选)
你的现有前端逻辑没问题,可简化为更简洁的写法:
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const chatSocket = new WebSocket(`${wsProtocol}//${window.location.host}/`);
5. 日志排查
若仍无法连接,通过Azure门户的「日志」->「日志流」查看实时日志,重点关注:
- ASGI服务器的启动状态
- WebSocket连接请求的错误详情(如路由匹配失败、权限问题等)
内容的提问来源于stack exchange,提问作者Vincent Tran
相关产品推荐
相关产品推荐

