Ejemplo n.º 1
0
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()
Ejemplo n.º 2
0
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()
Ejemplo n.º 3
0
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'.")
Ejemplo n.º 4
0
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()
Ejemplo n.º 5
0
 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
             )
         )
Ejemplo n.º 6
0
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()
Ejemplo n.º 7
0
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")
Ejemplo n.º 8
0
    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]
Ejemplo n.º 9
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()
Ejemplo n.º 10
0
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()
Ejemplo n.º 11
0
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()
Ejemplo n.º 12
0
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()
Ejemplo n.º 13
0
def subscribers_length_validator(val):
    if not len(val) > 0:
        raise ValidationError(
            "Subscribers list must include at least one subscriber id")
Ejemplo n.º 14
0
def log_level_validator(val):
    if val not in ['WARNING', 'ERROR']:
        raise ValidationError("logLevel must be one of WARNING or ERROR")
Ejemplo n.º 15
0
 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))
         )
Ejemplo n.º 16
0
 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")
Ejemplo n.º 17
0
def alphanumeric_param_validator(value):
    if not value.isalnum():
        raise ValidationError(
            "Parameter must be alphanumeric!").as_invalid_param(value)
Ejemplo n.º 18
0
def alphanumeric_field_validator(value):
    if value is not None and not value.isalnum():
        raise ValidationError("Field must be alphanumeric!").as_bad_request()
Ejemplo n.º 19
0
 def always_raise_validator(value):
     raise ValidationError("Just because!")
Ejemplo n.º 20
0
 def validator(value):
     if value < min_value:
         raise ValidationError("{} is not >= {}".format(value, min_value))
Ejemplo n.º 21
0
def behavioral_status_validator(val):
    if val not in ['online', 'idle', 'offline']:
        raise ValidationError(
            "behavioralStatus must be one of online, idle, or offline")
Ejemplo n.º 22
0
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()
Ejemplo n.º 23
0
def manager_length_validator(val):
    if not len(val) > 0:
        raise ValidationError("Channel must include manager")
Ejemplo n.º 24
0
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()
Ejemplo n.º 25
0
 def validator(value):
     if value > max_value:
         raise ValidationError("{} is not <= {}".format(value, max_value))
Ejemplo n.º 26
0
def is_lower_case(value):
    if value.lower() != value:
        raise ValidationError("{} is not lowercase".format(value))
Ejemplo n.º 27
0
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")