Django使用channels实现websocket并解决报错 object.__init__() takes no parameters
使用python3.6以及channels3.0.3是报错TypeError: object.__init__() takes no parameters
解决办法:给websocket的处理类加上as_asgi()就好了
websocket_urlpatterns = [
path('wx/', ChatConsumer.as_asgi()),
]
按照下面的来是能够正常运行的,具体代码及目录结构:
asgi.py
import os
from channels.auth import AuthMiddlewareStack
from django.conf.urls import url
from django.core.asgi import get_asgi_application
# Fetch Django ASGI application early to ensure AppRegistry is populated
# before importing consumers and AuthMiddlewareStack that may import ORM
# models.
from apps.websocket_app.urls import websocket_urlpatterns
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
# Import other Channels classes and consumers here.
from channels.routing import ProtocolTypeRouter, URLRouter
application = ProtocolTypeRouter({
# Explicitly set 'http' key using Django's ASGI application.
"http": get_asgi_application(),
'websocket': AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
})
settings.py
INSTALLED_APPS = [
'apps.websocket_app.apps.WebsocketAppConfig',
'channels'
]
# 指定ASGI的路由地址
ASGI_APPLICATION = 'blog.asgi.application'
urls.py
from channels.http import AsgiHandler
from django.urls import path
from .views import ChatConsumer
websocket_urlpatterns = [
path('wx/', ChatConsumer.as_asgi()),
]
views.py
from channels.generic.websocket import WebsocketConsumer
import json
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def disconnect(self, close_code):
pass
def receive(self, text_data):
print(text_data)
text_data_json = json.loads(text_data)
message = 'message:' + text_data_json['message']
self.send(text_data=json.dumps({
'message': message
}))
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="WebSocketTest()">test</button>
</body>
<script>
function WebSocketTest() {
if ("WebSocket" in window) {
// 打开一个 web socket
ws = new WebSocket("ws://127.0.0.1:8000/wx/");
ws.onopen = function () {
// Web Socket 已连接上,使用 send() 方法发送数据
ws.send('{"message": "dsadsa"}');
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("数据:" + received_msg)
};
ws.onclose = function () {
// 关闭 websocket
};
}
else {
// 浏览器不支持 WebSocket
}
}
</script>
</html>