前言
在做Django项目时,有一个需求要推送消息到客户端。
查阅网上资料后,发现有两种方法,一种使用dwebsocket,但是不兼容最新版django(2.1.5之后貌似都不行)。
第二种广泛使用的是channels,但网上教程参差不齐,阅读官方文档后最终实践成功,文档链接放在文末。
版本
django==4.1.5
channels==4.0.0
daphne==4.0.0
Channels是一个采用Django并将其能力扩展到HTTP之外的项目,用于处理WebSockets、聊天协议、物联网协议等。它建立在ASGI的Python规范之上。
Daphne是Django软件基金会开发的一个基于ASGI (HTTP/WebSocket)的服务器,可以用来启动我们的应用,因为默认启动方式是WSGI。
项目目录
websocket
是一个子应用
├─djangoSocket
│ │ asgi.py
│ │ settings.py
│ │ urls.py
│ │ wsgi.py
│ │ __init__.py
│
└─websocket
│ admin.py
│ apps.py
│ consumer.py
│ models.py
│ routing.py
│ tests.py
│ urls.py
│ views.py
│ __init__.py
websocket配置使用
配置ASGI
在asgi.py
中配置。
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from websocket.routing import websocket_urlpatterns
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoSocket.settings")
application = ProtocolTypeRouter({
"http": get_asgi_application(),
'websocket': AuthMiddlewareStack(URLRouter(websocket_urlpatterns)),
})
配置Settings
在settings.py
中配置,加入daphne
,指定ASGI_APPLICATION
参数。
INSTALLED_APPS = [
'daphne',
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
'websocket.apps.WebsocketConfig',
'rest_framework',
]
# 指定ASGI的路由地址
ASGI_APPLICATION = 'djangoSocket.asgi.application'
接收/发送消息代码
在websocket子应用中创建consumer.py文件,该文件简单实现了转发客户端消息。
import json
from channels.generic.websocket import WebsocketConsumer
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def disconnect(self, close_code):
pass
def receive(self, text_data):
# text_data_json = json.loads(text_data)
# message = text_data_json["message"]
# 设置ensure_ascii以支持中文
self.send(text_data=json.dumps({"message": text_data}, ensure_ascii=False))
定义路由
在websocket子应用中创建routing.py文件,与普通http请求的url.py做区分,该文件定义了ws的访问地址。注意as_asgi()
方法的使用。
from django.urls import path
from websocket.consumer import ChatConsumer
websocket_urlpatterns = [
path('ws/chat/', ChatConsumer.as_asgi()),
]
启动项目
如果配置正确,那么daphne会自动为我们以ASGI方式启动项目,注意控制台的输出。否则需要检查配置是否正确。
Run 'python manage.py migrate' to apply them.
May 04, 2023 - 23:34:35
Django version 4.1.5, using settings 'djangoSocket.settings'
Starting ASGI/Daphne version 4.0.0 development server at http://localhost:8000/
Quit the server with CTRL-BREAK.
测试
websocket接口在线测试网站http://www.easyswoole.com/wstool.html。
输入地址进行连接,发送不同消息进行测试。