浏览代码

多线程上传ai识别图到S3
优先存储推送消息,后上传图片

lang 3 年之前
父节点
当前提交
44324d850b
共有 1 个文件被更改,包括 60 次插入87 次删除
  1. 60 87
      Controller/AiController.py

+ 60 - 87
Controller/AiController.py

@@ -29,7 +29,6 @@ import calendar
 import datetime
 import logging
 import sys
-
 import requests
 from aliyunsdkcore import client
 from aliyunsdksts.request.v20150401 import AssumeRoleRequest
@@ -705,28 +704,10 @@ class AiView(View):
         else:
             return HttpResponseRedirect(pay_success_url)
 
-    def update_jpush_time(self,userID, request_dict, response):
-        logger = logging.getLogger('info')
-        msg_id = request_dict.get('msg_id', None)
-        apns_push_time = request_dict.get('apns_push_time', None)
-        logger.info("----init--apns----push_time={apns_push_time}".format(apns_push_time=apns_push_time))
-        apns_push_time = int(apns_push_time)
-        logger.info("---msg--id={msg_id}".format(msg_id=msg_id))
-        logger.info("---apns----push_time={apns_push_time}".format(apns_push_time=apns_push_time))
-        try:
-            aiRes = AiProcessTime.objects.filter(msg_id=msg_id).update(appPushTime=apns_push_time)
-        except Exception as e:
-            logger.info(repr(e))
-            return response.json(902,repr(e))
-        return response.json(0,aiRes)
-
     def do_ai_identification(self, request_dict,response):
-        msg_id = CommonService.createOrderID()
-        AiProcessTime.objects.create(detectTime=0, receiveTime=0, aiTime=0,
-                                     aiEndTime=0, pushTime=0,
-                                     pushEndTime=0, serverCountTime=0, msg_id=msg_id)
         etk = request_dict.get('etk', None)
         n_time = request_dict.get('n_time', None)
+        channel = request_dict.get('channel', '1')
         receiveTime = int(time.time())
         logger = logging.getLogger('info')
         logger.info('-----------into----ai--api')
@@ -824,10 +805,22 @@ class AiView(View):
             label_list = ','.join(labels['label_list'])
             logger.info(event_type)
             logger.info(label_list)
+
+            # 上传缩略图到s3
+            upload_cover_path = "{uid}/{channel}/cover{n_time}.jpg".format(uid=uid, channel=channel,
+                                                                           n_time=n_time)  # 封面图
+            upload_desc_path = "{uid}/{channel}/desc{n_time}.jpg".format(uid=uid, channel=channel,
+                                                                         n_time=n_time)  # 详情内容图
+            #多线程上传图片
+            thread_cover = threading.Thread(target=self.upload_s3, args=(cover, upload_cover_path))
+            thread_desc = threading.Thread(target=self.upload_s3, args=(desc, upload_desc_path))
+            thread_cover.start()
+            thread_desc.start()
+            #需要删除图片
+
+
             #存储消息以及推送
-            channel = request_dict.get('channel', '1')
             is_st = 1  #单图
-
             # 查询推送数据
             uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
                 values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id',
@@ -858,42 +851,6 @@ class AiView(View):
                 if tz is None or tz == '':
                     tz = 0
 
-                # 推送标题
-                msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
-                # 推送内容
-                msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz, label_list=label_list)
-                kwargs = {
-                    'uid': uid,
-                    'channel': channel,
-                    'event_type': event_type,
-                    'n_time': n_time,
-                    'appBundleId': appBundleId,
-                    'token_val': token_val,
-                    'msg_title': msg_title,
-                    'msg_text': msg_text,
-                     'msg_id' : msg_id,
-                }
-                # 推送消息
-                # if push_type == 0:  # ios apns
-                #     logger.info('into-------apns')
-                #     apns_start_time = int(time.time())
-                #     res = self.do_apns(**kwargs)
-                #     apns_end_time = int(time.time())
-                #     logger.info(res)
-                # # elif push_type == 1:  # android gcm
-                # #     self.do_fcm(**kwargs)
-                # elif push_type == 2:  # android jpush
-                #     logger.info('into-------jpush')
-                #     jpush_start_time = int(time.time())
-                #     res = self.do_jpush(**kwargs)
-                #     jpush_end_time = int(time.time())
-                #     logger.info(res)
-                if push_type == 1:  # android gcm
-                    logger.info('into-------gcm')
-                    apns_start_time = int(time.time())
-                    res = self.do_fcm(**kwargs)
-                    apns_end_time = int(time.time())
-
                 # 以下是存库
                 userID_id = up["userID_id"]
                 if userID_id not in userID_ids:
@@ -905,39 +862,56 @@ class AiView(View):
                         devUid=uid,
                         devNickName=nickname,
                         Channel=channel,
-                        alarm='检查到{labels} \tChannel:{channel}'.format(labels=','.join(labels['label_list']), channel=channel),
+                        alarm='检查到{labels} \tChannel:{channel}'.format(labels=','.join(labels['label_list']),
+                                                                       channel=channel),
                         is_st=is_st,
                         receiveTime=receiveTime,
                         addTime=now_time,
                         storage_location=2
                     ))
                     userID_ids.append(userID_id)
-            Ai_Push_Info.objects.bulk_create(eq_list)
 
-            #上传缩略图到s3
-            cover_start_time = int(time.time())
-            upload_cover_path = "{uid}/{channel}/cover{n_time}.jpg".format(uid=uid, channel=channel, n_time=n_time)  #封面图
-            upload_desc_path = "{uid}/{channel}/desc{n_time}.jpg".format(uid=uid, channel=channel, n_time=n_time)   #详情内容图
-            c_res = self.upload_s3(cover, upload_cover_path)
-            d_res = self.upload_s3(desc, upload_desc_path)
-            if c_res and d_res:
-                logger.info('upload-----S3----success')
-                endTime = int(time.time())
-                count_time = endTime - receiveTime
-                AiProcessTime.objects.filter(msg_id=msg_id).update(detectTime=n_time, receiveTime=receiveTime, aiTime=ai_start_time,
-                                             aiEndTime=ai_end_time, pushTime=apns_start_time,
-                                             pushEndTime=apns_end_time, serverCountTime=count_time,picUploadTime=cover_start_time,
-                                                                   picUploadEndTime = endTime, endTime=endTime)
-                #删除临时文件
-                # delf = os.path.join(BASE_DIR, 'static/ai')
-                # logger.info(f"删除目录:{delf}下得文件")
-                self.delfile(path=delf)
-                return JsonResponse(status=200, data='success', safe=False)
-            return JsonResponse(status=500, data='fail', safe=False)
+                # 推送标题
+                msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
+                # 推送内容
+                msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz, label_list=label_list)
+                kwargs = {
+                    'uid': uid,
+                    'channel': channel,
+                    'event_type': event_type,
+                    'n_time': n_time,
+                    'appBundleId': appBundleId,
+                    'token_val': token_val,
+                    'msg_title': msg_title,
+                    'msg_text': msg_text,
+                }
+                try:
+                    # 推送消息
+                    if push_type == 0:  # ios apns
+                        res = self.do_apns(**kwargs)
+                    elif push_type == 1:  # android gcm
+                        self.do_fcm(**kwargs)
+                    elif push_type == 2:  # android jpush
+                        self.do_jpush(**kwargs)
+                    # if push_type == 1:  # android gcm
+                    #     logger.info('into-------gcm')
+                    #     apns_start_time = int(time.time())
+                    #     res = self.do_fcm(**kwargs)
+                    #     apns_end_time = int(time.time())
+                except Exception as e:
+                    logger.info("errLine={errLine}, errMsg={errMsg}".format(errLine=e.__traceback__.tb_lineno,errMsg=repr(e)))
+                    continue
+
+            Ai_Push_Info.objects.bulk_create(eq_list)
+            return JsonResponse(status=200, data='success', safe=False)
 
         except Exception as e:
             print(e)
-            return response.json(500, repr(e))
+            data = {
+                'errLine':e.__traceback__.tb_lineno,
+                'errMsg':repr(e)
+            }
+            return response.json(500, data)
 
     def delfile(self, path):
 
@@ -1028,7 +1002,7 @@ class AiView(View):
             send_text = '{msg} channel:{channel} date:{date}'.format(msg=msg, channel=channel, date=n_date)
         return send_text
 
-    def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text, msg_id=0):
+    def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
         app_key = JPUSH_CONFIG[appBundleId]['Key']
         master_secret = JPUSH_CONFIG[appBundleId]['Secret']
         # 此处换成各自的app_key和master_secre
@@ -1046,14 +1020,13 @@ class AiView(View):
         print(res)
         return res.status_code
 
-    def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text, msg_id=0):
+    def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
         try:
 
             serverKey = FCM_CONFIG[appBundleId]
             push_service = FCMNotification(api_key=serverKey)
             data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
-                    "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel,
-                    "msg_id": msg_id}
+                    "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
             result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
                                                        message_body=msg_text, data_message=data,
                                                        extra_kwargs={
@@ -1068,7 +1041,7 @@ class AiView(View):
             return 'serverKey abnormal'
 
 
-    def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text, msg_id=0):
+    def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
         logger = logging.getLogger('info')
         logger.info("进来do_apns函数了")
         logger.info(token_val)
@@ -1077,7 +1050,7 @@ class AiView(View):
         try:
             cli = apns2.APNSClient(mode=APNS_MODE, client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
             push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
-                         "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel, "msg_id": msg_id}
+                         "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
             alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
             payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
             n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)