class AliveDeleteForm(FlaskForm): table_id = HiddenField('table_id', validators=[InputRequired()]) alive = BooleanField('alive', default=True) delete = BooleanField('delete', default=False) string = Field() regexp = Field() ipaddress = Field()
def __init__(self, label=None, validators=None, checked_value=None, unchecked_value=None, checked_by_default=False, **kwargs): Field.__init__(self, label, validators, **kwargs) self.checked_by_default = checked_by_default if checked_value is not None: self.checked_value = checked_value if unchecked_value is not None: self.unchecked_value = unchecked_value
def __call__(self, form: Form, field: Field) -> None: if (field.data is None or (isinstance(field.data, str) and not field.data.strip()) or (isinstance(field.data, (list, dict)) and not field.data)): if self.message is None: message = field.gettext("This field is required.") else: message = self.message field.errors[:] = [] raise validators.StopValidation(message)
class ConfigValidator(Form): listen_host = StringField('listen_host', [String_and(validators.Length(min=2))]) listen_port = IntegerField('listen_port', [validators.NumberRange(0, 65535)]) filename_metrics = StringField('filename_metrics', [String_and(validators.Length(min=2))]) log_file = StringField('log_file', [String_and(validators.Length(min=2))]) graphite_url_server = StringField('graphite_url_server', [String_and(validators.Length(min=2))]) graphite_url_client = StringField('graphite_url_client', [String_and(validators.Length(min=2))]) # the following 4 can be None. validators.InputRequired gives weird errors graphite_username = StringField( 'graphite_username', [is_None_or(String_and(validators.Length(min=1)))]) graphite_password = StringField( 'graphite_password', [is_None_or(String_and(validators.Length(min=1)))]) # anthracite_url = StringField('anthracite_url', [is_None_or(String_and(validators.Length(min=1)))]) anthracite_host = StringField( 'anthracite_host', [is_None_or(String_and(validators.Length(min=2)))]) anthracite_port = IntegerField( 'anthracite_port', [is_None_or(validators.NumberRange(0, 65535))]) anthracite_index = StringField( 'anthracite_index', [is_None_or(String_and(validators.Length(min=2)))]) anthracite_add_url = StringField( 'anthracite_add_url', [is_None_or(String_and(validators.Length(min=1)))]) locations_plugins_structured_metrics = Field( 'locations_plugins_structured_metrics', [is_iterable()]) locations_dashboards = Field('locations_dashboards', [is_iterable()]) es_host = StringField('es_host', [String_and(validators.Length(min=2))]) es_port = IntegerField('es_port', [validators.NumberRange(0, 65535)]) es_index = StringField('es_index', [String_and(validators.Length(min=2))]) limit_es_metrics = IntegerField('limit_es_metrics', [validators.NumberRange(0, 1000000000000)]) process_native_proto2 = Field('process_native_proto2', [isBool]) alerting = Field('alerting', [isBool]) alerting_db = StringField('alerting_db', [String_and(validators.Length(min=2))]) alerting_smtp = StringField('alerting_smtp', [String_and(validators.Length(min=2))]) # note: validation.Email() doesn't recognize strings like 'Graph Explorer <*****@*****.**>' alerting_from = StringField('alerting_from', [String_and(validators.Length(min=2))]) alert_backoff = IntegerField('alerting_backoff', [validators.NumberRange(1, 99999)]) alerting_base_uri = StringField('alerting_base_uri', [String_and(validators.Length(min=2))]) collectd_StoreRates = Field('collectd_StoreRates', [isBool]) collectd_prefix = StringField('collectd_prefix', [String_and(validators.Length(min=2))])
class UserRegisterForm(JSONForm): username = Field('name', [DataRequired(), Length(max=20, min=1)]) password = StringField( 'description', [DataRequired(), Length(max=20, min=4)]) email = StringField('email', [DataRequired(), Email()]) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def validate_username(self, field): e = User.query.filter_by(username=field.data).first() if e: raise ValidationError('Duplicate username') def validate_email(self, field): e = User.query.filter_by(email=field.data).first() if e: raise ValidationError('Duplicate Email') def save(self, uid=None): if uid: user = User.query.get_or_404(uid) else: user = User() db.session.add(user) user.username = self.username.data user.password = self.password.data user.email = self.email.data db.session.commit() return user
class CaseLogsSearchForm(Form): id = IntegerField(validators=[Optional()]) name = StringField(validators=[Optional()]) url = StringField(validators=[Optional()]) # 工程名称 project = StringField(validators=[Optional()]) # 任务id task = IntegerField(validators=[Optional()]) # 结果 result = Field(validators=[Optional()]) page = IntegerField(default=1) count = IntegerField(default=10, validators=[Optional()]) start = DateTimeField(validators=[]) end = DateTimeField(validators=[]) def validate_start(self, value): if value.data: try: _ = time.strptime(value.data, '%Y-%m-%d %H:%M:%S') except ValueError as e: raise e def validate_end(self, value): if value.data: try: _ = time.strptime(value.data, '%Y-%m-%d %H:%M:%S') except ValueError as e: raise e
class AttenderForm(FForm): name = Field('name', [DataRequired(), Length(max=20, min=1)]) city = StringField('city', [DataRequired(), Length(max=500, min=1)]) role = StringField('role', [DataRequired()]) org = StringField('org', [DataRequired(), Length(min=1)]) bch = StringField('bch', [DataRequired(), Length(min=5)]) slogan = StringField('slogan') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def save(self): if current_user: u = current_user else: raise LoginRequired() a = get_file('file') if a: u.avatar = a logger.debug('avatar url: ' + u.avatar) u.hacker_name = self.name.data u.city = self.city.data u.role = self.role.data u.organization = self.org.data u.bch = self.bch.data if self.slogan.data: u.slogan = self.slogan.data u.is_hacker = True db.session.commit() return u
class FeedbackForm(JSONForm): title = Field('title', [DataRequired(), Length(max=100, min=1)]) content = StringField('content', [DataRequired(), Length(min=1)]) type = StringField() email = StringField('email', [DataRequired(), Email()]) def __init__(self, uid=None, *args, **kwargs): super().__init__(*args, **kwargs) self.uid = uid or current_user.id def save(self, pid=None): if pid: p = Suggestion.query.get_or_404(pid) else: p = Suggestion(uid=self.uid) p.title = self.title.data p.content = self.content.data p.type = self.type.data p.email = self.email.data db.session.commit() return p def setup(self, owner_id=None): if owner_id: owner = User.query.get_or_404(owner_id) else: owner = current_user return self.save()
class DAppForm(FForm): id = IntegerField('id', [DataRequired()]) name = Field('name', [DataRequired(), Length(max=50, min=1)]) git = StringField('git', [DataRequired(), URL()]) intro = StringField('intro', [DataRequired()]) demo = StringField('demo', [URL()]) logo_uri = StringField('logo_uri') is_new = StringField('is_new') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def set(self, pid): item = DApp.query.get(pid) if not item: raise NoData() item.name = self.name.data item.git = self.git.data item.intro = self.intro.data item.demo = self.demo.data if self.is_new.data == 'true': logo_url = get_file('logo') item.logo = logo_url else: item.logo = self.logo_uri.data db.session.commit() return item def create(self): p = DApp(uid=current_user.id) current_user.owned_dust += 100 db.session.add(p) db.session.flush() return self.set(p.id)
class ProductForm(FlaskForm): title = StringField('Название товара', validators=[DataRequired()]) content = TextAreaField("Описание") photo = Field('Фото', validators=[DataRequired()]) connection = StringField('Связаться с нами(введите телефон)', validators=[DataRequired()]) category = StringField('Категория', validators=[DataRequired()]) submit = SubmitField('Добавить')
class OrderForm(Form): """ Form to validate incoming POST requests """ customer_id = StringField(validators=[ validators.DataRequired(), validators.Length(min=8, max=8) ]) products = Field(validators=[validators.DataRequired(), validate_products])
def load(self, cfg: ReadOnlyOrderedDict, field: Field): """ Sets the field's value to the corresponding config node """ for key in self.cfg_path[:-1]: cfg = cast(ReadOnlyOrderedDict, cfg.get(key)) data = cfg.get(self.cfg_path[-1]) field.data = self.translator.load(data)
class VoteUpdateForm(Form): announcement = StringField('投票公告', validators=[Length(max=200)]) title = StringField('投票标题', validators=[Length(max=200)]) description = StringField('投票描述', validators=[Length(max=200)]) rules = StringField('奖品和规则') start_time = DateTimeField("开始时间") end_time = DateTimeField("结束时间") banners = FieldList(Field("宣传海报"))
class SetupPlanetForm(JSONForm): name = Field('name', [DataRequired(), Length(max=30, min=1)]) email = StringField('email', [DataRequired(), Email()]) keywords = StringField('keywords', [DataRequired(), Length(max=32, min=1)]) description = StringField('description', [DataRequired(), Length(min=1)]) demo_url = StringField('demo_url', [DataRequired(), URL()]) github_url = StringField('github_url', [DataRequired(), URL()]) team_intro = StringField('team') def __init__(self, uid=None, *args, **kwargs): super().__init__(*args, **kwargs) self.uid = uid or current_user.id def validate_name(self, field): e = Planet.query.filter_by(name=field.data).first() if e: raise ValidationError('Duplicate project name') def validate_github_url(self, field): e = Planet.query.filter_by(github_url=field.data).first() if e: raise ValidationError('This github project already exits.') def validate_demo_url(self, field): e = Planet.query.filter_by(github_url=field.data).first() if e: raise ValidationError('This demo already exits.') def save(self, pid=None): if pid: p = Planet.query.get_or_404(pid) else: p = Planet(owner_id=self.uid) db.session.add(p) p.dust_num = 100 p.name = self.name.data p.description = self.description.data p.keywords = self.keywords.data p.demo_url = self.demo_url.data p.github_url = self.github_url.data p.team_intro = self.team_intro.data p.email = self.email.data db.session.commit() return p def setup(self, owner_id=None): if owner_id: owner = User.query.get_or_404(owner_id) else: owner = current_user owner.owned_dust += 100 owner.planet_dust_sum += 100 return self.save()
def __call__(self, form: Form, field: Field) -> None: filters = self.datamodel.get_filters().add_filter( self.col_name, self.datamodel.FilterEqual, field.data) count, obj = self.datamodel.query(filters) if count > 0: # only test if Unique, if pk value is different on update. if not hasattr( form, "_id") or form._id != self.datamodel.get_keys(obj)[0]: if self.message is None: self.message = field.gettext(u"Already exists.") raise ValidationError(self.message)
class CreateLoginForm(Form): username = TextField('Username', [validators.Required()]) password1 = PasswordField('Password1', [validators.Required()]) password2 = PasswordField('Password2', [validators.Required()]) gender = Field('Gender', [validators.Required()]) age = IntegerField('Age', [validators.Required()]) session_id = Field('Session Id', [validators.Required()]) def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) self.user = None def validate(self): rv = Form.validate(self) if not rv: return False if not self.password1.data == self.password2.data: return False userEntry = app.mongo.db.users.find_one( {'username': self.username.data}) if userEntry: return False doc = { 'username': self.username.data, 'gender': self.gender.data, 'age': self.age.data, 'password': generate_password_hash(self.password1.data), 'facilitator': False, 'session_id': self.session_id.data } try: app.mongo.db.users.insert(doc) except pymongo.errors.DuplicateKeyError as e: return False user = User(self.username.data) self.user = user return True
class BuildPlanetForm(JSONForm): planet_name = Field('planet_name', [DataRequired()]) dust_num = IntegerField('dust_num', [DataRequired(), NumberRange(min=1)]) def __init__(self, uid=None, *args, **kwargs): super().__init__(*args, **kwargs) self.planet = Planet.query.filter_by( name=self.planet_name.data).first() def validate_planet_name(self, field): if not self.planet: raise ValidationError('No such planet.') def validate_dust_num(self, field): if field.data > current_user.owned_dust: raise ValidationError('You donnot have so mach dust.') # def validate_builder(self): # if self.planet.owner_id == current_user.id: # raise ValidationError('Owner of the planet cannot build it.') def validate_time(self): if datetime.now() - self.planet.created_at > timedelta(days=30): self.planet.status = Status.UNSHELVED db.session.commit() raise ValidationError('Build timeout.') # def validate_build_times(self): # t = redis_store.get("%s:build_times" % current_user.id) # if t <= 0: # raise ValidationError('Today\'s three times have been used. Please build tomorrow.') def build(self): record = BuildRecord(builder_id=current_user.id) db.session.add(record) record.planet_id = self.planet.id record.dust_num = self.dust_num.data self.planet.dust_num += self.dust_num.data self.planet.builder_num += 1 planet_owner = User.query.get(self.planet.owner_id) planet_owner.planet_dust_sum += self.dust_num.data current_user.owned_dust -= self.dust_num.data db.session.flush() record.planet_dust = self.planet.dust_num db.session.commit() # t = redis_store.get("%s:build_times" % current_user.id) # tleft = redis_store.ttl("%s:build_times" % current_user.id) # redis_store.set("%s:build_times" % current_user.id, int(t)-1, ex=tleft) return record
class ProjectForm(FForm): id = IntegerField('id', [DataRequired()]) name = Field('name', [DataRequired(), Length(max=50, min=1)]) git = StringField('git', [DataRequired(), URL()]) desc = StringField('desc', [DataRequired()]) demo = StringField('demo', [URL()]) logo_uri = StringField('logo_uri') is_new = StringField('is_new') # logo = StringField('logo', [DataRequired(), URL()]) # photos = Field('demo_photos', default=[]) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def set(self, pid): item = Project.query.get(pid) item.name = self.name.data item.git = self.git.data if self.is_new.data == 'true': logo_url = get_file('logo') item.logo = logo_url else: item.logo = self.logo_uri.data item.description = self.desc.data if self.demo.data: item.demo = self.demo.data logger.debug('project demo: ', self.demo.data) # else: # logger.debug('request.files', request.files) # logger.debug('request.files', request.files.keys()) # urls = get_files() # for url in urls: # logger.debug('project photo url: %s', url) # d = DemoPhoto(url=url, project_id=pid) # db.session.add(d) # item.photos.append(d) db.session.commit() return item def create(self): p = Project(team_id=current_user.cteam_id) t = Team.query.get(current_user.cteam_id) for usr in t.users: usr.owned_dust += 100 db.session.add(p) db.session.flush() return self.set(p.id)
class LoginForm(FlaskForm): username = StringField(label='Username', validators=[InputRequired('Username field is required')] ) password = PasswordField(label='Password', validators=[InputRequired('Password field is requiered')] ) remember = BooleanField(label='Remember me?') check_user = Field(None) def validate_check_user(self, form): user_exists = User.query.filter_by(username=self.username.data).first() if not(user_exists and user_exists.check_psw(self.password.data)): raise ValidationError('Invalid username or password.') form.data = user_exists
class VoteForm(Form): announcement = StringField( '投票公告', validators=[Length(max=200), DataRequired(message="请输入投票公告")]) title = StringField( '投票标题', validators=[Length(max=200), DataRequired(message="请输入投票标题")]) description = StringField( '投票描述', validators=[Length(max=200), DataRequired(message="请输入投票描述")]) rules = StringField('奖品和规则', validators=[DataRequired(message="请输入奖品和规则")]) start_time = DateTimeField("开始时间", validators=[DataRequired(message="请输入开始时间")]) end_time = DateTimeField("结束时间", validators=[DataRequired(message="请输入结束时间")]) banners = FieldList( Field("宣传海报", validators=[DataRequired(message="请输入宣传海报列表")]))
class UploadProjectForm(JSONForm): contact = Field('contact', [DataRequired(), Length(max=50, min=1)]) phone = StringField('phone', [DataRequired()], PhoneNumber()) title = StringField('title', [DataRequired(), Length(max=50, min=1)]) desc = StringField('desc', [DataRequired(), Length(min=1)]) file = StringField('file', [DataRequired(), URL()]) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def create(self): item = Project() item.contact = self.name.contact item.phone = self.phone.data item.title = self.title.data item.desc = self.desc.data item.file = self.file.data db.session.add(item) db.session.commit() return item
class SetupBountyRewardForm(JSONForm): name = Field('name', [DataRequired(), Length(max=100, min=1)]) company_name = StringField() description = StringField('description', [DataRequired(), Length(min=1)]) keywords = StringField('team') background = StringField() email = StringField('email', [Email()]) reward = IntegerField('reward') def __init__(self, uid=None, *args, **kwargs): super().__init__(*args, **kwargs) self.uid = uid or current_user.id def validate_name(self, field): e = BountyReward.query.filter_by(name=field.data).first() if e: raise ValidationError('Duplicate BountyReward name') def save(self, pid=None): if pid: p = BountyReward.query.get_or_404(pid) else: p = BountyReward(owner_id=self.uid) db.session.add(p) p.name = self.name.data p.company_name = self.company_name.data p.description = self.description.data p.keywords = self.keywords.data p.background = self.background.data p.email = self.email.data p.reward = self.reward.data db.session.commit() return p def setup(self, owner_id=None): if owner_id: owner = User.query.get_or_404(owner_id) else: owner = current_user # owner.owned_dust += 500 return self.save()
def __call__(self, form: FlaskForm, field: Field) -> None: if self.other_field_name in form: other_field = form[self.other_field_name] if bool(other_field.data): if self.custom_message != "": self.message = self.custom_message else: self.message = gettext( 'The "{name}" field is required when "{other_name}" is set.' .format(other_name=self.other_field_name, name=field.name)) super(RequiredIf, self).__call__(form, field) else: field.errors[:] = [] raise StopValidation() else: raise ValidationError( gettext( 'The "{other_name}" field was not found - it is required by "{name}".' .format(other_name=self.other_field_name, name=field.name)))
class BaseForm(FlaskForm): """Add an invisible field to hold form-wide errors.""" non_field_errors = Field()
def process(self, formdata, data=object()): ori_name = self.name self.name = ori_name + '_selected' Field.process(self, formdata, data) self.name = ori_name
def bootstrap_field( field: Field, form_group: bool = True, placeholder: Union[bool, str] = True, label: bool = True, errors: bool = True, horizontal: bool = False, inline: bool = False, btn_color: str = 'default', icon: Union[bool, str] = False, **kwargs ) -> Markup: """Render a WTForms Field with Bootstrap markup. Args: field: The field to render. form_group: Whether or not to make it a form-group. placeholder: The string to display as a placeholder, True to display the default placeholder and something falsey to display nothing. label: Whether or not to display the field label. errors: Whether or not to display errors. horizontal: Whether to display the field horizontally. icon: inline: Whether to display the field inline. btn_color: The color name to pass as the button color. """ # TODO respect inline if isinstance(field, HiddenField): # Handles CSRFTokenFields return Markup(str(field)) is_text_field = field.type in TEXT_FIELD_TYPES field_classes = _space_join_cond({ 'form-control': is_text_field, 'btn btn-' + btn_color: field.type == 'SubmitField', }) if placeholder is True and field.type in TEXT_FIELD_TYPES: placeholder = 'Enter %s' % field.label.text html_str = field( class_=field_classes, placeholder=placeholder, **kwargs ) html_str = _insert_icon(html_str, field, icon, is_text_field) horizontal_field_offset = 2 label_html = '' if horizontal and field.errors: html_str += ERROR_ICON if field.type == 'BooleanField': html_str = ( f'<div class="checkbox"><label>{html_str} {field.label.text}' '</label></div>' ) elif field.type != 'SubmitField' and label: label_html = field.label(class_=_space_join_cond({ 'control-label': True, 'col-sm-2': horizontal })) horizontal_field_offset = 0 if horizontal: html_str = label_html + _col(html_str, 10, offset=horizontal_field_offset) else: html_str = label_html + html_str if form_group and field.errors: html_str += ERROR_ICON if form_group: form_group_classes = _space_join_cond({ 'form-group': True, 'has-error has-feedback': field.errors, 'required': field.flags.required, }) html_str = f'<div class="{form_group_classes}">{html_str}</div>' html_str += _field_description(field, horizontal) html_str += _field_errors(field, errors, horizontal) return Markup(html_str)
class ProjectConfigForm(Form): projectId = IntegerField(validators=[DataRequired(message='请输入工程id')]) # 配置 [[configId, caseId, isRun, order], []] configs = FieldList(Field(validators=[Optional()]))
class MockForm(Form): username = Field('Username', [forms.UniqueEmail(allow_unregistered=True)])
class MockFormWithAlwaysError(FlaskForm): field = Field(validators=[Required(), AlwaysError()])
class MockForm(Form): username = Field('Username', [forms.UniqueEmail()])
class CryptoForm(FlaskForm): From = SelectField('From', choices=cryptos) Q = StringField('Q', validators=[DataRequired()]) To = SelectField('To', id='To', choices=cryptos) ToQ = Field('ToQ')
def bootstrap_field(field: Field, form_group: bool = True, placeholder: Union[bool, str] = True, label: bool = True, errors: bool = True, horizontal: bool = False, inline: bool = False, btn_color: str = 'default', icon: Union[bool, str] = False, **kwargs) -> Markup: """Render a WTForms Field with Bootstrap markup. Args: field: The field to render. form_group: Whether or not to make it a form-group. placeholder: The string to display as a placeholder, True to display the default placeholder and something falsey to display nothing. label: Whether or not to display the field label. errors: Whether or not to display errors. horizontal: Whether to display the field horizontally. icon: inline: Whether to display the field inline. btn_color: The color name to pass as the button color. """ # TODO respect inline if isinstance(field, HiddenField): # Handles CSRFTokenFields return Markup(str(field)) is_text_field = field.type in TEXT_FIELD_TYPES field_classes = _space_join_cond({ 'form-control': is_text_field, 'btn btn-' + btn_color: field.type == 'SubmitField', }) if placeholder is True and field.type in TEXT_FIELD_TYPES: placeholder = 'Enter %s' % field.label.text html_str: Markup = field(class_=field_classes, placeholder=placeholder, **kwargs) html_str = _insert_icon(html_str, field, icon, is_text_field) horizontal_field_offset = 2 label_html = '' if horizontal and field.errors: html_str += ERROR_ICON if field.type == 'BooleanField': html_str = Markup( f'<div class="checkbox"><label>{html_str} {field.label.text}' '</label></div>') elif field.type != 'SubmitField' and label: label_html = field.label(class_=_space_join_cond({ 'control-label': True, 'col-sm-2': horizontal })) horizontal_field_offset = 0 if horizontal: html_str = label_html + _col( html_str, 10, offset=horizontal_field_offset) else: html_str = label_html + html_str if form_group and field.errors: html_str += ERROR_ICON if form_group: form_group_classes = _space_join_cond({ 'form-group': True, 'has-error has-feedback': field.errors, 'required': field.flags.required, }) html_str = Markup( f'<div class="{form_group_classes}">{html_str}</div>') html_str += _field_description(field, horizontal) html_str += _field_errors(field, errors, horizontal) return Markup(html_str)
def __init__(self, label=None, validators=None, format='%H:%M', empty_to_none=False, **kwargs): Field.__init__(self, label, validators, **kwargs) self.format = format self.empty_to_none = empty_to_none
def __init__(self, label=None, validators=None, empty_to_none=False, **kwargs): Field.__init__(self, label, validators, **kwargs) self.empty_to_none = empty_to_none
class MockForm(FlaskForm): field = Field(validators=[Required()])
def __init__(self, *args, **kwargs): """Initialize the ListField""" FormField.__init__(self, *args, **kwargs) self.data = None