Django:使用channels创建websocket,实现消息推送
感谢:(1)Django+channels配置与编写:https://blog.csdn.net/weixin_40105587/article/details/87375886
(2)Django+channels配置:https://www.jianshu.com/p/d6394ca19d92
(3)channels文档:https://channels.readthedocs.io/en/stable/introduction.html
一、环境版本
python 3.8
Django 3.1.5
channels 3.0.3
(安装channels时会自动安装Twisted、daphne等必须的依赖包)
windows环境下安装channels,在安装twisted时会报错,提示
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/----------------------------------------ERROR: Failed building wheel for twistedRunning setup.py clean for twisted Failed to build twisted
解决方法: 前往https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted下载.whl格式文件。
cp38对应python3.8版本,win_amd64对应64位系统
PS:一定要对应python的版本,否则可能会安装出错!!!
将下载的.whl文件放进对应python3.8版本的安装目录的Scripts文件夹,在该文件夹下执行 pip install Twisted-20.3.0-cp38-cp38-win_amd64.whl
(如果是在虚拟环境,则在 项目所在盘:\项目名\venv\Scripts)
安装完后再次,pip install channels
二、添加到项目
参考channels文档:https://channels.readthedocs.io/en/stable/installation.html
(我的项目配置与文档有一点区别)
1、在 项目的settings.py文件的INSTALLED_APPS添加 “channels”:
INSTALLED_APPS = ('django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.sites',...'你的项目app名','channels',
)ASGI_APPLICATION = '项目名.routing.application'
2、修改在settings.py同级目录的asgi.py(Django3以上版本会自动创建改文件)
(ps:我这里如果安装文档一样填写,用daphne启动项目时会报错,所以做了改动)
(daphne启动:daphne -p 8991 项目名.asgi:application)
import osimport djangofrom channels.routing import get_default_applicationos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pay_python.settings')django.setup()
application = get_default_application()
# application = ProtocolTypeRouter({
# "http": django_asgi_app,
# 'websocket': AuthMiddlewareStack(
# URLRouter(
# aliPay.ali_routing.websocket_urlpatterns
# )
# ),
# })
3、在settings.py 同级目录创建routing.py,其作用与 urls.py相同,主要用于分发webscoket请求,内容如下
# -*- coding: utf-8 -*-
"""
Created with:PyCharm
@Author: Jcsim
@Date: 2021-2-25 10:41
@Project: pay_python
@File: routing.py
@Blog:https://blog.csdn.net/weixin_38676276
@Description:
@Python:
"""
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_applicationdjango_asgi_app = get_asgi_application()
application = ProtocolTypeRouter({# "http": django_asgi_app,'websocket': AuthMiddlewareStack(URLRouter(# 后面会完善)),
})
4、在项目app目录下新增app_routing.py,app_consumers.py
app_routing.py内容:
# -*- coding: utf-8 -*- """ Created with:PyCharm @Author: Jcsim @Date: 2021-2-25 10:45 @Project: pay_python @File: ali_routing.py @Blog:https://blog.csdn.net/weixin_38676276 @Description: 接收ws请求处理 @Python: """ from django.urls import path from aliPay.ali_consumers import OrderStatusConsumers, AsyncOrderStatusConsumers # 建议url前缀使用 ws/xxx 用于区分ws请求和http请求 websocket_urlpatterns = [path('ws/qosws', OrderStatusConsumers.as_asgi()),# path('ws/asqosws/<tradeNo>', AsyncOrderStatusConsumers.as_asgi()), ]
app_consumers.py内容:
consumer类中的函数依次用于处理连接(connect)、断开连接(disconnect)、接收消息(receive)和处理对应类型的消息
# -*- coding: utf-8 -*- """ Created with:PyCharm @Author: Jcsim @Date: 2021-2-25 10:47 @Project: pay_python @File: ali_consumers.py @Blog:https://blog.csdn.net/weixin_38676276 @Description: @Python: """ from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer import json# 我项目的日志操作 from aliPay.log import logger # 数据库模型 from aliPay.models import Orders, WsChannels from utils import idCreaterclass OrderStatusConsumers(WebsocketConsumer):def connect(self):self.accept()def disconnect(self, close_code):passdef receive(self, text_data):# 这里是接受数据后的操作,下面的方法按需修改# logger.info("接受订单号,发送数据")text_data_json = json.loads(text_data)trade_no = text_data_json['tradeNo']stop = Falseorder_info = Orders.objects.filter(orders_id=trade_no).first()order_status = order_info.orders_statusstatus = 201password = "******"if order_status == 20:password = order_info.project.passwordstatus = 200stop = Truedata = {"status": status,"password": password}# 推送信息到前端 self.send(text_data=json.dumps(data))# 我项目ws推送的结束逻辑if stop:self.close()# 异步通讯 redis版本需为5.0及以上 class AsyncOrderStatusConsumers(AsyncWebsocketConsumer):async def connect(self):self.tradeNo = self.scope['url_route']['kwargs']['tradeNo']self.tradeNo_group_name = 'chat_%s' % self.tradeNo# Join room groupawait self.channel_layer.group_add(self.tradeNo_group_name,self.channel_name)await self.accept()async def disconnect(self, close_code):# Leave room groupawait self.channel_layer.group_discard(self.tradeNo_group_name,self.channel_name)# Receive message from WebSocketasync def receive(self, text_data):# text_data_json = json.loads(text_data)# message = text_data_json['message']logger.info("接受订单号,发送数据aaaaaaaaaaaa")text_data_json = json.loads(text_data)trade_no = text_data_json['tradeNo']# Send message to room groupawait self.channel_layer.group_send(self.tradeNo_group_name,{ 'type': 'chat_message', # type 用于指定该消息的类型,根据消息类型调用不同的函数去处理消息'message': trade_no # message 内为消息主体})# Receive message from room groupasync def chat_message(self, event):trade_no = event['tradeNo']stop = False# while not stop:order_info = Orders.objects.filter(orders_id=trade_no).first()order_status = order_info.orders_statuspassword = "******"if order_status == 20:password = order_info.project.passwordstop = Truedata = {"order_status": order_status,"password": password}# Send message to WebSocketawait self.send(text_data=json.dumps(data))if stop:await self.close()
5、修改 settings.py同级目录的routing.py
# -*- coding: utf-8 -*-
"""
Created with:PyCharm
@Author: Jcsim
@Date: 2021-2-25 10:41
@Project: pay_python
@File: routing.py
@Blog:https://blog.csdn.net/weixin_38676276
@Description:
@Python:
"""
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_applicationimport aliPay.ali_routingdjango_asgi_app = get_asgi_application()
application = ProtocolTypeRouter({'websocket': AuthMiddlewareStack(URLRouter(app_name.app_routing.websocket_urlpatterns)),
})
6、前端ws请求
前端websocket 教程:https://www.runoob.com/html/html5-websocket.html
<script type="text/javascript">let createWebSocket = (function () {return function (urlValue) {if (window.WebSocket) return new WebSocket(urlValue);if (window.MozWebSocket) return new MozWebSocket(urlValue);return false;}})();$(function () {const tradeNo = $(".orderNO").text()const socket = createWebSocket("ws://"+window.location.host+"/ws/qosws"){#console.log("传数据==")#}let send_data = {"tradeNo": tradeNo}socket.onopen = () => {$(document).ready(() => {{#console.log('WebSocket open');//成功连接上Websocket#}socket.send(JSON.stringify(send_data))})}{#console.log("获取数据==")#}socket.onmessage = (serverPush) => {{#console.log(serverPush)#}let data = JSON.parse(serverPush.data)$(".password").text(data.password){#console.log(data.password)#}if (data.status === 200){alert("支付成功,请保存密码")}}const timer2 = self.setInterval(() =>{socket.send(JSON.stringify(send_data))}, 3000)const timer_close = setTimeout(() =>{{#console.log("===关闭定时器====",10)#}clearInterval(timer2)socket.close()}, 60000*10)socket.onclose = () =>{{#console.log("关闭连接")#}clearInterval(timer2)clearTimeout(timer_close)socket.close()}})</script>
7、至此,操作完成。
Django:使用channels创建websocket,实现消息推送相关推荐
- python websocket实现消息推送_python Django websocket 实时消息推送
[实例简介] Django websocket 实时消息推送 服务端主动推送 调用 send(username, title, data, url) username:用户名 title:消息标题 d ...
- springboot定时发送短信_springboot 整合websocket实现消息推送(主动推送,具体用户推送,群发,定时推送)...
websocket springboot 整合websocket实现消息推送(主动推送,具体用户推送,群发,定时推送) 使用WebSocket构建交互式Web应用程序 本指南将引导您完成创建" ...
- php通知websocket,php实现websocket实时消息推送
php实现websocket实时消息推送,供大家参考,具体内容如下 SocketService.php /** * Created by xwx * Date: 2017/10/18 * Time: ...
- python websocket实时消息推送
python websocket实时消息推送 十分想念顺店杂可... 本人写的渣,大神勿喷. 转载请附带本文链接,谢谢. 服务端代码 # -*- coding: utf-8 -*- # @Time : ...
- java整合消息推送_SpringMVC整合websocket实现消息推送及触发功能
本文为大家分享了SpringMVC整合websocket实现消息推送,供大家参考,具体内容如下 1.创建websocket握手协议的后台 (1)HandShake的实现类 /** *Project N ...
- vue-admin websocket接收消息推送+语音提示(详细代码)
websocket接收消息推送+语音提示 这个是同事的代码,我拿来记录一下,希望以后可以看得懂-- utils/websocket.js const audioUrl = require('@/ass ...
- springboot整合websocket进行消息推送
什么是websocket? WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议,使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据. ...
- SpringMVC整合websocket实现消息推送及触发
2019独角兽企业重金招聘Python工程师标准>>> 1.创建websocket握手协议的后台 (1)HandShake的实现类 [java] view plain copy /* ...
- uniapp接收服务器消息,【教程】uniapp websocket实现消息推送
部分开发者在使用uniapp的过程中会用到websocket,但是uniapp框架提供的websocket服务并不是尽善尽美. 我在这里为大家介绍一款第三方的websocket推送服务:GoEasy, ...
- Vue-全局websocket 实现消息推送
在上一篇文章 WebSocket 消息推送https://blog.csdn.net/qq_63312957/article/details/125375122?spm=1001.2014.3001. ...
最新文章
- 奇葩问题解决-----解决异常情况下的黑屏
- 重载内核全程分析笔记
- 1. 机器学习-特征工程
- [恢]hdu 2098
- php如何发起远程请求,PHP请求远程地址如何设置超时时间
- 618 京东到家-小程序也狂欢
- 多个安卓设备投屏到电脑_辅助多手机同时直播控场 TotalControl手机投屏软件
- Maven 中央仓库地址
- matlab meshgrid函数_matlab入门(三)图像可视化
- 配置ISCSI客户端(LINUX)
- Android大事记(不断更新中)
- AS3还可以通过CDATA标签声明多行字符串
- [转]一个叫你看过后感动想哭的对白
- MySQL 索引详解大全
- 2016北理复试机试题
- HTML 空格转义符的用法
- JavaScript DOM高级程序设计 5动态修改样式和层叠样式表1(源代码)--我要坚持到底!...
- 期末复习概率论与数理统计时遇到的那些证明题
- Linux zlog日志打印
- java单点登录需求分析与代码实现