示例#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 FieldError(
                '"{}" is not a recognized protocol'.format(protocol))
        if unpack_protocol.lower() not in ("same", "ipv6", "ipv4"):
            raise FieldError('"{}" is not a recognized unpack_protocol'.format(
                unpack_protocol))
        if protocol.lower() != "both" and unpack_protocol != "same":
            raise FieldError(
                "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,
        )
示例#2
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 FieldError(
                '"{}" is not a recognized protocol'.format(protocol))
        if unpack_protocol.lower() not in ('same', 'ipv6', 'ipv4'):
            raise FieldError('"{}" is not a recognized unpack_protocol'.format(
                unpack_protocol))
        if protocol.lower() != 'both' and unpack_protocol != 'same':
            raise FieldError(
                '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)
示例#3
0
 def set_field_name(self, db_column):
     if "__" in db_column:
         raise FieldError('db_column can not contain "__"')
     if db_column.startswith("_"):
         raise FieldError('db_column can not start with "_"')
     if db_column.endswith("_"):
         raise FieldError('db_column can not end with "_"')
     self.db_column = db_column
示例#4
0
    def validate(self, value):
        try:
            IPNetwork(value)
        except AddrFormatError:
            raise FieldError("Not a correct IP address")

        if self.protocol.lower() != "both" and IPNetwork(value).version != int(
                self.protocol[-1:]):
            raise FieldError("{} is not a correct {} IP address".format(
                value, self.protocol))
示例#5
0
 def validate(self, value):
     super().validate(value)
     if value:
         items_type = self.homogeneous_type(value)
         if not items_type:
             raise FieldError("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 FieldError(
                     "Multi-dimensional arrays must have items of the same size"
                 )
     return value
示例#6
0
    def validate(self, value):
        if value is None and not self.null:
            raise FieldError("null value in NOT NULL field")

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

        if value is not None and not isinstance(value, self.internal_type):
            raise FieldError(
                "{value} is a wrong datatype for field {cls}".format(
                    value=value, cls=self.__class__.__name__))
示例#7
0
    def validate_kwargs(self, kwargs):
        for kw in self.required_kwargs:
            if not kwargs.get(kw, None):
                raise FieldError('"{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 FieldError("Wrong value for {k}".format(k=k))

        if kwargs.get("db_column", ""):
            self.set_field_name(kwargs["db_column"])
示例#8
0
 def sanitize_data(self, value):
     exp = r"^[a-zA-Z0-9\-\b]{36}$"
     if re.match(exp, value):
         return value
     raise FieldError(
         "The expresion doesn't validate as a correct {}".format(
             self.__class__.__name__))
示例#9
0
 def sanitize_data(self, value):
     value = super().sanitize_data(value)
     if len(value) > self.max_length:
         raise FieldError(
             'The string entered is bigger than the "max_length" defined ({})'
             .format(self.max_length))
     return str(value)
示例#10
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 FieldError(
                        "The data entered can not be converted to json")
            value = json.dumps(value)

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

        return value
示例#11
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 FieldError(
                '"{}" 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)
示例#12
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 FieldError('{} 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)
示例#13
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 ModelError(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 FieldError('Models can not be generated with forced id')
示例#14
0
 def validate(self, value):
     try:
         EUI(value)
     except AddrFormatError:
         raise FieldError("Not a correct MAC address")
示例#15
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 FieldError('"{}" not a valid email address'.format(value))
示例#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 FieldError("not correct data for BooleanField")