Beispiel #1
0
    def validate_class_fields(cls, dict, validate_all=False):
        """This is a convenience function that loops over _fields in
        cls to validate them. If the field is not required AND not present,
        it is skipped.
    
        'not present' is defined as not having a value OR having '' (or u'')
        as a value.
        """
        if not hasattr(cls, '_fields'):
            raise ValueError('cls is not a DictShield')

        internal_fields = cls._get_internal_fields()

        if validate_all:
            exceptions = list()
            handle_exception = lambda e: exceptions.append(e)
        else:

            def handle_exception(e):
                raise e

        for k, v in cls._fields.items():
            # handle common id name
            if k is 'id':
                k = '_id'

            # we don't accept internal fields from users
            if k in internal_fields:
                e = DictPunch('Overwrite of internal fields attempted', k, v)
                handle_exception(e)
                continue

            if v.required or dict.has_key(k):
                datum = dict[k]
                # treat empty strings as empty values and skip
                if isinstance(datum,
                              (str, unicode)) and len(datum.strip()) == 0:
                    continue
                try:
                    v.validate(datum)
                except DictPunch as e:
                    handle_exception(e)

        if validate_all:
            return exceptions
Beispiel #2
0
    def make_json_publicsafe(cls, doc_dict_or_dicts):
        """This funciton ensures found_data only contains the keys as
        listed in cls._public_fields.

        This function can be safely called without calling make_json_ownersafe
        first because it treats cls._public_fields as a whitelist and
        removes anything not listed.
        """
        if cls._public_fields is None:
            raise DictPunch(
                'make_json_publicsafe called cls with no _public_fields')

        def handle_doc(doc):
            # public_fields is a whitelist
            for f in doc.keys():
                if f not in cls._public_fields:
                    del doc[f]
            return doc

        return cls._safe_data_from_input(handle_doc, doc_dict_or_dicts)
Beispiel #3
0
 def validate(self, value):
     if not isinstance(value, bool):
         raise DictPunch('Not a boolean', self.field_name, value)
Beispiel #4
0
 def validate(self, value):
     if not isinstance(value, datetime.datetime):
         raise DictPunch('Not a datetime', self.field_name, value)
Beispiel #5
0
 def validate(self, value):
     if not EmailField.EMAIL_REGEX.match(value):
         raise DictPunch('Invalid email address', self.field_name, value)