def set_prerequisites(self, params): try: Logger.info(ObjectDetectionService.LOG_TAG, params) self.url_root = params.get("url_root") self.user_id = params.get("user_id") self.app_name = params.get("app_name") self.path_to_image = os.path.join(ObjectDetectionService.CWD_PATH, 'storage', self.user_id, self.app_name) self.path_to_upload_original = os.path.join(self.path_to_image, config["storage"]["upload_dir"], config["storage"]["original_dir"]) self.path_to_upload_thumbnail = os.path.join(self.path_to_image, config["storage"]["upload_dir"], config["storage"]["thumbnail_dir"]) self.path_to_output = os.path.join(self.path_to_image, config["storage"]["output_dir"]) if not os.path.isdir(self.path_to_image): mkdir_p(self.path_to_image) if not os.path.isdir(self.path_to_upload_original): mkdir_p(self.path_to_upload_original) if not os.path.isdir(self.path_to_upload_thumbnail): mkdir_p(self.path_to_upload_thumbnail) if not os.path.isdir(self.path_to_output): mkdir_p(self.path_to_output) except Exception as e: ApiResponse.set_msg(1, "Internal server error") Logger.error(ObjectDetectionService.LOG_TAG, "Exception: {error}".format(error=str(e))) return ApiResponse.get(config["api"]["base_code_object_detection"])
def wrapper(request, *args, **kwargs): if not monitor_api_auth_method(request): Logger().log(message='API认证未通过', mode=False) response = ApiResponse() response.code = 401 response.message = 'API认证未通过' return JsonResponse(data=response.__dict__, json_dumps_params={'ensure_ascii': False}) return func(request, *args, **kwargs)
def save_object_detected_image(self, image_name): try: Logger.info(ObjectDetectionService.LOG_TAG, "Image name received: {image_name}".format(image_name=image_name)) if(image_name): image_path = os.path.join(self.path_to_upload_original, image_name) image_file = imread(image_path) self.input_q.put(image_file) scipy.misc.imsave(os.path.join(self.path_to_output, image_name), self.output_q.get()) ApiResponse.set_body(0, "Success", { "image_url": ObjectDetectionService.get_image_url( image_name, self.user_id, self.app_name, config["storage"]["output_dir"], self.url_root )}) else: ApiResponse.set_msg(2,"Image name is required") except FileNotFoundError as e: ApiResponse.set_msg(3, "Image not found. Please try it after uploading the image.") Logger.error(ObjectDetectionService.LOG_TAG, "Exception: {error}".format(error=str(e))) except Exception as e: ApiResponse.set_msg(4, "Internal server error") Logger.error(ObjectDetectionService.LOG_TAG, "Exception: {error}".format(error=str(e))) return ApiResponse.get(config["api"]["base_code_object_detection"])
def resize_image(self, image_name): try: im = Image.open(os.path.join(self.path_to_upload_original, image_name)) im.thumbnail(ObjectDetectionService.SIZE, Image.ANTIALIAS) im.save(os.path.join(self.path_to_upload_thumbnail , image_name) , "JPEG") ApiResponse.set_body(0, "Image resized successfully", { "image_name": image_name }) except IOError: ApiResponse.set_msg(46, "Cannot create thumbnail for '%s'" % image_name) return ApiResponse.get(config["api"]["base_code_object_detection"])
def client_config(request): """客户端向api提交申请并返回配置数据""" hostname = request.GET.get('hostname') response = ApiResponse() get_client_config_handle_obj = GetClientConfigHandle( hostname, response.__dict__) client_config_dict = get_client_config_handle_obj.fetch_config() return JsonResponse(client_config_dict)
def get_lastest_images(self): try: list_of_files = glob.iglob(self.path_to_upload_thumbnail + '/*') # * means all if need specific format then *.csv files = sorted(list_of_files, key=os.path.getctime, reverse=True) if len(files): latest_images = [] for file in files: image_name = os.path.basename(file) latest_images.append(ObjectDetectionService.get_image_url( image_name, self.user_id, self.app_name, os.path.join(config["storage"]["upload_dir"], config["storage"]["thumbnail_dir"]), self.url_root )) if len(latest_images) == config["storage"]["retrieval_limit"]: break ApiResponse.set_body(0, "Records found", {"latest_images": latest_images}) else: ApiResponse.set_msg(32, "Record not found") except Exception as e: ApiResponse.set_msg(33, "Internal server error") Logger.error(ObjectDetectionService.LOG_TAG, "Exception: {error}".format(error=str(e))) return ApiResponse.get(config["api"]["base_code_object_detection"])
def save_image(self, image_file): try: # submit a empty part without filename if image_file.filename == '': ApiResponse.set_msg(16, "Image file is required") elif image_file and ObjectDetectionService.allowed_file(image_file.filename): filename = secure_filename(image_file.filename) unique_filename = ObjectDetectionService.get_unique_filename(filename) image_file.save(os.path.join(self.path_to_upload_original, unique_filename)) response = self.resize_image(unique_filename) if(response['header']['code'] == 0): ApiResponse.set_body(0, "Image uploaded successfully", { "image_name": response['body']['image_name'] }) else: return response else: ApiResponse.set_msg(17, "Allowed extensions are: " + ObjectDetectionService.ALLOWED_EXTENSIONS) except Exception as e: ApiResponse.set_msg(18, "Internal server error") Logger.error(ObjectDetectionService.LOG_TAG, "Exception: {error}".format(error=str(e))) return ApiResponse.get(config["api"]["base_code_object_detection"])
def client_data(request): """客户端向api提交监控数据""" response = ApiResponse() if request.method == 'POST': try: client_report_data_dict = json.loads( request.body.decode('utf-8')) # 获取客户端汇报数据字典 hostname = client_report_data_dict.get('hostname', None) # 获取主机名 application_name = client_report_data_dict.get( 'application_name', None) # 获取应用集名称 data = client_report_data_dict.get('data', None) # 获取监控数据 data_verification_obj = DataVerificationHandle( response=response.__dict__, hostname=hostname, application_name=application_name, data=data) response, data = data_verification_obj.check_data( ) # 检查数据返回响应及数据,检查成功data有数据,失败data为None if not data: # 无效数据或基础信息有误 return JsonResponse(response) else: # 有效数据 data_store_optimization_obj = DataStoreOptimizationHandle( hostname=hostname, application_name=application_name, data=data, redis_obj=REDIS_OBJ) # 对客户端汇报上来的数据进行优化存储 data_store_optimization_obj.process_and_save() # 数据处理及存储 # 触发器检测 host_obj = models.Host.objects.filter( hostname=hostname).first() # 获取主机实例 trigger_obj_set = get_application_trigger_obj_set( application_name=application_name) # 获取应用集对应触发器集合 data_handle_obj = DataHandle(redis_obj=REDIS_OBJ) # 实例化数据处理 for trigger_obj in trigger_obj_set: # 循环每个触发器 data_handle_obj.load_application_data_and_calculating( host_obj=host_obj, trigger_obj=trigger_obj) # 加载应用集数据并计算 except Exception as e: response['code'] = 500 response['message'] = '服务器错误,%s' % str(e) Logger().log(message='服务器错误,%s' % str(e), mode=False) return JsonResponse(response)
def decorated_function(*args, **kwargs): if 'image_file' not in request.files: ApiResponse.set_msg(RESPONSE['image']['offset'], RESPONSE['image']['message']) return ApiResponse.get(config["api"]["base_code_object_detection"]) return f(*args, **kwargs)
def prerequisite(key): if key not in request.params: ApiResponse.set_msg(RESPONSE[key]['offset'], RESPONSE[key]['message']) else: ApiResponse.set_msg(0, 'Success') return ApiResponse.get(config["api"]["base_code_decorators"])