Django使用channels實現websocket並解決報錯object.__init__() takes no parameters
阿新 • • 發佈:2021-01-08
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 = '運維咖啡吧:' + 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>