首页 > 解决方案 > Python Django中的Websocket握手错误

问题描述

我遇到了 websocket 连接的问题,因为它由于握手错误而关闭。错误信息如下:

WebSocket HANDSHAKING /ws/polData/ [127.0.0.1:59304]
Exception inside application: object.__init__() takes exactly one argument (the instance to initialize)
Traceback (most recent call last):
  File "/usr/lib/python3.7/site-packages/channels/routing.py", line 71, in __call__
    return await application(scope, receive, send)
  File "/usr/lib/python3.7/site-packages/channels/sessions.py", line 47, in __call__
    return await self.inner(dict(scope, cookies=cookies), receive, send)
  File "/usr/lib/python3.7/site-packages/channels/sessions.py", line 172, in __call__
    return await self.inner(self.scope, receive, self.send)
  File "/usr/lib/python3.7/site-packages/channels/auth.py", line 181, in __call__
    return await super().__call__(scope, receive, send)
  File "/usr/lib/python3.7/site-packages/channels/middleware.py", line 26, in __call__
    return await self.inner(scope, receive, send)
  File "/usr/lib/python3.7/site-packages/channels/routing.py", line 160, in __call__
    send,
  File "/usr/local/lib/python3.7/dist-packages/asgiref/compatibility.py", line 33, in new_application
    instance = application(scope)
  File "/usr/lib/python3.7/site-packages/channels/generic/websocket.py", line 159, in __init__
    super().__init__(*args, **kwargs)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
WebSocket DISCONNECT /ws/polData/ [127.0.0.1:59304]\

标签: pythondjangowebsocketdjango-channels

解决方案


在应用程序中检查您的 routing.py,

websocket_urlpatterns下,在repath你可能错过了.as_asgi()

例如:-

websocket_urlpatterns = [

    re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
]

推荐阅读