Python Django 中的 Websocket 握手错误

Websocket Handshaking Error in Python Django

我遇到了 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]\

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

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

例如:-

websocket_urlpatterns = [

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

在 routing.py 中,python 3.6 以上的版本需要“as_asgi()”。

我是这样解决问题并允许不同版本的。

if float(platform.python_version()[0:3]) > 3.6:
    cons = consumers.myConsumer.as_asgi()
else:
    cons = consumers.myConsumer

websocket_urlpatterns = [
    path("ws/example/", cons),
]
websocket_urlpatterns = [
    path("ws/example/", cons.as_asgi()),
]