无法打开安全Websocket请求与达芙妮+ Django Rest框架



我想启用安全websocket连接到我的Django Rest框架应用程序。我看到所有服务都正确启动,但是当我尝试通过以下URL连接时,仍然没有建立连接。它只是失败了,没有任何跟踪。

wss://127.0.0.1:8000/ws/notifications/

当它在ws

上运行良好时
ws://127.0.0.1:8000/ws/notifications/

docker-compose.yml

services:
api:
platform: linux/amd64
build:
context: .
dockerfile: Dockerfile.dev
command: 'sh -c "./manage.py migrate && python manage.py runserver 0.0.0.0:8080"'
restart: always
networks:
- default
- fake_microservices
volumes:
- ./:/app
- $HOME/.aws:/root/.aws:ro
- /var/run/docker.sock:/var/run/docker.sock
- type: bind
source: ./docker/cpuinfo_with_fake_speed.txt
target: /proc/cpuinfo
ports:
- 8080:8080
env_file:
- ./.env
depends_on:
- db
daphne:
platform: linux/amd64
build:
context: .
dockerfile: Dockerfile.dev
command: 'sh -c "daphne -v 3 --access-log daphne.log -b 0.0.0.0 -p 8000  apps.asgi:application"'
restart: always
working_dir:  /app
volumes:
- ./:/app
- /var/run/docker.sock:/var/run/docker.sock

asgi.py

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.local")
django_asgi_app = get_asgi_application()
from channels.routing import ProtocolTypeRouter, URLRouter
application = ProtocolTypeRouter(
{
"http": django_asgi_app,
"websocket": URLRouter([path('ws/notifications/', NotificationConsumer.as_asgi())]),
}
)

我可以看到Daphne开始没有问题:

daphne_1   | 2023-04-06 09:05:27,576 INFO     Starting server at tcp:port=8000:interface=0.0.0.0
daphne_1   | 2023-04-06 09:05:27,578 INFO     HTTP/2 support enabled
daphne_1   | 2023-04-06 09:05:27,578 INFO     Configuring endpoint tcp:port=8000:interface=0.0.0.0
daphne_1   | 2023-04-06 09:05:27,580 INFO     HTTPFactory starting on 8000
daphne_1   | 2023-04-06 09:05:27,585 INFO     Starting factory <daphne.http_protocol.HTTPFactory object at 0x7f93ca9abc40>
daphne_1   | 2023-04-06 09:05:27,587 INFO     Listening on TCP address 0.0.0.0:8000
api_1      | Django version 3.2.14, using settings 'config.local'
api_1      | Starting ASGI/Channels version 3.0.5 development server at http://0.0.0.0:8080/
api_1      | Quit the server with CONTROL-C.

应用配置8080端口

我怀疑Daphne根本没有接收到wss请求。
有人能帮帮我吗?

请记住,当使用达芙妮通道时,您实际上是在设置达芙妮来重定向web流量并运行单独的容器。与其他语言相比,你的websocket会连接到另一个服务器,我们连接的是同一台服务器。因此,我们正在连接到我们的本地主机,并且您可以期望它将与ws一起工作。

这个问题,正如你可能意识到的,是在生产网站所需的wss中使用Daphne。

考虑以下apache服务器配置,如果您在本地运行,那么您不应该重写/ws/的任何规则,但如果您在生产级别,则需要将httpws连接重定向到httpswss

<VirtualHost _default_:443>
...
RewriteEngine on
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR]
RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
RewriteRule .* ws://127.0.0.1:8001%{REQUEST_URI} [P,QSA,L]
ProxyPass /wss/ wss://127.0.0.1:8001/
ProxyPassReverse /wss/ wss://127.0.0.1:8001/
...

最新更新