def __init__(self, request): """Base class for input validation. Subclass to add validators. :param request: flask.Request object to validate. """ #: List of errors from all validators. self.errors = [] self._request = request self._forms = dict() for name in dir(self): if not name.startswith('_') and name not in [ 'errors', 'validate', 'valid_attrs' ]: input = getattr(self, name) fields = dict() if isinstance(input, dict): for field, validators in input.items(): fields[field] = Field(validators=validators) elif isinstance(input, collections.Iterable): fields['_input'] = Field(validators=input) self._forms[name] = BaseForm(fields)
class PhotographersForm(Form, baseForms.SliceMixin): sortby = SelectField('sortby', default="number", choices=[ ("number", "number"), ("create_time", "create_time"), ("likes", "likes"), ]) order = SelectField('order', default="asc", choices=[ ("asc", "asc"), ("desc", "desc"), ]) styles = Field('styles', default=[], validators=[baseValidators.styles_get]) themes = Field('themes', default=[], validators=[baseValidators.themes_get]) schools = Field('schools', default=[], validators=[baseValidators.schools_get]) categories = Field('categories', default=[], validators=[baseValidators.categories_get])
class ProfileForm(Form): self_password = StringField('self_password') password = StringField('password', [ Length(min=6), Optional(), ]) tags = Field('tags', default=[]) school = StringField('school', [ baseValidators.school_get, Optional(), ]) categories = Field('categories', default=[], validators=[baseValidators.categories_get]) styles = Field('styles', default=[], validators=[baseValidators.styles_get]) name = StringField('name') avatar = StringField('avatar', [ baseValidators.image_get, Optional(), ]) sex = BooleanField('sex', false_values={False, 'false', 0}) description = TextAreaField('description') major = StringField('major') imagelink = StringField('imagelink') def validate_self_password(form, field): current_user = form.kwargs.get("current_user", None) if current_user is None: return if not current_user.password: return if not form.password.data: return if not current_user.check_password(field.data): _ = field.gettext raise StopValidation(_("密码错误.")) def validate_tags(form, field): current_user = form.kwargs.get("current_user", None) if current_user is None: return tags = list() for text in list(field.data): nd = models.Tag(user=current_user, text=text) tags.append(nd) field.data = tags def validate_sex(form, field): current_user = form.kwargs.get("current_user", None) if current_user is None: return if field.data == '': field.data = current_user.sex
def test_check_validators(self): v1 = "Not callable" v2 = validators.DataRequired with self.assertRaisesRegexp( TypeError, "{} is not a valid validator because " "it is not callable".format(v1)): Field(validators=[v1]) with self.assertRaisesRegexp( TypeError, "{} is not a valid validator because " "it is a class, it should be an " "instance".format(v2)): Field(validators=[v2])
def test_check_validators(): v1 = "Not callable" v2 = validators.DataRequired with pytest.raises( TypeError, match=rf"{v1} is not a valid validator because it is not callable", ): Field(validators=[v1]) with pytest.raises( TypeError, match=r"{} is not a valid validator because " "it is a class, it should be an " "instance".format(v2), ): Field(validators=[v2])
class CollectionForm(Form): name = StringField('name') description = TextAreaField('description') model_name = StringField('model_name') photoshop = StringField('photoshop') filming_time = StringField('filming_time') images = Field('images', default=[], validators=[baseValidators.images_get])
class BannerSortForm(Form): """ Used in: user.BannersHandler method=['PATCH'] exchange two banners' number. """ banners = Field('banners', default=[], validators=[baseValidators.banners_get])
class PatientForm(BaseForm): record = IntegerField(validators=[DataAuto(Patient), NumberRange(min=1)]) firstname = StringField(validators=[DataRequired(), Length(min=2)]) middlename = StringField(validators=[DataOptional()]) surname = StringField(validators=[DataOptional(), Length(min=2)]) birthdate = DateField(validators=[DataRequired(), DateRange(min=date(1900, 1, 1), max=date.today)], format="%Y-%m-%d") nationality = StringField(validators=[DataRequired(), AnyOf(values=NATIONALITIES)]) occupation = StringField(validators=[DataRequired(), Length(min=3)]) children = FieldList(Field(validators=[DataOptional(), Entity(ChildForm, Child)])) cellphone = StringField(validators=[DataOptional(), Telephone()]) cellphone2 = StringField(validators=[DataOptional(), Telephone()]) telephone = StringField(validators=[DataOptional(), Telephone()]) email = StringField(validators=[DataOptional(), Email()]) province = StringField(validators=[DataOptional(), AnyOf(values=PROVINCES)]) city = StringField(validators=[DataOptional(), Length(min=2)]) district = StringField(validators=[DataOptional()]) advisor = Field(validators=[DataOptional(), Entity(AdvisorForm, Advisor)]) coadvisors = FieldList(Field(validators=[DataOptional(), Entity(AdvisorForm, Advisor)]), validators=[Coadvisors()]) notes = StringField(validators=[DataOptional()])
class ValidatePastePermissions(Form): paste = Field() user = Field() validate_edit = BooleanField() validate_delete = BooleanField() password = StringField(validators=[validators.Length(max=128)]) def validate(self): Form.validate(self) target_paste = self.paste.data editor = self.user.data validate_edit = self.validate_edit.data validate_delete = self.validate_delete.data paste_is_open_edit = target_paste.open_edit editor_owns_paste = (target_paste.owner_id == editor.id) paste_requires_password = target_paste.password is not None if validate_edit and not editor_owns_paste and not paste_is_open_edit: self.paste.errors.append( "You do not own this paste and open edit is not enabled for it." ) return False if validate_delete and not editor_owns_paste: self.paste.errors.append( "You can not delete pastes you do not own.") return False if paste_requires_password and not editor_owns_paste: if self.password.data is None: self.password.errors.append( "A password is required to complete this action.") return False if not target_paste.password_correct(self.password.data): self.password.errors.append("Password is incorrect.") return False return True
def __init__(self, req=None): if req is None: req = request self._request = req self.errors = {} fields = {} for name, validators in self.headers.items(): fields[name] = Field(validators=validators) self._headers_form = BaseForm(fields) fields.clear() for name, validators in self.args.items(): fields[name] = Field(validators=validators) self._args_form = BaseForm(fields) fields.clear() for name, validators in self.form.items(): fields[name] = Field(validators=validators) self._form_form = BaseForm(fields) fields.clear() fields['_jsonschema'] = Field(validators=self.json) self._json_form = BaseForm(fields)
def select_multi_checkbox(field: Field, **kwargs: Any) -> str: html = ["<ul {}>".format(html_params(id=field.id, class_="multi-select"))] show_other = False for value, label, _ in field.iter_choices(): if value == "OTHER": show_other = True continue field_id = f"{field.id}-{value}" options = dict(kwargs, type="checkbox", name=field.name, value=value, id=field_id) if value in (field.data or ()): options["checked"] = "checked" html.append("<li><input %s /> " % html_params(**options)) html.append('<label for="%s">%s</label></li>' % (field_id, label)) if show_other: data = field.data or () all_choices = set(value for value, _, _ in field.iter_choices()) other_value = [v for v in data if v not in all_choices] other_value = other_value[0] if other_value else "" other_id = f"{field_id}-{value}" options = dict(kwargs, type="text", name=field.name, value=other_value, id=other_id) html.append( f'<li class="other"><label for="{field_id}">{label}:</label> ') html.append("<input %s /></li>" % html_params(**options)) html.append("</ul>") return Markup("".join(html))
def test_process_formdata(self): Field.process_formdata(self.field, [42]) self.assertEqual(self.field.data, 42)
def __init__(self, text, field_id='', **kwargs): _Label.__init__(self, field_id, text) Field.__init__(self, **kwargs)
def test_process_formdata(self): field = self.F().a Field.process_formdata(field, [42]) assert field.data == 42
class HomePhotographerSortForm(Form): photographers = Field('photographers', default=[], validators=[ baseValidators.photographers_get, ])
class UserQueryForm(Form): status = Field('status', default=[])
class HomeCollectionSortForm(Form): collections = Field('collections', default=[], validators=[ baseValidators.collections_get, ])