【Python】Django Channels2.0 使用
阿新 • • 發佈:2019-02-02
簡介
- channels2.0 可以讓django具有處理http2,websocket的能力
相關庫
- Python3.6
- Django 2.0
- pip install channels
- pip install channels_redis
配置settings.py
# 新增app
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
...
'channels',
)
# 繫結應用,routing.py稍後建立
ASGI_APPLICATION = "myproject.routing.application"
# 設定訊息佇列,選用redis
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost", 6379)],
},
},
}
建立路由檔案routing.py
# routing.py
from django.urls import path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from .consumers import MyConsumer
application = ProtocolTypeRouter({
# WebSocket chat handler
"websocket": AuthMiddlewareStack(
URLRouter([
path("chart/push" , MyConsumer),
])
),
})
建立路由處理類檔案consumers.py
# consumers.py
# -*- coding: utf-8 -*-
from channels.generic.websocket import AsyncWebsocketConsumer
# from asgiref.sync import async_to_sync
# 自定義websocket處理類
class MyConsumer(AsyncWebsocketConsumer):
async def connect(self):
# 建立連線時呼叫
await self.accept()
# 將新的連線加入到群組
await self.channel_layer.group_add("chat", self.channel_name)
async def receive(self, text_data=None, bytes_data=None):
# 收到資訊時呼叫
# 資訊單發
# await self.send(text_data="Hello world!")
# 資訊群發
await self.channel_layer.group_send(
"chat",
{
"type": "chat.message",
"text": "Hello world!",
},
)
async def disconnect(self, close_code):
# 連線關閉時呼叫
# 將關閉的連線從群組中移除
await self.channel_layer.group_discard("chat", self.channel_name)
await self.close()
async def chat_message(self, event):
# Handles the "chat.message" event when it's sent to us.
await self.send(text_data=event["text"])
啟動Django
python manage.py runserver 0.0.0.0:8080
測試HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Django websocket</title>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("您的瀏覽器支援 WebSocket!");
// 開啟一個 web socket
var ws = new WebSocket("ws://localhost:8080/chart/push");
ws.onopen = function()
{
// Web Socket 已連線上,使用 send() 方法傳送資料
alert("資料傳送中...");
ws.send("hello world")
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
console.log(received_msg)
};
ws.onclose = function()
{
// 關閉 websocket
alert("連線已關閉...");
};
}
else
{
// 瀏覽器不支援 WebSocket
alert("您的瀏覽器不支援 WebSocket!");
}
}
</script>
</head>
<body>
<div id="sse">
<a href="javascript:WebSocketTest()">執行 WebSocket</a>
</div>
</body>
</html>
效果
- 連線成功時,Django會輸出狀態,handshaking -> connect
- 點選連線後,在console會輸出hello world