Beispiel #1
0
class Settings(FlaskForm):
    letters_number = IntegerRangeField('Количество символов', default=6,
                                  validators=[DataRequired(), NumberRange(min=1, max=32)])
    passwords_number = IntegerRangeField('Количество паролей', default=4,
                                    validators=[DataRequired(), NumberRange(min=1, max=20)])
    submit = SubmitField('Применить настройки')
Beispiel #2
0
class SearchForm(Form):
    q = StringField(validators=[DataRequired(), Length(min=1, max=30)])
    page = IntegerField(validators=[NumberRange(min=1, max=99)], default=1)
Beispiel #3
0
class PostStatusForm(FormBase):
    post_status = IntegerField(validators=[
        InputRequired(message='状态不能为空'),
        NumberRange(max=1, min=0, message="状态选项在0-1区间")
    ])
Beispiel #4
0
class CategoryWeightForm(FlaskForm):
    weight = FloatField(
        'Category Weight',
        validators=[DataRequired(),
                    NumberRange(min=1.0, max=100.0)])
Beispiel #5
0
class Survey(Form):
    """ Survey questions including all skills for a user to provide personal ratings  """
    q0 = IntegerRangeField(label=skill_names_list[0],
                           default=0,
                           validators=[NumberRange(min=0, max=5)])
    q1 = IntegerRangeField(label=skill_names_list[1],
                           default=0,
                           validators=[NumberRange(min=0, max=5)])
    q2 = IntegerRangeField(label=skill_names_list[2],
                           default=0,
                           validators=[NumberRange(min=0, max=5)])
    q3 = IntegerRangeField(label=skill_names_list[3],
                           default=0,
                           validators=[NumberRange(min=0, max=5)])
    q4 = IntegerRangeField(label=skill_names_list[4],
                           default=0,
                           validators=[NumberRange(min=0, max=5)])
    q5 = IntegerRangeField(label=skill_names_list[5],
                           default=0,
                           validators=[NumberRange(min=0, max=5)])
    q6 = IntegerRangeField(label=skill_names_list[6],
                           default=0,
                           validators=[NumberRange(min=0, max=5)])
    q7 = IntegerRangeField(label=skill_names_list[7],
                           default=0,
                           validators=[NumberRange(min=0, max=5)])
    q8 = IntegerRangeField(label=skill_names_list[8],
                           default=0,
                           validators=[NumberRange(min=0, max=5)])
    q9 = IntegerRangeField(label=skill_names_list[9],
                           default=0,
                           validators=[NumberRange(min=0, max=5)])
    q10 = IntegerRangeField(label=skill_names_list[10],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q11 = IntegerRangeField(label=skill_names_list[11],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q12 = IntegerRangeField(label=skill_names_list[12],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q13 = IntegerRangeField(label=skill_names_list[13],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q14 = IntegerRangeField(label=skill_names_list[14],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q15 = IntegerRangeField(label=skill_names_list[15],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q16 = IntegerRangeField(label=skill_names_list[16],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q17 = IntegerRangeField(label=skill_names_list[17],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q18 = IntegerRangeField(label=skill_names_list[18],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q19 = IntegerRangeField(label=skill_names_list[19],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q20 = IntegerRangeField(label=skill_names_list[20],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q21 = IntegerRangeField(label=skill_names_list[21],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q22 = IntegerRangeField(label=skill_names_list[22],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q23 = IntegerRangeField(label=skill_names_list[23],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q24 = IntegerRangeField(label=skill_names_list[24],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q25 = IntegerRangeField(label=skill_names_list[25],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q26 = IntegerRangeField(label=skill_names_list[26],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q27 = IntegerRangeField(label=skill_names_list[27],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q28 = IntegerRangeField(label=skill_names_list[28],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q29 = IntegerRangeField(label=skill_names_list[29],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q30 = IntegerRangeField(label=skill_names_list[30],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q31 = IntegerRangeField(label=skill_names_list[31],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q32 = IntegerRangeField(label=skill_names_list[32],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q33 = IntegerRangeField(label=skill_names_list[33],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
    q34 = IntegerRangeField(label=skill_names_list[34],
                            default=0,
                            validators=[NumberRange(min=0, max=5)])
Beispiel #6
0
class FoodForm(FlaskForm):
    name =StringField('name', validators=[InputRequired(), Length(min=1, max=20)])
    quantity = IntegerField('quantity', validators=[InputRequired(), NumberRange(min=0, max=100)])
    price = IntegerField('price', validators=[InputRequired(), NumberRange(min=0, max=100)])
    picture = FileField('picture', validators=[InputRequired()])
Beispiel #7
0
class Perchase_foodForm(FlaskForm):
    quantity = IntegerField('quantity', validators=[InputRequired(), NumberRange(min=0, max=100)])
Beispiel #8
0
class SettingsForm(Form):
    username = StringField("用户名: ", validators=[InputRequired()])
    age = IntegerField("年龄: ", validators=[NumberRange(10, 100)])
    remember = BooleanField("记住我: ")
    tags = SelectField("选项: ", choices=[('1',"python"), ('2',"ios")])
Beispiel #9
0
class CsvToDatabaseForm(DynamicForm):
    # pylint: disable=E0211
    def csv_enabled_dbs():
        return db.session.query(
            models.Database).filter_by(allow_csv_upload=True).all()

    sez = ''
    list = os.listdir('/etc/coliot/unirec/')

    for ln in list:
        sez = sez + ' <tr> <td>' + ln + '</td> <td>root</td> <td>28.08.2018 11:21</td> <td>.md</td> <td>342 Kb</td> <td><p data-placement="top" data-toggle="tooltip" title="Edit"><div class="btn btn-success btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" data-path="' + ln + '"><span class="glyphicon glyphicon-open"></span></div></p></td> </tr>'

    name = StringField(
        _('Table Name'),
        description=_('Name of table to be created from csv data.'),
        validators=[DataRequired()],
        widget=BS3TextFieldWidget())
    unirec_file = StringField(
        _('Select UniRec'),
        description=
        _('<div class="container"> <button type="button" class="btn btn-info" data-toggle="modal" data-target="#myModal">Select file</button>'
          '<!-- Modal --> '
          '<div class="modal fade" id="myModal" role="dialog" style="display: none;"> '
          '<div class="modal-dialog"> '
          '<!-- Modal content--> '
          '<div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button>'
          '<h4 class="modal-title">Chose file</h4> </div> <div class="modal-body"> '
          '<table id="mytable" class="table table-bordred table-striped"> '
          '<thead> '
          '<tr>'
          '<th>File name</th> <th>Author</th> <th>Data and time</th>'
          '<th>Format</th> '
          '<th>Size</th> '
          '<th>Translate</th> '
          '</tr>'
          '</thead> '
          '<tbody id="file_name"> </tbody> '
          '</table>'
          '</div> <div class="modal-footer"> </div> </div> </div> </div> </div>'
          ))
    con = QuerySelectField(_('Database'),
                           query_factory=csv_enabled_dbs,
                           get_pk=lambda a: a.id,
                           get_label=lambda a: a.database_name)
    if_exists = SelectField(
        _('Table Exists'),
        description=_('If table exists do one of the following: '
                      'Fail (do nothing), Replace (drop and recreate table) '
                      'or Append (insert data).'),
        choices=[('fail', _('Fail')), ('replace', _('Replace')),
                 ('append', _('Append'))],
        validators=[DataRequired()])
    schema = StringField(
        _('Schema'),
        description=_('Specify a schema (if database flavour supports this).'),
        validators=[Optional()],
        widget=BS3TextFieldWidget(),
        filters=[lambda x: x or None])
    header = IntegerField(_('Header Row'),
                          description=_(
                              'Row containing the headers to use as '
                              'column names (0 is first line of data). '
                              'Leave empty if there is no header row.'),
                          validators=[Optional()],
                          widget=BS3TextFieldWidget(),
                          filters=[lambda x: x or None])
    index_col = IntegerField(_('Index Column'),
                             description=_(
                                 'Column to use as the row labels of the '
                                 'dataframe. Leave empty if no index column.'),
                             validators=[Optional(),
                                         NumberRange(0, 1E+20)],
                             widget=BS3TextFieldWidget(),
                             filters=[lambda x: x or None])
    mangle_dupe_cols = BooleanField(
        _('Mangle Duplicate Columns'),
        description=_('Specify duplicate columns as "X.0, X.1".'))
    skipinitialspace = BooleanField(
        _('Skip Initial Space'), description=_('Skip spaces after delimiter.'))
    skiprows = IntegerField(
        _('Skip Rows'),
        description=_('Number of rows to skip at start of file.'),
        validators=[Optional(), NumberRange(0, 1E+20)],
        widget=BS3TextFieldWidget(),
        filters=[lambda x: x or None])
    nrows = IntegerField(_('Rows to Read'),
                         description=_('Number of rows of file to read.'),
                         validators=[Optional(),
                                     NumberRange(0, 1E+20)],
                         widget=BS3TextFieldWidget(),
                         filters=[lambda x: x or None])
    skip_blank_lines = BooleanField(
        _('Skip Blank Lines'),
        description=_('Skip blank lines rather than interpreting them '
                      'as NaN values.'))
    parse_dates = CommaSeparatedListField(
        _('Parse Dates'),
        description=_('A comma separated list of columns that should be '
                      'parsed as dates.'),
        filters=[filter_not_empty_values])
    infer_datetime_format = BooleanField(
        _('Infer Datetime Format'),
        description=_('Use Pandas to interpret the datetime format '
                      'automatically.'))
    decimal = StringField(
        _('Decimal Character'),
        description=_('Character to interpret as decimal point.'),
        validators=[Optional()],
        widget=BS3TextFieldWidget(),
        filters=[lambda x: x or '.'])
    index = BooleanField(_('Dataframe Index'),
                         description=_('Write dataframe index as a column.'))
    index_label = StringField(
        _('Column Label(s)'),
        description=_('Column label for index column(s). If None is given '
                      'and Dataframe Index is True, Index Names are used.'),
        validators=[Optional()],
        widget=BS3TextFieldWidget(),
        filters=[lambda x: x or None])
Beispiel #10
0
class CsvToDatabaseForm(DynamicForm):
    # pylint: disable=E0211
    def csv_allowed_dbs() -> List[Database]:  # type: ignore
        csv_enabled_dbs = (
            db.session.query(Database).filter_by(allow_csv_upload=True).all()
        )
        return [
            csv_enabled_db
            for csv_enabled_db in csv_enabled_dbs
            if CsvToDatabaseForm.at_least_one_schema_is_allowed(csv_enabled_db)
        ]

    @staticmethod
    def at_least_one_schema_is_allowed(database: Database) -> bool:
        """
        If the user has access to the database or all datasource
            1. if schemas_allowed_for_csv_upload is empty
                a) if database does not support schema
                    user is able to upload csv without specifying schema name
                b) if database supports schema
                    user is able to upload csv to any schema
            2. if schemas_allowed_for_csv_upload is not empty
                a) if database does not support schema
                    This situation is impossible and upload will fail
                b) if database supports schema
                    user is able to upload to schema in schemas_allowed_for_csv_upload
        elif the user does not access to the database or all datasource
            1. if schemas_allowed_for_csv_upload is empty
                a) if database does not support schema
                    user is unable to upload csv
                b) if database supports schema
                    user is unable to upload csv
            2. if schemas_allowed_for_csv_upload is not empty
                a) if database does not support schema
                    This situation is impossible and user is unable to upload csv
                b) if database supports schema
                    user is able to upload to schema in schemas_allowed_for_csv_upload
        """
        if security_manager.can_access_database(database):
            return True
        schemas = database.get_schema_access_for_csv_upload()
        if schemas and security_manager.get_schemas_accessible_by_user(
            database, schemas, False
        ):
            return True
        return False

    name = StringField(
        _("Table Name"),
        description=_("Name of table to be created from csv data."),
        validators=[DataRequired()],
        widget=BS3TextFieldWidget(),
    )
    csv_file = FileField(
        _("CSV File"),
        description=_("Select a CSV file to be uploaded to a database."),
        validators=[
            FileRequired(),
            FileAllowed(
                config["ALLOWED_EXTENSIONS"],
                _(
                    "Only the following file extensions are allowed: "
                    "%(allowed_extensions)s",
                    allowed_extensions=", ".join(config["ALLOWED_EXTENSIONS"]),
                ),
            ),
        ],
    )
    con = QuerySelectField(
        _("Database"),
        query_factory=csv_allowed_dbs,
        get_pk=lambda a: a.id,
        get_label=lambda a: a.database_name,
    )
    schema = StringField(
        _("Schema"),
        description=_("Specify a schema (if database flavor supports this)."),
        validators=[Optional()],
        widget=BS3TextFieldWidget(),
    )
    sep = StringField(
        _("Delimiter"),
        description=_("Delimiter used by CSV file (for whitespace use \\s+)."),
        validators=[DataRequired()],
        widget=BS3TextFieldWidget(),
    )
    if_exists = SelectField(
        _("Table Exists"),
        description=_(
            "If table exists do one of the following: "
            "Fail (do nothing), Replace (drop and recreate table) "
            "or Append (insert data)."
        ),
        choices=[
            ("fail", _("Fail")),
            ("replace", _("Replace")),
            ("append", _("Append")),
        ],
        validators=[DataRequired()],
    )
    header = IntegerField(
        _("Header Row"),
        description=_(
            "Row containing the headers to use as "
            "column names (0 is first line of data). "
            "Leave empty if there is no header row."
        ),
        validators=[Optional(), NumberRange(min=0)],
        widget=BS3TextFieldWidget(),
    )
    index_col = IntegerField(
        _("Index Column"),
        description=_(
            "Column to use as the row labels of the "
            "dataframe. Leave empty if no index column."
        ),
        validators=[Optional(), NumberRange(min=0)],
        widget=BS3TextFieldWidget(),
    )
    mangle_dupe_cols = BooleanField(
        _("Mangle Duplicate Columns"),
        description=_('Specify duplicate columns as "X.0, X.1".'),
    )
    skipinitialspace = BooleanField(
        _("Skip Initial Space"), description=_("Skip spaces after delimiter.")
    )
    skiprows = IntegerField(
        _("Skip Rows"),
        description=_("Number of rows to skip at start of file."),
        validators=[Optional(), NumberRange(min=0)],
        widget=BS3TextFieldWidget(),
    )
    nrows = IntegerField(
        _("Rows to Read"),
        description=_("Number of rows of file to read."),
        validators=[Optional(), NumberRange(min=0)],
        widget=BS3TextFieldWidget(),
    )
    skip_blank_lines = BooleanField(
        _("Skip Blank Lines"),
        description=_(
            "Skip blank lines rather than interpreting them " "as NaN values."
        ),
    )
    parse_dates = CommaSeparatedListField(
        _("Parse Dates"),
        description=_(
            "A comma separated list of columns that should be " "parsed as dates."
        ),
        filters=[filter_not_empty_values],
    )
    infer_datetime_format = BooleanField(
        _("Infer Datetime Format"),
        description=_("Use Pandas to interpret the datetime format " "automatically."),
    )
    decimal = StringField(
        _("Decimal Character"),
        default=".",
        description=_("Character to interpret as decimal point."),
        validators=[Optional(), Length(min=1, max=1)],
        widget=BS3TextFieldWidget(),
    )
    index = BooleanField(
        _("Dataframe Index"), description=_("Write dataframe index as a column.")
    )
    index_label = StringField(
        _("Column Label(s)"),
        description=_(
            "Column label for index column(s). If None is given "
            "and Dataframe Index is True, Index Names are used."
        ),
        validators=[Optional()],
        widget=BS3TextFieldWidget(),
    )
Beispiel #11
0
class ProductForm(Form):
    name = TextField('Name', [Length(max=255)])
    description = TextAreaField('Description')
    price = FloatField('price', [NumberRange(0.00), required()])
Beispiel #12
0
class BasePlanForm(Form):
    category = StringField('Category', [DataRequired()])
    load_unit = StringField('Load Unit', [DataRequired()])

    private = BooleanField('Private', [Optional()])
    active = BooleanField('Active', [Optional()])

    title = StringField('Title', [DataRequired(), Length(min=2, max=50)])
    description = StringField('Description', [
        DataRequired(), Length(min=5, max=500)
    ])

    cron = StringField('Cron', [DataRequired()])
    start_at = DateTimeField('Start at', [DataRequired()])
    end_at = DateTimeField('End at', [
        RequiredIfNot(['total_load', 'daily_load'], use_and=False), Optional(),
    ])

    load_index = IntegerField('Load Index', [NumberRange(min=0)])
    total_load = IntegerField('Total Load', [
        RequiredIfNot(['daily_load', 'end_at'], use_and=False), Optional(),
        NumberRange(min=0)
    ])
    daily_load = IntegerField('Daily Load', [
        RequiredIfNot(['total_load', 'end_at'], use_and=False), Optional(),
        NumberRange(min=0)
    ])

    def validate_total_load(form, field):
        daily_load = form.daily_load.data
        cron = form.cron.data
        start_at = form.start_at.data
        end_at = form.end_at.data

        # validate only when necessity condition is met.
        if not (daily_load and cron and start_at and end_at):
            return

        try:
            given = field.data
            expected = Plan.get_total_load_from(
                daily_load=daily_load, cron=cron,
                start_at=start_at, end_at=end_at,
            )
            if given and given != expected:
                raise ValidationError(
                    'Inconsistent total load: expected {}, given {}'
                    .format(expected, given)
                )
        # validate only the field that the validator is responsible of.
        except CronFormatError:
            pass

    def validate_daily_load(form, field):
        total_load = form.total_load.data,
        cron = form.cron.data,
        start_at = form.start_at.data
        end_at = form.end_at.data

        # validate only when necessity condition is met.
        if not (total_load and cron and start_at and end_at):
            return

        try:
            given = field.data
            expected = Plan.get_daily_load_from(
                total_load=total_load, cron=cron,
                start_at=start_at, end_at=end_at,
            )
            if given and given != expected:
                raise ValidationError(
                    'Inconsistent daily load: expected {}, given {}'
                    .format(expected, given)
                )
        # validate only the field that the validator is responsible of.
        except CronFormatError:
            pass

    def validate_cron(form, field):
        try:
            croniter(field.data)
        except (ValueError, AttributeError):
            raise ValidationError(
                'Invalid cron format: given {}'
                .format(field.data)
            )

    def validate_end_at(form, field):
        total_load = form.total_load.data
        daily_load = form.daily_load.data
        cron = form.cron.data
        start_at = form.start_at.data

        # validate only when necessity condition is met.
        if not (total_load and daily_load and cron and start_at):
            return

        try:
            given = field.data
            expected = Plan.get_end_from(
                total_load=total_load,
                daily_load=daily_load,
                cron=cron, start_at=start_at
            )

            if given and given != expected:
                raise ValidationError(
                    'Inconsistent end: expected {}, given {}'
                    .format(expected, given)
                )
        # validate only the field that the validator is responsible of.
        except CronFormatError:
            pass
Beispiel #13
0
class BaseStageForm(Form):
    plan = IntegerField('Plan', [NumberRange(min=0)])
    title = StringField('Title', [Length(min=2, max=50)])
    load = IntegerField('Load', [NumberRange(min=0)])
Beispiel #14
0
class CampaignForm(FlaskForm):
    next = HiddenField()
    name = TextField(_('Campaign Name'), [
        Required(),
        Unique(Campaign.name, message="Campaign with that name already exists")
    ])
    campaign_country = DisabledSelectField(_('Country'), [Optional()],
                                           choices=COUNTRY_CHOICES)
    campaign_type = DisabledSelectField(_('Type'), [Optional()])
    campaign_state = SelectField(_('State'), [Optional()])
    campaign_subtype = SelectField(_('Subtype'), [Optional()])
    # nested_type passed to data-field in template, but starts empty

    segment_by = RadioField(_('Segment By'), [Required()],
                            choices=choice_items(SEGMENT_BY_CHOICES),
                            description=True,
                            default=SEGMENT_BY_CHOICES[0][0])
    locate_by = RadioField(_('Locate By'), [Optional()],
                           choices=choice_items(LOCATION_CHOICES),
                           description=True,
                           default=None)
    show_special = BooleanField(_('Include Special Targets'), [Optional()],
                                default=False)
    include_special = SelectField(
        _('User\'s Representatives'), [Optional()],
        choices=choice_items(INCLUDE_SPECIAL_CHOCIES),
        description=True,
        default=INCLUDE_SPECIAL_CHOCIES[0][0])
    target_set = FieldList(FormField(TargetForm, _('Choose Targets')),
                           validators=[Optional()])
    target_ordering = RadioField(_('Target Order'), [Optional()],
                                 description=True)
    target_shuffle_chamber = BooleanField(_('Shuffle within Chamber'),
                                          [Optional()],
                                          default=True,
                                          description=True)
    target_offices = RadioField(_('Target Offices'), [Optional()],
                                choices=choice_items(TARGET_OFFICE_CHOICES),
                                description=True,
                                default=TARGET_OFFICE_CHOICES[0][0])

    call_limit = BooleanField(_('Limit Maximum Calls'), [Optional()],
                              default=False)
    call_maximum = IntegerField(_('Call Maximum'),
                                [Optional(), NumberRange(min=0)])

    phone_number_set = QuerySelectMultipleField(
        _('Select Phone Numbers'),
        query_factory=TwilioPhoneNumber.available_numbers,
        description=True,
        validators=[Required()])
    allow_call_in = BooleanField(_('Allow Call In'))
    allow_intl_calls = BooleanField(_('Allow International Calls'))
    prompt_schedule = BooleanField(_('Prompt to Schedule Recurring Calls'))

    submit = SubmitField(_('Edit Audio'))
    submit_skip_audio = SubmitField(_('Save and Test'))

    def __init__(self, campaign_data, *args, **kwargs):
        super(CampaignForm, self).__init__(*args, **kwargs)

        read_only(self.campaign_country)
        read_only(self.campaign_type)

        self.campaign_type.choices = choice_items(
            campaign_data.data_provider.campaign_type_choices)
        self.campaign_state.choices = choice_items(
            campaign_data.region_choices)
        self.campaign_subtype.choices = choice_items(
            campaign_data.subtype_choices)
        self.target_ordering.choices = choice_items(
            campaign_data.target_order_choices)

    def validate(self):
        # check default validation
        if not FlaskForm.validate(self):
            return False

        # check nested forms
        for t in self.target_set:
            if not t.form.validate():
                error_fields = ','.join(t.form.errors.keys())
                self.target_set.errors.append({
                    'target':
                    t.name,
                    'message':
                    'Invalid target ' + error_fields
                })
                return False

        return True
Beispiel #15
0
class UserInput(FlaskForm):
    budget = DecimalField('Budget',
                          validators=[
                              DataRequired(),
                              NumberRange(
                                  min=7500,
                                  message='Please enter a value above Rs.7500')
                          ])
    os = SelectField('Operating System',
                     choices=[('Android', 'Android'), ('iOS', 'iOS')],
                     validators=[DataRequired()])
    p1 = RadioField('Enter Your 1st Priority',
                    choices=[(1, 'Browsing Social Media'),
                             (2, 'Watching Videos or Movies'),
                             (3, 'Taking Photos And Videos'),
                             (4, 'Taking Selfies'), (5, 'Gaming'),
                             (6, 'Multitasking')],
                    validators=[DataRequired()])
    p2 = RadioField('Enter Your 2nd Priority',
                    choices=[(1, 'Browsing Social Media'),
                             (2, 'Watching Videos or Movies'),
                             (3, 'Taking Photos And Videos'),
                             (4, 'Taking Selfies'), (5, 'Gaming'),
                             (6, 'Multitasking')],
                    validators=[DataRequired()])
    p3 = RadioField('Enter Your 3rd Priority',
                    choices=[(1, 'Browsing Social Media'),
                             (2, 'Watching Videos or Movies'),
                             (3, 'Taking Photos And Videos'),
                             (4, 'Taking Selfies'), (5, 'Gaming'),
                             (6, 'Multitasking')],
                    validators=[DataRequired()])
    p4 = RadioField('Enter Your 4th Priority',
                    choices=[(1, 'Browsing Social Media'),
                             (2, 'Watching Videos or Movies'),
                             (3, 'Taking Photos And Videos'),
                             (4, 'Taking Selfies'), (5, 'Gaming'),
                             (6, 'Multitasking')],
                    validators=[DataRequired()])
    p5 = RadioField('Enter Your 5th Priority',
                    choices=[(1, 'Browsing Social Media'),
                             (2, 'Watching Videos or Movies'),
                             (3, 'Taking Photos And Videos'),
                             (4, 'Taking Selfies'), (5, 'Gaming'),
                             (6, 'Multitasking')],
                    validators=[DataRequired()])
    submit = SubmitField("Submit")

    def validate_p5(self, p5):
        if p5.data in [self.p1.data, self.p2.data, self.p3.data, self.p4.data]:
            raise ValidationError("You have already chosen this priority!")

    def validate_p4(self, p4):
        if p4.data in [self.p1.data, self.p2.data, self.p3.data]:
            raise ValidationError("You have already chosen this priority!")

    def validate_p3(self, p3):
        if p3.data in [self.p1.data, self.p2.data]:
            raise ValidationError("You have already chosen this priority!")

    def validate_p2(self, p2):
        if p2.data in [self.p1.data]:
            raise ValidationError("You have already chosen this priority!")
Beispiel #16
0
class DelayForm(FlaskForm):
    delay = IntegerField('Delay', validators=[InputRequired(), NumberRange(min=0, max=None, message='Must be a number > 0')])
Beispiel #17
0
class DrinkForm(FlaskForm):
    
    flavar=StringField('flavar', validators=[InputRequired(), Length(min=1, max=20)])
    price = IntegerField('price', validators=[InputRequired(), NumberRange(min=0, max=100)])
    picture = FileField('picture', validators=[InputRequired()])
Beispiel #18
0
class WLANAttack(FlaskForm):
    timeout = StringField('Timeout', validators=[NumberRange()])
    submit = SubmitField('Update')
Beispiel #19
0
class Perchase_drinkForm(FlaskForm):
    quantity = IntegerField('quantity', validators=[InputRequired(), NumberRange(min=0, max=100)])
    drinks_sizes = [(-1, 'Small'), (0, 'Medium'), (1, 'Large')]
    size = SelectField('size', choices = drinks_sizes)
    drink_tem = [('h', 'Hot'), ('c', 'Cold')]
    tem = SelectField('tem', choices = drink_tem)
Beispiel #20
0
class RadiusLogin(FlaskForm):
    timeout = StringField('Timeout', validators=[NumberRange()])
    duration = StringField('Duration', validators=[NumberRange()])
    count = StringField('Count', validators=[NumberRange()])
    submit = SubmitField('Update')
Beispiel #21
0
class UpdateTrackForm(FlaskForm):
    track_name = StringField('Track Name', validators=[DataRequired(), Length(min=2, max=20)])
    track_length = FloatField('Track Length', validators=[DataRequired()])
    # Validate that the track album_id is within the range of album album_ids
    album_id = IntegerField('Album ID', validators=[DataRequired(), NumberRange(min=Album.query.first().id, max=Album.query.order_by(Album.id.desc()).first().id)])
    submit = SubmitField('Update Track')
Beispiel #22
0
class ServicesCli(FlaskForm):
    mode_options = [('1', 'Enable'), ('2', 'Disable')]
    clish_mode = SelectField('Mode', choices=mode_options)
    ssh_mode = SelectField('Mode', choices=mode_options)
    ssh_port = StringField('Port', validators=[DataRequired(), NumberRange()])
    submit = SubmitField('Update')
Beispiel #23
0
class CreateEventForm(Form):
    """A form for the creation of a :class:`~app.models.Event` object.

    :ivar title: :class:`wtforms.fields.StringField` - The title of the event.
    :ivar slug: :class:`wtforms.fields.StringField` - A unique url fragment for
        this blog post. This may only contain letters, numbers, and dashes
        (``-``).
    :ivar location: :class:`wtforms.fields.StringField` - The location of the
        event.
    :ivar start_date: :class:`wtforms.fields.DateField` - The date the event
        starts on.
    :ivar end_date: :class:`wtforms.fields.DateField` - The date the event
        ends on.
    :ivar start_time: :class:`TimeField` - The time the event starts.
    :ivar end_time: :class:`TimeField` - The time the event ends.
    :ivar is_recurring: :class:`wtforms.fields.BooleanField` - True if the
        event is recurring.
    :ivar frequency: :class:`wtforms.fields.SelectField` - The interval of the
        occurrence. Can only take the value ``"weekly"``.
    :ivar every: :class:`wtforms.fields.IntegerField` - The number of
        ``frequency`` units after which the event repeats. For example,
        ``frequency = "weekly"`` and ``every = 2`` indicates that the event
        occurs every two weeks.
    :ivar ends: :class:`wtforms.fields.RadioField` - ``"after"`` if the event
        ends after ``num_occurrences`` occurrences, or ``"on"`` if the date
        ends on ``recurrence_end_date``.
    :ivar num_occurrences: :class:`wtforms.fields.IntegerField` - The number of
        occurrences for a recurring event.  Should be set only if ``ends`` is
        set to ``"after"``.
    :ivar recurrence_end_date: :class:`wtforms.fields.DateField` - The date
        that the recurrence ends on.  Should be set only if ``ends`` is set to
        ``"on"``.
    :ivar recurrence_summary: :class:`wtforms.fields.StringField` - A plain
        English explanation of the recurrence. Generated in JavaScript but
        stored here.
    :ivar short_description: :class:`wtforms.fields.TextAreaField` - The
        markdown text of the short description for the event.
    :ivar long_description: :class:`wtforms.fields.TextAreaField` - The
        markdown text of the long description for the event.
    :ivar published: :class:`wtforms.fields.BooleanField` - True if the event
        is published.
    :ivar facebook_url: :class:`wtforms.fields.StringField` - The URL of the
        associated Facebook event.
    :ivar event_image: :class:`wtforms.fields.StringField` - The filename of
        the headline image.
    """

    title = StringField('Title',
                        [Required(message="Please provide an event title.")])
    slug = StringField('Slug', [UniqueEvent(),
                                Regexp(Regex.SLUG_REGEX,
                                       message=INVALID_SLUG)])
    location = StringField('Location')
    start_date = DateField('Start date', [Optional()], format=DATE_FORMAT)
    start_time = TimeField('Start time', [Optional()])
    end_date = DateField('End date', [Optional()], format=DATE_FORMAT)
    end_time = TimeField('End time', [Optional()])
    is_recurring = BooleanField('Is Recurring')
    frequency = SelectField('Repeats', choices=[('weekly', 'Weekly')],
                            default="weekly")
    every = IntegerField('Every', [NumberRange(min=1, max=30)], default=1)
    ends = RadioField('Ends', choices=[("after", "After"), ("on", "On")],
                      default="after")
    num_occurrences = IntegerField('Every', [NumberRange(min=1)], default=1)
    recurrence_end_date = DateField('Repeat End Date', [Optional()],
                                    format=DATE_FORMAT)
    recurrence_summary = StringField('Summary')
    short_description = TextAreaField('Short description',
                                      default=SHORT_DESCRIPTION_PLACEHOLDER)
    long_description = TextAreaField('Long description',
                                     default=LONG_DESCRIPTION_PLACEHOLDER)
    published = BooleanField('Published')
    facebook_url = StringField('Facebook  URL', [Optional(), URL()])
    event_image = StringField('Image', [image_with_same_name])

    def post_validate(self, validation_stopped):
        """Make sure that the start datetime comes before the end datetime.


        :param self: The form to validate
        :type self: :class:`Form`
        :param bool validation_stopped: True if any validator raised
            :class:`~wtforms.validators.StopValidation`.
        :raises: :class:`wtforms.validators.ValidationError`
        """
        if not validation_stopped:
            start_date = self.start_date.data
            start_time = self.start_time.data
            end_date = self.end_date.data
            end_time = self.end_time.data

            # Start and end dates should be in order.
            if start_date and end_date and start_date > end_date:
                raise ValidationError("Start date should come before end date")
            if (all([start_date, start_time, end_date, end_time]) and
                    start_time > end_time):
                raise ValidationError("Start time should come before end date")
Beispiel #24
0
class VCRoomListFilterForm(IndicoForm):
    direction = SelectField(_('Sort direction'), [DataRequired()],
                            choices=[('asc', _('Ascending')), ('desc', _('Descending'))])
    abs_start_date = IndicoDateField(_('Start Date'), [Optional(), Exclusive('rel_start_date')])
    abs_end_date = IndicoDateField(_('End Date'), [Optional(), Exclusive('rel_end_date')])
    rel_start_date = IntegerField(_('Days in the past'), [Optional(), Exclusive('abs_start_date'), NumberRange(min=0)],
                                  default=0)
    rel_end_date = IntegerField(_('Days in the future'), [Optional(), Exclusive('abs_end_date'), NumberRange(min=0)],
                                default=7)

    @generated_data
    def start_date(self):
        if self.abs_start_date.data is None and self.rel_start_date.data is None:
            return None
        return self.abs_start_date.data or (date.today() - timedelta(days=self.rel_start_date.data))

    @generated_data
    def end_date(self):
        if self.abs_end_date.data is None and self.rel_end_date.data is None:
            return None
        return self.abs_end_date.data or (date.today() + timedelta(days=self.rel_end_date.data))
Beispiel #25
0
class PetForm(FlaskForm):
    name = StringField('Pet Name', validators=[InputRequired(message="Name canot be blanck")])
    speacies = SelectField('Species', choices=['Cat', 'Dog', 'Porcupine'])
    photo = StringField('Photo', validators=[URL()])
    age = FloatField("Age", validators=[NumberRange(min=0, max=30, message="Age canot be Over 30 or negative")])
    notes = StringField("Notes")
Beispiel #26
0
class SettingsForm(FlaskForm):
    theme = SelectField('Background', validators=[DataRequired()],
                        choices=['default', 'magic girl', 'Odyssey', 'lonely mountain', 'winter dreams',
                                 'people routine', 'house in the forest'])
    number_of_cards_in_hand = IntegerField('Number of cards in hand', validators=[DataRequired(), NumberRange(max=9,
                                           min=3)], default=6)
    number_of_cards_in_deck = IntegerField('Number of cards in deck', validators=[DataRequired(), NumberRange(max=72,
                                           min=31)], default=72)
    submit = SubmitField('Apply')
Beispiel #27
0
class GameInformation(FlaskForm):
    no_stats = SelectField('No Stats',
                           choices=[('Yes', 'Yes'), ('No', 'No')],
                           default='No')
    week = IntegerField('Week', validators=[Required(), NumberRange(0, 16)])
    added_by = HiddenField('Added By')

    home_team = SelectField('Home Team')
    home_score = IntegerField('Home Score',
                              validators=[Required(),
                                          NumberRange(0, 100)])

    away_team = SelectField('Away Team')
    away_score = IntegerField('Away Score',
                              validators=[Required(),
                                          NumberRange(0, 100)])

    winning_team = SelectField('Winning Team',
                               choices=[('Home', 'Home'), ('Away', 'Away')])

    home_passing_yards = IntegerField('Home Passing Yards',
                                      validators=[NumberRange(0, 1000)],
                                      default=0)
    home_rushing_yards = IntegerField('Home Rushing Yards',
                                      validators=[NumberRange(0, 1000)],
                                      default=0)
    home_turn_overs = IntegerField('Home Turnovers',
                                   validators=[NumberRange(0, 10)],
                                   default=0)
    home_qbr = DecimalField('Home QBR',
                            validators=[NumberRange(0, 159)],
                            default=0)

    away_passing_yards = IntegerField('Away Passing Yards',
                                      validators=[NumberRange(0, 1000)],
                                      default=0)
    away_rushing_yards = IntegerField('Away Rushing Yards',
                                      validators=[NumberRange(0, 1000)],
                                      default=0)
    away_turn_overs = IntegerField('Away Turnovers',
                                   validators=[NumberRange(0, 10)],
                                   default=0)
    away_qbr = DecimalField('Away QBR',
                            validators=[NumberRange(0, 159)],
                            default=0)

    submit = SubmitField('Add Game')

    def __init__(self, *args, **kwargs):
        super(GameInformation, self).__init__(*args, **kwargs)
        self.home_team.choices = [
            (team.team_name, team.team_name)
            for team in Teams.query.order_by(Teams.team_name).all()
        ]

        self.away_team.choices = [
            (team.team_name, team.team_name)
            for team in Teams.query.order_by(Teams.team_name).all()
        ]
Beispiel #28
0
class PostForm(FlaskForm):
    picture = FileField('Insert picture', validators=[InputRequired(),FileAllowed(['jpg', 'png','jpeg'])])
    colors=IntegerField('Enter no. of colors',
    	validators=[InputRequired(),NumberRange(min=2,max=64, message='Value must be between 2 and 64')])
    submit = SubmitField('Submit')
Beispiel #29
0
class SearchForm(Form):
    q = StringField(
        validators=[Length(min=1, max=30, message='+++q不在指定范围+++')])
    page = IntegerField(
        validators=[NumberRange(min=1, max=99, message='考虑一下,page是否错误?')],
        default=1)
Beispiel #30
0
class SearchForm(FlaskForm):
    # Brands
    brand = SelectMultipleField("Brand", choices=[(_, _) for _ in brands])

    # Min/max price
    min_price = FloatField("Min. Price",
                           default=0,
                           validators=[
                               InputRequired(),
                               LessThanEqualTo('max_price'),
                               NumberRange(min=0)
                           ])
    max_price = FloatField("Max. Price",
                           default=prices[MAX_PRICE],
                           validators=[
                               InputRequired(),
                               GreaterThanEqualTo('min_price'),
                               NumberRange(min=0)
                           ])

    # Min/max year
    min_year = FloatField("Min. Year",
                          default=0,
                          validators=[
                              InputRequired(),
                              LessThanEqualTo('max_year'),
                              NumberRange(min=0)
                          ])
    max_year = FloatField("Max. Year",
                          default=years[MAX_YR],
                          validators=[
                              InputRequired(),
                              GreaterThanEqualTo('min_year'),
                              NumberRange(min=0)
                          ])

    # Min/max range
    min_range = FloatField("Min. Range",
                           default=0,
                           validators=[
                               InputRequired(),
                               LessThanEqualTo('max_range'),
                               NumberRange(min=0)
                           ])
    max_range = FloatField("Max. Range",
                           default=range_capacities[MAX_RANGE],
                           validators=[
                               InputRequired(),
                               GreaterThanEqualTo('min_range'),
                               NumberRange(min=0)
                           ])

    # Drivetrain
    drivetrain = SelectMultipleField(
        "Drivetrain",
        # choices = [(_, _) for _ in drivetrains]
        choices=[("AWD", "All Wheel Drive (AWD)"),
                 ("RWD", "Rear Wheel Drive (RWD)"),
                 ("FWD", "Front Wheel Drive (FWD)")])

    # Form factor
    form_factor = SelectMultipleField(
        "Form Factor",
        choices=[(_, _) for _ in form_factors]
        # choices=[
        #     ("Compact", "Compact"),
        #     ("Hatchback", "Hatchback"),
        #     ("Small", "Small"),
        #     ("Large", "Large"),
        #     ("Mid-size", "Mid-size"),
        #     ("Minivan", "Minivan"),
        #     ("Sedan", "Sedan"),
        #     ("Sport", "Sport"),
        #     ("Station Wagon", "Station Wagon"),
        #     ("Subcompact", "Subcompact"),
        #     ("SUV", "SUV")
        # ]
    )

    # EV Type
    ev_type = SelectMultipleField(
        "Electric Type",
        # choices = [(_, _) for _ in ev_types]
        choices=[("BEV", "Battery Electric Vehicle (BEV)"),
                 ("PHEV", "Plug-in Hybrid Electric Vehicle (PHEV)"),
                 ("HFCV", "Hydrogen Fuel Cell Vehicle (HFCV)")])

    # Min/max power (horsepower)
    min_power = FloatField("Min. Power",
                           default=0,
                           validators=[
                               InputRequired(),
                               LessThanEqualTo('max_power'),
                               NumberRange(min=0)
                           ])
    max_power = FloatField("Max. Power",
                           default=powers[MAX_POWER],
                           validators=[
                               InputRequired(),
                               GreaterThanEqualTo('min_power'),
                               NumberRange(min=0)
                           ])

    submit = SubmitField("Search")  # Submit button