Beispiel #1
0
class TagForm(FlaskForm):
    tag = StringField('添加标签 (空格分割)', validators=[Optional(), Length(0, 64)])
    submit = SubmitField()
Beispiel #2
0
class UploadForm(FlaskForm):
    torrent_file = FileField('Torrent file', [FileRequired()])

    display_name = StringField('Torrent display name (optional)', [
        Optional(),
        Length(
            min=3,
            max=255,
            message=
            'Torrent display name must be at least %(min)d characters long and '
            '%(max)d at most.')
    ])

    recaptcha = RecaptchaField(validators=[upload_recaptcha_validator_shim])

    category = DisabledSelectField('Category')

    def validate_category(form, field):
        cat_match = re.match(r'^(\d+)_(\d+)$', field.data)
        if not cat_match:
            raise ValidationError('Please select a category')

        main_cat_id = int(cat_match.group(1))
        sub_cat_id = int(cat_match.group(2))

        cat = models.SubCategory.by_category_ids(main_cat_id, sub_cat_id)

        if not cat:
            raise ValidationError('Please select a proper category')

        field.parsed_data = cat

    is_hidden = BooleanField('Hidden')
    is_remake = BooleanField('Remake')
    is_anonymous = BooleanField('Anonymous')
    is_complete = BooleanField('Complete')
    is_trusted = BooleanField('Trusted')

    information = StringField('Information', [
        Length(max=255,
               message='Information must be at most %(max)d characters long.')
    ])
    description = TextAreaField('Description', [
        Length(max=10 * 1024,
               message='Description must be at most %(max)d characters long.')
    ])

    ratelimit = HiddenField()

    def validate_torrent_file(form, field):
        # Decode and ensure data is bencoded data
        try:
            torrent_dict = bencode.decode(field.data)
            # field.data.close()
        except (bencode.MalformedBencodeException, UnicodeError):
            raise ValidationError('Malformed torrent file')

        # Uncomment for debug print of the torrent
        # _debug_print_torrent_metadata(torrent_dict)

        try:
            _validate_torrent_metadata(torrent_dict)
        except AssertionError as e:
            raise ValidationError('Malformed torrent metadata ({})'.format(
                e.args[0]))

        site_tracker = app.config.get('MAIN_ANNOUNCE_URL')
        ensure_tracker = app.config.get('ENFORCE_MAIN_ANNOUNCE_URL')

        try:
            tracker_found = _validate_trackers(torrent_dict, site_tracker)
        except AssertionError as e:
            raise ValidationError('Malformed torrent trackers ({})'.format(
                e.args[0]))

        # Ensure private torrents are using our tracker
        if torrent_dict['info'].get('private') == 1:
            if torrent_dict['announce'].decode('utf-8') != site_tracker:
                raise ValidationError(
                    'Private torrent: please set {} as the main tracker'.
                    format(site_tracker))

        elif ensure_tracker and not tracker_found:
            raise ValidationError(
                'Please include {} in the trackers of the torrent'.format(
                    site_tracker))

        # Note! bencode will sort dict keys, as per the spec
        # This may result in a different hash if the uploaded torrent does not match the
        # spec, but it's their own fault for using broken software! Right?
        bencoded_info_dict = bencode.encode(torrent_dict['info'])
        info_hash = utils.sha1_hash(bencoded_info_dict)

        # Check if the info_hash exists already in the database
        existing_torrent = models.Torrent.by_info_hash(info_hash)
        existing_torrent_id = existing_torrent.id if existing_torrent else None
        if existing_torrent and not existing_torrent.deleted:
            raise ValidationError('This torrent already exists (#{})'.format(
                existing_torrent.id))
        if existing_torrent and existing_torrent.banned:
            raise ValidationError('This torrent is banned'.format(
                existing_torrent.id))

        # Torrent is legit, pass original filename and dict along
        field.parsed_data = TorrentFileData(
            filename=os.path.basename(field.data.filename),
            torrent_dict=torrent_dict,
            info_hash=info_hash,
            bencoded_info_dict=bencoded_info_dict,
            db_id=existing_torrent_id)
Beispiel #3
0
class UserForm(FlaskForm):
    """WTForm for users to edit profile"""
    email = StringField('E-mail', validators=[Optional(), Email()])
    bio = TextAreaField('Bio', render_kw={'rows': 5})
    submit_user = SubmitField('Save')
Beispiel #4
0
class LandingAddressForm(FlaskForm):
    street_address = StringField('Street Address', validators=[Optional()])
    street_number = StringField('Street Number', validators=[Optional()])
    route = StringField('Route', validators=[Optional()])
    apt_number = StringField('Apt / Unit #', validators=[Optional()])
    locality = StringField('City', validators=[Optional()])
    administrative_area_level_1 = SelectField('State', choices=[
        ('', ''),
        ('AK', 'Alaska'),
        ('AL', 'Alabama'),
        ('AR', 'Arkansas'),
        ('AZ', 'Arizona'),
        ('CA', 'California'),
        ('CT', 'Connecticut'),
        ('DC', 'Washington DC'),
        ('DE', 'Delaware'),
        ('FL', 'Florida'),
        ('GA', 'Georgia'),
        ('HI', 'Hawaii'),
        ('IA', 'Iowa'),
        ('ID', 'Idaho'),
        ('IL', 'Illinois'),
        ('IN', 'Indiana'),
        ('KS', 'Kansas'),
        ('KY', 'Kentucky'),
        ('LA', 'Louisiana'),
        ('MA', 'Massachusetts'),
        ('MA', 'Massachusetts'),
        ('MD', 'Maryland'),
        ('ME', 'Maine'),
        ('MI', 'Michigan'),
        ('MN', 'Minnesota'),
        ('MO', 'Missouri'),
        ('MS', 'Mississippi'),
        ('MT', 'Montana'),
        ('NC', 'North Carolina'),
        ('ND', 'North Dakota'),
        ('NE', 'Nebraska'),
        ('NH', 'New Hampshire'),
        ('NJ', 'New Jersey'),
        ('NM', 'New Mexico'),
        ('NV', 'Nevada'),
        ('NY', 'New York'),
        ('OH', 'Ohio'),
        ('OK', 'Oklahoma'),
        ('OR', 'Oregon'),
        ('PA', 'Pennsylvania'),
        ('RI', 'Rhode Island'),
        ('SC', 'South Carolina'),
        ('SD', 'South Dakota'),
        ('TN', 'Tennessee'),
        ('TX', 'Texas'),
        ('UT', 'Utah'),
        ('VA', 'Virginia'),
        ('VT', 'Vermont'),
        ('WA', 'Washington'),
        ('WI', 'Wisconsin'),
        ('WV', 'West Virginia'),
        ('WY', 'Wyoming')
    ], validators=[Optional()])
    postal_code = StringField('ZIP Code', validators=[Optional()])
    country = StringField('Country', validators=[Optional()])
Beispiel #5
0
class PollForm(FlaskForm):
    poll_text = TextField('Poll Text', validators=[DataRequired()])
    user_tag = StringField('User Tag', validators=[Optional()])
Beispiel #6
0
class HomeownerLocationForm(FlaskForm):

    streetNumber = IntegerField(
        'Street Number',
        validators=[InputRequired("Please enter a street number")],
        render_kw={
            "icon": "home",
            "required": False,
            "helperText": "Ex. 1234"
        })

    streetName = StringField(
        'Street Name',
        validators=[
            InputRequired("Please enter a street name"),
            Length(
                min=1,
                max=200,
                message="Please enter a street name less that 200 characters.")
        ],
        render_kw={
            "icon": "home",
            "required": False,
            "helperText": "Ex. Front St."
        })

    city = StringField(
        'City',
        validators=[
            InputRequired("Please enter a city"),
            Length(min=1,
                   max=100,
                   message="Please enter a city less that 100 characters.")
        ],
        render_kw={
            "icon": "location_city",
            "required": False,
            "helperText": "Ex. Toronto"
        })

    province = StringField(
        'Province',
        validators=[
            InputRequired("Please enter a province"),
            Length(min=1,
                   max=100,
                   message="Please enter a city less that 100 characters.")
        ],
        render_kw={
            "icon": "location_city",
            "required": False,
            "helperText": "Ex. Ontario"
        })

    postalCode = StringField(
        'Postal Code',
        validators=[
            InputRequired("Please enter a postal code"),
            Length(
                min=1,
                max=10,
                message="Please enter a postal code less that 10 characters.")
        ],
        render_kw={
            "icon": "markunread_mailbox",
            "required": False,
            "helperText": "Ex. L1T 0E2"
        })

    poBox = StringField('P.O. Box',
                        validators=[Optional()],
                        render_kw={
                            "icon": "markunread_mailbox",
                            "required": False,
                            "helperText": "Ex. 1234"
                        })

    unitNumber = StringField(
        'Unit Number',
        validators=[
            Optional(),
            Length(
                min=1,
                max=10,
                message="Please enter a unit number less that 10 characters.")
        ],
        render_kw={
            "icon": "home",
            "required": False,
            "helperText": "Ex. 1234"
        })
Beispiel #7
0
class ImageFilterForm(Form):
    start_date = DateField('Start date', validators=[Optional()])
    end_date = DateField('End date', validators=[Optional()])
    filter = SubmitField('filter')
Beispiel #8
0
class PIDModBase(FlaskForm):
    function_id = StringField('Function ID', widget=widgets.HiddenInput())
    function_type = StringField('Function Type', widget=widgets.HiddenInput())
    name = StringField(TRANSLATIONS['name']['title'],
                       validators=[DataRequired()])
    measurement = StringField(TRANSLATIONS['measurement']['title'],
                              validators=[DataRequired()])
    direction = SelectField(lazy_gettext('Direction'),
                            choices=[('raise', lazy_gettext('Raise')),
                                     ('lower', lazy_gettext('Lower')),
                                     ('both', lazy_gettext('Both'))],
                            validators=[DataRequired()])
    period = DecimalField(
        TRANSLATIONS['period']['title'],
        validators=[validators.NumberRange(min=1, max=86400)],
        widget=NumberInput(step='any'))
    log_level_debug = BooleanField(TRANSLATIONS['log_level_debug']['title'])
    start_offset = DecimalField(TRANSLATIONS['start_offset']['title'],
                                widget=NumberInput(step='any'))
    max_measure_age = DecimalField(
        TRANSLATIONS['max_age']['title'],
        validators=[validators.NumberRange(min=1, max=86400)],
        widget=NumberInput(step='any'))
    setpoint = DecimalField(
        TRANSLATIONS['setpoint']['title'],
        validators=[validators.NumberRange(min=-1000000, max=1000000)],
        widget=NumberInput(step='any'))
    band = DecimalField(lazy_gettext('Band (+/- Setpoint)'),
                        widget=NumberInput(step='any'))
    store_lower_as_negative = BooleanField(
        lazy_gettext('Store Lower as Negative'))
    k_p = DecimalField(lazy_gettext('Kp Gain'),
                       validators=[validators.NumberRange(min=0)],
                       widget=NumberInput(step='any'))
    k_i = DecimalField(lazy_gettext('Ki Gain'),
                       validators=[validators.NumberRange(min=0)],
                       widget=NumberInput(step='any'))
    k_d = DecimalField(lazy_gettext('Kd Gain'),
                       validators=[validators.NumberRange(min=0)],
                       widget=NumberInput(step='any'))
    integrator_max = DecimalField(lazy_gettext('Integrator Min'),
                                  widget=NumberInput(step='any'))
    integrator_min = DecimalField(lazy_gettext('Integrator Max'),
                                  widget=NumberInput(step='any'))
    raise_output_id = StringField(lazy_gettext('Output (Raise)'))
    lower_output_id = StringField(lazy_gettext('Output (Lower)'))
    setpoint_tracking_type = StringField(
        TRANSLATIONS['setpoint_tracking_type']['title'])
    setpoint_tracking_method_id = StringField('Setpoint Tracking Method')
    setpoint_tracking_input_math_id = StringField(
        'Setpoint Tracking Input/Math')
    setpoint_tracking_max_age = DecimalField('Max Age (seconds)',
                                             validators=[Optional()],
                                             widget=NumberInput(step='any'))
    pid_mod = SubmitField(TRANSLATIONS['save']['title'])
    pid_hold = SubmitField(lazy_gettext('Hold'))
    pid_pause = SubmitField(lazy_gettext('Pause'))
    pid_resume = SubmitField(lazy_gettext('Resume'))
    pid_delete = SubmitField(TRANSLATIONS['delete']['title'])
    pid_activate = SubmitField(TRANSLATIONS['activate']['title'])
    pid_deactivate = SubmitField(TRANSLATIONS['deactivate']['title'])
    order_up = SubmitField(TRANSLATIONS['up']['title'])
    order_down = SubmitField(TRANSLATIONS['down']['title'])

    pid_autotune_noiseband = DecimalField(lazy_gettext('Noise Band'),
                                          widget=NumberInput(step='any'))
    pid_autotune_outstep = DecimalField(lazy_gettext('Outstep'),
                                        widget=NumberInput(step='any'))
    pid_autotune = SubmitField(lazy_gettext('Start Autotune'))
Beispiel #9
0
class SearchPlayerForm(Form):
    player_name = StringField('Username', validators=[])
    aga_id = StringField('AGA id', validators=[Optional()])
    submit = SubmitField()
Beispiel #10
0
class RoleForm(Form):
    roles = SelectField(u'Роль', validators=[Optional()], choices=[])
Beispiel #11
0
class MemberDetailsForm(FlaskForm):
    member_id = HiddenField(label='Member Id')
    status = SelectField(label='Status',
                         choices=MemberStatus.choices(),
                         coerce=MemberStatus.coerce)
    first_name = StringField(label='First Name', validators=[InputRequired()])
    last_name = StringField(label='last_name', validators=[InputRequired()])
    proposer = SelectField(label='Proposer', coerce=int)
    email = StringField(label='Email', validators=[InputRequired()])
    address = StringField(label='Address')
    post_code = StringField(label='Post Code')
    phone = StringField(label='Phone')
    accepted_date = DateField(label='accepted')
    handicap = StringField(label='Handicap')
    as_of = DateField(label='as of', validators=[Optional()])
    access = SelectField(label='Access',
                         choices=UserRole.choices(),
                         coerce=UserRole.coerce)
    save = SubmitField(label='Save')
    member_id_return = HiddenField()
    name_return = HiddenField()
    status_return = HiddenField()
    handicap_return = HiddenField()

    def validate(self):
        new_member = self.member_id.data == 0
        self.member_id.data = self.member_id_return.data
        self.proposer.choices = get_member_select_choices()
        if not super(MemberDetailsForm, self).validate():
            return False
        result = True
        if new_member:
            current_members = [
                n.full_name().lower()
                for n in get_current_members_as_players()
            ]
            name = self.first_name.data + ' ' + self.last_name.data
            if name.lower() in current_members:
                self.first_name.errors.append(
                    '{} is already a member'.format(name))
                result = False
            date = datetime.date.today()
            current_guests = [
                n.full_name().lower()
                for n in get_players_as_of(date, PlayerStatus.guest)
            ]
            if not name.lower() in current_guests:
                self.first_name.errors.append(
                    '{} has not been a guest'.format(name))
                result = False
            else:
                player = get_player_by_name(name)
                self.handicap_return.data = player.handicaps[-1].handicap
                self.status_return.data = str(
                    player.handicaps[-1].status.value)

        return result

    def populate_member(self, member_id):
        new_member = member_id == 0
        if new_member:
            self.first_name.data = 'new'
            self.last_name.data = 'member'
            self.status_return.data = MemberStatus.full_member.value
            self.handicap_return.data = 0
            set_select_field_new(self.proposer,
                                 get_member_select_choices(),
                                 item_name='proposer')
        else:
            member = get_member(member_id)
            proposer = member.proposer_id if member.proposer else 0
            set_select_field_new(self.proposer,
                                 get_member_select_choices(),
                                 default_selection=proposer,
                                 item_name='proposer')
            player = member.player
            contact = member.contact
            state = player.state_as_of(datetime.date.today())
            set_select_field_new(self.status,
                                 MemberStatus.choices(),
                                 default_selection=member.status)
            self.status_return.data = member.status.value
            self.first_name.data = player.first_name
            self.last_name.data = player.last_name
            self.name_return.data = self.first_name.data + ' ' + self.last_name.data
            self.email.data = contact.email
            self.address.data = contact.address
            self.post_code.data = contact.post_code
            self.phone.data = contact.phone
            self.accepted_date.data = member.accepted or datetime.date(
                1992, 6, 17)
            self.handicap_return.data = self.handicap.data = state.handicap
            self.as_of.data = state.date
            role = member.user.roles[-1].role if member.user else UserRole.user
            set_select_field_new(self.access,
                                 UserRole.choices(),
                                 default_selection=role)

    def save_member(self, member_id):
        member = {
            'first_name': self.first_name.data,
            'last_name': self.last_name.data,
            'handicap': float(self.handicap.data or self.handicap_return.data),
            'status': self.status.data,
            'as_of': self.as_of.data,
            'proposer_id': self.proposer.data,
            'email': self.email.data,
            'address': self.address.data,
            'post_code': self.post_code.data,
            'phone': self.phone.data,
            'accepted': self.accepted_date.data,
            'orig_name': self.name_return.data,
            'orig_status': int(self.status_return.data),
            'orig_handicap': float(self.handicap_return.data),
            'access': self.access.data
        }
        save_member(member_id, member)
        return True
Beispiel #12
0
class BugReportForm(FlaskForm):
    program = SelectField('Program', validators=[InputRequired()], coerce=int)

    reportType = SelectField("Report Type",
                             choices=[(1, "Coding Error"), (2, "Design Issue"),
                                      (3, "Suggestion"), (4, "Documentation"),
                                      (5, "Hardware"), (6, "Query")],
                             validators=[InputRequired()],
                             coerce=int)
    severity = SelectField("Severity",
                           choices=[(3, "Minor"), (2, "Serious"),
                                    (1, "Fatal")],
                           validators=[InputRequired()],
                           coerce=int)
    summary = TextAreaField(
        "Summary", validators=[DataRequired(),
                               Length(min=1, max=400)])
    reproducable = BooleanField("Reproducable")
    description = TextAreaField(
        "Description", validators=[DataRequired(),
                                   Length(min=1, max=400)])
    suggestedFix = TextAreaField(
        "Description", validators=[Optional(),
                                   Length(min=1, max=400)])
    reportedBy = SelectField('Reported By',
                             validators=[InputRequired()],
                             coerce=int)
    discoveredDate = DateField('Discovered Date', default=date.today)
    assignedTo = SelectField('Assigned To',
                             validators=[Optional()],
                             coerce=int)
    comments = TextAreaField("comments",
                             validators=[Optional(),
                                         Length(min=1, max=400)])
    status = SelectField("Status",
                         choices=[(-1, ''), (1, "Open"), (2, "Closed")],
                         validators=[Optional()],
                         coerce=int)
    priority = SelectField("Priority",
                           choices=[(-1, ''), (1, "Fix immediately"),
                                    (2, "Fix as soon as possible"),
                                    (3, "Fix before next milestone"),
                                    (4, "Fix before release"),
                                    (5, "Fix if possible"), (6, "Optional")],
                           validators=[Optional()],
                           coerce=int)
    resolution = SelectField("Resolution",
                             choices=[(-1, ''), (1, "Pending"), (2, "Fixed"),
                                      (3, "Irreproducible"), (4, "Deferred"),
                                      (5, "As designed"),
                                      (6, "Withdrawn by reporter"),
                                      (7, "Need more info"),
                                      (8, "Disagree with suggestion"),
                                      (9, "Duplicate")],
                             validators=[Optional()],
                             coerce=int)
    resolutionVersion = IntegerField(
        "Resolution Version",
        validators=[
            Optional(),
            NumberRange(1, 1000,
                        "Resolution Version must be between 1 and 1000")
        ])
    resolvedBy = SelectField("Resolved By",
                             validators=[Optional()],
                             coerce=int)
    resolvedDate = DateField("Resolved Date", validators=[Optional()])
    testedBy = SelectField("Tested By", validators=[Optional()], coerce=int)
    testedDate = DateField("Tested Date", validators=[Optional()])
    deferred = BooleanField("Deferred")
Beispiel #13
0
class SearchForm(FlaskForm):
    program = SelectField('Program', validators=[Optional()], coerce=int)
    reportType = SelectField("Report Type",
                             choices=[(-1, ''), (1, "Coding Error"),
                                      (2, "Suggestion"), (3, "Documentation"),
                                      (4, "Hardware"), (5, "Query")],
                             default='',
                             validators=[Optional()],
                             coerce=int)
    severity = SelectField("Severity",
                           choices=[(-1, ''), (3, "Minor"), (2, "Serious"),
                                    (1, "Fatal")],
                           default='',
                           validators=[Optional()],
                           coerce=int)

    areaName = SelectField('Functional Area', validators=[Optional()])
    assignedTo = SelectField('Assigned To',
                             validators=[Optional()],
                             coerce=int)
    status = SelectField("Status",
                         choices=[(-1, ''), (1, "Open"), (2, "Closed")],
                         default='',
                         validators=[Optional()],
                         coerce=int)
    priority = SelectField("Priority",
                           choices=[(-1, ''), (1, "Fix immediately"),
                                    (2, "Fix as soon as possible"),
                                    (3, "Fix before next milestone"),
                                    (4, "Fix before release"),
                                    (5, "Fix if possible"), (6, "Optional")],
                           default='',
                           validators=[Optional()],
                           coerce=int)
    resolution = SelectField("Resolution",
                             choices=[(-1, ''), (1, "Pending"), (2, "Fixed"),
                                      (3, "Irreproducible"), (4, "Deferred"),
                                      (5, "As designed"),
                                      (6, "Withdrawn by reporter"),
                                      (7, "Need more info"),
                                      (8, "Disagree with suggestion"),
                                      (9, "Duplicate")],
                             default='',
                             validators=[Optional()],
                             coerce=int)
    reportedBy = SelectField('Reported By',
                             validators=[Optional()],
                             coerce=int)
    discoveredDate = DateField('Discovered Date',
                               validators=[Optional()],
                               default='')
    resolvedBy = SelectField("Resolved By",
                             validators=[Optional()],
                             coerce=int)
Beispiel #14
0
class editFuncAreaForm(FlaskForm):
    program = SelectField('Program', validators=[Optional()], coerce=int)
    area = StringField('Functional Area',
                       validators=[DataRequired(),
                                   Length(min=1, max=40)])
Beispiel #15
0
class NewFolloups(FlaskForm):
    dtof = DateTimeField('Date and Time of Appointment', format='%Y-%m-%d %H:%M', validators=[InputRequired()])
    stage = IntegerField('Stage of fu', validators=[InputRequired()])
    eyes = RadioField('OD or OS', choices=[('R', 'OD'), ('L', 'OS')])
    md = FloatField('MD', validators=[Optional()])
    psd = FloatField('PSD', validators=[Optional()])
    iop1 = IntegerField('IOP 1', validators=[NumberRange(max=99), Optional()])
    iop2 = IntegerField('IOP 2', validators=[NumberRange(max=99), Optional()])
    vfi = IntegerField('VFI', validators=[NumberRange(max=999), Optional()])
    cct = IntegerField('CCT', validators=[NumberRange(max=999), Optional()])
    rnfl = IntegerField('Average RNFL', validators=[NumberRange(max=999), Optional()])
    rim = FloatField('RIM', validators=[Optional()])
    disc = FloatField('Disc Area', validators=[Optional()])
    vcd = FloatField('VCD', validators=[Optional()])
    cup = FloatField('Cup Volume', validators=[Optional()])
    re = StringField('Remarks', validators=[Optional()])
    addfu = SubmitField('Add a new follow up record')
Beispiel #16
0
class RecipeForm(FlaskForm):
    ingredient_name = StringField('Ingredient Name',validators=[DataRequired()], description="Please enter ingredient name.")
    measurements = StringField('Measurement', widget=TextArea(), validators=[DataRequired()], description="Please enter recipe measurements.")
    calories = IntegerField('Calorie Count',validators=[DataRequired()], description="Please enter ingredient calories.")
    recipe_name = StringField('Recipe Name',validators=[DataRequired()], description="Please enter name of recipe.")
    prep_time = StringField('Preparation Time', validators=[DataRequired()], description="Please enter amount of time for prepare recipe.")
    procedure = StringField('Procedure', widget=TextArea(), validators=[DataRequired()], description="Please enter recipe procedure.")
    mealtype = SelectField('Meal Type', choices= [('Breakfast'), ('Lunch'), ('Dinner')], validators=[Optional()], description="Please select type of meal.")  
    servings = IntegerField('Servings',validators=[DataRequired()], description="Please enter amount of servings.")
    photo = FileField('Photo', validators=[FileRequired(), FileAllowed(['jpg', 'png', 'Photos only!'])], description="Add a Photo of the meal.")
Beispiel #17
0
class UpdateFollowup(FlaskForm):
    md = FloatField('MD', validators=[Optional()])
    psd = FloatField('PSD', validators=[Optional()])
    iop1 = IntegerField('IOP 1', validators=[NumberRange(max=99), Optional()])
    iop2 = IntegerField('IOP 2', validators=[NumberRange(max=99), Optional()])
    vfi = IntegerField('VFI', validators=[NumberRange(max=999), Optional()])
    cct = IntegerField('CCT', validators=[NumberRange(max=999), Optional()])
    rnfl = IntegerField('Average RNFL', validators=[NumberRange(max=999), Optional()])
    rim = FloatField('RIM', validators=[Optional()])
    disc = FloatField('Disc Area', validators=[Optional()])
    vcd = FloatField('VCD', validators=[Optional()])
    cup = FloatField('Cup Volume', validators=[Optional()])
    re = StringField('Remarks', validators=[Optional()])
    updatefu = SubmitField('Update follow up record')
Beispiel #18
0
class EditNotificationForm(Form):
    type = HiddenField()
    description = TextField(
        u'Description', [Required(), Length(max=255)],
        description=u'Brief description of this notification')
    suppress_timestamp = BooleanField(
        u'Suppress Timestamp?', [Optional()],
        description=u'Removes Timestamp from Message Body and Subject')
    time_field = FormField(TimeSettingsInternalForm)
    subscriptions = MultiCheckboxField(
        u'Notification Events',
        choices=[(str(k), v) for k, v in SUBSCRIPTIONS.iteritems()])

    def populate_settings(self, settings, id=None):
        settings['subscriptions'] = self.populate_setting(
            'subscriptions',
            json.dumps({str(k): True
                        for k in self.subscriptions.data}))
        settings['starttime'] = self.populate_setting(
            'starttime', self.time_field.starttime.data or '00:00:00')
        settings['endtime'] = self.populate_setting(
            'endtime', self.time_field.endtime.data or '23:59:59')
        settings['delay'] = self.populate_setting(
            'delay', self.time_field.delaytime.data)
        settings['suppress'] = self.populate_setting(
            'suppress', self.time_field.suppress.data)
        settings['suppress_timestamp'] = self.populate_setting(
            'suppress_timestamp', self.suppress_timestamp.data)

    def populate_from_settings(self, id):
        subscriptions = self.populate_from_setting(id, 'subscriptions')
        if subscriptions:
            self.subscriptions.data = [
                k if v == True else False
                for k, v in json.loads(subscriptions).iteritems()
            ]

        self.time_field.starttime.data = self.populate_from_setting(
            id, 'starttime', default='00:00:00')
        self.time_field.endtime.data = self.populate_from_setting(
            id, 'endtime', default='23:59:59')
        self.time_field.delaytime.data = self.populate_from_setting(id,
                                                                    'delay',
                                                                    default=0)
        # HACK: workaround for bad form that was pushed up.
        if self.time_field.delaytime.data is None or self.time_field.delaytime.data == '':
            self.time_field.delaytime.data = 0
        self.time_field.suppress.data = self.populate_from_setting(
            id, 'suppress', default=False)
        self.suppress_timestamp.data = self.populate_from_setting(
            id, 'suppress_timestamp', default=False)

    def populate_setting(self, name, value, id=None):
        if id is not None:
            setting = NotificationSetting.query.filter_by(notification_id=id,
                                                          name=name).first()
        else:
            setting = NotificationSetting(name=name)

        setting.value = value

        return setting

    def populate_from_setting(self, id, name, default=None):
        ret = default

        setting = NotificationSetting.query.filter_by(notification_id=id,
                                                      name=name).first()
        if setting is not None:
            ret = setting.value

        return ret
Beispiel #19
0
    class SettingstableForm(Form, FormMixin):
        settings_name = StringField(
            'settings name',
            description='unique name for settings used to autopopulate',
            validators=[InputRequired(), Length(max=63)])
        description = TextAreaField(
            'description',
            description='longer description to describe settings',
            validators=[Optional(), Length(max=4000)],
            render_kw={'nullable': True})
        func = FormField(FuncForm)
        global_settings = DictField(
            'global settings',
            description=
            'dict of keyword arguments to pass to function for every entry',
            validators=[InputRequired(),
                        JsonSerializableValidator(dict)])
        entry_settings = DictField(
            'entry settings',
            description=
            'dict of keyword arguments to pass to function specific to each entry as defined by columns of the joined table',
            validators=[InputRequired(),
                        JsonSerializableValidator(dict)])
        fetch_method = SelectField(
            'fetch method',
            description='method used to fetch data',
            choices=[('fetch1', 'fetch1'), ('fetch', 'fetch')],
        )
        fetch_tables = FieldList(FormField(FetchTableForm),
                                 label='fetch tables',
                                 min_entries=1,
                                 render_kw={'nullable': True})
        assign_output = SelectField(
            'assign output',
            description='assign the output of the function to a single column',
            choices=[('NULL', 'NULL')] +
            [(str(ele), str(ele))
             for ele in table_class.child_table().heading.secondary_attributes
             ])
        restrictions = RestrictionField(RESTRICTION_LABEL,
                                        description=RESTRICTION_DESCRIPTION,
                                        validators=[
                                            Optional(),
                                            OptionalJsonSerializableValidator(
                                                (list, dict))
                                        ],
                                        render_kw={'nullable': True})
        parse_unique = ListField(
            'parse as unique',
            description=
            'list of unique entries when using fetch - not wrapped into numpy.array',
            validators=[Optional(),
                        JsonSerializableValidator(list)],
            render_kw={'nullable': True})

        def get_formatted(self):

            formatted = super().get_formatted()

            if formatted['fetch_tables'] is not None:
                formatted['fetch_tables'] = {
                    key: value
                    for table_dict in formatted['fetch_tables']
                    for key, value in table_dict.items()
                }

            return formatted
Beispiel #20
0
class MemberDetailsForm(FlaskForm):
    full_name = StringField(label='Full Name')
    return_url = HiddenField(label='Return URL')
    member_number = HiddenField(label='Member Number')
    dt_number = StringField(label='Id')
    status = MySelectField(label='Status',
                           choices=MemberStatus.choices(),
                           coerce=MemberStatus.coerce)
    type = MySelectField(label='Type',
                         choices=MembershipType.choices(),
                         coerce=MembershipType.coerce)
    start_date = DateField(label='Start')
    end_date = DateField(label='End')
    birth_date = DateField(label='DoB', validators=[Optional()])
    age = HiddenField(label='Age')
    last_updated = StringField(label='Updated')
    access = MySelectField(label='Access',
                           choices=UserRole.choices(blank=False, ),
                           coerce=UserRole.coerce)
    fan_id = StringField(label='AFCW Fan ID')
    external_access = MySelectField(label='External access',
                                    choices=ExternalAccess.choices(),
                                    coerce=ExternalAccess.coerce)
    payment_method = MySelectField(label='Pay method',
                                   choices=PaymentMethod.choices(blank=True),
                                   coerce=PaymentMethod.coerce)
    title = MySelectField(label='Title',
                          choices=Title.choices(blank=True),
                          coerce=Title.coerce)
    first_name = StringField(label='First', validators=[InputRequired()])
    last_name = StringField(label='Last', validators=[InputRequired()])
    sex = MySelectField(label='Sex',
                        choices=Sex.choices(blank=True),
                        coerce=int)

    line1 = StringField(label='Address line 1')
    line2 = StringField(label='Address line 2')
    line3 = StringField(label='Address line 3')
    city = StringField(label='City')
    state = MySelectField(label='State',
                          choices=state_choices(blank=True),
                          coerce=int)
    post_code = StringField(label='Post Code')
    county = MySelectField(label='County',
                           choices=county_choices(blank=True),
                           coerce=int)
    country = MySelectField(label='Country',
                            choices=country_choices(),
                            coerce=int)

    home_phone = StringField(label='Home Phone')
    mobile_phone = StringField(label='Mobile')
    email = StringField(
        label='Email ',
        validators=[Optional(), Email("Invalid email address")])
    comms = MySelectField(label='Comms ',
                          choices=CommsType.choices(),
                          coerce=CommsType.coerce)
    comms_status = MySelectField(label='Status ',
                                 choices=CommsStatus.choices(),
                                 coerce=CommsStatus.coerce)

    submit = SubmitField(label='Save')

    payment_list = FieldList(FormField(PaymentItemForm))
    action_list = FieldList(FormField(ActionItemForm))
    comment_list = FieldList(FormField(CommentItemForm))

    jd_email = StringField(
        label='JD Email ',
        validators=[Optional(), Email("Invalid email address")])
    jd_gift = MySelectField(label='JD Gift',
                            choices=JuniorGift.choices(blank=True),
                            coerce=JuniorGift.coerce)

    def populate_member(self, member_number, return_url, copy=False):
        self.return_url.data = return_url
        new_member = member_number == 0
        if new_member or copy:
            member = get_new_member()
        else:
            member = get_member(member_number)
        if copy:
            base_member = get_member(member_number)
            new_member = True
            member.last_name = base_member.last_name
            member.address = base_member.address
            member.home_phone = base_member.home_phone
            member.mobile_phone = base_member.mobile_phone
            member.email = base_member.email
            member.comms = base_member.comms
        address = member.address
        self.member_number.data = str(member.number)
        self.dt_number.data = member.dt_number()
        self.status.data = member.status.value
        self.type.data = member.member_type.value
        self.start_date.data = member.start_date
        self.end_date.data = member.end_date
        self.birth_date.data = member.birth_date
        self.age.data = str(member.age()) if member.age() is not None else None
        self.last_updated.data = fmt_date(member.last_updated)
        self.access.data = member.user.role.value if member.user else 0

        self.fan_id.data = member.season_ticket_id if member.season_ticket_id else ''
        self.external_access.data = (member.external_access
                                     or ExternalAccess.none).value
        self.payment_method.data = member.last_payment_method.value if member.last_payment_method else ''

        self.full_name.data = member.full_name()
        self.title.data = member.title.value if member.title else ''
        self.first_name.data = member.first_name
        self.last_name.data = member.last_name
        self.sex.data = member.sex.value if member.sex else ''

        self.line1.data = address.line_1
        self.line2.data = address.line_2
        self.line3.data = address.line_3
        self.city.data = address.city
        self.state.data = address.state.id if address.state else 0
        self.post_code.data = address.post_code
        self.county.data = address.county.id if address.county else 0
        self.country.data = address.country.id

        self.home_phone.data = member.home_phone
        self.mobile_phone.data = member.mobile_phone
        self.email.data = member.email
        self.comms.data = member.comms.value
        self.comms_status.data = member.comms_status.value if member.comms_status else CommsStatus.all_ok

        for payment in [get_new_payment()] + member.payments:
            item_form = PaymentItemForm()
            item_form.date = payment.date
            item_form.pay_type = payment.type.value  ## nb: don't set the data attribute for select fields in a fieldlist!
            item_form.amount = payment.amount
            item_form.method = payment.method.value if payment.method else None
            item_form.comment = payment.comment or ''
            self.payment_list.append_entry(item_form)

        for action in [get_new_action(new_member)] + member.actions:
            item_form = ActionItemForm()
            if action.action:
                item_form.action = action.action.value
            if action.status:
                item_form.status = action.status.value
            item_form.date = action.date
            item_form.comment = action.comment or ''
            self.action_list.append_entry(item_form)

        for comment in [get_new_comment()] + member.comments:
            item_form = CommentItemForm()
            item_form.date = comment.date
            item_form.comment = comment.comment or ''
            self.comment_list.append_entry(item_form)

        if new_member or member.member_type == MembershipType.junior:
            if not member.junior:
                member.junior = get_junior()
            self.jd_email.data = member.junior.email or ''
            self.jd_gift.data = member.junior.gift.value if member.junior.gift else ''
        else:
            self.jd_email = self.jd_gift = None

    def validate(self):
        result = True
        new_member = int(self.member_number.data) == 0
        if not super(MemberDetailsForm, self).validate():
            return False
        if new_member:
            name = self.first_name.data + ' ' + self.last_name.data
            existing = get_members_by_name(name)
            if len(existing) > 0:
                self.first_name.errors.append('{} is already member {}'.format(
                    name, existing[0].dt_number()))
                result = False
        return result

    def save_member(self, member_number):
        member_details = {
            'title': self.title.data,
            'first_name': self.first_name.data.strip(),
            'last_name': self.last_name.data.strip(),
            'sex': self.sex.data,
            'member_type': self.type.data,
            'status': self.status.data,
            'start_date': self.start_date.data,
            'end_date': self.end_date.data,
            'birth_date': self.birth_date.data,
            'access': self.access.data,
            'external_access': self.external_access.data,
            'fan_id': self.fan_id.data,
            'payment_method': self.payment_method.data,
            'home_phone': self.home_phone.data.strip(),
            'mobile_phone': self.mobile_phone.data.strip(),
            'email': self.email.data.strip(),
            'comms': self.comms.data,
            'comms_status': self.comms_status.data,
            'line_1': self.line1.data.strip(),
            'line_2': self.line2.data.strip(),
            'line_3': self.line3.data.strip(),
            'city': self.city.data.strip(),
            'state': get_state(self.state.data),
            'post_code': self.post_code.data.strip(),
            'county': get_county(self.county.data),
            'country': get_country(self.country.data),
            'payments': [],
            'actions': [],
            'comments': []
        }
        if self.type.data == MembershipType.junior.value:
            member_details['jd_mail'] = self.jd_email.data.strip()
            member_details['jd_gift'] = self.jd_gift.data

        for payment in self.payment_list.data:
            if payment['amount']:
                member_details['payments'].append(payment)

        for action in self.action_list.data:
            if action['action'] > 0:
                member_details['actions'].append(action)

        for comment in self.comment_list.data:
            if comment['comment']:
                member_details['comments'].append(comment)

        return save_member_details(member_number, member_details)
Beispiel #21
0
class PropertyForm(FlaskForm):
    address = FormField(AddressForm, default=lambda: Address())
    sq_foot = IntegerField('What is the square footage of the home?',
                           description='Do not include basement, \
                                        non-permitted additions, or \
                                        non-heated square footage.',
                           validators=[Optional()])
    year_built = IntegerField('What year was the home built?',
                              description='(For example, 2001)',
                              validators=[Optional()])
    stories_count = RadioField('How many stories does the home have?',
                               description="Don't include a basement... \
                                            We will git to that later.",
                               choices=[
                                    ('1', 'One story'),
                                    ('2', 'Two story'),
                                    ('3', 'Three story')],
                               validators=[Optional()])
    basement_type = RadioField('Does the home have a basement?',
                               description='A basement is a level that is \
                                            either completely or partially \
                                            below the ground floor. Finished \
                                            means that the space is sutable \
                                            for living, with fully finished \
                                            walls, flooring, as well as air \
                                            conditioning and heating.',
                               choices=[
                                    ('none', 'No Basement'),
                                    ('unfinished', 'Unfinished Basement'),
                                    ('partial', 'Partially Finished Basement'),
                                    ('finished', 'Finished Basement')
                               ],
                               validators=[Optional()])
    addition_type = RadioField('Have you or the previous owners made \
                                additions to the structure of the home?',
                               description='Additions include garages that \
                                            may have been converted, \
                                            sunrooms, bonus rooms, or any \
                                            other living area extensions.',
                               choices=[
                                    ('none', 'No additions'),
                                    ('additions-no-permits',
                                        'Additions without permits'),
                                    ('garage-no-permit',
                                        'Garage conversion without permits'),
                                    ('porch-no-permit',
                                        'Porch conversion without permits'),
                                    ('additions-with-permits',
                                        'Additions with permits'),
                                    ('garage-with-pemrit',
                                        'Garage conversion with permits'),
                                    ('porch-with-permit',
                                        'Porch conversion with permits')
                               ],
                               validators=[Optional()])
    bedroom_count = RadioField('How many bedrooms does the home have?',
                               description='A room counts as a bedroom if \
                                            it has a closet, door, \
                                            and window.',
                               choices=[
                                    ('0', 'Studio'),
                                    ('1', '1 Bed'),
                                    ('2', '2 Beds'),
                                    ('3', '3 Beds'),
                                    ('4', '4 Beds'),
                                    ('5', '5+ Beds')
                               ],
                               validators=[Optional()])
    full_bath_count = RadioField('How many full bathrooms does the home have?',
                                 description='A room counts as a full \
                                              bathroom if it includes a \
                                              toilet, sink and \
                                              bathtub/shower.',
                                 choices=[
                                    ('1', '1'),
                                    ('2', '2'),
                                    ('3', '3'),
                                    ('4', '4'),
                                    ('5', '5+')
                                 ],
                                 validators=[Optional()])
    half_bath_count = RadioField('How many half bathrooms does the home have?',
                                 description='A room counts as a half \
                                              bathroom if it includes a \
                                              toilet and sink but no \
                                              bathtub/shower.',
                                 choices=[
                                    ('0', '0'),
                                    ('1', '1'),
                                    ('2', '2'),
                                    ('3', '3'),
                                    ('4', '4'),
                                    ('5', '5+')
                                 ],
                                 validators=[Optional()])
    parking_type = RadioField('What kind of parking or garage does the \
                               home have?',
                              choices=[
                                ('single', '1-Car Garage'),
                                ('double', '2-Car Garage'),
                                ('triple', '3-Car Garage'),
                                ('quad', '4-Car Garage'),
                                ('1carport', '1 Carport'),
                                ('2carport', '2 Carport'),
                                ('outside', 'Outside'),
                                ('street', 'Street'),
                                ('other', 'Other')
                              ],
                              validators=[Optional()])
    countertops = RadioField('What kind of countertops are in the kitchen?',
                             description='Select the option that most closely \
                                          describes your counter tops.',
                             choices=[
                                ('granite-slab', 'Granite Slab'),
                                ('granite-tile', 'Granite Tile'),
                                ('quartz', 'Quartz'),
                                ('corian', 'Corian'),
                                ('laminate', 'Laminate'),
                                ('tile', 'Tile')
                             ],
                             validators=[Optional()])
    appliances = RadioField('What kind of appliances does the kitchen have?',
                            choices=[
                                ('stainless', 'Stainless Steel'),
                                ('black', 'Black'),
                                ('white', 'White'),
                                ('mixed', 'Mixed')
                            ],
                            validators=[Optional()])
    double_oven_ind = BooleanField('Double oven')
    walk_in_pantry_ind = BooleanField('Walk-in pantry')
    separate_cooktop_ind = BooleanField('Separate cooktop')
    built_in_oven_ind = BooleanField('Built-in wall oven')
    built_in_microwave_ind = BooleanField('Built-in microwave')
    kitchen_flooring = RadioField('What type of flooring is used in \
                                   the kitchen?',
                                  description='Select the option that most \
                                               closely matches the flooring.',
                                  choices=[
                                    ('tile', 'Tile'),
                                    ('vinyl', 'Vinyl'),
                                    ('laminate', 'Laminate'),
                                    ('hardwood', 'Hardwood'),
                                    ('travertine', 'Travertine'),
                                    ('saltillo-tile', 'Saltillo Tile'),
                                    ('carpet', 'Carpet'),
                                    ('woodplank-tile', 'Woodplank Tile'),
                                    ('concrete', 'Concrete'),
                                    ('other', 'other')
                                  ],
                                  validators=[Optional()])
    main_flooring = RadioField('What type of flooring is used in the main \
                                living areas?',
                               description='Select the option that most \
                                            closely matches the flooring.',
                               choices=[
                                    ('tile', 'Tile'),
                                    ('vinyl', 'Vinyl'),
                                    ('laminate', 'Laminate'),
                                    ('hardwood', 'Hardwood'),
                                    ('travertine', 'Travertine'),
                                    ('saltillo-tile', 'Saltillo Tile'),
                                    ('carpet', 'Carpet'),
                                    ('woodplank-tile', 'Woodplank Tile'),
                                    ('concrete', 'Concrete'),
                                    ('other', 'other')
                               ],
                               validators=[Optional()])
    bathroom_flooring_tile_ind = BooleanField('Tile')
    bathroom_flooring_vinyl_ind = BooleanField('Vinyl')
    bathroom_flooring_laminate_ind = BooleanField('Laminate')
    bathroom_flooring_hardwood_ind = BooleanField('Hardwood')
    bathroom_flooring_travertine_ind = BooleanField('Travertine')
    bathroom_flooring_saltillo_tile_ind = BooleanField('Saltillo Tile')
    bathroom_flooring_carpet_ind = BooleanField('Carpet')
    bathroom_flooring_woodplank_tile_ind = BooleanField('Woodplank Tile')
    bathroom_flooring_concrete_ind = BooleanField('Concrete')
    bathroom_flooring_other_ind = BooleanField('Other')
    bedroom_flooring_tile_ind = BooleanField('Tile')
    bedroom_flooring_vinyl_ind = BooleanField('Vinyl')
    bedroom_flooring_laminate_ind = BooleanField('Laminate')
    bedroom_flooring_hardwood_ind = BooleanField('Hardwood')
    bedroom_flooring_travertine_ind = BooleanField('Travertine')
    bedroom_flooring_saltillo_tile_ind = BooleanField('Saltillo Tile')
    bedroom_flooring_carpet_ind = BooleanField('Carpet')
    bedroom_flooring_woodplank_tile_ind = BooleanField('Woodplank Tile')
    bedroom_flooring_concrete_ind = BooleanField('concrete')
    bedroom_flooring_other_ind = BooleanField('other')
    landscaping = RadioField('Does the home have landscaping?',
                             choices=[
                                ('none', 'None'),
                                ('both', 'Both front and back yard'),
                                ('front', 'Front yard only'),
                                ('back', 'Back yard only')
                             ],
                             validators=[Optional()])
    pool = RadioField('Does the home have an in-ground pool?',
                      choices=[
                         (True, 'Yes'),
                         (False, 'No')
                      ], coerce=lambda x: x == 'True',
                      validators=[Optional()])
    hottub = RadioField('Does the home have an in-ground spa / hot tub?',
                        choices=[
                           (True, 'Yes'),
                           (False, 'No')
                        ], coerce=lambda x: x == 'True',
                        validators=[Optional()])
    gated_community_ind = BooleanField('Gated Community')
    hoa_ind = BooleanField('Homeowners Association')
    age_restricted_ind = BooleanField('Age Restricted')
    solar_panels_ind = BooleanField('Solar Panels')
    septic_system_ind = BooleanField('Septic System')
    well_water_ind = BooleanField('Well Water')
    poor_location_ind = BooleanField('The property backs to a busy road, \
                                      commercial buildings, or power lines')
    sinkholes_ind = RadioField('Are you aware of sinkholes on the property?',
                               choices=[
                                  (True, 'Yes'),
                                  (False, 'No')
                               ], coerce=lambda x: x == 'True',
                               validators=[Optional()])
    foundation_issues = RadioField('Are there foundation issues?',
                                   choices=[
                                    (True, 'Yes'),
                                    (False, 'No')
                                   ], coerce=lambda x: x == 'True',
                                   validators=[Optional()])
    additional_info = TextAreaField('Is there anything else you would like to \
                                     tell us?',
                                    description='This field is optional but \
                                                it gives you teh opportunity \
                                                to tell us what is special \
                                                about the home. \
                                                (Max 1500 characters)')
    submitter_type = RadioField('What is your relationship to this home?',
                                choices=[
                                    ('owner', 'Owner'),
                                    ('agent', 'Real Estate Agent'),
                                    ('other', 'Other')
                                ],
                                validators=[Optional()])
    listed_ind = RadioField('Is this home listed on the MLS?',
                            choices=[
                               (True, 'Yes'),
                               (False, 'No')
                            ], coerce=lambda x: x == 'True',
                            validators=[Optional()])
    submitter_first_name = StringField('First Name',
                                       validators=[DataRequired()])
    submitter_last_name = StringField('Last Name',
                                      validators=[DataRequired()])
    submitter_phone = StringField('Phone',
                                  validators=[DataRequired()])
    submitter_email = StringField('Email',
                                  validators=[DataRequired()])
Beispiel #22
0
class UpdateProductForm(ProductFormMixin, Form):
    name = StringField('Name', validators=[Optional()])
    categories = SelectMultipleField('Categories', coerce=int, validators=[])
Beispiel #23
0
class VenueForm(Form):
    name = StringField('name', validators=[DataRequired()])
    city = StringField('city', validators=[DataRequired()])
    state = SelectField('state',
                        validators=[DataRequired()],
                        choices=[
                            ('AL', 'AL'),
                            ('AK', 'AK'),
                            ('AZ', 'AZ'),
                            ('AR', 'AR'),
                            ('CA', 'CA'),
                            ('CO', 'CO'),
                            ('CT', 'CT'),
                            ('DE', 'DE'),
                            ('DC', 'DC'),
                            ('FL', 'FL'),
                            ('GA', 'GA'),
                            ('HI', 'HI'),
                            ('ID', 'ID'),
                            ('IL', 'IL'),
                            ('IN', 'IN'),
                            ('IA', 'IA'),
                            ('KS', 'KS'),
                            ('KY', 'KY'),
                            ('LA', 'LA'),
                            ('ME', 'ME'),
                            ('MT', 'MT'),
                            ('NE', 'NE'),
                            ('NV', 'NV'),
                            ('NH', 'NH'),
                            ('NJ', 'NJ'),
                            ('NM', 'NM'),
                            ('NY', 'NY'),
                            ('NC', 'NC'),
                            ('ND', 'ND'),
                            ('OH', 'OH'),
                            ('OK', 'OK'),
                            ('OR', 'OR'),
                            ('MD', 'MD'),
                            ('MA', 'MA'),
                            ('MI', 'MI'),
                            ('MN', 'MN'),
                            ('MS', 'MS'),
                            ('MO', 'MO'),
                            ('PA', 'PA'),
                            ('RI', 'RI'),
                            ('SC', 'SC'),
                            ('SD', 'SD'),
                            ('TN', 'TN'),
                            ('TX', 'TX'),
                            ('UT', 'UT'),
                            ('VT', 'VT'),
                            ('VA', 'VA'),
                            ('WA', 'WA'),
                            ('WV', 'WV'),
                            ('WI', 'WI'),
                            ('WY', 'WY'),
                        ])
    address = StringField('address', validators=[DataRequired()])
    phone = StringField('phone',
                        validators=[
                            validators.Regexp(
                                regex=r"\d{3}[-.\s]?\d{3}[-.\s]?\d{4}",
                                message="Enter valide phone number")
                        ])
    image_link = StringField('image_link', validators=[Optional()])
    genres = SelectMultipleField(
        # TODO implement enum restriction
        'genres',
        validators=[DataRequired()],
        choices=[
            ('Alternative', 'Alternative'),
            ('Blues', 'Blues'),
            ('Classical', 'Classical'),
            ('Country', 'Country'),
            ('Electronic', 'Electronic'),
            ('Folk', 'Folk'),
            ('Funk', 'Funk'),
            ('Hip-Hop', 'Hip-Hop'),
            ('Heavy Metal', 'Heavy Metal'),
            ('Instrumental', 'Instrumental'),
            ('Jazz', 'Jazz'),
            ('Musical Theatre', 'Musical Theatre'),
            ('Pop', 'Pop'),
            ('Punk', 'Punk'),
            ('R&B', 'R&B'),
            ('Reggae', 'Reggae'),
            ('Rock n Roll', 'Rock n Roll'),
            ('Soul', 'Soul'),
            ('Other', 'Other'),
        ])
    facebook_link = StringField('facebook_link',
                                validators=[Optional(), URL()])
    website = StringField('website', validators=[Optional(), URL()])
    seeking_talent = BooleanField('seeking_talent', validators=[Optional()])
    seeking_description = StringField('seeking_description',
                                      validators=[Optional()])
Beispiel #24
0
class ConnectionForm(DynamicForm):
    """Form for editing and adding Connection"""

    conn_id = StringField(
        lazy_gettext('Conn Id'),
        widget=BS3TextFieldWidget())
    conn_type = SelectField(
        lazy_gettext('Conn Type'),
        choices=sorted(_connection_types, key=itemgetter(1)),  # pylint: disable=protected-access
        widget=Select2Widget())
    host = StringField(
        lazy_gettext('Host'),
        widget=BS3TextFieldWidget())
    schema = StringField(
        lazy_gettext('Schema'),
        widget=BS3TextFieldWidget())
    login = StringField(
        lazy_gettext('Login'),
        widget=BS3TextFieldWidget())
    password = PasswordField(
        lazy_gettext('Password'),
        widget=BS3PasswordFieldWidget())
    port = IntegerField(
        lazy_gettext('Port'),
        validators=[Optional()],
        widget=BS3TextFieldWidget())
    extra = TextAreaField(
        lazy_gettext('Extra'),
        widget=BS3TextAreaFieldWidget())

    # Used to customized the form, the forms elements get rendered
    # and results are stored in the extra field as json. All of these
    # need to be prefixed with extra__ and then the conn_type ___ as in
    # extra__{conn_type}__name. You can also hide form elements and rename
    # others from the connection_form.js file
    extra__jdbc__drv_path = StringField(
        lazy_gettext('Driver Path'),
        widget=BS3TextFieldWidget())
    extra__jdbc__drv_clsname = StringField(
        lazy_gettext('Driver Class'),
        widget=BS3TextFieldWidget())
    extra__google_cloud_platform__project = StringField(
        lazy_gettext('Project Id'),
        widget=BS3TextFieldWidget())
    extra__google_cloud_platform__key_path = StringField(
        lazy_gettext('Keyfile Path'),
        widget=BS3TextFieldWidget())
    extra__google_cloud_platform__keyfile_dict = PasswordField(
        lazy_gettext('Keyfile JSON'),
        widget=BS3PasswordFieldWidget())
    extra__google_cloud_platform__scope = StringField(
        lazy_gettext('Scopes (comma separated)'),
        widget=BS3TextFieldWidget())
    extra__google_cloud_platform__num_retries = IntegerField(
        lazy_gettext('Number of Retries'),
        validators=[NumberRange(min=0)],
        widget=BS3TextFieldWidget(),
        default=5)
    extra__grpc__auth_type = StringField(
        lazy_gettext('Grpc Auth Type'),
        widget=BS3TextFieldWidget())
    extra__grpc__credential_pem_file = StringField(
        lazy_gettext('Credential Keyfile Path'),
        widget=BS3TextFieldWidget())
    extra__grpc__scopes = StringField(
        lazy_gettext('Scopes (comma separated)'),
        widget=BS3TextFieldWidget())
    extra__yandexcloud__service_account_json = PasswordField(
        lazy_gettext('Service account auth JSON'),
        widget=BS3PasswordFieldWidget(),
        description='Service account auth JSON. Looks like '
                    '{"id", "...", "service_account_id": "...", "private_key": "..."}. '
                    'Will be used instead of OAuth token and SA JSON file path field if specified.',
    )
    extra__yandexcloud__service_account_json_path = StringField(
        lazy_gettext('Service account auth JSON file path'),
        widget=BS3TextFieldWidget(),
        description='Service account auth JSON file path. File content looks like '
                    '{"id", "...", "service_account_id": "...", "private_key": "..."}. '
                    'Will be used instead of OAuth token if specified.',
    )
    extra__yandexcloud__oauth = PasswordField(
        lazy_gettext('OAuth Token'),
        widget=BS3PasswordFieldWidget(),
        description='User account OAuth token. Either this or service account JSON must be specified.',
    )
    extra__yandexcloud__folder_id = StringField(
        lazy_gettext('Default folder ID'),
        widget=BS3TextFieldWidget(),
        description='Optional. This folder will be used to create all new clusters and nodes by default',
    )
    extra__yandexcloud__public_ssh_key = StringField(
        lazy_gettext('Public SSH key'),
        widget=BS3TextFieldWidget(),
        description='Optional. This key will be placed to all created Compute nodes'
        'to let you have a root shell there',
    )
    extra__kubernetes__in_cluster = BooleanField(
        lazy_gettext('In cluster configuration'))
    extra__kubernetes__kube_config_path = StringField(
        lazy_gettext('Kube config path'),
        widget=BS3TextFieldWidget())
    extra__kubernetes__kube_config = StringField(
        lazy_gettext('Kube config (JSON format)'),
        widget=BS3TextFieldWidget())
    extra__kubernetes__namespace = StringField(
        lazy_gettext('Namespace'),
        widget=BS3TextFieldWidget())
Beispiel #25
0
class RegistrationFormForm(IndicoForm):
    _price_fields = ('currency', 'base_price')
    _registrant_notification_fields = ('notification_sender_address',
                                       'message_pending', 'message_unpaid',
                                       'message_complete')
    _manager_notification_fields = ('manager_notifications_enabled',
                                    'manager_notification_recipients')
    _special_fields = _price_fields + _registrant_notification_fields + _manager_notification_fields

    title = StringField(_("Title"), [DataRequired()],
                        description=_("The title of the registration form"))
    introduction = TextAreaField(
        _("Introduction"),
        description=
        _("Introduction to be displayed when filling out the registration form"
          ))
    contact_info = StringField(
        _("Contact info"),
        description=
        _("How registrants can get in touch with somebody for extra information"
          ))
    moderation_enabled = BooleanField(
        _("Moderated"),
        widget=SwitchWidget(),
        description=_("If enabled, registrations require manager approval"))
    require_login = BooleanField(
        _("Only logged-in users"),
        widget=SwitchWidget(),
        description=_("Users must be logged in to register"))
    require_user = BooleanField(
        _("Registrant must have account"),
        widget=SwitchWidget(),
        description=_(
            "Registrations emails must be associated with an Indico account"))
    limit_registrations = BooleanField(
        _("Limit registrations"),
        widget=SwitchWidget(),
        description=_("Whether there is a limit of registrations"))
    registration_limit = IntegerField(
        _("Capacity"), [
            HiddenUnless('limit_registrations'),
            DataRequired(),
            NumberRange(min=1)
        ],
        description=_("Maximum number of registrations"))
    modification_mode = IndicoEnumSelectField(
        _("Modification allowed"),
        enum=ModificationMode,
        description=_("Will users be able to modify their data? When?"))
    publish_registrations_enabled = BooleanField(
        _('Publish registrations'),
        widget=SwitchWidget(),
        description=_("Registrations from this form will be displayed in the "
                      "event page"))
    publish_registration_count = BooleanField(
        _("Publish number of registrations"),
        widget=SwitchWidget(),
        description=_("Number of registered participants will be displayed in "
                      "the event page"))
    publish_checkin_enabled = BooleanField(
        _('Publish check-in status'),
        widget=SwitchWidget(),
        description=_(
            "Check-in status will be shown publicly on the event page"))
    base_price = DecimalField(
        _('Registration fee'), [
            NumberRange(min=0, max=999999.99),
            Optional(), _check_if_payment_required
        ],
        filters=[lambda x: x if x is not None else 0],
        widget=NumberInput(step='0.01'),
        description=_("A fixed fee all users have to pay when registering."))
    currency = SelectField(_('Currency'), [DataRequired()],
                           description=_('The currency for new registrations'))
    notification_sender_address = StringField(_('Notification sender address'),
                                              [IndicoEmail()],
                                              filters=[lambda x: (x or None)])
    message_pending = TextAreaField(
        _("Message for pending registrations"),
        description=
        _("Text included in emails sent to pending registrations (Markdown syntax)"
          ))
    message_unpaid = TextAreaField(
        _("Message for unpaid registrations"),
        description=
        _("Text included in emails sent to unpaid registrations (Markdown syntax)"
          ))
    message_complete = TextAreaField(
        _("Message for complete registrations"),
        description=
        _("Text included in emails sent to complete registrations (Markdown syntax)"
          ))
    manager_notifications_enabled = BooleanField(
        _('Enabled'),
        widget=SwitchWidget(),
        description=_("Enable notifications to managers about registrations"))
    manager_notification_recipients = EmailListField(
        _('List of recipients'), [
            HiddenUnless('manager_notifications_enabled', preserve_data=True),
            DataRequired()
        ],
        description=_("Email addresses that will receive notifications"))

    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        super().__init__(*args, **kwargs)
        self._set_currencies()
        self.notification_sender_address.description = _(
            'Email address set as the sender of all '
            'notifications sent to users. If empty, '
            'then {} is used.'.format(config.NO_REPLY_EMAIL))

    def _set_currencies(self):
        currencies = [(c['code'], '{0[code]} ({0[name]})'.format(c))
                      for c in payment_settings.get('currencies')]
        self.currency.choices = sorted(currencies, key=lambda x: x[1].lower())
Beispiel #26
0
class SearchForm(AbstractForm):
    """
    Form associated to the Search page
    """
    fmt = '%Y-%m-%dT%H:%M'
    app_name = StringField(
        "Application Name",
        validators=[
            Optional(strip_whitespace=True),
            Regexp(regex='^[a-zA-Z0-9\-_]*$',
                   message="Only letters, numbers, _ or - allowed.")
        ])
    app_id = StringField(
        "Application ID",
        validators=[
            Optional(strip_whitespace=True),
            Regexp(regex='^[a-zA-Z0-9\-_]*$',
                   message="Only letters, numbers, _ or - allowed.")
        ])
    username = StringField(
        "Username",
        validators=[
            Optional(strip_whitespace=True),
            Regexp(regex='^[a-zA-Z0-9\-_]*$',
                   message="Only letters, numbers, _ or - allowed.")
        ])
    start_time = HiddenField("Start Time")  # just for the label
    start_from = DateTimeLocalField("From",
                                    format=fmt,
                                    validators=[Optional()])
    start_to = DateTimeLocalField("To", format=fmt, validators=[Optional()])
    end_time = HiddenField("End Time")  # just for the label
    end_from = DateTimeLocalField("From", format=fmt, validators=[Optional()])
    end_to = DateTimeLocalField("To", format=fmt, validators=[Optional()])
    search_btn = SubmitField("Search")

    def validate(self):
        """
        Validate the SearchForm
        :return: True if valid. False otherwise.
        """
        rv = FlaskForm.validate(self)
        if not rv:
            return False
        # validate the dates (from < to)
        if self.start_from.data and self.start_to.data:
            if self.start_from.data > self.start_to.data:
                self.start_time.errors.append(
                    f"Invalid From/To datetimes: '{self.start_from.label.text}' should be before '{self.start_to.label.text}'"
                )
                return False
        if self.end_from.data and self.end_to.data:
            if self.end_from.data > self.end_to.data:
                self.end_time.errors.append(
                    f"Invalid From/To datetimes: '{self.end_from.label.text}' should be before '{self.end_to.label.text}'"
                )
                return False
        return True

    def apply_filters(self, query):
        """
        Filter the results of the existing query by Form criteria
        :param query: SQLAlchemy query
        :return: filtered query
        """
        query = query.filter(ApplicationEntity.name.like(f"%{self.app_name.data.strip()}%")) \
                     .filter(ApplicationEntity.app_id.like(f"%{self.app_id.data.strip()}%")) \
                     .filter(ApplicationEntity.spark_user.like(f"%{self.username.data.strip()}%"))
        query = query.filter(
            ApplicationEntity.start_time >= self.start_from.data
        ) if self.start_from.data else query
        query = query.filter(ApplicationEntity.start_time <= self.start_to.data
                             ) if self.start_to.data else query
        query = query.filter(ApplicationEntity.end_time >= self.end_from.data
                             ) if self.end_from.data else query
        query = query.filter(ApplicationEntity.end_time <= self.end_to.data
                             ) if self.end_to.data else query
        return query
Beispiel #27
0
class UpdateSubscriptionForm(Form):
    coupon_code = StringField(_('Do you have a coupon code?'),
                              [Optional(), Length(1, 254)])
Beispiel #28
0
class UpdateGroup(Form):
    # 分组name
    name = StringField(validators=[DataRequired(message='请输入分组名称')])
    # 非必须
    info = StringField(validators=[Optional()])
Beispiel #29
0
class ProfileForm(Form):
    name = StringField('Name', validators=[Optional(), Length(1, 64)])
    location = StringField('Location', validators=[Optional(), Length(1, 64)])
    bio = TextAreaField('Bio')
    submit = SubmitField('Submit')
Beispiel #30
0
class DescriptionForm(FlaskForm):
    description = TextAreaField('介绍', validators=[Optional(), Length(0, 500)])
    submit = SubmitField()