def post(self): ''' file: schemas/create_dns.yml ''' data = request.get_json() validate( data, 'DnsModel', 'schemas/create_dns.yml', validation_error_handler=utils.validation_error_inform_error ) dns = '{}.{}'.format(data.get('name'), data.get('domain')) dnsapi = DNSAPI('dev') domain_id = dnsapi.get_domain_id_by_name(domain=data.get('domain')) if domain_id is None: error = "Domain '{}' not found!".format(data.get('domain')) return jsonify(error=dict(message=error, code=404)), 404 record_id = dnsapi.get_record_by_name(name=data.get('name'), domain_id=domain_id) if record_id: error = "Could not create dns '{}', it already exists!".format(dns) return jsonify(error=dict(message=error, code=422)), 422 dnsapi.create_record(data.get('name'), data.get('ip'), domain_id=domain_id) dns_document = models.DNS( ip=data.get('ip'), name=data.get('name'), domain=data.get('domain') ) dns_document.save() return jsonify(data=dns_document.serialize()), 201
def store_parking_event(): try: # validate schema validate(request.json, 'ParkingEvent', 'swagger_specs/parkingEvent.yml', root=__file__) # validate payment if paid context if request.json['parkingContextType'] == 'PAID': if not payment.is_test_payment( request.json, app.config['PAYMENT_VALIDATION_TEST_METHOD_TYPE'], app.config['PAYMENT_VALIDATION_TEST_RECEIPT']): payment.validate(request.json) # store valid information store_result = ParkingEventRepository().store_parking_event( request.json, app.config['PARKING_EVENT_FIREBASE_TIME_IN_SECONDS']) return store_result, 201 except ValidationError as e: logger.exception(e) abort(400) except payment.PaymentException as e: logger.exception(e) abort(400) except Exception as e: pass abort(500)
def addCloneRequest(): data = request.json validate(data, 'Clone', relative_path + '/swgger/CloneRequestAPI/addCloneRequest.yml') NewCloneRequest = request.get_json() if NewCloneRequest.get("machine_id") is None: raise Exception("machine_id was not found in request") if machineDB.GetMachine(NewCloneRequest["machine_id"]) is None: raise Exception("Machine was not found") result = cloneRequestDB.GetCloneRequestsByMachineId( NewCloneRequest["machine_id"]) if result.count() > 0: raise Exception("Request already exists for this machine") if NewCloneRequest.get("tool_list") and len( NewCloneRequest.get("tool_list")) > 0: # GET ORDER IN WHICH TOOLS SHOULD BE CLONED tool_list = [] tool_names = [] for req in NewCloneRequest.get("tool_list"): version_details = versionsDB.get_version(req.get("version_id"), False) version_details["source_version_id"] = req.get("version_id") process_order, toolNames = ToolHelperService.get_ordered_tools( [version_details]) req["clone_order"] = process_order tool_names = list(set(tool_names + toolNames)) tool_list.append(req) NewCloneRequest["tool_list"] = tool_list # GET TOOL NAMES TO BE CLONED tool_list = [] for req in NewCloneRequest.get("tool_list"): tool_name = tooldb.get_tool_by_version(req.get("version_id"), False)["name"] if tool_name in tool_names: tool_names.remove(tool_name) req["tool_name"] = tool_name tool_list.append(req) NewCloneRequest["tool_list"] = tool_list # IF size of tool_names >0 . Then we are missing tools to clone if len(tool_names) > 0: raise ValueError("Please add missing dependent tools: " + ",".join(tool_names)) # SET THEM UP IN ORDER NewCloneRequest.get("tool_list").sort(key=cloneRequestDB.clone_order, reverse=False) Clone_request_id = cloneRequestDB.AddCloneRequest(NewCloneRequest) return jsonify( json.loads( dumps({ "result": "success", "message": "New clone request has been added successfully", "data": { "id": Clone_request_id } }))), 200
def wrapper(*args, **kwargs): if schema_name: validate( request.json, schema_name, current_app.config.get('SWAGGER', {}).get('SWAGGER_FILE_PATH')) return fn(*args, **kwargs)
def wrapper(*inner_args, **inner_kwargs): api_key = request.headers.get('x-api-key') if app.config['AUTH_TYPE'] == 'api_key': if not APIKey.get_one(api_key): if api_key: app.logger.info( 'Invalid authorization with API key: {0}...'. format(api_key[0:24])) else: app.logger.info('No API key was provided') raise RedapError(message='Unauthorized', status_code=401) if method == 'GET': # Inject _params url = furl(request.url) inner_kwargs['_params'] = dict(url.query.params) elif method in ['POST', 'PUT']: # Inject validated parameters on insert / update operations (if a body is expected) if any(p for p in spec.data['parameters'] if p['name'] == 'body' and p['required']): if method == 'POST': validate(request.get_json(), specs=spec.data, validation_error_handler=validation_error) inner_kwargs['_payload'] = request.get_json() response = f(*inner_args, **inner_kwargs) if isinstance(response, str): app.logger.info(response) response = {'result': response} return jsonify(response), status
def retryGroupDeploymentRequest(): data = request.json validate(data, 'Retry', relative_path + '/swgger/DeploymentGroupRequestAPI/retryGroupDeploymentRequest.yml') DeploymentRequest = request.get_json() dep_id = DeploymentRequest.get("_id") if dep_id is None: raise Exception("_id is missing") oid = dep_id.get("oid") if oid is None: raise Exception("oid is missing") data = deploymentRequestGroupDB.get_group_deployment_request(str(oid), False,False) details = data.get("details") if data is None: raise Exception("Request was not found") if data.get('status').lower() != 'failed': raise Exception("Only failed request can be retried") retryCount = data.get("retry_count") if retryCount is None: retryCount = "1" else: retryCount = str(int(retryCount) + 1) data = {} data["_id"] = DeploymentRequest["_id"] data["retry_count"] = retryCount data["status"] = "Retry" # GETS UPDATED WITH METHOD # update_DeploymentGroups updated = deploymentRequestGroupDB.upd_group_depreq(data) # UPDATE INDIVIDUAL REQUESTS for rec in details: if str(rec.get("status")).lower() in ["Failed".lower()]: updated = deploymentRequestService.retryDeploymentRequest( str(rec["deployment_id"])) return jsonify(json.loads(dumps({"result": "success", "message": "The request was updated successfully", "data": updated}))), 200
def manualvalidation(): """ In this example you need to call validate() manually passing received data, Definition (schema: id), specs filename """ data = request.json validate(data, 'User', "test_validation.yml") return jsonify(data)
def genAuth(): data = request.json validate(data, 'User', relative_path + '/swgger/UserAPI/genAuth.yml') user = request.json.get('user') password = request.json.get('password') print " The user: "******" is trying to log in." response = user_login(user, password) print " The user: "******" has logged in." return response
def addNewAccounts(): data = request.json validate(data, 'Accounts', relative_path + '/swgger/AccountAPI/addNewAccounts.yml') newAccount = request.get_json() if (newAccount.get("name"))is None: raise Exception("Mandatory fields name to create a new account was not found.") if accountDB.get_account_by_name(newAccount.get("name")) is not None: raise Exception("Account with name " + newAccount.get("name") + " already exists") return jsonify(json.loads(dumps({"result": "success", "message": "The account is saved successfully", "data": {"id": accountDB.add_account(newAccount)}}))), 200
def add(): validate(request.json, "BookSchema", "specs/book_add.yml") data = request.json book = model.Book( title=data["title"], author=data["author"], publisher=data["publisher"], pages=data["pages"], ) command = commands.AddBook(book=book) context.messagebus.handle(command) return dict(success=True), 200
def update(): validate(request.json, "BookSchema", "specs/book_put.yml") data = request.json book = model.Book( title=data["title"], author=data["author"], publisher=data["publisher"], pages=data["pages"], ) command = commands.UpdateBook(book=book) result = context.messagebus.handle(command) return dict(success=result), 201
def ef(): data = _extract_request_data(interface.exposed_method_args(method)) try: result = interface.execute(method, data) if hasattr(result, 'read'): rlogger.debug('Got response for [%s]: <binary content>', flask.g.ebonite_id) return send_file(result, attachment_filename=getattr(result, 'name', None)) response = {'ok': True, 'data': result} rlogger.debug('Got response for [%s]: %s', flask.g.ebonite_id, response) if VALIDATE: validate(response, specs=spec, definition='response_{}'.format(method)) return jsonify(response) except ExecutionError as e: raise FlaskServerError(*e.args)
def UpdateMachineGroups(): machine_group_details = request.get_json() validate( machine_group_details, 'MachineGroup', relative_path + '/swgger/MachineGroupsAPI/UpdateMachineGroups.yml') if machine_group_details.get("_id"): if type(machine_group_details.get("_id")) is not dict: raise Exception("The type of _id is invalid") if not machine_group_details.get("_id").get("oid"): raise Exception("oid was not found in _id") else: raise Exception("_id was not found in input request ") MachineGroupHelperService.add_update_machinegroups( machine_group_details, machine_group_details["_id"]["oid"]) return jsonify( json.loads( dumps({ "result": "success", "message": "Machinegroup updated successfully" }))), 200
def AddMachineGroups(): machine_group_details = request.get_json() validate(machine_group_details, 'MachineGroup', relative_path + '/swgger/MachineGroupsAPI/AddMachineGroups.yml') existing_machine_group_detail = machinegroupsDB.machine_groups_by_name( machine_group_details.get("group_name")) if existing_machine_group_detail: raise Exception( "duplicate machinegroup was found with same Group Name") machine_group_id = MachineGroupHelperService.add_update_machinegroups( machine_group_details, None) return jsonify( json.loads( dumps({ "result": "success", "message": "The machine groups is saved successfully", "data": { "id": machine_group_id } }))), 200
def updateConfig(): data = request.json validate(data, 'Config', relative_path + '/swgger/ConfigAPI/updateConfig.yml') conf_data = request.get_json() validation = validateConfigData(conf_data) if validation is not None: return validation conf_data = removeExtraData(conf_data) conf_data = add_extra_message(conf_data) updated = configdb.UpdateConfig(conf_data) id = conf_data["_id"]["oid"] result = configdb.get_config_by_id(id) if str(result["configid"]) == "2": mailerService.schedule() elif str(result["configid"]) == "3": deploymentRequestService.schedule() elif str(result["configid"]) == "4": cloneRequestService.schedule() elif str(result["configid"]) == "9": syncServices.schedule() elif str(result["configid"]) == "10": pullServices.schedule() elif str(result["configid"]) == "11": pushServices.schedule() elif str(result["configid"]) == "12": distributionCenterService.schedule() elif str(result["configid"]) == "13": distributionSyncServices.schedule() elif str(result["configid"]) == "14": contributionGitPushService.schedule() elif str(result["configid"]) == "15": cleanerServices.schedule() return jsonify( json.loads( dumps({ "result": "success", "message": "The Config was updated successfully", "data": updated }))), 200
def retryCloneRequest(): data = request.json validate(data, 'Retry', relative_path + '/swgger/CloneRequestAPI/retryCloneRequest.yml') clone_request = request.get_json() oid = clone_request.get("_id").get("oid") data = cloneRequestDB.GetCloneRequest(oid) if data is None: raise Exception("Request was not found") if data.get('status').lower() != 'failed': raise Exception("Only failed request can be retried") if len(data.get("tool_list")) > 0: for version in data.get("tool_list"): if (version.get("status") == 'Failed'): cloneRequestDB.updateToolList(oid, version.get("version_id"), status='Retry') cloneRequestDB.UpdateStepDetails(oid, str(data.get("current_step_id")), step_status='Retry', step_message='Marked for retry') retryCount = data.get("retry_count") if retryCount is None: retryCount = "1" else: retryCount = str(int(retryCount) + 1) data = {} data["_id"] = clone_request["_id"] data["retry_count"] = retryCount data["status"] = "Retry" data['status_message'] = 'Marked for retry' updated = cloneRequestDB.UpdateCloneRequest(data) return jsonify( json.loads( dumps({ "result": "success", "message": "The request was updated successfully", "data": updated }))), 200
def update_state(): deployment_fields_data = None keys_allowed_to_update = ["deployment_field", "approval_status", "_id"] data = request.json validate(data, 'UpdateStateData', relative_path + '/swgger/StateAPI/updateState.yml') state = request.get_json() for key in state.keys(): if key not in keys_allowed_to_update: state.pop(key) if (state.get("deployment_field") is not None): deployment_fields_data = state.get("deployment_field") StateHelperService.add_update_state(state, state.get("_id").get("oid")) if (deployment_fields_data is not None): HelperServices.add_update_deployment_fields( deployment_fields_data.get("fields"), str(state.get("_id").get("oid"))) return jsonify( json.loads( dumps({ "result": "success", "message": "State was updated successfully" }))), 200
def add_state(): try: state_id = None deployment_fields_data = None deployment_fields_id = None states_to_rollback = [] parent_entity_id_list = [] data = request.json validate(data, 'State', relative_path + '/swgger/StateAPI/addStates.yml') state_data = request.get_json() StateHelperService.check_state_mandate_fields(state_data) if state_data.get("deployment_field") and len( state_data.get("deployment_field").get("fields", [])) > 0: deployment_fields_data = state_data.get("deployment_field") else: deployment_fields_data = deploymentFieldsdb.GetDeploymentFields( state_data.get("parent_entity_id")) for idx, item in enumerate(state_data.get("states", [])): if isinstance(item, dict): build_details = buildDB.get_build_by_id( item.get("build_id"), False) if build_details: state_data["states"][idx]=StateHelperService.generate_new_state({"build_id":str(build_details.get("_id")),\ "name":item.get("name"),"parent_entity_id":build_details.get("parent_entity_id"),"deployment_field":item.get("deployment_field")}) parent_entity_id_list.append( build_details.get("parent_entity_id")) states_to_rollback.append(state_data["states"][idx]) else: raise Exception("Invalid build_id:" + str(item.get("build_id"))) elif statedb.get_state_by_id(item): parent_entity_id_list.append( statedb.get_state_by_id(item).get("parent_entity_id")) else: raise Exception("Invalid build_id/state_id: " + item) duplicates = [ x for x in parent_entity_id_list if parent_entity_id_list.count(x) > 1 ] if len(duplicates) > 0: raise Exception( "More than one state request was found for parent_entity_id:" + ",".join(list(set(duplicates)))) state_id = StateHelperService.add_update_state(state_data, None) if deployment_fields_data: deployment_fields_id = HelperServices.add_update_deployment_fields( deployment_fields_data.get("fields"), str(state_id)) return jsonify( json.loads( dumps({ "result": "success", "message": "State created successfully", "data": { "_id": state_id } }))), 200 except Exception as e: # catch *all* exceptions for new_state_id in states_to_rollback: StateHelperService.delete_state(new_state_id) if state_id is not None: StateHelperService.delete_state(state_id) if deployment_fields_id is not None: deploymentFieldsdb.DeleteDeploymentFields(deployment_fields_id) raise e
def create_foo(): validate(request.json, 'Bar', 'swagger.yaml') return jsonify({"message": "it worked!"})