websocke在django中使用

Python学习之旅 / 2023-08-04 / 原文

目录
  • 一、websocket介绍:
  • 二、后端
    • 1. 安装(基于django3.x)
    • 2. settings配置
    • 3.修改asgi文件(默认不支持websocket,只支持http)

一、websocket介绍:

channels 4.0之后默认不带Daphne服务器了。

解决方案可以有两种:
1.指定channels的版本为3.x;
2.安装时使用pip3 install -U channels[“daphne”]

二、后端

1. 安装(基于django3.x)

pip3 install channels==3.0.3  -i https://pypi.douban.com/simple

2. settings配置

a. app注册


INSTALLED_APPS = [
    'channels',
]

b. 配置变量

ASGI_APPLICATION = "qq_chart.asgi.application"
ASGI_APPLICATION = '当前项目名同名的文件名.asgi.application'

3.修改asgi文件(默认不支持websocket,只支持http)


import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from . import routings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qq_chart.settings')
 
# application = get_asgi_application()
application = ProtocolTypeRouter({
    'http':get_asgi_application(),
    'websocket':URLRouter(routings.websocket_urlpatterns)
})