| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195 | # -*- encoding: utf-8 -*-"""@File    : AlgorithmShopController.py@Time    : 2022/8/24 20:02@Author  : stephen@Email   : zhangdongming@asj6.wecom.work@Software: PyCharm"""import loggingimport timefrom django.db.models import Ffrom django.views.generic.base import Viewfrom Model.models import DeviceAlgorithmExplain, DeviceAlgorithmBanner, DeviceUidAlgorithmType, DeviceTypeAlgorithmInfofrom Object.ResponseObject import ResponseObjectfrom Object.TokenObject import TokenObjectlogger = logging.getLogger('info')class AlgorithmShopView(View):    def get(self, request, *args, **kwargs):        request.encoding = 'utf-8'        operation = kwargs.get('operation')        return self.validation(request.GET, request, operation)    def post(self, request, *args, **kwargs):        request.encoding = 'utf-8'        operation = kwargs.get('operation')        return self.validation(request.POST, request, operation)    def validation(self, request_dict, request, operation):        token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))        lang = request_dict.get('lang', token.lang)        response = ResponseObject(lang)        if token.code != 0:            return response.json(token.code)        if operation == 'list':            return self.algorithm_list(request_dict, response)        elif operation == 'banner-list':            return self.get_algorithm_banner(response)        elif operation == 'uid-details':            return self.get_algorithm_details(request_dict, response)        elif operation == 'save':            return self.algorithm_setting_save(request_dict, response)    @classmethod    def get_algorithm_banner(cls, response):        """        获取算法小店banner        """        banner_qs = DeviceAlgorithmBanner.objects.all()        banner_vs = banner_qs.order_by('sort') \            .values('algorithm_type__type', 'algorithm_type__id', 'image_url')        banner_list = []        if not banner_vs.exists():            return response.json(0, banner_list)        for item in banner_vs:            banner_list.append({                'typeId': item['algorithm_type__id'],                'type': item['algorithm_type__type'],                'imageUrl': item['image_url'],            })        return response.json(0, banner_list)    @classmethod    def algorithm_list(cls, request_dict, response):        """        获取算法小店列表        """        try:            lang = request_dict.get('lang', 'en')            uid = request_dict.get('uid', None)            algorithm_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).order_by('algorithm_type__sort') \                .values('algorithm_type__id', 'algorithm_type__type',                        'algorithm_type__icon_url',                        'title', 'subtitle', 'algorithm_type__image_url',                        'algorithm_type__basic_function', 'concerning')            algorithm_list = []            if not algorithm_qs.exists():                return response.json(0, algorithm_list)            for item in algorithm_qs:                setting = ''                if uid:                    setting = cls.get_uid_algorithm_info(item['algorithm_type__id'], uid)                    setting = setting if setting else {'status': 0, 'function': {}}                algorithm_list.append({                    'typeId': item['algorithm_type__id'],                    'type': item['algorithm_type__type'],                    'iconUrl': item['algorithm_type__icon_url'],                    'imageUrl': item['algorithm_type__image_url'],                    'title': item['title'],                    'subtitle': item['subtitle'],                    'setting': setting,                    'basicFunction': item['algorithm_type__basic_function'],                    'concerning': item['concerning']                })            return response.json(0, algorithm_list)        except Exception as e:            print('查询算法小店列表异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))            return response.json(177, repr(e))    @classmethod    def get_algorithm_details(cls, request_dict, response):        """        获取算法小店类型详情        """        try:            lang = request_dict.get('lang', 'en')            type_id = request_dict.get('typeId', None)            if not type_id:                return response.json(444, 'typeId not null')            type_id = int(type_id)            uid = request_dict.get('uid', None)            explain_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).filter(algorithm_type__id=type_id) \                .values('algorithm_type__id', 'algorithm_type__type',                        'algorithm_type__down_count',                        'algorithm_type__details_img_url',                        'algorithm_type__icon_url',                        'title', 'subtitle', 'introduction',                        'install_explain', 'risk_warning',                        'algorithm_type__basic_function', 'concerning')            if not explain_qs.exists():                return response.json(0, {})            item = explain_qs.first()            algorithm_dict = {                'typeId': item['algorithm_type__id'],                'type': item['algorithm_type__type'],                'downCount': item['algorithm_type__down_count'],                'detailsImgUrl': item['algorithm_type__details_img_url'],                'iconUrl': item['algorithm_type__icon_url'],                'title': item['title'],                'subtitle': item['subtitle'],                'introduction': item['introduction'],                'installExplain': item['install_explain'],                'riskWarning': item['risk_warning'],                'basicFunction': item['algorithm_type__basic_function'],                'concerning': item['concerning']            }            dt_info_qs = DeviceTypeAlgorithmInfo.objects.filter(algorithm_type=algorithm_dict['type']) \                .annotate(deviceName=F('device_name'), deviceType=F('device_type'),                          algorithmType=F('algorithm_type'),                          typeIcon=F('type_icon'),                          deviceLink=F('device_link'), ) \                .values('deviceName', 'deviceType', 'typeIcon', 'deviceLink')            algorithm_dict['recommendDevices'] = list(dt_info_qs)            if uid:                setting = cls.get_uid_algorithm_info(item['algorithm_type__id'], uid)                algorithm_dict['setting'] = setting if setting else {'status': 0, 'function': {}}            return response.json(0, algorithm_dict)        except Exception as e:            print('查询算法详情异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))            return response.json(177, repr(e))    @staticmethod    def get_uid_algorithm_info(type_id, uid):        """        获取当前设备使用算法状态信息        @param type_id: 算法类型ID        @param uid: 设备唯一标识        @return: dict        """        uid_algorithm_qs = DeviceUidAlgorithmType.objects.filter(algorithm_type_id=type_id, device_uid=uid) \            .values('status', 'function')        if not uid_algorithm_qs.exists():            return None        return uid_algorithm_qs.first()    @classmethod    def algorithm_setting_save(cls, request_dict, response):        """        算法设置保存        """        try:            type_id = request_dict.get('typeId', None)            uid = request_dict.get('uid', None)            status = request_dict.get('status', None)            setting_json = request_dict.get('function')            if not all([type_id, uid, status, setting_json]):                return response.json(444)            status = int(status)            type_id = int(type_id)            now_time = int(time.time())            uid_algorithm_qs = DeviceUidAlgorithmType.objects.filter(algorithm_type_id=type_id, device_uid=uid)            if not uid_algorithm_qs.exists():                param = {'algorithm_type_id': int(type_id), 'uid': uid, 'function': setting_json,                         'status': status, 'updated_time': now_time, 'created_time': now_time}                DeviceUidAlgorithmType.objects.create(**param)                return response.json(0)            uid_algorithm_qs.update(status=status, function=setting_json, updated_time=now_time)            return response.json(0)        except Exception as e:            print('保存算法设置异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))            return response.json(177, repr(e))
 |