def validator(value): if min is not None and value < min: raise ValidationError('%s is less than minimum value of %s.' % (value, min)) if max is not None and value > max: raise ValidationError('%s is greater than maximum value of %s.' % (value, max))
def validator_ws_uri(value): """Validate if the value is a valid ws/wss uri.""" DOMAIN_PATTERN = re.compile( r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+' r'(?:[A-Z]{2, 6}\.?|[A-Z0-9-]{2,}(?<!-)\.?)' # domain r'(?::\d+)?\Z', # optional port re.IGNORECASE ) PATH_PATTERN = re.compile(r'\A\S*\Z') scheme, rest = value.split('://') if scheme.lower() not in ['ws', 'wss']: raise ValidationError('Unrecognized scheme: ' + scheme) domain, _, path = rest.partition('/') if not PATH_PATTERN.match(path): raise ValidationError('Invalid path: ' + path) if not DOMAIN_PATTERN.match(domain): # Check if it is an IP address try: ipaddress.ip_address(domain) except ValueError: try: # Check if there's a port. Remove it, and try again. domain, port = domain.rsplit(':', 1) ipaddress.ip_address(domain) except ValueError: raise ValidationError('Invalid URL: ' + rest)
def clean_fields(self, exclude=None): """Validate the values of all fields. This method will raise a :exc:`~pymodm.errors.ValidationError` that describes all issues with each field, if any field fails to pass validation. :parameters: - `exclude`: A list of fields to exclude from validation. """ exclude = validate_list_tuple_or_none('exclude', exclude) exclude = set(exclude) if exclude else set() error_dict = {} for field in self._mongometa.get_fields(): if field.attname in exclude: continue try: field_value = field.value_from_object(self) field_empty = field.is_undefined(self) if field_empty and field.required: error_dict[field.attname] = [ ValidationError('field is required.') ] elif not field_empty: field.validate(field_value) except Exception as exc: error_dict[field.attname] = [ValidationError(exc)] if error_dict: raise ValidationError(error_dict)
def validate_mentor(user_id): user = User.objects.get({'_id': user_id}) if user: if not user.role == 'mentor': raise ValidationError('Given user is not a mentor') else: raise ValidationError('Mentor ID is invalid.')
def validate_mentor(user_id): user = User.objects.get({'_id': user_id}) if user: # code.interact(local=dict(globals(), **locals())) if not user.role == 'mentor': raise ValidationError('Given user is not a mentor') else: raise ValidationError('Mentor ID is invalid.')
def validator(value): len_value = len(value) if min is not None and len_value < min: raise ValidationError('%s is under the minimum length of %d.' % (value, min)) if max is not None and len_value > max: raise ValidationError('value exceeds the maximum length of %d.' % (max, ))
def validate_related_model(value): if not isinstance(value, list): raise ValidationError('%r must be a list.' % value) for v in value: if not isinstance(v, self.related_model): raise ValidationError('%r is not an instance of %s.' % (v, self.related_model.__name__)) v.full_clean()
def validate_keys(value): for key in value: if not isinstance(key, string_types): raise ValidationError( 'All dictionary keys must be strings: %r' % value) if '.' in key or '$' in key: raise ValidationError( 'Dictionary keys must not contain "$" or ".": %r' % value)
def validate_type(self): if self.type_ != None: if self.type_ == 'multiple' and len(self.members) < 2: raise ValidationError( "Atleast two members are required to start a multiple session." ) if self.type_ == 'single' and len(self.members) > 1: raise ValidationError( "Only one member is allowed in single mode.")
def validate_users(user_ids): try: for id_ in user_ids: user = User.objects.get({"_id": ObjectId(id_)}) if not user.role == 'student': raise ValidationError('Given user/users is not a student') except Exception as e: message = "User does not exists." if str(e) == "" else str(e) raise ValidationError(message)
def set_role(self, role: GroupRole): if not role: raise ValidationError("Необходимо указать id роли") if self.role_id: raise ValidationError("Роль уже задана") if not self.group_id: raise ValidationError( "Перед установкой роли необходимо задать группу") self.role_id = role.pk self.save()
def _validate_choices(self, value): # Is self.choices a list of pairs? A flat list? if isinstance(self.choices[0], (list, tuple)): flat_choices = [pair[0] for pair in self.choices] if value not in flat_choices: raise ValidationError('%r is not a choice. Choices are %r.' % (value, flat_choices)) elif value not in self.choices: raise ValidationError('%r is not a choice. Choices are %r.' % (value, self.choices))
def validate_sessions(session_ids): try: # code.interact(local=dict(globals(), **locals())) for id_ in session_ids: session = Session.objects.get({"_id": ObjectId(id_)}) if not session: raise ValidationError('Not a session') except Exception as e: message = "Session does not exists." if str(e) == "" else str(e) raise ValidationError(message)
def clean(self): if self.role_id: target_group = Group.objects.get({"_id": self.group_id.pk}) if self.role_id not in target_group.role_list: raise ValidationError("Группа %s не предусматривает роль %s" % (target_group.name, self.role_id.name)) if [ x for n, x in enumerate(self.permissions) if x in self.permissions[:n] ]: raise ValidationError("Разрешения не должны повторяться")
def _mode_validation(key, value): if not isinstance(value, dict) or len(value) != 3 or not all(k in value.keys() for k in _REQUIRED_MODE_KEYS): raise ValidationError( 'field must have {} key with value dict of length 3 and keys {}.'.format(key, _REQUIRED_MODE_KEYS)) dist_dur = _REQUIRED_MODE_KEYS[:2] for key in dist_dur: _dist_dur_validation(key, value[key]) show = value[_REQUIRED_MODE_KEYS[2]] if not isinstance(show, bool): raise ValidationError('field show in {} must be a boolean'.format(key))
def validate_coordinates(coordinates): try: coordinates[0][0] except Exception: raise ValidationError('LineString must contain at least one Point.') errors = [] for point in coordinates: try: PointField.validate_coordinates(point) except ValidationError as e: errors.append(e) if errors: raise ValidationError(errors)
def validate_coordinates(coordinates): try: coordinates[0][0][0][0] except Exception: raise ValidationError( 'MultiPolygon must contain at least one Polygon.') errors = [] for polygon in coordinates: try: PolygonField.validate_coordinates(polygon) except ValidationError as e: errors.append(e) if errors: raise ValidationError(errors)
def validate_coordinates(coordinates): try: coordinates[0][0][0] except Exception: raise ValidationError( 'MultiLineString must contain at least one LineString.') errors = [] for linestring in coordinates: try: LineStringField.validate_coordinates(linestring) except ValidationError as e: errors.append(e) if errors: raise ValidationError(errors)
def to_mongo(self, value): if isinstance(value, abc.Mapping): return value try: return dict(value) except ValueError as e: raise ValidationError(e)
def to_mongo(self, value): if isinstance(value, OrderedDict): return value try: return OrderedDict(value) except ValueError as e: raise ValidationError(e)
def to_mongo(self, value): if isinstance(value, uuid.UUID): return value try: return uuid.UUID(value) except ValueError as e: raise ValidationError(e)
def to_mongo(self, value): if isinstance(value, Code): return value try: return Code(value) except TypeError as e: raise ValidationError(e)
def validate_ldatatype(value): try: self.DATA_TYPE(value) except ValueError: msg = '%r is not a valid %s.' % value, self.DATA_TYPE.__name__ raise ValidationError(msg)
def to_mongo(self, value): if isinstance(value, Binary): return value try: return Binary(value, subtype=self.subtype) except (TypeError, ValueError) as exc: raise ValidationError(exc)
def to_mongo(cls, value): """Convert value for storage.""" try: return str(EUI64(value)) except ValueError: msg = '%r is not a valid EUID.' % value raise ValidationError(msg)
def to_python(cls, value): """Convert value back to Python.""" try: return EUI64(value) except ValueError: msg = '%r is not a valid EUID.' % value raise ValidationError(msg)
def validate_plmnid(value): try: PLMNID(value) except ValueError: msg = '%r is not a valid PLMN id.' % value raise ValidationError(msg)
def validate_ssid(value): try: SSID(value) except ValueError: msg = '%r is not a valid SSID.' % value raise ValidationError(msg)
def validate_ethernet_address(value): try: EtherAddress(value) except ValueError: msg = '%r is not a valid Ethernet address.' % value raise ValidationError(msg)
def validate_coordinates(coordinates): if not (isinstance(coordinates, (list, tuple)) and len(coordinates) == 2): raise ValidationError('Point is not a pair: %r' % coordinates) validate_number = validators.validator_for_type((float, int), 'coordinate value') validate_number(coordinates[0]) validate_number(coordinates[1])