Преглед изворни кода

添加设备开启事务,增加日志

locky пре 2 година
родитељ
комит
8280b2e785
1 измењених фајлова са 129 додато и 110 уклоњено
  1. 129 110
      Controller/EquipmentManagerV3.py

+ 129 - 110
Controller/EquipmentManagerV3.py

@@ -19,7 +19,7 @@ from Controller.SensorGateway.EquipmentFamilyController import EquipmentFamilyVi
 from Controller.UnicomCombo.UnicomComboController import UnicomComboView
 from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidChannelSetModel, \
     Device_User, iotdeviceInfoModel, UIDCompanySerialModel, UnicomDeviceInfo, CountryModel, \
-    DeviceCloudPhotoInfo, UidPushModel
+    DeviceCloudPhotoInfo, UidPushModel, ExperienceContextModel, LogModel
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Service.CommonService import CommonService
@@ -106,7 +106,6 @@ class EquipmentManagerV3(View):
         View_Account = request_dict.get('View_Account', None)
         View_Password = request_dict.get('View_Password', '')
         encrypt_pass = View_Password
-        print("准备解密")
         Type = request_dict.get('Type', None)
         ChannelIndex = request_dict.get('ChannelIndex', None)
         version = request_dict.get('version', '')
@@ -216,122 +215,142 @@ class EquipmentManagerV3(View):
             res['isMainUserExists'] = 1
             return response.json(0, res)
 
+        # 日志数据
+        nowTime = int(time.time())
+        ip = CommonService.get_ip_address(request)
+        content = json.loads(json.dumps(request_dict))
+        log = {
+            'ip': ip,
+            'user_id': 1,
+            'status': 200,
+            'time': nowTime,
+            'content': json.dumps(content),
+            'url': 'v3/equipment/add',
+            'operation': '{}添加{}成功'.format(userID, UID)
+        }
+
         try:
-            # 判断是否有用户绑定
-            nowTime = int(time.time())
-            us_qs = UidSetModel.objects.filter(uid=UID)
-            if us_qs.exists():
-                us_qs.update(nickname=NickName, device_type=Type)
-                UidSet_id = us_qs.first().id
-            else:
-                ip = CommonService.get_ip_address(request)
-                ipInfo = CommonService.getIpIpInfo(ip, 'CN')
-                country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('id')
-                country = country_qs.exists() if country_qs[0]['id'] else 0
-                region_id = Device_Region().get_device_region(ip)
-                region_alexa = 'CN' if region_id == 1 else 'ALL'
-                uid_set_create_dict = {
-                    'uid': UID,
-                    'addTime': nowTime,
-                    'updTime': nowTime,
-                    'ip': CommonService.get_ip_address(request_dict),
-                    'channel': ChannelIndex,
-                    'nickname': NickName,
-                    'version': version,
-                    'region_alexa': region_alexa,
-                    'device_type': Type,
-                    'tb_country': country
-                }
-                UidSet = UidSetModel.objects.create(**uid_set_create_dict)
-                UidSet_id = UidSet.id
-
-            if all([token_val, m_code, appBundleId, app_type]):
-                uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=UID)
-                if uid_push_qs.exists():
-                    uid_push_update_dict = {
-                        'appBundleId': appBundleId,
-                        'app_type': app_type,
-                        'push_type': push_type,
-                        'token_val': token_val,
-                        'jg_token_val': jg_token_val,
-                        'updTime': nowTime,
-                        'lang': lang,
-                        'tz': tz
-                    }
-                    uid_push_qs.update(**uid_push_update_dict)
+            with transaction.atomic():
+                # 判断是否有用户绑定
+                us_qs = UidSetModel.objects.filter(uid=UID)
+                if us_qs.exists():
+                    us_qs.update(nickname=NickName, device_type=Type)
+                    UidSet_id = us_qs.first().id
                 else:
-                    uid_push_create_dict = {
-                        'uid_set_id': UidSet_id,
-                        'userID_id': userID,
-                        'appBundleId': appBundleId,
-                        'app_type': app_type,
-                        'push_type': push_type,
-                        'token_val': token_val,
-                        'jg_token_val': jg_token_val,
-                        'm_code': m_code,
+                    ipInfo = CommonService.getIpIpInfo(ip, 'CN')
+                    country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('id')
+                    country = country_qs.exists() if country_qs[0]['id'] else 0
+                    region_id = Device_Region().get_device_region(ip)
+                    region_alexa = 'CN' if region_id == 1 else 'ALL'
+                    uid_set_create_dict = {
+                        'uid': UID,
                         'addTime': nowTime,
                         'updTime': nowTime,
-                        'lang': lang,
-                        'tz': tz
+                        'ip': ip,
+                        'channel': ChannelIndex,
+                        'nickname': NickName,
+                        'version': version,
+                        'region_alexa': region_alexa,
+                        'device_type': Type,
+                        'tb_country': country
                     }
-                    # 绑定设备推送
-                    UidPushModel.objects.create(**uid_push_create_dict)
-            # 查询uid_channel表有无该uid的数据
-            uid_channel_set = UidChannelSetModel.objects.filter(uid_id=UidSet_id)
-            if not uid_channel_set.exists():
-                # 多通道设备设置通道名
-                if Type in dvr_type_list:
-                    UidChannelSet_bulk = []
-                    for i in range(1, ChannelIndex + 1):
-                        channel_name = 'channel' + str(i)  # channel1,channel2...
-                        UidChannelSet = UidChannelSetModel(uid_id=UidSet_id, channel=i, channel_name=channel_name)
-                        UidChannelSet_bulk.append(UidChannelSet)
-                    UidChannelSetModel.objects.bulk_create(UidChannelSet_bulk)
-
-            userDevice = Device_Info(id=id, userID_id=userID, UID=UID, NickName=NickName, View_Account=View_Account,
-                                     View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex, version=version,
-                                     vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
-            userDevice.save()
-            # 添加到家庭房间
-            if family_id:
-                EquipmentFamilyView.family_room_device_save(family_id, room_id, userDevice.id, Type)
-
-            uid_serial_qs = UIDCompanySerialModel.objects.filter(uid__uid=UID)
-            if uid_serial_qs.exists():
-                uid_serial = uid_serial_qs[0]
-                serial_number = uid_serial.company_serial.serial_number + uid_serial.company_serial.company.mark
-                Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
-                                                           vodPrimaryMaster=vodPrimaryMaster,
-                                                           serial_number=serial_number)
-                self.unicom_user_info_save(userID, serial_number)
-            else:
-                Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
-                                                           vodPrimaryMaster=vodPrimaryMaster)
+                    UidSet = UidSetModel.objects.create(**uid_set_create_dict)
+                    UidSet_id = UidSet.id
 
-            if not us_qs.exists():
-                us_qs = UidSetModel.objects.filter(uid=UID)
+                if all([token_val, m_code, appBundleId, app_type]):
+                    uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=UID)
+                    if uid_push_qs.exists():
+                        uid_push_update_dict = {
+                            'appBundleId': appBundleId,
+                            'app_type': app_type,
+                            'push_type': push_type,
+                            'token_val': token_val,
+                            'jg_token_val': jg_token_val,
+                            'updTime': nowTime,
+                            'lang': lang,
+                            'tz': tz
+                        }
+                        uid_push_qs.update(**uid_push_update_dict)
+                    else:
+                        uid_push_create_dict = {
+                            'uid_set_id': UidSet_id,
+                            'userID_id': userID,
+                            'appBundleId': appBundleId,
+                            'app_type': app_type,
+                            'push_type': push_type,
+                            'token_val': token_val,
+                            'jg_token_val': jg_token_val,
+                            'm_code': m_code,
+                            'addTime': nowTime,
+                            'updTime': nowTime,
+                            'lang': lang,
+                            'tz': tz
+                        }
+                        # 绑定设备推送
+                        UidPushModel.objects.create(**uid_push_create_dict)
+                # 查询uid_channel表有无该uid的数据
+                uid_channel_set = UidChannelSetModel.objects.filter(uid_id=UidSet_id)
+                if not uid_channel_set.exists():
+                    # 多通道设备设置通道名
+                    if Type in dvr_type_list:
+                        UidChannelSet_bulk = []
+                        for i in range(1, ChannelIndex + 1):
+                            channel_name = 'channel' + str(i)  # channel1,channel2...
+                            UidChannelSet = UidChannelSetModel(uid_id=UidSet_id, channel=i, channel_name=channel_name)
+                            UidChannelSet_bulk.append(UidChannelSet)
+                        UidChannelSetModel.objects.bulk_create(UidChannelSet_bulk)
 
-            if us_qs.exists() and us_qs[0].is_alexa == 1:
-                if us_qs[0].channel > 1:
-                    data_list = []
-                    uid_channel_set_qs = UidChannelSetModel.objects.filter(uid_id=us_qs[0].id). \
-                        values('channel', 'channel_name')
-                    if uid_channel_set_qs.exists():
-                        # 多通道设备名为 UidChannelSetModel 的 channel_name
-                        for uid_channel_set in uid_channel_set_qs:
-                            data_list.append({'userID': userID, 'UID': UID, 'uid_nick': uid_channel_set['channel_name'],
-                                              'channel': uid_channel_set['channel'], 'password': encrypt_pass})
+                userDevice = Device_Info(id=id, userID_id=userID, UID=UID, NickName=NickName, View_Account=View_Account,
+                                         View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex, version=version,
+                                         vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
+                userDevice.save()
+                # 添加到家庭房间
+                if family_id:
+                    EquipmentFamilyView.family_room_device_save(family_id, room_id, userDevice.id, Type)
+
+                uid_serial_qs = UIDCompanySerialModel.objects.filter(uid__uid=UID)
+                if uid_serial_qs.exists():
+                    uid_serial = uid_serial_qs[0]
+                    serial_number = uid_serial.company_serial.serial_number + uid_serial.company_serial.company.mark
+                    Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
+                                                               vodPrimaryMaster=vodPrimaryMaster,
+                                                               serial_number=serial_number)
+                    self.unicom_user_info_save(userID, serial_number)
                 else:
-                    data_list = [{'userID': userID, 'UID': UID, 'uid_nick': NickName, 'password': encrypt_pass}]
+                    Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
+                                                               vodPrimaryMaster=vodPrimaryMaster)
 
-                # 请求Alexa服务器更新事件网关
-                data_list = json.dumps(data_list)
-                data = {'data_list': data_list}
-                url = 'https://www.zositech.xyz/deviceStatus/addOrUpdateV2'
-                requests.post(url, data=data, timeout=2)
+                if not us_qs.exists():
+                    us_qs = UidSetModel.objects.filter(uid=UID)
+
+                if us_qs.exists() and us_qs[0].is_alexa == 1:
+                    if us_qs[0].channel > 1:
+                        data_list = []
+                        uid_channel_set_qs = UidChannelSetModel.objects.filter(uid_id=us_qs[0].id). \
+                            values('channel', 'channel_name')
+                        if uid_channel_set_qs.exists():
+                            # 多通道设备名为 UidChannelSetModel 的 channel_name
+                            for uid_channel_set in uid_channel_set_qs:
+                                data_list.append({'userID': userID, 'UID': UID, 'uid_nick': uid_channel_set['channel_name'],
+                                                  'channel': uid_channel_set['channel'], 'password': encrypt_pass})
+                    else:
+                        data_list = [{'userID': userID, 'UID': UID, 'uid_nick': NickName, 'password': encrypt_pass}]
 
+                    # 请求Alexa服务器更新事件网关
+                    data_list = json.dumps(data_list)
+                    data = {'data_list': data_list}
+                    url = 'https://www.zositech.xyz/deviceStatus/addOrUpdateV2'
+                    requests.post(url, data=data, timeout=2)
+
+                # 记录添加日志
+                LogModel.objects.create(**log)
         except Exception as e:
-            return response.json(10, repr(e))
+            # 记录添加失败日志
+            error_msg = 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e))
+            operation = '{}添加{}失败:{}'.format(userID, UID, error_msg)
+            log['operation'] = operation
+            LogModel.objects.create(**log)
+            return response.json(10, error_msg)
         else:
             dvqs = Device_Info.objects.filter(id=id).values('id', 'userID', 'NickName', 'UID',
                                                             'View_Account',
@@ -778,7 +797,7 @@ class EquipmentManagerV3(View):
             p['View_Password'] = self.encrypt_pwd(p['View_Password'])
 
             # 判断设备是否支持4G
-            uid_set_qs =UidSetModel.objects.filter(uid=p['UID']).values('mobile_4g')
+            uid_set_qs = UidSetModel.objects.filter(uid=p['UID']).values('mobile_4g')
             if uid_set_qs.exists():
                 uid_set_qs = uid_set_qs.first()
                 if uid_set_qs['mobile_4g'] == 1:
@@ -958,7 +977,7 @@ class EquipmentManagerV3(View):
                         items.append(item)
             return response.json(0, items)
         except Exception as e:
-            return response.json(500, 'error_ine:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
     # 加密
     def encrypt_pwd(self, userPwd):
@@ -1083,7 +1102,7 @@ class EquipmentManagerV3(View):
                     EquipmentInfoService.get_equipment_info_model('', val).filter(device_uid=uid).delete()
             return response.json(0)
         except Exception as e:
-            return response.json(500, repr(e))
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
     def do_get_device_features(self, request_dict, response):
         uid = request_dict.get('uid', None)