WebSocket django 频道不适用于邮递员

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

Django Channels Throw error with postman while working well with Html.

我正在关注Django Socket教程

“这是 Django 中显示的错误”。

WebSocket HANDSHAKING /ws/chat/roomName/ [127.0.0.1:56504]
WebSocket REJECT /ws/chat/roomName/ [127.0.0.1:56504]
WebSocket DISCONNECT /ws/chat/roomName/ [127.0.0.1:56504]

“连接到 ws://127.0.0.1:8000/ws/chat/roomName/ 时在邮递员中显示错误”

Sec-WebSocket-Version: 13
Sec-WebSocket-Key: fSSuMD2QozIrgywqTX38/A==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: 127.0.0.1:8000

我的代码 阿斯吉.py

django_asgi_app = get_asgi_application()

import digital_signage.playlist_management.routing

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(digital_signage.playlist_management.routing.websocket_urlpatterns))
        ),
    }
)

消费者.py

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        print("self", self)
        self.accept()
python django django-rest-framework websocket django-channels
2个回答
0
投票

发生这种情况是因为设置中的 ALLOWED_HOST。如果你处于开发模式,你可以放 * 但它会影响整个项目。相反,您可以执行以下操作

你可以用 OriginValidator 包装 asgi.py(可以导入 来自 channels.security.websocket)

application = ProtocolTypeRouter(
{
    "http": django_asgi_app,
    "websocket": OriginValidator(
        AuthMiddlewareStack(
            URLRouter(Chat.routing.websocket_urlpatterns)
        ),
        ['*']
    )
    
}

)


0
投票

单步执行

\channels\security\websocket.py
模块,Channels 的
OriginValidator
正在寻找原始标头,而不是 hosts 标头,这是 Postman 默认的。

假设你的

ALLOWED_HOSTS
看起来像:

ALLOWED_HOSTS = ["localhost", "127.0.0.1"]

然后在 Postman 中,在标题中添加:

origin:http://127.0.0.1:8000

这将通过原始验证器,而无需修改 Django 或 ASGI 配置中允许的主机。

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