Exemple #1
0
    def __init__(self,
                 db_column="",
                 db_index=False,
                 null=False,
                 protocol="both",
                 unique=False,
                 unpack_protocol="same"):
        if protocol.lower() not in ("both", "ipv6", "ipv4"):
            raise AsyncOrmFieldError(
                '"{}" is not a recognized protocol'.format(protocol))
        if unpack_protocol.lower() not in ("same", "ipv6", "ipv4"):
            raise AsyncOrmFieldError(
                '"{}" is not a recognized unpack_protocol'.format(
                    unpack_protocol))
        if protocol.lower() != "both" and unpack_protocol != "same":
            raise AsyncOrmFieldError(
                "if the protocol is restricted the output will always be in the same protocol version, "
                'so unpack_protocol should be default value, "same"')

        super().__init__(
            db_column=db_column,
            db_index=db_index,
            default=None,
            null=null,
            protocol=protocol,
            unique=unique,
            unpack_protocol=unpack_protocol,
        )
Exemple #2
0
 def set_field_name(self, db_column):
     if "__" in db_column:
         raise AsyncOrmFieldError('db_column can not contain "__"')
     if db_column.startswith("_"):
         raise AsyncOrmFieldError('db_column can not start with "_"')
     if db_column.endswith("_"):
         raise AsyncOrmFieldError('db_column can not end with "_"')
     self.db_column = db_column
Exemple #3
0
    def validate(self, value):
        try:
            IPNetwork(value)
        except AddrFormatError:
            raise AsyncOrmFieldError("Not a correct IP address")

        if self.protocol.lower() != "both" and IPNetwork(value).version != int(self.protocol[-1:]):
            raise AsyncOrmFieldError("{} is not a correct {} IP address".format(value, self.protocol))
Exemple #4
0
 def validate(self, value):
     super().validate(value)
     if value:
         items_type = self.homogeneous_type(value)
         if not items_type:
             raise AsyncOrmFieldError("Array elements are not of the same type")
         if items_type == list:
             if not all(len(item) == len(value[0]) for item in value):
                 raise AsyncOrmFieldError("Multi-dimensional arrays must have items of the same size")
     return value
Exemple #5
0
 def validate(self, value):
     super(EmailField, self).validate(value)
     # now validate the emailfield here
     email_regex = r"^[\w][\w0-9_.+-]+@[\w0-9-]+\.[\w0-9-.]+$"
     if not re.match(email_regex, value):
         raise AsyncOrmFieldError(
             '"{}" not a valid email address'.format(value))
Exemple #6
0
 def sanitize_data(self, value):
     value = super().sanitize_data(value)
     if len(value) > self.max_length:
         raise AsyncOrmFieldError(
             'The string entered is bigger than the "max_length" defined ({})'.format(self.max_length)
         )
     return str(value)
Exemple #7
0
    def __init__(self, db_column="", db_index=False, default=None, dialect="unix", null=False, unique=True):
        if dialect not in (self.mac_dialects.keys()):
            raise AsyncOrmFieldError('"{}" is not a correct mac dialect'.format(dialect))

        super().__init__(
            db_column=db_column, db_index=db_index, default=default, dialect=dialect, null=null, unique=unique
        )
Exemple #8
0
 def sanitize_data(self, value):
     value = super().sanitize_data(value)
     exp = r"^[a-zA-Z0-9\-\b]{36}$"
     if re.match(exp, value):
         return value
     raise AsyncOrmFieldError(
         "The expression doesn't validate as a correct {}".format(
             self.__class__.__name__))
Exemple #9
0
    def sanitize_data(self, value):
        self.validate(value)

        if value is not None:
            if isinstance(value, str):
                try:
                    value = json.loads(value)
                except JSONDecodeError:
                    raise AsyncOrmFieldError("The data entered can not be converted to json")
            value = json.dumps(value)

        if len(value) > self.max_length:
            raise AsyncOrmFieldError(
                'The string entered is bigger than the "max_length" defined ({})'.format(self.max_length)
            )

        return value
Exemple #10
0
    def __init__(self, db_column="", db_index=False, null=False, unique=True, uuid_type="v4"):
        self.field_requirement = 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp";'

        if uuid_type not in ["v1", "v4"]:
            raise AsyncOrmFieldError("{} is not a recognized type".format(uuid_type))

        super().__init__(
            db_column=db_column, db_index=db_index, default=None, null=null, unique=unique, uuid_type=uuid_type
        )
Exemple #11
0
    def validate_kwargs(self, kwargs):
        """Validate the kwargs provided.

        :param kwargs: Field creation kwargs
        :type kwargs: dict
        :raises AsyncOrmFieldError:
            If a required field is not provided or when a value
            provided doesn't comply to Field requirements.
        """
        for kw in self.required_kwargs:
            if not kwargs.get(kw, None):
                raise AsyncOrmFieldError('"{cls}" field requires {kw}'.format(cls=self.__class__.__name__, kw=kw))

        for k, v in kwargs.items():
            null_choices = v is None and k == "choices"
            if not isinstance(v, KWARGS_TYPES[k]) and not null_choices:
                raise AsyncOrmFieldError("Wrong value for {k}".format(k=k))

        if kwargs.get("db_column", ""):
            self.set_field_name(kwargs["db_column"])
Exemple #12
0
    def validate(self, value):
        """Validate the value.

        :param value: value in the field
        :type value: self.internal_type
        :raises AsyncOrmFieldError:
            * When a null value sent to a non nullable field.
            * When the value provided is not in the field choices.
            * When the value provided is not in the self.internal_type
        """
        if value is None and not self.null:
            raise AsyncOrmFieldError("null value in NOT NULLABLE field")

        if hasattr(self, "choices") and self.choices is not None:
            if value not in self.choices.keys():
                raise AsyncOrmFieldError('"{}" not in field choices'.format(value))

        if value is not None and not isinstance(value, self.internal_type):
            raise AsyncOrmFieldError(
                "{value} is a wrong datatype for field {cls}".format(value=value, cls=self.__class__.__name__)
            )
Exemple #13
0
    def sanitize_data(self, value):
        if value is not None:
            if isinstance(value, str):
                try:
                    value = json.loads(value)
                except JSONDecodeError:
                    raise AsyncOrmFieldError(
                        "The data entered can not be converted to json")
            value = json.dumps(value)

        value = super().sanitize_data(value)

        return value
Exemple #14
0
    def validate_kwargs(self, kwargs):
        """validate the kwargs on object instantiation only"""
        attr_errors = [k for k in kwargs.keys() if k not in self.fields.keys()]

        if attr_errors:
            err_string = '"{}" is not an attribute for {}'
            error_list = [err_string.format(k, self.__class__.__name__) for k in attr_errors]
            raise AsyncOrmModelError(error_list)

        for k, v in kwargs.items():
            att_field = getattr(self.__class__, k)
            att_field.validate(v)

            if att_field.__class__ is AutoField and v:
                raise AsyncOrmFieldError("Models can not be generated with forced id")
Exemple #15
0
 def validate(self, value):
     try:
         EUI(value)
     except AddrFormatError:
         raise AsyncOrmFieldError("Not a correct MAC address")
Exemple #16
0
 def sanitize_data(self, value):
     """method used to convert to SQL data"""
     if isinstance(value, bool) or value is None:
         return value
     raise AsyncOrmFieldError("not correct data for BooleanField")