Alexa.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: Ansjer
  7. @software: PyCharm
  8. @DATE: 2020/8/14 10:13
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: AlexaConnectNum.py
  12. @Contact: sonalh@foxmail.com
  13. """
  14. from django.views.generic.base import View
  15. import os
  16. import json
  17. import math
  18. import time
  19. import urllib
  20. import logging
  21. import logging
  22. import requests
  23. import time
  24. import datetime
  25. from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
  26. from Model.models import AlexaConnectStatisticsModel
  27. from django.views.generic import TemplateView
  28. from django.utils.decorators import method_decorator
  29. from django.views.decorators.csrf import csrf_exempt
  30. from django.views.generic.base import View
  31. from django.contrib.auth.hashers import make_password, check_password # 对密码加密模块
  32. from Object.ResponseObject import ResponseObject
  33. from Object.TokenObject import TokenObject
  34. from Service.ModelService import ModelService
  35. from django.db import connection
  36. rtspServer = "rtsp.zositech.org,3.16.66.144"
  37. # 获取alexa连接数接口
  38. class AlexaConnectNum(TemplateView):
  39. @method_decorator(csrf_exempt)
  40. def dispatch(self, *args, **kwargs):
  41. return super(AlexaConnectNum, self).dispatch(*args, **kwargs)
  42. def get(self, request, *args, **kwargs):
  43. response = ResponseObject()
  44. request.encoding = 'utf-8'
  45. operation = kwargs.get('operation')
  46. #每隔十分钟定时保存每天最高连接数,crontab 在alexa_oauth2_oserver
  47. if operation == 'saveConnectNum':
  48. today = datetime.date.today()
  49. today_start_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d')))
  50. today_end_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d'))) + 86399
  51. #获取当前连接数
  52. current_connect_num = self.currentConnect()
  53. today_data = AlexaConnectStatisticsModel.objects.\
  54. filter(data_time__lte=today_end_time,data_time__gte=today_start_time).values('num','data_time')
  55. if today_data.exists():
  56. num = list(today_data)[0]['num']
  57. if current_connect_num > num:
  58. today_data.update(num=current_connect_num, data_time=time.time())
  59. else:
  60. today_data.create(num=current_connect_num, data_time=time.time())
  61. return response.json(0)
  62. return response.json(10006)
  63. def post(self, request, *args, **kwargs):
  64. request.encoding = 'utf-8'
  65. response = ResponseObject()
  66. operation = kwargs.get('operation')
  67. post_data = request.POST
  68. token = post_data.get('token', None)
  69. # tko = TokenObject()
  70. # newToken = tko.generate( data={'userID': '158943594633713800138000', 'lang': 'cn', 'user': '597471180@qq.com', 'm_code': '123413243214'})
  71. # return response.json(0, {'data': newToken})
  72. tko = TokenObject(token)
  73. response.lang = tko.lang
  74. if tko.code != 0:
  75. return response.json(tko.code)
  76. userID = tko.userID
  77. own_permission = ModelService.check_perm(userID=userID, permID=30)
  78. if own_permission is not True:
  79. return response.json(404)
  80. #获取当前连接数
  81. current_connect_num = self.currentConnect()
  82. res = []
  83. #最近三十天每天最高连接数
  84. if operation == 'thirtyDays':
  85. query_num = AlexaConnectStatisticsModel.objects.\
  86. extra(select={"data_time": "FROM_UNIXTIME(data_time, '%%m-%%d')"}).\
  87. values('num', 'data_time').order_by('-data_time')[:30]
  88. res = list(query_num)
  89. #最近十二个月每月最高连接数
  90. if operation == 'years':
  91. cursor=connection.cursor()
  92. cursor.execute("SELECT FROM_UNIXTIME(data_time,'%Y-%m') as month, max(num) as max_num FROM alexa_statistics GROUP BY month order by month asc LIMIT 12")
  93. res_query = cursor.fetchall()
  94. for max_num, month in res_query:
  95. res.append({'num':month, 'month':max_num})
  96. res_desc = {'result_code': 0, 'reason': '成功', 'current_num':current_connect_num, 'top_num': res, 'error_code': 0}
  97. result_json = json.dumps(res_desc, ensure_ascii=False)
  98. return HttpResponse(result_json)
  99. def currentConnect(self):
  100. urls = rtspServer.split(',')
  101. httpPrefix = 'http://'
  102. postfix = ':10008/api/v1/pushers'
  103. current_connect_num = 0
  104. for url in urls:
  105. apiUrl = httpPrefix + url + postfix
  106. try:
  107. selectRtsp = requests.get(url=apiUrl, timeout=5)
  108. current_connect_num += selectRtsp.json()['total']
  109. except Exception as e:
  110. continue
  111. return current_connect_num