def datetime_param_format_validator(date_str): try: datetime.strptime(date_str, DATETIME_FORMAT) except ValueError: raise ValidationError( "Datetime parameters must be in {} format!".format( DATETIME_FORMAT)).as_invalid_param()
def datetime_field_format_validator(date_str): try: if date_str: datetime.strptime(date_str, DATETIME_FORMAT) except ValueError: raise ValidationError("Datetime fields must be in {} format!".format( DATETIME_FORMAT)).as_bad_request()
def channel_type_validator(val): if val not in [ 'public', 'private', 'invisible', 'public-announcement', 'private-announcement', 'invisible-announcement', 'all' ]: raise ValidationError( "Channel type must be one of 'public', 'public-group', 'private-group', " "'announcement', 'private'.")
def email_validator(email): """ Check email format with regex. Args: email: Returns: ValidationError """ email_format = re.compile('[^@]+@[^@]+\.[^@]+') if not bool(re.match(email_format, email)): raise ValidationError("Email address is not valid.").as_bad_request()
def validator(value): if not compiled.match(value): # note: make it a list for consistent representation raise ValidationError( "{} does not match pattern: {}".format( value, compiled.pattern if hasattr(compiled, 'pattern') else compiled ) )
def phone_validator(phone_number): """ `phone_number`s length is equal to 11? Args: phone_number: Raises: ValidationError """ phone_format = re.compile('[0-9]{11}') if not bool(re.match(phone_format, phone_number)): raise ValidationError( "Phone number is not proper format.").as_bad_request()
def is_service_code(val): """ This method validates if service_code is one of "push", "roc", or "sms" else raises ValidationError. Args: val (string): service code name Raises: Validation error """ if val not in ["push", "roc", "sms"]: raise ValidationError("service_code must be one of push, roc, sms")
def require_validated(self, req, partial=False, bulk=False): """Require fully validated internal object dictionary. Internal object dictionary creation is based on content-decoded representation retrieved from request body. Internal object validation is performed using resource serializer. Args: req (falcon.Request): request object partial (bool): set to True if partially complete representation is accepted (e.g. for patching instead of full update). Missing fields in representation will be skiped. bulk (bool): set to True if request payload represents multiple resources instead of single one. Returns: dict: dictionary of fields and values representing internal object. Each value is a result of ``field.from_representation`` call. """ representations = [self.require_representation(req) ] if not bulk else self.require_representation(req) if bulk and not isinstance(representations, list): raise ValidationError( "Request payload should represent a list of resources." ).as_bad_request() object_dicts = [] try: for representation in representations: object_dict = self.serializer.from_representation( representation) self.serializer.validate(object_dict, partial) object_dicts.append(object_dict) except DeserializationError as err: # when working on Resource we know that we can finally raise # bad request exceptions raise err.as_bad_request() except ValidationError as err: # ValidationError is a suggested way to validate whole resource # so we also are prepared to catch it raise err.as_bad_request() return object_dicts if bulk else object_dicts[0]
def residents_validator(residents): """ ```json "residents": { "sets": { "a": {"key": "age", "relation": ">", "value": "15", "intention": "target"}, "b": {"key": "eye-color", "relation": "=", "value": "blue", "intention": "target"} }, "expression": "a n b" } ``` Args: residents (dict): Returns: """ if not (residents.get("sets") or residents.get("expression")): raise ValidationError( "Fields: sets and expression cannot be empty!").as_bad_request()
def intention_validator(residents): """ ```json "residents": { "sets": { "a": {"key": "age", "relation": ">", "value": "15", "intention": "target"}, "b": {"key": "eye-color", "relation": "=", "value": "blue", "intention": "target"} }, "expression": "a n b" } ``` Args: residents (dict): """ sets = residents.get("sets") for set in sets: if set.get("intention") not in ['client', 'target']: raise ValidationError( "Field: intention must be one of client or target!" ).as_bad_request()
def device_type_validator(device_type): if device_type not in ['android', 'ios']: raise ValidationError( "Device type must be android or ios!").as_bad_request()
def tag_type_validator(tag_type): if tag_type not in ['key', 'key-value', 'multi']: raise ValidationError( "Tag type must be key, key-value or multi!").as_bad_request()
def subscribers_length_validator(val): if not len(val) > 0: raise ValidationError( "Subscribers list must include at least one subscriber id")
def log_level_validator(val): if val not in ['WARNING', 'ERROR']: raise ValidationError("logLevel must be one of WARNING or ERROR")
def validator(value): if value not in choices: # note: make it a list for consistent representation raise ValidationError( "{} is not in {}".format(value, list(choices)) )
def validate(self, object_dict, partial=False): super().validate(object_dict, partial) # possible use case: kind of uniqueness relationship if object_dict['one'] == object_dict['two']: raise ValidationError("one must be different than two")
def alphanumeric_param_validator(value): if not value.isalnum(): raise ValidationError( "Parameter must be alphanumeric!").as_invalid_param(value)
def alphanumeric_field_validator(value): if value is not None and not value.isalnum(): raise ValidationError("Field must be alphanumeric!").as_bad_request()
def always_raise_validator(value): raise ValidationError("Just because!")
def validator(value): if value < min_value: raise ValidationError("{} is not >= {}".format(value, min_value))
def behavioral_status_validator(val): if val not in ['online', 'idle', 'offline']: raise ValidationError( "behavioralStatus must be one of online, idle, or offline")
def tag_value_type_validator(tag_value_type): if tag_value_type not in ['int', 'float', 'str', None]: raise ValidationError( "Tag value type must be an int, float str or null!" ).as_bad_request()
def manager_length_validator(val): if not len(val) > 0: raise ValidationError("Channel must include manager")
def list_of_consumer_validator(consumer_list): if len(consumer_list) > 100: raise ValidationError( "You can send maximum 100 consumer id in a request" ).as_bad_request()
def validator(value): if value > max_value: raise ValidationError("{} is not <= {}".format(value, max_value))
def is_lower_case(value): if value.lower() != value: raise ValidationError("{} is not lowercase".format(value))
def invite_approve_validator(val): if val not in ['approved', 'rejected', 'not_evaluated', None]: raise ValidationError( "approve must be one of approved, rejected, not_evaluated")