| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 | #!/usr/bin/env python3# -*- coding: utf-8 -*-"""@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.@AUTHOR: ASJRD018@NAME: Ansjer@software: PyCharm@DATE: 2020/8/14 10:13@Version: python3.6@MODIFY DECORD:ansjer dev@file: AlexaConnectNum.py@Contact: sonalh@foxmail.com"""from django.views.generic.base import Viewimport osimport jsonimport mathimport timeimport urllibimport loggingimport loggingimport requestsimport timeimport datetimefrom django.http import JsonResponse, HttpResponseRedirect, HttpResponsefrom Model.models import AlexaConnectStatisticsModelfrom django.views.generic import TemplateViewfrom django.utils.decorators import method_decoratorfrom django.views.decorators.csrf import csrf_exemptfrom django.views.generic.base import Viewfrom django.contrib.auth.hashers import make_password, check_password  # 对密码加密模块from Object.ResponseObject import ResponseObjectfrom Object.TokenObject import TokenObjectfrom Service.ModelService import ModelServicefrom django.db import connectionrtspServer = "rtsp.zositech.org,3.16.66.144"# 获取alexa连接数接口class AlexaConnectNum(TemplateView):    @method_decorator(csrf_exempt)    def dispatch(self, *args, **kwargs):        return super(AlexaConnectNum, self).dispatch(*args, **kwargs)    def get(self, request, *args, **kwargs):        response = ResponseObject()        request.encoding = 'utf-8'        operation = kwargs.get('operation')        #每隔十分钟定时保存每天最高连接数,crontab 在alexa_oauth2_oserver        if operation == 'saveConnectNum':            today = datetime.date.today()            today_start_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d')))            today_end_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d'))) + 86399             #获取当前连接数            current_connect_num = self.currentConnect()            today_data = AlexaConnectStatisticsModel.objects.\                filter(data_time__lte=today_end_time,data_time__gte=today_start_time).values('num','data_time')            if today_data.exists():                num = list(today_data)[0]['num']                if current_connect_num > num:                    today_data.update(num=current_connect_num, data_time=time.time())            else:                today_data.create(num=current_connect_num, data_time=time.time())            return response.json(0)        return response.json(10006)    def post(self, request, *args, **kwargs):        request.encoding = 'utf-8'        response = ResponseObject()        operation = kwargs.get('operation')        post_data = request.POST        token = post_data.get('token', None)        # tko = TokenObject()        # newToken = tko.generate( data={'userID': '158943594633713800138000', 'lang': 'cn', 'user': '597471180@qq.com', 'm_code': '123413243214'})        # return response.json(0, {'data': newToken})        tko = TokenObject(token)        response.lang = tko.lang        if tko.code != 0:            return response.json(tko.code)        userID = tko.userID        own_permission = ModelService.check_perm(userID=userID, permID=30)        if own_permission is not True:            return response.json(404)        #获取当前连接数        current_connect_num = self.currentConnect()        res = []        #最近三十天每天最高连接数        if operation == 'thirtyDays':            query_num = AlexaConnectStatisticsModel.objects.\                extra(select={"month_day_time": "FROM_UNIXTIME(data_time, '%%m-%%d')"}).\                values('num', 'month_day_time').order_by('-data_time')[:30]            res = list(query_num)        #最近十二个月每月最高连接数        if operation == 'years':            cursor=connection.cursor()            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")            res_query = cursor.fetchall()            for max_num, month in res_query:                res.append({'num':month, 'month':max_num})        res_desc = {'result_code': 0, 'reason': '成功', 'current_num':current_connect_num, 'top_num': res, 'error_code': 0}        result_json = json.dumps(res_desc, ensure_ascii=False)        return HttpResponse(result_json)    def currentConnect(self):        urls = rtspServer.split(',')        httpPrefix = 'http://'        postfix = ':10008/api/v1/pushers'        current_connect_num = 0        for url in urls:            apiUrl = httpPrefix + url + postfix            try:                selectRtsp = requests.get(url=apiUrl, timeout=5)                current_connect_num += selectRtsp.json()['total']            except Exception as e:                continue        return current_connect_num
 |