| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295 | # -*- coding: utf-8 -*-from django.views.decorators.csrf import csrf_exemptfrom django.views.generic import TemplateViewfrom django.utils.decorators import method_decoratorfrom django.contrib.auth.hashers import make_password  # 对密码加密模块from Model.models import Device_Info, Rolefrom Service.ModelService import ModelServicefrom django.utils import timezonefrom Model.models import Access_Log, Device_Userfrom django.views.decorators.http import require_http_methodsfrom Object.ResponseObject import ResponseObjectfrom Object.TokenObject import TokenObjectfrom Ansjer.config import OFF_LINE_TIME_DELTAimport datetime, simplejson as jsonfrom Service.CommonService import CommonServicefrom Object.RedisObject import RedisObject'''http://192.168.136.40:8077/adminManage/manage?operation=getAllDeviceArea&token=debughttp://192.168.136.40:8077/adminManage/manage?operation=getAllUserName&token=debughttp://192.168.136.40:8077/adminManage/manage?operation=getAllUID&token=debughttp://127.0.0.1:8000/adminManage/manage?operation=getAllOnLine&token=stesthttp://127.0.0.1:8000/adminManage/manage?operation=getOnLine&token=stest'''class AdminManage(TemplateView):    @method_decorator(csrf_exempt)    def dispatch(self, *args, **kwargs):        return super(AdminManage, self).dispatch(*args, **kwargs)    def get(self, request, *args, **kwargs):        request.encoding = 'utf-8'        return self.validation(request_dict=request.GET)    def post(self, request, *args, **kwargs):        request.encoding = 'utf-8'        return self.validation(request_dict=request.POST)    def validation(self, request_dict, *args, **kwargs):        response = ResponseObject()        token = request_dict.get('token', None)        tko = TokenObject(token)        response.lang = tko.lang        if tko.code != 0:            return response.json(tko.code)        userID = tko.userID        operation = request_dict.get('operation', None)        if userID is None or operation is None:            return response.json(444, 'operation')        if operation == 'resetUserPwd':            return self.resetUserPwd(request_dict, userID, response)        if operation == 'getAllOnLine':            return self.getAllOnLine(userID, response)        if operation == 'getOnLine':            return self.getRedisOnline(userID, response)            return self.getOnLine(userID, response)        if operation == 'getAllUserName':            return self.getAllUserName(userID, response)        if operation == 'getStatisAccess':            return self.getStatisAccess(userID, request_dict, response)        if operation == 'getAllUID':            return self.getAllUID(userID, response)        if operation == 'getAllDeviceArea':            return self.getAllDeviceArea(userID, response)    def resetUserPwd(self, request_dict, userID, response):        own_permission = ModelService.check_perm(userID=userID, permID=50)        if not own_permission:            return response.json(404)        duserID = request_dict.get('duserID', None)        userPwd = request_dict.get('userPwd', None)        if not duserID:            return response.json(444, 'duserID')        UserValid = Device_User.objects.filter(userID=duserID)        if UserValid:            if userPwd is None:                userPwd = '123456'            is_update = UserValid.update(password=make_password(userPwd))            if is_update:                return response.json(0)            else:                return response.json(177)        else:            return response.json(104)    def getAllUserName(self, userID, response):        # 权限固定为30        own_permission = ModelService.check_perm(userID=userID, permID=30)        if own_permission is not True:            return response.json(404)        username_list = Device_User.objects.all().values_list('username', flat=True)        if username_list:            return response.json(0, {'username_list': list(username_list)})        else:            return response.json(0)    #    获取全部用户的在线个数    def getAllOnLine(self, userID, response):        # 权限固定为30        own_permission = ModelService.check_perm(userID=userID, permID=30)        if own_permission is not True:            return response.json(404)        allonline = Device_User.objects.all().values('online')        # 两个变量,分别是在线,离线        onlinenum = 0        noonlinenum = 0        for q in allonline:            if q['online'] == True:                onlinenum += 1            else:                noonlinenum += 1        print("在线人数:")        print(onlinenum)        return response.json(0, {"onlinenum": onlinenum, "no_onlinenum": noonlinenum})    #    获取全部用户的在线人数    def getOnLine(self, userID, response):        # 权限固定为30        own_permission = ModelService.check_perm(userID=userID, permID=30)        if own_permission is True:            online_list = Device_User.objects.all().values('online', 'last_login')            # 两个变量,分别是在线,离线            onlinenum = 0            noonlinenum = 0            for q in online_list:                # print(q['last_login'] )                # 最后访问时间加5分种                dl_time = q['last_login'] + datetime.timedelta(minutes=OFF_LINE_TIME_DELTA)                # print(dl_time)                # 当前时间                now_time = timezone.localtime(timezone.now())                # print(now_time)                # 如果当前时间大于最后访问的时间                if now_time < dl_time:                    onlinenum += 1                else:                    noonlinenum += 1            print("在线人")            print(onlinenum)            return response.json(0, {"onlinenum": onlinenum, "no_onlinenum": noonlinenum})        else:            return response.json(404)    #    获取全部用户的在线人数    def getRedisOnline(self, userID, response):        # 权限固定为30        own_perm = ModelService.check_perm(userID, 30)        if own_perm:            count = int(Device_User.objects.count())            redisObj = RedisObject(db=3)            onlines = int(redisObj.get_size())            return response.json(0, {"onlinenum": onlines, "no_onlinenum": count - onlines})        else:            return response.json(404)    # 获取所有设备地区    def getAllDeviceArea(self, userID, response):        own_permission = ModelService.check_perm(userID=userID, permID=30)        if own_permission is True:            qs = Device_Info.objects.all().values('area', 'UID')            uid_area_dict = {}            for q in qs:                if q['UID'] and q['area']:                    uid_area_dict[q['UID']] = q['area']            if len(uid_area_dict):                area_dict = {}                for k, v in uid_area_dict.items():                    if v in area_dict:                        area_dict[v] += 1                    else:                        area_dict[v] = 1                return response.json(0, {'area': area_dict})            else:                return response.json(0)        else:            return response.json(404)    '''    统计一天访问量    http://192.168.136.45:8077/adminManage/manage?token=test&operation=getStatisAccess×tamp=1528773308    '''    def getStatisAccess(self, userID, request_dict, response):        own_permission = ModelService.check_perm(userID=userID, permID=30)        if own_permission is not True:            return response.json(404)        time_stamp = int(request_dict.get('timestamp', None))        times = datetime.datetime.fromtimestamp(time_stamp)        time_dict = CommonService.getTimeDict(times)        res = {}        for k, v in time_dict.items():            start_date = time_dict[k]            end_date = time_dict[k] + datetime.timedelta(hours=1)            count = Access_Log.objects.filter(time__range=(start_date, end_date)).count()            if count:                res[k] = count            else:                res[k] = 0        return response.json(0, {'count': res})    def getAllUID(self, userID, response):        own_permission = ModelService.check_perm(userID=userID, permID=30)        if own_permission is not True:            return response.json(404)        uid_list = Device_Info.objects.all().values_list('UID', flat=True)        res = {}        if uid_list:            res = {'count': uid_list.count(), 'uid_list': list(uid_list)}        return response.json(0, res)@require_http_methods(["GET"])def getUserIds(request):    token = request.GET.get('token', None)    response = ResponseObject()    tko = TokenObject(token)    response.lang = tko.lang    if tko.code != 0:        return response.json(tko.code)    userID = tko.userID    own_perm = ModelService.check_perm(userID, 30)    if own_perm is not True:        return response.json(404)    dn = Device_User.objects.all().values('userID', 'username')    return response.json(0, {"datas": list(dn)})@csrf_exemptdef search_user_by_content(request):    if request.method == 'GET':        request_dict = request.GET    if request.method == 'POST':        request_dict = request.POST    token = request_dict.get('token', None)    page = request_dict.get('page', None)    line = request_dict.get('line', None)    content = request_dict.get('content', None)    rstime = request_dict.get('rstime', None)    retime = request_dict.get('retime', None)    response = ResponseObject()    if page is not None and line is not None:        page = int(page)        line = int(line)    else:        return response.json(10, 'page,line is none')    tko = TokenObject(token)    response.lang = tko.lang    if tko.code != 0:        return response.json(tko.code)    userID = tko.userID    own_perm = ModelService.check_perm(userID=userID, permID=20)    if own_perm is not True:        return response.json(404)    try:        content = json.loads(content)        search_kwargs = CommonService.get_kwargs(data=content)        queryset = Device_User.objects.filter(**search_kwargs)    except Exception as e:        return response.json(444, repr(e))    if rstime is not None and rstime != '' and retime is not None and retime != '':        startt = datetime.datetime.fromtimestamp(int(rstime))        rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")        endt = datetime.datetime.fromtimestamp(int(retime))        retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")        queryset = queryset.filter(data_joined__range=(rstime, retime))    elif rstime is not None and rstime != '':        startt = datetime.datetime.fromtimestamp(int(rstime))        rstime = startt.strftime("%Y-%m-%d %H:%M:%S.%f")        queryset = queryset.filter(data_joined__gte=rstime)    elif retime is not None and retime != '':        endt = datetime.datetime.fromtimestamp(int(retime))        retime = endt.strftime("%Y-%m-%d %H:%M:%S.%f")        queryset = queryset.filter(data_joined__lte=retime)    if queryset.exists():        count = queryset.count()        res = queryset[(page - 1) * line:page * line]        sqlDict = CommonService.qs_to_dict(res)        for k, v in enumerate(sqlDict["datas"]):            if len(v['fields']['role']) > 0:                role_query_set = Role.objects.get(rid=v['fields']['role'][0])                sqlDict["datas"][k]['fields']['role'].append(role_query_set.roleName)            for val in res:                if v['pk'] == val.userID:                    if sqlDict["datas"][k]['fields']['online'] is True:                        dl_time = val.last_login + datetime.timedelta(minutes=5)                        now_time = timezone.localtime(timezone.now())                        if now_time > dl_time:                            sqlDict["datas"][k]['fields']['online'] = False        sqlDict['count'] = count        return response.json(0, sqlDict)    return response.json(0, {'datas': [], 'count': 0})
 |