def validate(self, message: dict) -> dict: """ The validate methods looks up a schema with the same event_type in the schema.json file, and uses the validation rules described in the file to determine if the message is valid. This method returns a dictionary with the status of the validation and, if not successful, an error message. :param message: :return: dictionary """ # check that message is a dictionary if not isinstance(message, dict): error_message = 'the message does not decode into a dictionary object' logging.info(error_message) return {'isSuccess': False, 'description': error_message} # check basic structure of the message / event cerberus = Cerberus(self.schema['basic_message_structure']['cerberus_rules']) cerberus.allow_unknown = self.schema['basic_message_structure']['allow_unknown'] if not cerberus.validate(message): logging.info(' - message failed basic validation') return {'isSuccess': False, 'description': cerberus.errors} # if the message passes basic validation, test again # against specific event type cerberus = Cerberus(self.schema[message['event_type']]['cerberus_rules']) cerberus.allow_unknown = self.schema[message['event_type']]['allow_unknown'] if cerberus.validate(message): logging.info(' - message passed validation for type: ' + message['event_type']) return {'isSuccess': True, 'description': ''} else: logging.info(' - message failed validation for type: ' + message['event_type']) return {'isSuccess': False, 'description': cerberus.errors}
def scan_sensors(self): sensors = dict() v_sensor = Validator('sensor') v_sensor.allow_unknown = True for entry_name in sorted(os.listdir(self.sensors_dir)): entry_path = os.path.join(self.sensors_dir, entry_name) if os.path.isfile(entry_path) and entry_name.endswith('.yaml'): self.logger.debug('Loading sensor file "{entry_name}" from "{entry_path}"'.format( entry_name=entry_name, entry_path=entry_path)) with open(entry_path, 'r') as sensor_file: sensor = yaml.load(sensor_file) # Check basic parameters if not v_sensor.validate(sensor): self.logger.warning( '"{entry_name}" is not a sensor file, please check format, message: {message}'.format( entry_name=entry_name, message=v_sensor.errors)) continue try: # Check format matching sensor file sensor_type = sensor['type'] type_validator = Validator('sensor_' + sensor_type) type_validator.allow_unknown = True if not type_validator.validate(sensor): self.logger.warning( 'Invalid sensor file "{entry_name}" - check parameters! Message: {message}'.format( entry_name=entry_name, message=v_sensor.errors, ) ) continue except SchemaError: # Schema not found self.logger.error('Can´t verify sensor file "{entry_name}" - no matching schema found, skipping!'.format( entry_name=entry_name)) continue sensors[sensor['name']] = sensor self.logger.info('Added sensor "{sensor_name}" of type "{sensor_type}" to list'.format( sensor_name=sensor['name'], sensor_type=sensor['type'])) else: continue if not sensors: self.logger.fatal('No valid sensor definition found') raise NoSensorFoundException('No valid sensor definition found in {sensors_dir}'.format(sensors_dir=self.sensors_dir)) self.sensors = sensors
def validate(self, config_dict): """Validates the mode using its relevant configuration dict Returns a validated configuration dict with the mode filled in. If no mode is given in the input dict, a default mode will be filled in if availble. If the mode has a validation_schema, it will be used to validate the input dict. If any error is encountered during the process, A serializer ValidationError will be raised with the error. Args: config_dict (dict): A dictionary of input structure that this mode is a part of Returns: dict: A version of the input dictionary with defaults filled in based on the validation_schema Raises: serializers.ValidationError: If validation fails """ mode_value = self._get_mode_from_config_dict(config_dict) if not mode_value: mode_value = self.get_default_mode() if not mode_value: return config_dict if not self.mode_exists(mode_value): return config_dict config_dict = self._set_mode_in_config_dict(mode_value, config_dict) mode = configdb.get_mode_with_code(self._instrument_type, mode_value, self._mode_type) validation_schema = mode.get('validation_schema', {}) validator = Validator(validation_schema) validator.allow_unknown = True validated_config_dict = validator.validated( config_dict) or config_dict.copy() if validator.errors: raise serializers.ValidationError( _(f'{self._mode_type.capitalize()} mode {mode_value} requirements are not met: {cerberus_validation_error_to_str(validator.errors)}' )) return validated_config_dict
def validate_create_user_payload(**kwargs) -> tuple: schema = { "badge_number": { "type": "string", 'minlength': 2, 'maxlength': 8, "required": True }, "agency": { "type": "string", 'minlength': 4, 'maxlength': 40, "required": True }, "first_name": { "type": "string", 'minlength': 2, 'maxlength': 30, "required": True }, "last_name": { "type": "string", 'minlength': 2, 'maxlength': 30, "required": True } } cerberus = Validator(schema) cerberus.allow_unknown = False if cerberus.validate(kwargs.get('payload')): return True, kwargs logging.warning("validation error: " + json.dumps(cerberus.errors)) kwargs['validation_errors'] = cerberus.errors return False, kwargs
def validateData(cls, data, _request): if _request.method == "POST": schema = { 'brand_name': { 'required': True, 'empty': False, 'type': 'string' }, 'industry_id': { 'required': True, 'empty': False, 'type': 'integer' }, 'brand_category_id': { 'required': True, 'empty': False, 'type': 'integer' } } else: schema = { 'brand_name': { 'required': True, 'empty': False, 'type': 'string' } } v = Validator(schema) v.allow_unknown = True return True if (v.validate(data)) else v.errors
def _validate(self, doc, **kwargs): lookup = {'act': doc['act'], 'type': doc[ITEM_TYPE]} use_headline = kwargs and 'headline' in kwargs validators = superdesk.get_resource_service('validators').get( req=None, lookup=lookup) for validator in validators: v = Validator() v.allow_unknown = True v.validate(doc['validate'], validator['schema']) error_list = v.errors response = [] for e in error_list: if error_list[e] == 'required field' or type( error_list[e]) is dict: message = '{} is a required field'.format(e.upper()) elif 'min length is' in error_list[e]: message = '{} is too short'.format(e.upper()) elif 'max length is' in error_list[e]: message = '{} is too long'.format(e.upper()) else: message = '{} {}'.format(e.upper(), error_list[e]) if use_headline: response.append('{}: {}'.format( doc['validate'].get('headline', doc['validate'].get('_id')), message)) else: response.append(message) return response else: return ['validator was not found for {}'.format(doc['act'])]
def request_validation(self, request): if len(request.body) > 0 and len(request.FILES) == 0: data = json.loads(request.body) data_validator = Validator(self.validation_schema, error_handler=CustomErrorHandler) data_validator.allow_unknown = True # Validating password and email using cerberus library data_validator(data) errors_dict = {} if data_validator.errors: errors_dict = {'errors': []} for key, value in data_validator.errors.items(): for index in range( len(data_validator.document_error_tree[key].errors)): errors_dict['errors'].append({ "field": key, "code": data_validator.document_error_tree[key].errors[index]. rule, "message": value[index] }) return errors_dict
def validate(self, message: dict) -> dict: """ The validate methods looks up a schema with the same event_type in the schemas json file, and uses the validation rules described in the file to determine if the message is valid. This method returns a dictionary with the status of the validation and, if not successful, an error message. :param message: :return: dictionary """ cerberus_errors = [] # check that message is a dictionary if not isinstance(message, dict): error_message = 'the message does not decode into a dictionary object' logging.warning(error_message) return { 'isSuccess': False, "queue": "error", 'description': error_message } # check that that the message has an event_type attribute if 'event_type' not in message: error_message = 'the message does not have an event_type attribute' logging.warning(error_message) return { 'isSuccess': False, "queue": "error", 'description': error_message } # check that that the message has an associated validation schema if message['event_type'] not in self.schemas: error_message = 'the message does not have an associated validation schema' logging.warning(error_message) return { 'isSuccess': False, "queue": "error", 'description': error_message } # return the validation error message from the associated schema schema = self.schemas[message['event_type']] cerberus = Cerberus(schema['cerberus_rules']) cerberus.allow_unknown = schema['allow_unknown'] if cerberus.validate(message): logging.info(' - message passed validation') return { 'isSuccess': True, "queue": schema['valid-queue'], 'description': '' } else: logging.info(' - message failed validation validation') return { 'isSuccess': False, "queue": schema['invalid-queue'], 'description': cerberus.errors }
def _validate(self, doc, **kwargs): lookup = {'act': doc['act'], 'type': doc[ITEM_TYPE]} use_headline = kwargs and 'headline' in kwargs validators = superdesk.get_resource_service('validators').get(req=None, lookup=lookup) for validator in validators: v = Validator() v.allow_unknown = True v.validate(doc['validate'], validator['schema']) error_list = v.errors response = [] for e in error_list: if error_list[e] == 'required field' or type(error_list[e]) is dict: message = '{} is a required field'.format(e.upper()) elif 'min length is' in error_list[e]: message = '{} is too short'.format(e.upper()) elif 'max length is' in error_list[e]: message = '{} is too long'.format(e.upper()) else: message = '{} {}'.format(e.upper(), error_list[e]) if use_headline: response.append('{}: {}'.format(doc['validate'].get('headline', doc['validate'].get('_id')), message)) else: response.append(message) return response else: return ['validator was not found for {}'.format(doc['act'])]
def validate_pay_bc_post_receipt(**args) -> tuple: config = args.get('config') payload = args.get('payload') method_name = 'receipt' schemas = helper.load_json_into_dict(config.SCHEMA_PATH + config.SCHEMA_FILENAME) # check that that the method_name has an associated validation schema if method_name not in schemas: logging.critical( '{} does not have an associated validation schema'.format( method_name)) # return the validation error message from the associated schema schema = schemas[method_name] logging.debug('schema: {}'.format(json.dumps(schema))) logging.debug('payload: {}'.format(payload)) cerberus = Cerberus(schema['cerberus_rules']) cerberus.allow_unknown = schema['allow_unknown'] if cerberus.validate(payload): args['prohibition_number'] = payload['invoices'][0]["trx_number"] logging.info('payload passed validation') return True, args else: logging.warning('payload failed validation: {}'.format( json.dumps(cerberus.errors))) return False, args
def validateData(cls, data, _request): schema = { 'service_name': { 'required': True, 'empty': False, 'type': 'string' }, 'logo': { 'required': True, 'empty': False, 'type': 'string' }, 'brand_id': { 'required': True, 'empty': False, 'type': 'integer' }, 'category_id': { 'required': True, 'empty': False, 'type': 'integer' } } v = Validator(schema) v.allow_unknown = True return True if (v.validate(data)) else v.errors
def add_book_validation(self, dict_data): schema = { 'title': { 'type': 'string', 'required': True, 'empty': False, 'maxlength': 25, 'minlength': 4 }, 'author': { 'type': 'string', 'required': True, 'empty': False, 'maxlength': 25, 'minlength': 4 }, 'genre': { 'type': 'string', 'required': True, 'empty': False, 'maxlength': 10, 'minlength': 4 }, 'description': { 'type': 'string', 'required': False, 'maxlength': 200, 'minlength': 4 }, } v = Validator(schema) v.allow_unknown = True return v.validate(dict_data)
def create(self, request, *args, **kwargs): # custom parameters post_req = self.cleaned_data(request=request) # validate data enter v = Validator(announcements_schema()) v.allow_unknown = True if not v.validate(post_req): return Response({"message": v.errors}, status=status.HTTP_400_BAD_REQUEST) # add announcement announcement = Announcement( title=post_req['title'], description=post_req['description'], date=post_req['date'] if post_req.get('date', None) else datetime.datetime.now(), release_time=post_req['release_time'] if post_req.get( 'release_time', None) else datetime.datetime.now(), has_date=post_req.get('has_date', False), image=request.data.get('image') if request.data.get('image') else "", creator_id=self.request.user.id) announcement.save() AnnouncementViewSet.last_announcement_date = get_last_announcement_publish_date( ) AnnouncementViewSet.near_next_announcement_date = get_near_next_announcement_publish_date( ) # add files for announcement self.save_file(announcement, request) # add announcement receiver self.add_announcement_receiver(announcement, post_req) return Response(status=status.HTTP_201_CREATED)
def check_kwargs(kwargs): """ 检测必要的字段是否满足创建要求 """ schema = { "name": {"type": "string", "required": True}, "nick_name": {"type": "string"}, "class_info": { # 注意这里也是要标注rule的 "type": "dict", "schema": { "class_type": {"type": "integer", "required": True}, "class_fee": {"type": "integer"} } }, } v = Validator() v.allow_unknown = True # default False flag = v(kwargs, schema), ret = { "flag": flag, "mag": "订单信息填写不符合要求" if not flag else "success", "data": v.errors, } return ret
def __validate_task_config(self, grp_cfg=None): if getattr(self, 'TASK_DESCENT', None): task_name = self.TASK_DESCENT else: task_name = self.task_name if self.check_schema: if os.path.exists('conf/schema/task/' + task_name.lower() + '.yml') and os.path.isfile('conf/schema/task/' + task_name.lower() + '.yml'): with open('conf/schema/task/' + task_name.lower() + '.yml', 'r') as stream: schema = yaml.safe_load(stream) v = Validator() v.allow_unknown = True if v.validate(document=grp_cfg['TASKS']['Provision'], schema=schema): return self.messages['valid'], None else: return self.messages['invalid'], v.errors else: return self.messages['error'], None else: return self.messages['deactivated'], None
def test_unknown_keys(): schema = {} # test that unknown fields are allowed when allow_unknown is True. v = Validator(allow_unknown=True, schema=schema) assert_success({"unknown1": True, "unknown2": "yes"}, validator=v) # test that unknown fields are allowed only if they meet the # allow_unknown schema when provided. v.allow_unknown = {'type': 'string'} assert_success(document={'name': 'mark'}, validator=v) assert_fail({"name": 1}, validator=v) # test that unknown fields are not allowed if allow_unknown is False v.allow_unknown = False assert_fail({'name': 'mark'}, validator=v)
def validate(self, ignore_required=False): """Validate itself against the internal schema. Args: ignore_required (bool): If True, required fields won't be checked. Necessary when checking all mappings against the schema. Raises: ValueError: If validation fails. """ validator = Validator(self._schema[self._schema_name]) validator.allow_unknown = True def _validate(dict_, update): """Run the actual validator. Args: dict_ (dict): The data to validate_data. update (bool): If True, required fields won't be checked. Raises: ValueError: If validation fails. """ if not validator.validate(dict_, update=update): msg = 'Validation failure(s): {0}'.format( validator.errors) raise ValueError(msg) _validate(self.data, ignore_required)
def compute_attendances(attendances): # change to datetime YYYY-MM-DD for date attendances['date'] = pd.to_datetime(attendances['date'], format='%Y-%m-%d').dt.date # employee_id attendances['employee_id'] = attendances['employee_id'].map( lambda x: str(int(x)) if x != '' else '') # hours attendances['hours'] = attendances['hours'].map( lambda x: round(float(x), 2)) # gross attendances['gross'] = attendances['gross'].map( lambda x: round(float(x), 2)) schema = { 'employee_id': { 'type': 'string', 'empty': False, 'required': True }, 'employer_id': { 'type': 'string', 'empty': False, 'required': True }, 'date': { 'type': 'date', 'empty': False, 'required': True }, 'hours': { 'type': 'float', 'min': 0, 'empty': False, 'required': True }, 'gross': { 'type': 'float', 'min': 0, 'empty': False, 'required': True } } attendances_dict = attendances.to_dict(orient='records') v = Validator(schema) v.allow_unknown = False #print("Attendances file errors: " + names + "\n") for idx, record in enumerate(attendances_dict): if not v.validate(record): print( f'row {idx}, employee_id: {attendances.employee_id[idx]}, {v.errors}' )
def check_config_file( config_file: Union[Text, Path], path: Union[Text, Path, None] = None, exit=True, verbose=False, testing=False, ) -> Optional[Path]: """Validate and return the full absolute Path to the config file otherwise exit or return False. Will search of the configuration file int he following order: 1. the current working directory 2. the user configuration directory ('~/.config/duplicity_backup/') 3. the system configuration directory ('~/etc/duplicity_backup/') :param config_file: filename and/or path to the config file :param path: helper path if the config_file if the config_file is not a full path :param exit: when exit is true, exit with return_code 2 :param testing: in testing mode, no CLI verbosity :return: Path to the config file """ config_path = search_config(config_file, path=path, exit=exit and not testing) if not config_path.exists(): if exit: echo_failure( "Config file does not exist in '{}', please provide or " "create an empty one using the command `init`.".format( config_file)) sys.exit(2) else: # could be a file that does not exist return Path(config_path) # performing validation from cerberus import Validator import yaml validator = Validator() validator.allow_unknown = False with config_path.open() as config_fd, CONFIG_SCHEMA_PATH.open( ) as schema_fd: if not validator.validate(yaml.safe_load(config_fd), yaml.safe_load(schema_fd)): if not testing: echo_failure( "The configuration file is incorrectly formatted: \n{}". format(validator.errors)) if exit and not testing: sys.exit(2) return validator.errors if verbose and not testing: echo_info( "The configuration file is succesfully validated against the validation schema." ) return config_path
def validateData(cls, data, _request): schema = { 'campaign_name': { 'required': True, 'empty': False, 'type': 'string' }, 'description': { 'required': True, 'empty': False, 'type': 'string' }, 'brand_id': { 'required': True, 'empty': False, 'type': 'integer' }, 'product_ids': { 'required': True, 'empty': False, 'type': 'string' }, 'currency_id': { 'required': True, 'empty': False, 'type': 'integer' }, 'budget_amount': { 'required': True, 'empty': False, 'type': 'integer' }, 'objective_id': { 'required': True, 'empty': False, 'type': 'integer' }, 'kpi_id': { 'required': True, 'empty': False, 'type': 'integer' }, 'target_locations': { 'required': True, 'empty': False, 'type': 'string' }, 'exclude_locations': { 'required': True, 'empty': False, 'type': 'string' } } v = Validator(schema) v.allow_unknown = True return True if (v.validate(data)) else v.errors
def validate(self, source=None, lookup_type=None): if lookup_type == c.CONFIG_LOOKUP_TYPE_GET_DEVICE_CFG or lookup_type == c.CONFIG_LOOKUP_TYPE_ADD_DEVICE_CFG: if 'device_type' in source['yapt']: with open('conf/schema/device/' + source['yapt']['device_type'].lower() + c.CONFIG_FILE_SUFFIX_DEVICE, 'r') as stream: schema = yaml.safe_load(stream) v = Validator() v.allow_unknown = True return v.validate(document=source, schema=schema), v.errors else: Tools.create_log_msg(self.name, None, logmsg.SOURCE_DEV_TYPE_NOK.format(hex(id(source)))) return False, None elif lookup_type == c.CONFIG_LOOKUP_TYPE_GET_DEVICE_CFG_FILE: with open(source, 'r') as stream: doc = yaml.safe_load(stream) if 'device_type' in doc['yapt']: with open('conf/schema/device/' + doc['yapt']['device_type'].lower() + c.CONFIG_FILE_SUFFIX_DEVICE, 'r') as stream: schema = yaml.safe_load(stream) v = Validator() v.allow_unknown = True return v.validate(document=doc, schema=schema), v.errors else: Tools.create_log_msg(self.name, None, logmsg.SOURCE_DEV_TYPE_NOK.format(hex(id(source)))) return False, None elif lookup_type == c.CONFIG_LOOKUP_TYPE_GET_GROUP or lookup_type == c.CONFIG_LOOKUP_TYPE_ADD_GROUP: with open('conf/schema/group/group.yml', 'r') as stream: schema = yaml.safe_load(stream) v = Validator() v.allow_unknown = True return v.validate(document=source, schema=schema), v.errors
def _validate(self, data, schema): v = Validator(schema) v.allow_unknown = True v.validate(data, schema) if v.errors: raise InvalidConfiguration( self.file_name, json.dumps(v.errors, indent=4, separators=(',', ': '))) return v.__dict__['document']
def _validate(self, schema, details): validator = Validator(schema) validator.allow_unknown = True res = validator.validate(details) if not res: message = '; '.join([ f'"{key}": {", ".join(validator.errors[key])}' for key in validator.errors ]) raise InvalidInputException(message=message)
def article_add_api(): INPUT = request.form v = Validator() schema = { 'title': { 'type': 'string', 'required': True, 'empty': False }, 'contents': { 'type': 'string', 'required': True, 'empty': False }, } v.allow_unknown = True if v.validate(INPUT, schema) == False: return {"status": 5000, "msg": "validation error", "errors": v.errors} if request.files.get('cover') == None: return { "status": 5000, "msg": "validation error", "errors": { "cover": ["cover is required"] } } try: ALLOWED_EXTENSIONS_COVER = {'png', 'jpg', 'jpeg'} cover = request.files["cover"] cover_file_ext = cover.filename.split('.')[1] if cover_file_ext in ALLOWED_EXTENSIONS_COVER: cover_unique_filename = str(uuid.uuid4()) new_cover_name = cover_unique_filename + '.' + cover_file_ext cover.save( os.path.join(app.config["UPLOAD_FOLDER"], new_cover_name)) else: return { "status": 5000, "msg": "validation error", "errors": { "cover": ["cover file format is invalid"] } } cur = mysql.connection.cursor() cur.execute( "INSERT INTO articles (title, contents, cover) VALUES (%s,%s,%s)", (INPUT['title'], INPUT['contents'], new_cover_name)) mysql.connection.commit() return {"status": 2000, "msg": "successfully added"} except Exception as e: return {"status": 5000, "msg": "something went wrong", "error": str(e)}
def validateResetPassword(req): validator = Validator( { 'password': {'type': 'string', 'minlength': 5, 'required': True}, 'token': {'type': 'string', 'minlength': 4, 'required': True} }, ) validator.allow_unknown = False valid = validator.validate(req.json) if (valid != True): return abort(400, 'Bad request')
def test_descriptions(submissions_dir, submission, schema): v = Validator(schema) # traverse root directory, and list directories as dirs and files as files # list files in results description_file = os.path.join(submissions_dir, submission, 'description.yml') stream = file(description_file, 'r') document = yaml.load(stream) v.allow_unknown = True assert v.validate(document), v.errors
def allow_unknown_example(): """默认需要data中所有的key都要在schema中被预定义。而设置allow_unknown = True可以允许出现 没有被预定义的key """ schema = {"name": {"type": "string", "maxlength": 10}} v = Validator(schema) print(v.validate({"name": "john", "sex": "M"})) print(v.errors) v.allow_unknown = True print(v.validate({"name": "john", "sex": "M"}))
def wrapper(*args, **kwargs): validate_data = request.json.copy() if request.json else {} if not isinstance(schema, dict): raise TypeError('The schema should be a dict') v = Validator(schema, error_handler=CustomErrorHandler) v.allow_unknown = True if not v.validate(validate_data): response = make_response(jsonify(v.errors), 422) else: response = f(*args, **kwargs) return response
def validateLogin(req): loginValidator = Validator( { 'email': {'type': 'string', 'minlength': 4, 'required': True}, 'password': {'type': 'string', 'minlength': 5, 'required': True} }, ) loginValidator.allow_unknown = False valid = loginValidator.validate(req.json) if (valid != True): return abort(400, 'Bad request')
def validate(sois, validate_schema): is_bool = lambda v: v.lower() in ('true', '1', 'y', 'false', '0', 'n') v = Validator(validate_schema) v.allow_unknown = True for soi in sois: if soi['hits'] is not None: for hit in soi['hits']: if not v.validate(hit): hit['errors'] = v.errors
def validateData(cls, data, _request): schema = { 'education_name': { 'required': True, 'empty': False, 'type': 'string' } } v = Validator(schema) v.allow_unknown = True return True if (v.validate(data)) else v.errors
def password_validation(self, dict_data): '''Password validation method''' schema = { 'password': { 'type': 'string', 'required': True, 'maxlength': 16, 'minlength': 6}} v = Validator(schema) v.allow_unknown = True return v.validate(dict_data)
def __init__(self, origem=None): validator = Validator(schema={ 'debug': { 'type': 'boolean', 'required': True}, 'usuario': { 'type': 'string', 'required': True, 'minlength': 2, 'maxlength': 60}, 'senha': { 'type': 'string', 'required': True, 'minlength': 6}, 'codigo_ativacao': { 'type': 'string', 'required': True, 'minlength': 1}, 'caminho_biblioteca': { 'type': 'string', 'required': True}, 'convencao_chamada': { 'type': 'integer', 'required': True, 'allowed': [v for v,s in \ satcomum.constantes.CONVENCOES_CHAMADA]}, 'descricao': { 'type': 'string', 'minlength': 1, 'maxlength': 100}, }, purge_unknown=True) self._origem = origem or os.path.join(PROJECT_ROOT, 'config-sathub.json') if origem is None: # a origem do arquivo de configurações é a padrão if not os.path.isfile(self._origem): # arquivo de configurações padrão não existe; # cria um para que possa ser editado with open(self._origem, 'w') as f: f.write(json.dumps(DEFAULT_CONFIG, indent=4)) with open(self._origem, 'r') as f: self._confdata = json.load(f) validator.allow_unknown = True if not validator.validate(self._confdata): raise RuntimeError('Configuration error: {!r}'.format( validator.errors))
def _validate(self, doc): lookup = {'act': doc['act'], 'type': doc['type']} validators = superdesk.get_resource_service('validators').get(req=None, lookup=lookup) for validator in validators: v = Validator() v.allow_unknown = True v.validate(doc['validate'], validator['schema']) error_list = v.errors response = [] for e in error_list: if error_list[e] == 'required field': response.append('{} is a required field'.format(e.upper())) elif 'min length is' in error_list[e]: response.append('{} is too short'.format(e.upper())) elif 'max length is' in error_list[e]: response.append('{} is too long'.format(e.upper())) else: response.append('{} {}'.format(e.upper(), error_list[e])) return response else: return ['validator was not found for {}'.format(doc['act'])]
'--width' : { 'type' : 'float', 'coerce' : float }, '--spacing' : { 'type' : 'float', 'coerce' : float }, '--center' : { 'type' : 'float', 'coerce' : float }, '--ratio' : { 'type' : 'float', 'coerce' : float }, '--rectangle-width' : { 'type' : 'float', 'coerce' : float }, '--dogbone' : { 'type' : 'string', 'allowed' : ['none', 'sides', 'ends', 'corners'] }, '--drill' : { 'type' : 'float', 'coerce' : float }, 'circle' : { 'type' : 'boolean' }, 'square' : { 'type' : 'boolean' }, 'rectangle' : { 'type' : 'boolean' }, 'triangle' : { 'type' : 'boolean' }, 'hexagon' : { 'type' : 'boolean' }, } validator = Validator(schema) validator.allow_unknown = True if not validator.validate(arguments): exit(validator.errors) validatedArguments = validator.document spacing = validatedArguments['--spacing'] width = validatedArguments['--width'] ratio = validatedArguments['--ratio'] center = validatedArguments['--center'] rectangle_width = validatedArguments['--rectangle-width'] dogbone = validatedArguments['--dogbone'] drill = validatedArguments['--drill'] file_type = validatedArguments['--type'] is_circle = validatedArguments['circle']
document = {'name': 1337, 'age': 5} print v.validate(document, schema) print v.errors #=============================================================================== # 3. setting the unknown # 可以在schema中设置是否允许未知key的出现 #=============================================================================== # 设置不允许未知key出现 schema = {'name': {'type': 'string', 'maxlength': 10}} print v.validate({'name': 'john', 'sex': 'M'}) print v.errors # 设置允许未知key的出现 v.allow_unknown = True print v.validate({'name': 'john', 'sex': 'M'}) # 初始化Validator时设置是否允许未知key的出现 v = Validator(schema=schema, allow_unknown=True) print v.validate({'name': 'john', 'sex': 'M'}) #=============================================================================== # 4. 定制化schema中的评价metrics #=============================================================================== class MyValidator(Validator): def _validate_isodd(self, isodd, field, value): if isodd and not bool(value & 1): self._error(field, "Must be an odd number")