当前位置:   article > 正文

python Django Vue3 使用websockert 实现Echarts实时更新_django echarts 数据的动态更新

django echarts 数据的动态更新

前端vue

  1. <template>
  2. <div>
  3. <div id="main">
  4. </div>
  5. </div>
  6. </template>
  7. <script>
  8. import axios from 'axios'
  9. import * as echarts from 'echarts';
  10. import {reactive} from 'vue'
  11. export default {
  12. setup() {
  13. let data1 = reactive({'data':[]})
  14. let data2 = reactive({'data':[]})
  15. let initEarcharts=()=>{
  16. var chartDom = document.getElementById('main');
  17. var myChart = echarts.init(chartDom);
  18. var option;
  19. option = {
  20. xAxis: {
  21. type: 'category',
  22. data: data1.data
  23. },
  24. yAxis: {
  25. type: 'value'
  26. },
  27. series: [
  28. {
  29. data: data2.data,
  30. type: 'line'
  31. }
  32. ]
  33. };
  34. option && myChart.setOption(option);
  35. }
  36. //初始化websocket
  37. const initWebsocket=()=>{
  38. let socket = new WebSocket('ws://127.0.0.1:8000/web_conn/')
  39. //建立
  40. socket.onopen=function(){
  41. console.log('建立连接')
  42. }
  43. //接收消息
  44. socket.onmessage=function(msg){
  45. let data = JSON.parse(msg.data)
  46. console.log(msg.data)
  47. data1.data = data[0]
  48. data2.data = data[1]
  49. // 调用echarts
  50. initEarcharts()
  51. }
  52. //关闭
  53. socket.close=function(e){
  54. console.log(e)
  55. console.log('close')
  56. }
  57. }
  58. return{
  59. data1,
  60. data2,
  61. initEarcharts,
  62. initWebsocket,
  63. }
  64. },
  65. data() {
  66. return {
  67. }
  68. },
  69. methods: {
  70. // 调用定时任务
  71. times(){
  72. axios.get("http://localhost:8000/times1/?id="+localStorage.getItem('userid'))
  73. },
  74. },
  75. mounted() {
  76. this.times()
  77. this.initWebsocket()
  78. },
  79. }
  80. </script>
  81. <style scoped>
  82. #main{
  83. width: 1000px;
  84. height: 400px;
  85. }
  86. </style>

后端django

  1. from dwebsocket.decorators import accept_websocket
  2. websocketlist=[]
  3. # 和前端进行连接
  4. @accept_websocket
  5. def web_conn(request):
  6. if request.is_websocket:
  7. websocketlist.append(request.websocket)
  8. for message in request.websocket:
  9. break
  10. import datetime
  11. def send1(id):
  12. # 逻辑代码
  13. etime = datetime.datetime.strftime(datetime.datetime.now(),'Y-%m-%d')
  14. stime = datetime.datetime.strftime((datetime.datetime.now() - datetime.timedelta(days=7)), '%Y-%m-%d')
  15. sql = "select from_unixtime(ctime,'%%Y-%%m-%%d') as addtime,sum(integral) as integral from user_integral where userid=%d and type=1 and from_unixtime(ctime,'%%Y-%%m-%%d') between '%s' and '%s' group by from_unixtime(ctime,'%%Y-%%m-%%d') " % (
  16. int(id), stime, etime)
  17. res = db2.find_all(sql)
  18. stimelist = []
  19. for i in range(7, 0, -1):
  20. stimelist.append(datetime.datetime.strftime((datetime.datetime.now() - datetime.timedelta(days=i)), '%Y-%m-%d'))
  21. list = []
  22. print(stimelist)
  23. list1 = []
  24. list2 = []
  25. for i in stimelist:
  26. flag = False
  27. list2.append(str(i))
  28. for j in res:
  29. if i == j['addtime']:
  30. flag = True
  31. list1.append(int(j['integral']))
  32. continue
  33. if flag == False:
  34. list2.append(i)
  35. list1.append(0)
  36. list.append(stimelist)
  37. list.append(list1)
  38. # print(list)
  39. if websocketlist:
  40. for i in websocketlist:
  41. b1 = json.dumps(list, ensure_ascii=False).encode('utf-8')
  42. i.send(b1)
  43. return HttpResponse('ok')
  44. from apscheduler.schedulers.background import BackgroundScheduler
  45. def times1(request):
  46. id = request.GET.get('id')
  47. scheduler = BackgroundScheduler()
  48. # 添加调度任务
  49. # 调度方法为 timedTask,触发器选择 interval(间隔性),间隔时长为 2 秒
  50. scheduler.add_job(send1, 'interval', seconds=2,args=[id])
  51. # 启动调度任务
  52. scheduler.start()
  53. return HttpResponse('ok')

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号