def _update_base_info(self, request, app_code): app = App.objects.get(code=app_code) form = BaseInfoForm(request.POST) if not form.is_valid(): message = first_error_message(form) raise BadRequestException(message) name = form.cleaned_data["name"] developer = form.cleaned_data["developer"] app_tags = form.cleaned_data["app_tags"] old_name = app.name is_valid, message = validate_app_name(name, old_name) if not is_valid: raise BadRequestException(message) developer_list = developer.split(';') if developer else [] # 保存用户基本信息 with transaction.atomic(): app.name = name app.tags = app_tags app.save() # 保存开发负责人信息 if developer_list: app.developer.clear() user_model = get_user_model() for dev in developer_list: d_user = user_model.objects.get(username=dev) app.developer.add(d_user)
def parse_request(request: Request, model_type: Type[T]) -> T: request_json = request.get_json(silent=True) if not request_json: raise BadRequestException("Request body is not a valid JSON") try: return model_type(**request_json) except ValidationError as e: raise BadRequestException(f"Bad request: {e}")
def get_daemon_config_for_current_network(event, context): logger.info(f"event for get_daemon_config_for_current_network:: {event}") username = event["requestContext"]["authorizer"]["claims"]["email"] path_parameters = event["pathParameters"] query_parameters = event["queryStringParameters"] if not validate_dict(path_parameters, ["org_uuid", "service_uuid", "group_id" ]) or 'network' not in query_parameters: raise BadRequestException() org_uuid = path_parameters["org_uuid"] service_uuid = path_parameters["service_uuid"] group_id = path_parameters["group_id"] if query_parameters["network"] == EnvironmentType.TEST.value: response = ServicePublisherService( username, org_uuid, service_uuid).daemon_config(environment=EnvironmentType.TEST.value) elif query_parameters["network"] == EnvironmentType.MAIN.value: response = ServicePublisherService( username, org_uuid, service_uuid).daemon_config(environment=EnvironmentType.MAIN.value) else: raise EnvironmentNotFoundException() return generate_lambda_response(StatusCode.OK, { "status": "success", "data": response, "error": {} }, cors_enabled=True)
def post(self, request): """添加/编辑第三方服务信息 """ form = ExternalServerForm(request.POST) if not form.is_valid(): message = first_error_message(form) raise BadRequestException(message) server_id = form.cleaned_data["server_id"] server_ip = form.cleaned_data["server_ip"] server_port = form.cleaned_data["server_port"] server_cate = form.cleaned_data["server_cate"] username = form.cleaned_data["username"] password = form.cleaned_data["password"] if ThirdServer.objects.is_server_exists(server_id, server_ip, server_port): message = "IP为[{ip}], 端口为 [{port}] 的服务器已经存在".format( ip=server_ip, port=server_port) return FailJsonResponse(message) try: data = ThirdServer.objects.update_or_create_server( server_id, server_ip, server_port, username, password, server_cate) return OKJsonResponse("保存成功", data=data) except Exception as e: logger.exception("保存服务信息异常:%s", e) return FailJsonResponse("保存出错", data={})
def post(self, request): """添加/编辑AppServer信息 """ form = ServerForm(request.POST) if not form.is_valid(): message = first_error_message(form) raise BadRequestException(message) server_id = form.cleaned_data["server_id"] server_ip = form.cleaned_data["server_ip"] server_port = form.cleaned_data["server_port"] app_port = form.cleaned_data["app_port"] server_cate = form.cleaned_data["server_cate"] # 验证 ip & port 是否重复 if BkServer.objects.is_server_exists(server_id, server_ip, server_port): message = "IP为[{ip}], 端口为 [{port}] 的服务器已经存在".format( ip=server_ip, port=server_port) return FailJsonResponse(message) # 编辑信息 try: data = BkServer.objects.update_or_create_server( server_id, server_ip, server_port, app_port, server_cate) return OKJsonResponse("保存成功", data=data) except Exception as e: logger.exception("保存应用服务器信息异常:%s", e) return FailJsonResponse("保存出错", data={})
def _update_introduction(self, request, app_code): app = App.objects.get(code=app_code) introduction = request.POST.get('introduction', '').replace(' ', ' ').strip() if not introduction: raise BadRequestException("应用简介不能为空") app.introduction = introduction app.save()
def get_context_data(self, **kwargs): context = super(AppRecordView, self).get_context_data(**kwargs) app_code = self.kwargs["app_code"] operate_code = self.kwargs["operate_code"] if operate_code not in OPERATE_CODE_LIST: raise BadRequestException("operate_code is invalid") query = Record.objects.query_records(app_code, operate_code, size=100) record_list = [] for _record in query: # 提测展示信息 extra_data = _record.get_extra_data() if not extra_data: task_detail = '' extra_msg = '--' else: task_detail = extra_data.get("task_detail", "") if _record.operate_id in [ OperateIDEnum.IN_OFFLINE.value, OperateIDEnum.TO_OFFLINE.value ]: _extra_data_mode = extra_data.get("mode", ModeEnum.ALL.value) _env = ModeNameDict.get(_extra_data_mode, "--") extra_msg = "选择下架环境:{}".format(_env) else: extra_msg = "--" is_done = _record.operate_id in APP_DID_OPERATE_ID_LIST record_list.append({ "operate_type": _record.get_operate_id_display(), "operate_user": _record.operate_user, "is_success": _record.is_success, "is_done": is_done, "operate_time": _record.operate_time_display, "extra_data": extra_msg, "detail": _record.message.replace('\n', '<br/>') if _record.message else "没有返回信息!", "task_detail": task_detail }) context.update({ "record_list": record_list, "app_code": app_code, }) return context
def get_document_types_handler(event, context): required_keys = ["countryCode"] if not validate_dict(event["pathParameters"], required_keys): raise BadRequestException() country_code = event["pathParameters"]["countryCode"] response = verification_service.get_document_types(country_code) return generate_lambda_response(StatusCode.OK, { "status": ResponseStatus.SUCCESS, "data": response })
def publish_service_metadata_to_ipfs(event, context): username = event["requestContext"]["authorizer"]["claims"]["email"] path_parameters = event["pathParameters"] if "org_uuid" not in path_parameters and "service_uuid" not in path_parameters: raise BadRequestException() org_uuid = path_parameters["org_uuid"] service_uuid = path_parameters["service_uuid"] response = ServicePublisherService(username, org_uuid, service_uuid).publish_service_data_to_ipfs() return generate_lambda_response( StatusCode.OK, {"status": "success", "data": response, "error": {}}, cors_enabled=True )
def get_service_details_using_org_id_service_id(event, context): logger.info(f"event: {event}") query_parameters = event["queryStringParameters"] if not validate_dict(query_parameters, ["org_id", "service_id"]): raise BadRequestException() org_id = query_parameters["org_id"] service_id = query_parameters["service_id"] response = ServicePublisherService.get_service_for_org_id_and_service_id(org_id, service_id) return generate_lambda_response( StatusCode.OK, {"status": "success", "data": response, "error": {}}, cors_enabled=True )
def create_service(event, context): username = event["requestContext"]["authorizer"]["claims"]["email"] path_parameters = event["pathParameters"] payload = json.loads(event["body"]) if not path_parameters.get("org_uuid", ""): raise BadRequestException() org_uuid = path_parameters["org_uuid"] response = ServicePublisherService(username, org_uuid, None).create_service(payload) return generate_lambda_response( StatusCode.OK, {"status": "success", "data": response, "error": {}}, cors_enabled=True )
def delete(self, request, server_id): """删除第三方服务 """ if not server_id: raise BadRequestException('请选择要删除的服务') try: ThirdServer.objects.filter(id=server_id).delete() except Exception: logger.exception("删除服务[id:%s]失败", server_id) return FailJsonResponse("删除服务失败") return OKJsonResponse("删除成功")
def get_free_call_signer_address(event, context): username = event["requestContext"]["authorizer"]["claims"]["email"] query_string_parameters = event["queryStringParameters"] if "org_id" not in query_string_parameters and "service_id" not in query_string_parameters and "group_id" not in query_string_parameters: raise BadRequestException() response = {"free_call_signer_address": SIGNER_ADDRESS} return generate_lambda_response(StatusCode.OK, { "status": "success", "data": response, "error": {} }, cors_enabled=True)
def delete(self, request, server_id): """删除AppServer信息 """ if not server_id: raise BadRequestException("请选择要删除的服务器") try: BkServer.objects.filter(id=server_id).delete() except Exception: logger.exception("删除服务器[id:%s]失败", server_id) return FailJsonResponse("删除服务器失败") return OKJsonResponse("删除成功")
def list_of_service_pending_for_approval_from_slack(event, context): path_parameters = event["pathParameters"] if "org_uuid" not in path_parameters: raise BadRequestException() org_uuid = path_parameters["org_uuid"] response = ServicePublisherService( None, org_uuid, None).get_list_of_service_pending_for_approval() return generate_lambda_response(StatusCode.OK, { "status": "success", "data": response, "error": {} }, cors_enabled=True)
def verify_service_id(event, context): username = event["requestContext"]["authorizer"]["claims"]["email"] path_parameters = event["pathParameters"] query_parameters = event["queryStringParameters"] if "org_uuid" not in path_parameters and "service_id" not in query_parameters: raise BadRequestException() org_uuid = path_parameters["org_uuid"] service_id = query_parameters["service_id"] response = ServicePublisherService(username, org_uuid, None).get_service_id_availability_status(service_id) return generate_lambda_response( StatusCode.OK, {"status": "success", "data": response, "error": {}}, cors_enabled=True )
def post(self, request): form = PasswordChangeForm(request.POST) if not form.is_valid(): message = first_error_message(form) raise BadRequestException(message) new_password1 = form.cleaned_data.get("new_password1") bk_token = request.COOKIES.get(settings.BK_COOKIE_NAME, None) data = {'new_password': new_password1} ok, message = change_password(bk_token, data) if not ok: return FailJsonResponse(message or "密码重置失败") return OKJsonResponse("success")
def register_org_member(event, context): username = event["requestContext"]["authorizer"]["claims"]["email"] payload = json.loads(event["body"]) required_keys = ["wallet_address", "invite_code"] if not validate_dict(payload, required_keys): raise BadRequestException() response = OrganizationOrchestratorService().register_org_member( username, payload) return generate_lambda_response(StatusCode.CREATED, { "status": ResponseStatus.SUCCESS, "data": response, "error": {} }, cors_enabled=True)
def save_service_attributes(event, context): logger.info(f"Event for save service {event}") username = event["requestContext"]["authorizer"]["claims"]["email"] path_parameters = event["pathParameters"] payload = json.loads(event["body"]) if not path_parameters.get("org_uuid", "") and not path_parameters.get("service_uuid", ""): raise BadRequestException() org_uuid = path_parameters["org_uuid"] service_uuid = path_parameters["service_uuid"] response = ServicePublisherService(username, org_uuid, service_uuid).save_service_attributes(payload) return generate_lambda_response( StatusCode.OK, {"status": "success", "data": response, "error": {}}, cors_enabled=True )
def save_transaction_hash_for_published_service(event, context): username = event["requestContext"]["authorizer"]["claims"]["email"] path_parameters = event["pathParameters"] payload = json.loads(event["body"]) if "org_uuid" not in path_parameters and "service_uuid" not in path_parameters: raise BadRequestException() org_uuid = path_parameters["org_uuid"] service_uuid = path_parameters["service_uuid"] response = ServicePublisherService(username, org_uuid, service_uuid).save_transaction_hash_for_published_service( payload) return generate_lambda_response( StatusCode.OK, {"status": "success", "data": response, "error": {}}, cors_enabled=True )
def legal_approval_of_service(event, context): path_parameters = event["pathParameters"] if "org_uuid" not in path_parameters and "service_uuid" not in path_parameters: raise BadRequestException() org_uuid = path_parameters["org_uuid"] service_uuid = path_parameters["service_uuid"] response = ServicePublisherService(None, org_uuid, service_uuid).approve_service() return generate_lambda_response(StatusCode.OK, { "status": "success", "data": response, "error": {} }, cors_enabled=True)
def _add_or_update(self, request, app_code, var_id=None): if not var_id: form = AppEnvForm(request.POST) else: put = QueryDict(request.body) form = AppEnvForm(put) if not form.is_valid(): message = first_error_message(form) # print form.errors raise BadRequestException(message) # app_code = form.cleaned_data["app_code"] name = form.cleaned_data["name"] value = form.cleaned_data["value"] intro = form.cleaned_data["intro"] mode = form.cleaned_data["mode"] name = 'BKAPP_%s' % name # do add if not var_id: if AppEnvVar.objects.exists(app_code, mode, name): message = "变量名已经存在, 请勿重复添加!" return FailJsonResponse(message) try: env_var = AppEnvVar.objects.create(app_code=app_code, mode=mode, name=name, value=value, intro=intro) var_id = env_var.id except Exception: # 保存app环境变量异常 message = "保存app环境变量失败" logger.exception(message) return FailJsonResponse(message) # do update else: if AppEnvVar.objects.update_target_exists(app_code, mode, name, var_id): message = "同名变量已经存在! 无法对当前变量进行更新" return FailJsonResponse(message) AppEnvVar.objects.update(var_id, name, value, intro, mode) return OKJsonResponse("保存变量成功", id=var_id)
def _update_vsc_info(self, request, app_code): vcs_info_form = VCSInfoForm(request.POST) if not vcs_info_form.is_valid(): message = first_error_message(vcs_info_form) raise BadRequestException(message) vcs_url = vcs_info_form.cleaned_data["vcs_url"] vcs_username = vcs_info_form.cleaned_data["vcs_username"] vcs_password = vcs_info_form.cleaned_data["vcs_password"] SecureInfo.objects.filter(app_code=app_code).update( vcs_url=vcs_url, vcs_username=vcs_username, vcs_password=vcs_password )
def post_bookmarks(version: Version) -> Dict[str, Any]: if not accept_new_syncs(): raise BadRequestException("Server is not accepting new syncs") bookmarks = BookmarksModel(id_=new_id(), bookmarks="", last_updated=now(), version=version.version) get_document(bookmarks.id_).set(bookmarks.dict()) return { "id": bookmarks.id_, "lastUpdated": bookmarks.last_updated.isoformat(), "version": bookmarks.version }
def post(self, request, *args, **kwargs): app_code = self.kwargs["app_code"] username = request.user.username logger.info("[app:%s] 开始进行[正式部署]...", app_code) app = App.objects.get(code=app_code) try: form_data = json.loads(request.POST.get("form_data", '{}')) except Exception as e: message = "参数错误!" logger.exception("[app:%s] %s error=%s", app_code, message, e) return BadRequestException(message) is_prod_app_deployable = BkServer.objects.check_prod_app_deployable() if not is_prod_app_deployable: message = "当前没有可用的[正式服务器], 无法进行提测操作. 请到<a href='/engine/server/'> [蓝鲸智云-开发者中心-服务器信息] </a> 注册并激活服务器" logger.info("[app:%s] %s", app_code, message) return FailJsonResponse(message) # 前端变量不要一直向后, 限制 is_tips = form_data.get("is_tips", 0) features = form_data.get("features", "") bugs = form_data.get("bugs", "") can_be_online, message = app.can_be_online() if not can_be_online: logger.info("[app:%s] %s", app_code, message) return FailJsonResponse(message) # 上线操作 ok, event_id, message = app_to_online_task(app_code, app, username, is_tips, features, bugs) # 操作流水日志 extra_data = {"username": username, "form_data": form_data} _r(app_code, username, UserOperateTypeEnum.RELEASE_ONLINE.value, extra_data) if not ok: logger.info("[app:%s] %s event_id: %s", app_code, message, event_id) return FailJsonResponse(message, event_id=event_id) message = "正式部署事件提交成功!" logger.info("[app:%s] %s event_id: %s", app_code, message, event_id) return OKJsonResponse(message, event_id=event_id)
def put_bookmarks(id_: str, bookmarks_patch: BookmarksPatch) -> Dict[str, Any]: doc_ref = get_document(id_) doc = doc_ref.get() if not doc.exists: raise NotFoundException() bookmarks = BookmarksModel(**doc.to_dict()) if bookmarks.last_updated != bookmarks_patch.last_updated: raise BadRequestException( f"lastUpdated does not match: {bookmarks_patch.last_updated.isoformat()} != {bookmarks.last_updated.isoformat()}" ) bookmarks.bookmarks = bookmarks_patch.bookmarks bookmarks.last_updated = now() doc_ref.set(bookmarks.dict()) return {"lastUpdated": bookmarks.last_updated.isoformat()}
def _update_db_info(self, request, app_code): form = DBInfoForm(request.POST) if not form.is_valid(): message = first_error_message(form) raise BadRequestException(message) db_host = form.cleaned_data["db_host"] db_port = form.cleaned_data["db_port"] db_username = form.cleaned_data["db_username"] db_password = form.cleaned_data["db_password"] SecureInfo.objects.filter(app_code=app_code).update( db_host=db_host, db_port=db_port, db_username=db_username, db_password=db_password, )
def post(self, request, *args, **kwargs): app_code = self.kwargs["app_code"] username = request.user.username logger.info("[app:%s] 开始进行[下架]...", app_code) try: form_data = json.loads(request.POST.get("form_data", '{}')) except Exception: message = "参数错误!" logger.exception("[app:%s] %s", app_code, message) return BadRequestException(message) # NOTE: 下架不加检查服务器, 因为此时已经提测/上线的, 所以默认可以下架成功 # 获取应用基本信息 app = App.objects.get(code=app_code) # 状态判定 mode = form_data.get("mode", "all") can_be_offline, message = app.can_be_offline(mode) if not can_be_offline: logger.info("[app:%s] %s", app_code, message) return FailJsonResponse(message) # 执行下架 app_old_state = app.state auth_token = app.auth_token ok, event_id = app_to_offline_task(app_code, auth_token, username, mode, app_old_state) # 操作流水日志 extra_data = {"username": username, "form_data": form_data} _r(app_code, username, UserOperateTypeEnum.RELEASE_OFFLINE.value, extra_data) if ok: message = "下架事件提交成功!" logger.info("[app:%s] %s event_id: %s", app_code, message, event_id) return OKJsonResponse(message, event_id=event_id) message = "下架事件提交失败!" logger.info("[app:%s] %s event_id: %s", app_code, message, event_id) return FailJsonResponse(message, event_id=event_id)
def process_interaction(self, payload): data = {} if payload["type"] == "block_actions": for action in payload["actions"]: if "button" == action.get("type"): data = json.loads(action.get("value", {})) if not data: raise BadRequestException() individual_username = data["username"] self.create_and_send_view_individual_modal( individual_username, payload["trigger_id"]) elif payload["type"] == "view_submission": individual_username = payload["view"]["blocks"][0]["fields"][1][ "text"] comment = payload["view"]["state"]["values"]["review_comment"][ "comment"]["value"] review_request_state = \ payload["view"]["state"]["values"]["approval_state"]["selection"]["selected_option"]["value"] self.process_approval_comment(review_request_state, comment, individual_username)
def post(self, request, *args, **kwargs): app_code = self.kwargs["app_code"] operate = request.POST.get('operate', '') if not operate: raise BadRequestException("参数异常") # 保存基本信息 try: if operate == 'base': self._update_base_info(request, app_code) elif operate == 'introduction': self._update_introduction(request, app_code) elif operate == 'vcs': self._update_vsc_info(request, app_code) elif operate == 'db': self._update_db_info(request, app_code) except BadRequestException as e: raise e except Exception as e: logger.exception("保存用户基本信息异常:%s", e) return FailJsonResponse("编辑失败") return OKJsonResponse("编辑成功")