django中配置使用websocket

Django 默认情况下并不支持 WebSocket,但你可以通过集成第三方库如 channels 来实现 WebSocket 功能。channels 是一个 Django 应用,它提供了对 WebSocket、HTTP2 和其他协议的支持。

下面是如何在 Django 项目中使用 WebSocket 的基本步骤:

一:安装 channels

首先,你需要安装 channels 和 channels-redis(用于消息传递):

pip install channels channels-redis

二:配置项目

在你的 settings.py 中,添加以下配置:

INSTALLED_APPS

INSTALLED_APPS = [

...

'channels',

]

Channels 配置

ASGI_APPLICATION = 'your_project.routing.application'

Channels layers 配置

CHANNEL_LAYERS = {

'default': {

'BACKEND': 'channels_redis.core.RedisChannelLayer',

'CONFIG': {

"hosts": ('127.0.0.1', 6379),

},

},

}

三:创建路由

在 your_project 目录下创建一个名为 routing.py 的文件,并添加以下内容

from django.urls import path

from your_app.consumers import YourConsumer

websocket_urlpatterns = [

path('ws/your-path/', YourConsumer.as_asgi()),

]

四:创建 Consumer

在你的应用中创建一个名为 consumers.py 的文件,并添加一个Consumer

from channels.generic.websocket import AsyncWebsocketConsumer

import json

class YourConsumer(AsyncWebsocketConsumer):

async def connect(self):

当 WebSocket 连接建立时,此方法会被调用

await self.accept()

async def disconnect(self, close_code):

当 WebSocket 连接关闭时,此方法会被调用

pass

async def receive(self, text_data=None, bytes_data=None):

当从客户端接收到消息时,此方法会被调用

data = json.loads(text_data)

处理接收到的数据

pass

async def your_custom_method(self, data):

你可以定义自己的方法来处理特定逻辑

然后从其他地方调用这个方法

pass

async def send_message_to_client(self, message):

发送消息给客户端

await self.send(text_data=json.dumps(message))

五:前端连接 WebSocket

在前端,你可以使用原生的 WebSocket API 或其他库(如 socket.io)来连接你的 WebSocket 服务。以下是一个使用原生 API 的示例

const ws = new WebSocket('ws://your-domain/ws/your-path/');

ws.onopen = function(event) {

console.log("WebSocket 已连接");

ws.send(JSON.stringify({ your_data: 'here' }));

};

ws.onmessage = function(event) {

const data = JSON.parse(event.data);

console.log("接收到数据:", data);

};

ws.onclose = function(event) {

console.log("WebSocket 已关闭");

};

ws.onerror = function(error) {

console.error("WebSocket 错误:", error);

};

六:运行项目

使用 Daphne 或 Daphne + Runserver 运行你的项目:

daphne your_project.asgi:application

或python manage.py runserver

相关推荐
2601_9620782316 分钟前
Python接口自动化流程(pytest)
python·pytest·接口自动化·测试框架·断言
杨女士YRJ42 分钟前
python+pytest+01
python·pytest
鸽芷咕1 小时前
Mu Editor 鸿蒙 PC 适配全记录:用 Qt 与嵌入式 CPython 重建教学型 Python IDE
python·qt·harmonyos
微软技术分享1 小时前
基于 HuggingFace Tokenizers 训练自定义分词器
python·ubuntu·大模型·huggingface
gf13211111 小时前
python_调用远程服务器上的openclaw
服务器·python·php
lbb 小魔仙1 小时前
Jupyter Notebook / Lab 深度配置指南:插件 + 内核 + 远程访问 + 容器化部署
ide·python·jupyter
2601_962300471 小时前
python是跨平台的吗
python·开源·跨平台·面向对象·
2401_844582951 小时前
软件架构设计与持续重构:模块化开发实战建
python
东莞市云毅网络有限公司2 小时前
用 SQLite FTS5 给企业知识库做问答检索原型:中文二元切分与 BM25 排序
python·sqlite·自动化运维·geo·数据监测
承渊政道2 小时前
PR-Agent鸿蒙PC适配全记录:从Python服务端代理到ArkTS原生评审客户端
python·华为·代理模式·agent·harmonyos·pc端