def get_pagination_user(cls, start=DEFAULT_START_PAGE, page_size=DEFAULT_PAGE_SIZE, **kwargs): result = None accurated_dict, kwargs = get_accurated_dict(['level', 'client_type'], **kwargs) try: # 精确查询部分处理 q = cls.query.filter_by(**accurated_dict) # 模糊匹配部分处理 if 'account' in kwargs: q = q.filter(User.account.like('%' + kwargs['account'] + '%')) if 'mobile' in kwargs: q = q.filter(User.mobile.like('%' + kwargs['mobile'] + '%')) if 'nick_name' in kwargs: q = q.filter( User.nick_name.like('%' + kwargs['nick_name'] + '%')) return q.order_by(cls.created_time.desc()).paginate( start, page_size, error_out=False) except Exception as e: logger.error(e) return result
def process_single_file(file): success = False if file and allowed_file(file.filename): file_path = None try: org_file_name = file.filename file_name = CommonHelper.get_uuid_file_name(org_file_name) file_path = os.path.join(UPLOADS_DEFAULT_DEST, file_name) if not os.path.exists(UPLOADS_DEFAULT_DEST): os.mkdir(UPLOADS_DEFAULT_DEST) file.save(file_path) ret_file = SysFile(file_name=file_name, org_name=org_file_name) ret_file.save() session_commit() success = True data = {'id': ret_file.id, 'filename': ret_file.file_name} except Exception as e: logger.error('file save error: {}, {}'.format(file_path, e.args)) data = ResultEnum.FILE_UPLOAD_ERROR else: data = ResultEnum.FILE_NOT_ALLOWED_EXTENSION return success, data
def get_pagination(cls, start=DEFAULT_START_PAGE, page_size=DEFAULT_PAGE_SIZE, **kwargs): result = None accurated_dict, kwargs = get_accurated_dict(['method', 'type'], **kwargs) try: # 精确查询部分处理 q = cls.query.filter_by(**accurated_dict) # 模糊匹配部分处理 if 'name' in kwargs: q = q.filter(cls.name.like('%' + kwargs['name'] + '%')) if 'code' in kwargs: q = q.filter(cls.code.like('%' + kwargs['code'] + '%')) if 'node_url' in kwargs: q = q.filter(cls.node_url.like('%' + kwargs['node_url'] + '%')) return q.order_by(desc(cls.created_time)).paginate(start, page_size, error_out=False) except Exception as e: logger.error(e) return result
def global_error_handler(e): if isinstance(e, APIException): api_exception = e elif isinstance(e, HTTPException): api_exception = http_to_api_exception(e) elif isinstance(e, JsonValidationError): api_exception = APIException(ResultEnum.JSON_SCHEMA_VALIDATION_ERROR, e.message) else: logger.error(e) code = error_code = e.code if hasattr(e, 'code') else 500 if hasattr(e, 'description'): msg = e.description elif hasattr(e, 'args'): msg = e.args[0] else: msg = 'unknown error' api_exception = APIException(code=code, error_code=error_code, msg=msg) logger.debug('code: {}, error_code: {}, msg: {} )'.format( api_exception.code, api_exception.error_code, api_exception.msg)) return api_exception
def disable_permission(permission_id): permission_data = g.json_data if permission_data.get('id') != permission_id: raise APIException(ResultEnum.PERMISSION_INVALID_ID) permission = AuthPermission.get_or_404(permission_id) try: permission.toggle_disable() return HttpHelper.normal_handler(permission) except Exception as e: logger.error(e) raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
def disable_role(role_id): role_data = g.json_data if role_data.get('id') != role_id: raise APIException(ResultEnum.ROLE_INVALID_ID) role = AuthRole.get_by_status(role_id) try: role.toggle_disable() return HttpHelper.normal_handler(role) except Exception as e: logger.error(e) raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
def get_current_jwt_user(): """ 校验当前用户是否进行Jwt登录 :return: 当前jwt登录用户信息 """ current_user = None try: current_user = get_jwt_identity() except Exception as e: logger.error(e) finally: if not current_user: raise APIException(ResultEnum.TOKEN_VALIDATE_ERROR) return current_user
def get_pagination(cls, start=DEFAULT_START_PAGE, page_size=DEFAULT_PAGE_SIZE, **kwargs): result = None try: result = cls.query.filter_by(**kwargs).order_by( desc(cls.created_time)).paginate(start, page_size, error_out=False) except Exception as e: logger.error(e) return result
def __register_by_email(account, password): try: client_type = ClientTypeEnum.USER_EMAIL.code user = User(account=account, password=generate_password_hash(password), client_type=client_type) user.save() return user except Exception as e: logger.error(e) if isinstance(e, APIException): ret = e.result_enum else: ret = ResultEnum.USER_REGISTER_ERROR raise APIException(ret)
def change_password(user_id): usr = User.get_by_status_or_404(user_id) password = g.json_data.get('password', None) if not password: raise APIException(ResultEnum.USER_OR_PASS_EMPTY_ERROR) usr.password = generate_password_hash(password) try: usr.update() return HttpHelper.normal_handler(usr) except Exception as e: logger.error(e) return HttpHelper.error_handler(ResultEnum.UNKNOWN_ERROR)
def bind_user_roles(user_id): json_data = g.json_data if user_id != json_data.get('user_id'): raise APIException(ResultEnum.USER_INVALID_ID) role_ids = json_data.get('roles') if not role_ids: raise APIException(ResultEnum.INVALID_PARAMETER) try: user = User.get_by_status_or_404(user_id) user.refresh_roles(role_ids) return HttpHelper.normal_handler() except Exception as e: logger.error(e) return HttpHelper.error_handler(ResultEnum.UNKNOWN_ERROR)
def bind_role_permissions(role_id): json_data = g.json_data if role_id != json_data.get('role_id'): raise APIException(ResultEnum.ROLE_INVALID_ID) permission_ids = json_data.get('permissions') if not permission_ids: raise APIException(ResultEnum.INVALID_PARAMETER) try: role = AuthRole.get_by_status_or_404(role_id) role.refresh_permissions(permission_ids) return HttpHelper.normal_handler() except Exception as e: logger.error(e) return HttpHelper.error_handler(ResultEnum.UNKNOWN_ERROR, e.args)
def edit_role(role_id): role_data = g.json_data if role_data.get('id') != role_id: raise APIException(ResultEnum.ROLE_INVALID_ID) role = AuthRole.get_by_status_or_404(role_id) if 'code' in role_data: role_by_code = AuthRole.get_by_code(role_data.get('code')) if role.id != role_by_code.id: raise APIException(ResultEnum.ROLE_CODE_EXIST) try: role.update(**role_data) return HttpHelper.normal_handler(role) except Exception as e: logger.error(e) raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
def edit_permission(permission_id): permission_data = g.json_data if permission_data.get('id') != permission_id: raise APIException(ResultEnum.PERMISSION_INVALID_ID) permission = AuthPermission.get_by_status_or_404(permission_id) if 'code' in permission_data: permission_by_code = AuthPermission.get_by_code(permission_data.get('code')) if permission.id != permission_by_code.id: raise APIException(ResultEnum.PERMISSION_CODE_EXISTS) try: permission.update(**permission_data) return HttpHelper.normal_handler(permission) except Exception as e: logger.error(e) raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
def post(url, data=None, auth_token=None, return_json=True, auth_type='Bearer'): if auth_token: token = HttpHelper.get_auth_token_by_type(auth_type, auth_token) try: r = requests.post(url, json=data, auth_token=token) except Exception as e: logger.error(e) return HttpHelper.error_handler(ResultEnum.UNKNOWN_ERROR) else: try: r = requests.post(url, json=data) except Exception as e: logger.error(e) return HttpHelper.error_handler(ResultEnum.UNKNOWN_ERROR) return r.json() if return_json else r.text()
def add_role(): role_data = g.json_data if 'name' not in role_data or 'code' not in role_data: raise APIException(ResultEnum.INVALID_PARAMETER) role_code = role_data.get('code') role_name = role_data.get('name') role = AuthRole.get_by_code(role_code) if role: raise APIException(ResultEnum.ROLE_CODE_EXIST) role = AuthRole(code=role_code, name=role_name) try: if 'id' in role_data: del role_data['id'] role.save(**role_data) return HttpHelper.normal_handler(role) except Exception as e: logger.error(e) raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
def add_permission(): permission_data = g.json_data # Permission code cannot be empty code = permission_data.get('code', None) if not code: raise APIException(ResultEnum.PERMISSION_EMPTY_CODE) # Always existing permission with same code permission = AuthPermission.get_by_code(code) if permission: raise APIException(ResultEnum.PERMISSION_CODE_EXISTS) permission = AuthPermission() try: if 'id' in permission_data: del permission_data['id'] permission.save(**permission_data) return HttpHelper.normal_handler(permission) except Exception as e: logger.error(e) raise APIException(ResultEnum.UNKNOWN_ERROR, e.args)
def error_handler(result_enum, data=None, resp_status=200): logger.error(result_enum) return HttpHelper.json_response( ResultHelper.error_with_enum(result_enum, data), resp_status)