django中websocket怎么使用

django中websocket怎么使用

本文小编为大家详细介绍“django中websocket怎么使用”,内容详细,步骤清晰,细节处理妥当,希望这篇“django中websocket怎么使用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

websocket是一种持久化的协议,HTTP协议是一种无状态的协议,在特定场合我们需要使用长连接,做数据的实时更新,这种情况下我们就可以使用websocket做持久连接。http与websocket二者存在交集。

django中websocket怎么使用

后端:

fromdwebsocket.decoratorsimportaccept_websocketimportjson#存储连接websocket的用户clist=[]@accept_websocketdefwebsocketLink(request):#获取连接ifrequest.is_websocket:#新增用户连接信息clist.append(request.websocket)#监听接收客户端发送的消息或者客户端断开连接formessageinrequest.websocket:break#发送消息defwebsocketMsg(client,msg):b1=json.dumps(msg,ensure_ascii=False).encode('utf-8')client.send(b1)#服务端发送消息defsendmsg():sql="select*fromcustomer"res=db1.find_all(sql)iflen(clist)>0:foriinclist:i.send(json.dumps({'list':res},ensure_ascii=False).encode('utf-8'))#websocketMsg(i,{'list':res})returnHttpResponse("ok")fromapscheduler.schedulers.blockingimportBlockingSchedulerdefgetecharts(request):scheduler=BlockingScheduler()scheduler.add_job(sendmsg,'interval',seconds=1)scheduler.start()returnHttpResponse('ok')

前端:

<template><divclass="bgpic"><van-row><van-colspan="8"><divid="weekmain"></div></van-col><van-colspan="8">http://api.map.baidu.com/marker</van-col><van-colspan="8"><divid="monthmain"></div></van-col></van-row><van-row><van-colspan="8"></van-col><van-colspan="8"></van-col><van-colspan="8">{{infolist1}}</van-col></van-row></div></template><script>import*asechartsfrom'echarts';//importmyaxiosfrom"../../../https/myaxios";importaxiosfrom'axios';import{reactive}from'vue';exportdefault{name:"myweek",setup(){letinfolist1=reactive({"data":[]})//letmydata=reactive([])constinitdata=()=>{varsocket=newWebSocket("ws:127.0.0.1:8000/websocketLink");socket.onopen=function(){console.log('连接成功');//成功连接上Websocket};socket.onmessage=function(e){//alert('消息提醒:'+e.data);//打印服务端返回的数据infolist1.data=e.dataconsole.log(e.data)//mydata=infolist1.list//console.log(mydata)};socket.onclose=function(e){console.log(e);socket.close();//关闭TCP连接};}return{infolist1,initdata}},data(){return{infolist:[],}},methods:{mget(){axios.get("http://127.0.0.1:8000/getecharts").then(res=>{console.log(res)})},infoshow(){axios.get("http://localhost:8000/infoshow","get").then(res=>{this.infolist=res.data.listthis.getmonth()this.mget()})},getmonth(){varchartDom=document.getElementById('monthmain');varmyChart=echarts.init(chartDom);varoption;//prettier-ignoreletdataAxis=[];//prettier-ignoreletdata=[];for(leti=0;i<this.infolist.length;i++){dataAxis.push(this.infolist[i]["name"])data.push(this.infolist[i]["tmoney"])}letyMax=10000;letdataShadow=[];for(leti=0;i<data.length;i++){dataShadow.push(yMax);}option={title:{text:'特性示例:渐变色阴影点击缩放',subtext:'FeatureSample:GradientColor,Shadow,ClickZoom'},xAxis:{data:dataAxis,axisLabel:{inside:true,color:'#fff'},axisTick:{show:false},axisLine:{show:false},z:10},yAxis:{axisLine:{show:false},axisTick:{show:false},axisLabel:{color:'#999'}},dataZoom:[{type:'inside'}],series:[{type:'bar',showBackground:true,itemStyle:{color:newecharts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:'#83bff6'},{offset:0.5,color:'#188df0'},{offset:1,color:'#188df0'}])},emphasis:{itemStyle:{color:newecharts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:'#2378f7'},{offset:0.7,color:'#2378f7'},{offset:1,color:'#83bff6'}])}},data:data}]};//Enabledatazoomwhenuserclickbar.constzoomSize=6;myChart.on('click',function(params){console.log(dataAxis[Math.max(params.dataIndex-zoomSize/2,0)]);myChart.dispatchAction({type:'dataZoom',startValue:dataAxis[Math.max(params.dataIndex-zoomSize/2,0)],endValue:dataAxis[Math.min(params.dataIndex+zoomSize/2,data.length-1)]});});option&&myChart.setOption(option);},getweek(){varchartDom=document.getElementById('weekmain');varmyChart=echarts.init(chartDom);varoption;option={tooltip:{trigger:'axis',axisPointer:{type:'shadow'}},legend:{},grid:{left:'3%',right:'4%',bottom:'3%',containLabel:true},xAxis:[{type:'category',data:['Mon','Tue','Wed','Thu','Fri','Sat','Sun']}],yAxis:[{type:'value'}],series:[{name:'Direct',type:'bar',emphasis:{focus:'series'},data:[320,332,301,334,390,330,320]},{name:'Email',type:'bar',stack:'Ad',emphasis:{focus:'series'},data:[120,132,101,134,90,230,210]},{name:'UnionAds',type:'bar',stack:'Ad',emphasis:{focus:'series'},data:[220,182,191,234,290,330,310]},{name:'VideoAds',type:'bar',stack:'Ad',emphasis:{focus:'series'},data:[150,232,201,154,190,330,410]},{name:'SearchEngine',type:'bar',data:[862,1018,964,1026,1679,1600,1570],emphasis:{focus:'series'},markLine:{lineStyle:{type:'dashed'},data:[[{type:'min'},{type:'max'}]]}},{name:'Baidu',type:'bar',barWidth:5,stack:'SearchEngine',emphasis:{focus:'series'},data:[620,732,701,734,1090,1130,1120]},{name:'Google',type:'bar',stack:'SearchEngine',emphasis:{focus:'series'},data:[120,132,101,134,290,230,220]},{name:'Bing',type:'bar',stack:'SearchEngine',emphasis:{focus:'series'},data:[60,72,71,74,190,130,110]},{name:'Others',type:'bar',stack:'SearchEngine',emphasis:{focus:'series'},data:[62,82,91,84,109,110,120]}]};option&&myChart.setOption(option);},},mounted(){this.infoshow()this.getweek()this.initdata()}}</script><stylescoped>.bgpic{background-image:url("../../../https/4.jpg");width:1269px;height:781px;}</style>

读到这里,这篇“django中websocket怎么使用”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注恰卡编程网行业资讯频道。

发布于 2022-01-21 23:15:47
收藏
分享
海报
0 条评论
48
上一篇:怎么用C++ OpenCV实现像素画 下一篇:Django+Nginx+uWSGI定时任务怎么实现
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码