示例#1
0
class ExampleForm(ServiceForm):
    # Each service model must have an corresponding form.
    # The purpose of a form is twofold:
    # - Define how the service is displayed in the UI
    # - Check for each field that the user input is valid.
    # A service cannot be created/updated until all fields are validated.

    # The following line is mandatory: the default value must point
    # to the service.
    form_type = HiddenField(default="ExampleService")

    # string1 is defined as a "SelectField": it will be displayed as a
    # drop-down list in the UI.
    string1 = SelectField(choices=[("cisco",
                                    "Cisco"), ("juniper",
                                               "Juniper"), ("arista",
                                                            "Arista")])

    # String2 is a StringField, which is displayed as a standard textbox.
    # The "InputRequired" validator is used: this field is mandatory.
    string2 = StringField("String 2 (required)", [InputRequired()])

    # The main address field uses two validators:
    # - The input length must be comprised between 7 and 25 characters
    # - The input syntax must match that of an email address.
    mail_address = StringField(
        "Mail address", [Length(min=7, max=25), Email()])

    # This IP address validator will ensure the user input is a valid IPv4 address.
    # If it isn't, you can set the error message to be displayed in the GUI.
    ip_address = StringField(
        "IP address",
        [
            IPAddress(
                ipv4=True,
                message="Please enter an IPv4 address for the IP address field",
            )
        ],
    )

    # MAC address validator
    mac_address = StringField("MAC address", [MacAddress()])

    # The NumberRange validator will ensure the user input is an integer
    # between 3 and 8.
    number_in_range = IntegerField("Number in range",
                                   [NumberRange(min=3, max=8)])

    # The Regexp field will ensure the user input matches the regular expression.
    regex = StringField("Regular expression", [Regexp(r".*")])

    # URL validation, with or without TLD.
    url = StringField(
        "URL",
        [
            URL(
                require_tld=True,
                message="An URL with TLD is required for the url field",
            )
        ],
    )

    # The NoneOf validator lets you define forbidden value for a field.
    exclusion_field = StringField(
        "Exclusion field",
        [
            NoneOf(
                ("a", "b", "c"),
                message=("'a', 'b', and 'c' are not valid "
                         "inputs for the exclusion field"),
            )
        ],
    )
    an_integer = IntegerField()
    a_float = FloatField()

    # If validator the user input is more complex, you can create a python function
    # to implement the validation mechanism.
    # Here, the custom_integer field will be validated by the "validate_custom_integer"
    # function below.
    # That function will check that the custom integer value is superior to the product
    # of "an_integer" and "a_float".
    # You must raise a "ValidationError" when the validation fails.
    custom_integer = IntegerField("Custom Integer")

    # A SelectMultipleField will be displayed as a drop-down list that allows
    # multiple selection.
    a_list = SelectMultipleField(
        choices=[("value1", "Value 1"), ("value2",
                                         "Value 2"), ("value3", "Value 3")])
    a_dict = DictField()

    # A BooleanField is displayed as a check box.
    boolean1 = BooleanField()
    boolean2 = BooleanField("Boolean N°1")

    def validate_custom_integer(self, field: IntegerField) -> None:
        product = self.an_integer.data * self.a_float.data
        if field.data > product:
            raise ValidationError("Custom integer must be less than the "
                                  "product of 'An integer' and 'A float'")
class ReceiverDiskFrom(FlaskForm):

    numberReceiver = IntegerField(
        'Receiver', validators=[InputRequired(),
                                NumberRange(1, 1000000000)])
    numberSender = IntegerField(
        'Sender', validators=[InputRequired(),
                              NumberRange(1, 1000000000)])
    randomSeed = RandomSeedField
    formation = SelectField('formation', choices=[('random', 'random')])
    calcs_inLog10 = FloatField('calcs_inLog10',
                               validators=[InputRequired(),
                                           NumberRange(0, 9)])
    receiverX = FloatField('X', validators=[InputRequired()])
    receiverY = FloatField('Y', validators=[InputRequired()])
    receiverZ = FloatField('Z', validators=[InputRequired()])
    radius = FloatField('radius', validators=[InputRequired()])
    orientation = SelectField('Orientation',
                              choices=[('Horizontal', 'Horizontal'),
                                       ('Vertical', 'Vertical')])
    wavelength = FloatField('Wavelength', validators=[InputRequired()])
    pathLoss = FloatField('Path loss',
                          validators=[InputRequired(),
                                      NumberRange(1, 6)])
    b = FloatField('b', validators=[InputRequired(), NumberRange(-3, 3)])
    algorithms = AlgorithmField
    originRadius = FloatField('originRadius', validators=[InputRequired()])
    cutOrigin = BooleanField('cutOrigin')
    upperBound = FloatField('UpperBound', validators=[InputRequired()])
    useMax = BooleanField('useMax')
    lowerBound = FloatField('LowerBound', validators=[InputRequired()])
    useMin = BooleanField('useMin')

    logScale = BooleanField('logScale')
    isotropic = BooleanField('isotropic')
    dimension = DimensionField
    plotTyp = SelectField('PlotTyp',
                          choices=[('all', 'all'), ('real', 'real'),
                                   ('imag', 'imag'), ('|z|^2', '|z|^2'),
                                   ('|z|', '|z|')])
    colors = ColorsField
    submit = SubmitField('Simulate')
    getData = SubmitField('Download Data')

    def __init__(self, *args, **kwargs):
        super(ReceiverDiskFrom, self).__init__(*args, **kwargs)
        self.algorithms.choices.extend([
            (algo.algorithmName, algo.algorithmName)
            for algo in models.Algorithm.query.filter_by(legit=True)
        ])
示例#3
0
class PatientHistoryForm(SectionForm):
    fld_med_rec_no = StringField('Medical Record Number', default=tbd)
    fld_name = StringField('Name of the patient', default=tbd)
    fld_id_type = StringField('Enter type of ID used', default=tbd)
    fld_id_no = StringField('Identity Number', default=tbd)
    fld_first_visit_date = DateField('Date of first visit',
                                     default=date.today())
    fld_permanent_address = StringField('Permanent Address', default=tbd)
    fld_current_address = StringField('Current Address',
                                      default='Same as Permanent Address')
    fld_contact_number = IntegerField('Contact Number', default=999)
    fld_alternative_contact = IntegerField('Alternative Contact Number',
                                           default=999)
    fld_email = StringField('e-mail id', default=tbd)
    fld_occupation = StringField('Occupation', default=tbd)
    fld_gender = SelectField("Gender", choices=CommonDict.gender_choice)
    fld_gender_other = StringField('Other')
    fld_age = IntegerField('Current Age (yrs)', default=999)
    # todo format date.today() to dd/mm/yyyy
    fld_date_of_birth = DateField('Date Of Birth', default=date.today())
    fld_place_of_birth = StringField('Place Of Birth', default=tbd)
    fld_height_feet = StringField('Height (in feet eg., 5ft 2in) ',
                                  default='0ft 0in')
    fld_weight_kg = FloatField('Weight (in kg)', default=999)
    fld_diet = SelectField("Diet", choices=PatientHistoryDict.diet_choice)
    fld_diet_other = StringField("Other")
    fld_nutrition_supplement_form_present = SelectField(
        "Nutrition supplements taken", choices=CommonDict.form_yes_no_choice)
    nutrition_supplement_form = FormField(NutritionalSupplementsForm)
    fld_physical_activity_form_present = SelectField(
        "Physical Activity done", choices=CommonDict.form_yes_no_choice)
    physical_activity_form = FormField(PhysicalActivityForm)
    fld_alcohol_consumption_form_present = SelectField(
        "Alcohol Consumption", choices=CommonDict.form_yes_no_choice)
    alcohol_consumption_form = FormField(AlcoholConsumptionForm)
    fld_tobacco_exposure_form_present = SelectField(
        "Has the patient been exposed to tobacco?",
        choices=CommonDict.form_yes_no_choice)
    tobacco_exposure_form = FormField(TobaccoExposureForm)
    fld_other_del_habits = StringField(
        "Other Deleterious Habits (if present give details)")
    fld_marital_status = SelectField(
        "Marital Status", choices=PatientHistoryDict.marital_status_choice)
    fld_marital_status_other = StringField('Other')
    fld_siblings = SelectField("Siblings", choices=CommonDict.yes_no_choice)
    fld_siblings_other = StringField("Other")
    fld_sister = IntegerField('Number of sisters', default=999)
    fld_brother = IntegerField('Number of brothers', default=999)
    fld_child = SelectField("Children", choices=CommonDict.yes_no_choice)
    fld_child_other = StringField("Other")
    fld_daughter = IntegerField('Number of daughters', default=999)
    fld_son = IntegerField('Number of sons', default=999)
    fld_menarche = IntegerField('Age at menarche', default=999)
    fld_period_type = SelectField(
        "Period type", choices=PatientHistoryDict.period_type_choice)
    fld_period_type_other = StringField('Other')
    fld_last_date_period = DateField('Date of last menstrual period',
                                     default=date.today())
    fld_menopausal_status = SelectField(
        "Menopausal Status",
        choices=PatientHistoryDict.menopausal_status_choice)
    fld_menopausal_status_other = StringField('Other')
    fld_menopause_age = IntegerField('Age at menopause', default=0)
    fld_menopause_complications = StringField(
        "Complications associated with menopause", default=tbd)
    fld_pregnancy = IntegerField('Pregnancy carried to term', default=999)
    fld_pregnancy_complication = StringField(
        "Any complications during pregnancy", default=tbd)
    fld_abortion = IntegerField('Number of abortions', default=999)
    fld_pregnancy_number = IntegerField('Number of pregnancies', default=999)
    fld_age_first_child = IntegerField('Age of first child', default=999)
    fld_age_first_pregnancy = IntegerField('Age at first pregnancy',
                                           default=999)
    fld_age_last_pregnancy = IntegerField('Age at last pregnancy', default=999)
    fld_twice_birth_in_year = SelectField(
        "Twice birth in a year(not including twins)",
        choices=CommonDict.yes_no_choice)
    fld_twice_birth_in_year_other = StringField('Other')
    fld_breast_feed_form_present = SelectField(
        "Breast feeding", choices=CommonDict.form_yes_no_choice)
    breast_feed_form = FormField(BreastFeedingForm)
    fld_fertility_treat = SelectField("Fertility Treatment",
                                      choices=CommonDict.yes_no_choice)
    fld_type_fertility_treat = StringField("Type of fertility treatment",
                                           default=tbd)
    fld_detail_fertility_treat = StringField("Details of fertility treatments",
                                             default=tbd)
    fld_cycles_fertility_treat = StringField("Cycles of fertility treatment",
                                             default=tbd)
    fld_success_fertility_treat = SelectField("Success of fertility treatment",
                                              choices=CommonDict.yes_no_choice)
    fld_success_fertility_treat_other = StringField('Other')
    fld_birth_control = StringField("Type of birth control used", default=tbd)
    fld_detail_birth_control = StringField("Detail of birth control used",
                                           default=tbd)
    fld_duration_birth_control = StringField("Duration of birth control used",
                                             default=tbd)
    fld_cancer_history = SelectField("Diagnosed with cancer earlier",
                                     choices=CommonDict.yes_no_choice)
    fld_family_cancer = SelectField(
        "Any family member been detected with cancer",
        choices=CommonDict.yes_no_choice)
    fld_medical_history = SelectField("Diagnosed with any other disease",
                                      choices=CommonDict.yes_no_choice)
    fld_right_breast_symptoms_form_present = SelectField(
        "Are there symptoms in the right breast",
        choices=CommonDict.form_yes_no_choice)
    fld_right_breast_symptoms_form_present_other = StringField('Other')
    right_breast_symptoms_form = FormField(SymptomsRightBreastDurationForm)
    fld_left_breast_symptoms_form_present = SelectField(
        "Are there symptoms in the left breast",
        choices=CommonDict.form_yes_no_choice)
    left_breast_symptoms_form = FormField(SymptomsLeftBreastDurationForm)
    fld_complaint_detected_by = SelectField(
        "Current complains detected by",
        choices=PatientHistoryDict.current_complain_choice)
    fld_complaint_detected_by_other = StringField('Other')
    fld_metastasis_symptoms = SelectMultipleField(
        "Metastasis Symptoms",
        choices=PatientHistoryDict.metastasis_symptoms_choice)
    fld_metastasis_symptoms_other = StringField('Other')
    fld_annual_income = SelectField(
        "Annual house income is",
        choices=PatientHistoryDict.annual_income_choice)
    fld_annual_income_other = StringField('Other')
    submit_button = SubmitField('Submit Form')
class OneScale(FlaskForm):  # defining technology numbers in each scale
    Capkt = FloatField('Capkt (m3/year)')
    CCkt = FloatField('CCkt ($/(m3/year))')
    OCt = FloatField('OCt ($/m3)')
    SRWt = FloatField('SRWt ($/m3)')
    GPt = FloatField('GPt (gr CO2-eq/m3)')
示例#5
0
class BudgetForm(FlaskForm):
    category = SelectField('Catégorie', coerce=int)
    limit = FloatField('Limite', widget=NumberInput(step=0.01))
示例#6
0
class PriceForm(FlaskForm):
    cafeid = SelectField("Cafe", coerce=int)
    price_key = TextField("Coffee (e.g. large cap)")
    amount = FloatField("Amount", [validators.Required()])
示例#7
0
文件: forms.py 项目: dbmads/boxstripe
class OnePagePurchaseForm(Form):
    email = StringField('email',
                        validators=[
                            validators.DataRequired("Email is required"),
                            validators.Length(min=3, max=25),
                            validators.Email()
                        ])
    firstName = StringField(
        'fname',
        validators=[
            validators.DataRequired("First name is required"),
            validators.Length(min=2, max=30)
        ])

    lastName = StringField(
        'lname',
        validators=[
            validators.DataRequired("Last name is required"),
            validators.Length(min=2, max=30)
        ])

    address = StringField('address',
                          validators=[
                              validators.DataRequired("Address is required"),
                              validators.Length(min=10, max=255)
                          ])
    city = StringField('city',
                       validators=[
                           validators.DataRequired("City is required"),
                           validators.Length(min=1, max=55)
                       ])
    phone = IntegerField(
        'phone_number',
        validators=[validators.DataRequired("Zip code is required")])
    zip = IntegerField('zip_code',
                       validators=[
                           validators.DataRequired("Zip code is required"),
                           validators.Length(min=5, max=5)
                       ])
    state = StringField('state',
                        validators=[
                            validators.DataRequired("State is required"),
                            validators.Length(min=2, max=2)
                        ])
    country = StringField(
        'country', validators=[validators.DataRequired("Country is required")])
    name = StringField(
        'product_name',
        validators=[validators.DataRequired("product_name is required")])
    description = StringField(
        'description',
        validators=[validators.DataRequired("description is required")])

    amount = FloatField(
        'charge_amount',
        validators=[validators.DataRequired("amount is required")])
    recurring = BooleanField(
        'recurring',
        validators=[validators.DataRequired("recurring required")],
        choices=[True, False])
    tos = BooleanField('transaction_type',
                       validators=[validators.DataRequired()],
                       choices=["main_sale", "upsell1", "upsell2"])

    stripeToken = StringField('stripeToken',
                              validators=[validators.DataRequired()])
示例#8
0
class ProductAddForm(FlaskForm):
    """ 新增商品表单 """
    name = StringField(label='商品名称', validators=[validators.DataRequired('商品名称不能为空')], render_kw={
        'class': 'form-control'
    })
    desc = TextAreaField(label='商品简述', validators=[validators.Length(max=150, message='商品简述不能超过150个字!')], render_kw={
        'class': 'form-control'
    })
    content = TextAreaField(label='商品详情描述', render_kw={
        'class': 'form-control'
    })
    types = SelectField(label='商品类型', choices=(
        ('VIRTUAL', ProductTypes.VIRTUAL.value), ('PHYSICAL', ProductTypes.PHYSICAL.value)),
                        validators=[validators.DataRequired('商品类型不能为空')], render_kw={
            'class': 'form-control'
        })
    price = FloatField(label='销售价格', validators=[validators.DataRequired('商品销售价格不能为空')], render_kw={
        'class': 'form-control'
    })
    origin_price = FloatField(label='商品原价', validators=[validators.DataRequired('商品原价不能为空')], render_kw={
        'class': 'form-control'
    })
    img = FileField(label='商品主图', validators=[validators.DataRequired('商品主图不能为空')])
    img_list = MultipleFileField(label='商品轮播图', description='键盘按住Ctrl/Shift可多选')
    channel = StringField(label='渠道', render_kw={
        'class': 'form-control'
    })
    buy_link = StringField(label='商品购买链接', render_kw={
        'class': 'form-control'
    })
    buy_qr_code = FileField(label='小程序二维码')
    status = SelectField(label='商品状态', choices=(
        ('NOT_SALE', ProductStatus.NOT_SALE.value),
        ('ON_SALE', ProductStatus.ON_SALE.value),
        ('SOLD_OUT', ProductStatus.SOLD_OUT.value),
        ('OFF_THE_SHELF', ProductStatus.OFF_THE_SHELF.value)),
                         validators=[validators.DataRequired('商品状态不能为空')], render_kw={
            'class': 'form-control'
        })
    sku_count = IntegerField(label='商品库存', validators=[validators.DataRequired('商品库存不能为空')], render_kw={
        'class': 'form-control'
    })
    remain_count = IntegerField(label='商品剩余库存', validators=[validators.DataRequired('商品剩余库存不能为空')], render_kw={
        'class': 'form-control'
    })
    view_count = IntegerField(label='商品浏览次数', render_kw={
        'class': 'form-control'
    }, default=0)
    score = IntegerField(label='商品综合评分', render_kw={
        'class': 'form-control'
    }, default=10)
    reorder = IntegerField(label='商品排序', render_kw={
        'class': 'form-control'
    }, default=0)
    is_valid = BooleanField(label='是否有效', default=True)

    def save(self):
        # print(self.data)
        # product_obj = self.data
        uid = uuid.uuid4(),
        name = self.name.data
        desc = self.desc.data
        content = self.content.data
        types = self.types.data
        price = self.price.data
        origin_price = self.origin_price.data
        # img = self.img.data
        img = '/xxx.jpg'
        img_list = self.img_list.data
        channel = self.channel.data
        buy_link = self.buy_link.data
        buy_qr_code = self.buy_qr_code.data
        status = self.status.data
        sku_count = self.sku_count.data
        remain_count = self.remain_count.data
        view_count = self.view_count.data
        score = self.score.data
        reorder = self.reorder.data
        is_valid = self.is_valid.data
        try:
            product_obj = Product(uid=uid, name=name, desc=desc, content=content, types=types, price=price,
                                  origin_price=origin_price, img=img, img_list=img_list, channel=channel,
                                  buy_link=buy_link, buy_qr_code=buy_qr_code, status=status, sku_count=sku_count,
                                  remain_count=remain_count, view_count=view_count, score=score, reorder=reorder,
                                  is_valid=is_valid)
            db.session.add(product_obj)
            db.session.commit()
            return product_obj
        except Exception as e:
            print(e)
        return None

    def edit(self, prod_obj):
        prod_obj.name = self.name.data
        prod_obj.desc = self.desc.data
        prod_obj.content = self.content.data
        prod_obj.types = self.types.data
        prod_obj.price = self.price.data
        prod_obj.origin_price = self.origin_price.data
        # img = self.img.data
        prod_obj.img = '/xxx.jpg'
        prod_obj.img_list = self.img_list.data
        prod_obj.channel = self.channel.data
        prod_obj.buy_link = self.buy_link.data
        prod_obj.buy_qr_code = self.buy_qr_code.data
        prod_obj.status = self.status.data
        prod_obj.sku_count = self.sku_count.data
        prod_obj.remain_count = self.remain_count.data
        prod_obj.view_count = self.view_count.data
        prod_obj.score = self.score.data
        prod_obj.reorder = self.reorder.data
        prod_obj.is_valid = self.is_valid.data
        try:
            db.session.add(prod_obj)
            db.session.commit()
            return prod_obj
        except Exception as e:
            print(e)
        return None
示例#9
0
class New_Review_food(FlaskForm):
    item_name_food = StringField('Name of food item',
                                 validators=[DataRequired()])
    content_food = TextAreaField('Your Review', validators=[DataRequired()])
    rating_food = FloatField('Rating out of 5', validators=[DataRequired()])
    submit = SubmitField('Submit Your Review')
示例#10
0
class BaselineForm(FlaskForm):
    """ Form for the selection of the book and the method to use for the automatic extraction of prerequisites """
    book_cap = SelectField('Book', choices=[])
    baseline_method = SelectField('Method',
                                  choices=[
                                      ('1', '1: Lexical Relations'),
                                      ('2',
                                       '2: Lexical Syntactic Pattern Match'),
                                      ('3', '3: Relational Metric'),
                                      ('4', '4: Wikipedia'),
                                      ('5', '5: Textbook Structure'),
                                      ('6', '6: Temporal Patterns')
                                  ])
    threshold = FloatField('Threshold')

    # Burst method
    default = BooleanField('Default params', default='checked')
    s = FloatField('S', default='1.05')
    gamma = FloatField('Gamma', default='0.0001')
    level = FloatField('Level', default='1')
    # Allen weights
    equals = FloatField('Equals', default='2')
    before = FloatField('Before', default='5')
    after = FloatField('After', default='0')
    meets = FloatField('Meets', default='3')
    metby = FloatField('Met-by', default='0')
    overlaps = FloatField('Overlaps', default='7')
    overlappedby = FloatField('Overlapped-by', default='1')
    during = FloatField('During', default='7')
    includes = FloatField('Includes', default='7')
    starts = FloatField('Starts', default='4')
    startedby = FloatField('Started-by', default='2')
    finishes = FloatField('Finishes', default='2')
    finishedby = FloatField('Finished-by', default='8')

    max_gap = FloatField('Max gap', default='4')
    norm_formula = StringField('Norm Formula', default="modified")
    use_inverses = BooleanField('Use inverses', default='unchecked')

    submit = SubmitField('Launch Method')
示例#11
0
文件: forms.py 项目: JHHXYZ/DSCS2020
class PostForm(FlaskForm):
    item_name = StringField("Product Name", validators=[DataRequired()])
    description = StringField("Description", validators=[DataRequired()])
    price = FloatField("Price in CHF", validators=[DataRequired()])
    image_upload = FileField("Product Image", validators=[DataRequired()])
    submit_button = SubmitField("Submit")
示例#12
0
class RegistrationForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email(message='Enter valid email address')])
    phone = FloatField('Phone', validators=[DataRequired()])
    hourly = FloatField('Hourly Rate', validators=[DataRequired()])
    submit = SubmitField('Register')
示例#13
0
class clientForm(FlaskForm):
    clientName = StringField('Client Name')
    clientClass = IntegerField('client class')
    clientID = IntegerField('Client ID')
    clientSalary = FloatField('Client Salary')
示例#14
0
class manageBankDataForm(FlaskForm):
    sanction_list = FileField('Upload Sanction List:')
    risk_countries = SelectMultipleField(
        'High Risk Countries:',
        choices=[
            ('Afghanistan', 'Afghanistan'), ('Åland Islands', 'Åland Islands'),
            ('Albania', 'Albania'), ('Algeria', 'Algeria'),
            ('American', 'American'), ('Andorra', 'Andorra'),
            ('Angola', 'Angola'), ('Anguilla', 'Anguilla'),
            ('Antarctica', 'Antarctica'),
            ('Antigua and Barbuda', 'Antigua and Barbuda'),
            ('Argentina', 'Argentina'), ('Armenia', 'Armenia'),
            ('Austria', 'Austria'), ('Azerbaijan', 'Azerbaijan'),
            ('Bahamas', 'Bahamas'), ('Bahrain', 'Bahrain'),
            ('Bangladesh', 'Bangladesh'), ('Barbados', 'Barbados'),
            ('Belarus', 'Belarus'), ('Belgium', 'Belgium'),
            ('Belize', 'Belize'), ('Benin', 'Benin'), ('Bermuda', 'Bermuda'),
            ('Bhutan', 'Bhutan'),
            ('Bolivia, Plurinational State of',
             'Bolivia, Plurinational State of'),
            ('Bonaire, Sint Eustatius and Saba',
             'Bonaire, Sint Eustatius and Saba'),
            ('Bosnia and Herzegovina', 'Bosnia and Herzegovina'),
            ('Botswana', 'Botswana'), ('Bouvet Island', 'Bouvet Island'),
            ('Brazil', 'Brazil'),
            ('British Indian Ocean Territory',
             'British Indian Ocean Territory'),
            ('Brunei Darussalam', 'Brunei Darussalam'),
            ('Bulgaria', 'Bulgaria'), ('Burkina Faso', 'Burkina Faso'),
            ('Burundi', 'Burundi'), ('Cambodia', 'Cambodia'),
            ('Cameroon', 'Cameroon'), ('Canada', 'Canada'),
            ('Cape Verde', 'Cape Verde'), ('Cayman Islands', 'Cayman Islands'),
            ('Central African Republic', 'Central African Republic'),
            ('Chad', 'Chad'), ('Chile', 'Chile'), ('China', 'China'),
            ('Christmas Island', 'Christmas Island'),
            ('Cocos (Keeling) Islands', 'Cocos (Keeling) Islands'),
            ('Colombia', 'Colombia'), ('Comoros', 'Comoros'),
            ('Congo', 'Congo'),
            ('Congo, the Democratic Republic of the',
             'Congo, the Democratic Republic of the'),
            ('Cook Islands', 'Cook Islands'), ('Costa Rica', 'Costa Rica'),
            ('Côte d Ivoire', 'Côte d Ivoire'), ('Croatia', 'Croatia'),
            ('Cuba', 'Cuba'), ('Curaçao', 'Curaçao'), ('Cyprus', 'Cyprus'),
            ('Czech Republic', 'Czech Republic'), ('Denmark', 'Denmark'),
            ('Djibouti', 'Djibouti'), ('Dominica', 'Dominica'),
            ('Dominican Republic', 'Dominican Republic'), ('Ecuador',
                                                           'Ecuador'),
            ('Egypt', 'Egypt'), ('El Salvador', 'El Salvador'),
            ('Equatorial Guinea', 'Equatorial Guinea'), ('Eritrea', 'Eritrea'),
            ('Estonia', 'Estonia'), ('Ethiopia', 'Ethiopia'),
            ('Falkland Islands (Malvinas)', 'Falkland Islands (Malvinas)'),
            ('Faroe Islands', 'Faroe Islands'), ('Fiji', 'Fiji'),
            ('Finland', 'Finland'), ('France', 'France'),
            ('French Guiana', 'French Guiana'),
            ('French Polynesia', 'French Polynesia'),
            ('French Southern Territories', 'French Southern Territories'),
            ('Gabon', 'Gabon'), ('Gambia', 'Gambia'), ('Georgia', 'Georgia'),
            ('Germany', 'Germany'), ('Ghana', 'Ghana'),
            ('Gibraltar', 'Gibraltar'), ('Greece', 'Greece'),
            ('Greenland', 'Greenland'), ('Grenada', 'Grenada'),
            ('Guadeloupe', 'Guadeloupe'), ('Guam', 'Guam'),
            ('Guatemala', 'Guatemala'), ('Guernsey', 'Guernsey'),
            ('Guinea', 'Guinea'), ('Guinea-Bissau', 'Guinea-Bissau'),
            ('Guyana', 'Guyana'), ('Haiti', 'Haiti'),
            ('Heard Island and McDonald Islands',
             'Heard Island and McDonald Islands'),
            ('Holy See (Vatican City State)', 'Holy See (Vatican City State)'),
            ('Honduras', 'Honduras'), ('Hong Kong', 'Hong Kong'),
            ('Hungary', 'Hungary'), ('Iceland', 'Iceland'), ('India', 'India'),
            ('Indonesia', 'Indonesia'), ('Iran', 'Iran'), ('Iraq', 'Iraq'),
            ('Ireland', 'Ireland'), ('Isle of Man', 'Isle of Man'),
            ('Israel', 'Israel'), ('Italy', 'Italy'), ('Jamaica', 'Jamaica'),
            ('Japan', 'Japan'), ('Jersey', 'Jersey'), ('Jordan', 'Jordan'),
            ('Kazakhstan', 'Kazakhstan'), ('Kenya', 'Kenya'),
            ('Kiribati', 'Kiribati'), ('North Korea', 'North Korea'),
            ('South Korea', 'South Korea'), ('Kuwait', 'Kuwait'),
            ('Kyrgyzstan', 'Kyrgyzstan'), ('Lao', 'Lao'), ('Latvia', 'Latvia'),
            ('Lebanon', 'Lebanon'), ('Lesotho', 'Lesotho'),
            ('Liberia', 'Liberia'), ('Libya', 'Libya'),
            ('Liechtenstein', 'Liechtenstein'), ('Lithuania', 'Lithuania'),
            ('Luxembourg', 'Luxembourg'), ('Macao', 'Macao'),
            ('Macedonia', 'Macedonia'), ('Madagascar', 'Madagascar'),
            ('Malawi', 'Malawi'), ('Malaysia', 'Malaysia'),
            ('Maldives', 'Maldives'), ('Mali', 'Mali'), ('Malta', 'Malta'),
            ('Marshall Islands', 'Marshall Islands'),
            ('Martinique', 'Martinique'), ('Mauritania', 'Mauritania'),
            ('Mauritius', 'Mauritius'), ('Mayotte', 'Mayotte'),
            ('Mexico', 'Mexico'), ('Micronesia', 'Micronesia'),
            ('Moldova', 'Moldova'), ('Monaco', 'Monaco'),
            ('Mongolia', 'Mongolia'), ('Montenegro', 'Montenegro'),
            ('Montserrat', 'Montserrat'), ('Morocco', 'Morocco'),
            ('Mozambique', 'Mozambique'), ('Myanmar', 'Myanmar'),
            ('Namibia', 'Namibia'), ('Nauru', 'Nauru'), ('Nepal', 'Nepal'),
            ('Netherlands', 'Netherlands'), ('New Caledonia', 'New Caledonia'),
            ('New Zealand', 'New Zealand'), ('Nicaragua', 'Nicaragua'),
            ('Niger', 'Niger'), ('Nigeria', 'Nigeria'), ('Niue', 'Niue'),
            ('Norfolk Island', 'Norfolk Island'),
            ('Northern Mariana Islands', 'Northern Mariana Islands'),
            ('Norway', 'Norway'), ('Oman', 'Oman'), ('Pakistan', 'Pakistan'),
            ('Palau', 'Palau'), ('Palestinian', 'Palestinian'),
            ('Panama', 'Panama'), ('Papua New Guinea', 'Papua New Guinea'),
            ('Paraguay', 'Paraguay'), ('Peru', 'Peru'),
            ('Philippines', 'Philippines'), ('Pitcairn', 'Pitcairn'),
            ('Poland', 'Poland'), ('Portugal', 'Portugal'),
            ('Puerto Rico', 'Puerto Rico'), ('Qatar', 'Qatar'),
            ('Réunion', 'Réunion'), ('Romania', 'Romania'),
            ('Russian', 'Russian'), ('Rwanda', 'Rwanda'),
            ('Saint Barthélemy', 'Saint Barthélemy'),
            ('Saint Helena', 'Saint Helena'),
            ('Saint Kitts and Nevis', 'Saint Kitts and Nevis'),
            ('Saint Lucia', 'Saint Lucia'), ('Saint Martin', 'Saint Martin'),
            ('Saint Pierre and Miquelon', 'Saint Pierre and Miquelon'),
            ('Saint Vincent and the Grenadines',
             'Saint Vincent and the Grenadines'), ('Samoa', 'Samoa'),
            ('San Marino', 'San Marino'),
            ('Sao Tome and Principe', 'Sao Tome and Principe'),
            ('Saudi Arabia', 'Saudi Arabia'), ('Senegal', 'Senegal'),
            ('Serbia', 'Serbia'), ('Seychelles', 'Seychelles'),
            ('Sierra Leone', 'Sierra Leone'), ('Singapore', 'Singapore'),
            ('Sint Maarten', 'Sint Maarten'), ('Slovakia', 'Slovakia'),
            ('Slovenia', 'Slovenia'), ('Solomon Islands', 'Solomon Islands'),
            ('Somalia', 'Somalia'), ('South Africa', 'South Africa'),
            ('South Georgia', 'South Georgia'), ('South Sudan', 'South Sudan'),
            ('Spain', 'Spain'), ('Sri Lanka', 'Sri Lanka'), ('Sudan', 'Sudan'),
            ('Suriname', 'Suriname'),
            ('Svalbard and Jan Mayen', 'Svalbard and Jan Mayen'),
            ('Swaziland', 'Swaziland'), ('Sweden', 'Sweden'),
            ('Switzerland', 'Switzerland'), ('Syrian', 'Syrian'),
            ('Taiwan', 'Taiwan'), ('Tajikistan', 'Tajikistan'),
            ('Tanzania', 'Tanzania'), ('Thailand', 'Thailand'),
            ('Timor-Leste', 'Timor-Leste'), ('Togo', 'Togo'),
            ('Tokelau', 'Tokelau'), ('Tonga', 'Tonga'),
            ('Trinidad and Tobago', 'Trinidad and Tobago'),
            ('Tunisia', 'Tunisia'), ('Turkey', 'Turkey'),
            ('Turkmenistan', 'Turkmenistan'),
            ('Turks and Caicos Islands', 'Turks and Caicos Islands'),
            ('Tuvalu', 'Tuvalu'), ('Uganda', 'Uganda'), ('Ukraine', 'Ukraine'),
            ('United Arab Emirates', 'United Arab Emirates'),
            ('United Kingdom', 'United Kingdom'),
            ('United States', 'United States'),
            ('United States Minor Outlying Islands',
             'United States Minor Outlying Islands'), ('Uruguay', 'Uruguay'),
            ('Uzbekistan', 'Uzbekistan'), ('Vanuatu', 'Vanuatu'),
            ('Venezuela', 'Venezuela'), ('Viet Nam', 'Viet Nam'),
            ('Virgin Islands, British', 'Virgin Islands, British'),
            ('Virgin Islands, U.S.', 'Virgin Islands, U.S.'),
            ('Wallis and Futuna', 'Wallis and Futuna'),
            ('Western Sahara', 'Western Sahara'), ('Yemen', 'Yemen'),
            ('Zambia', 'Zambia'), ('Zimbabwe', 'Zimbabwe')
        ])
    exceed_avg_tran = FloatField('Exceeding Average Transactions With:',
                                 validators=[DataRequired()],
                                 widget=html5.NumberInput(step="any"))
    #type = SelectField('Type: ' , choices=[('Transfer', 'Transfer') , ('Cash out', 'Cash out')])
    amount = FloatField('Transaction Risk Amount:',
                        validators=[DataRequired()],
                        widget=html5.NumberInput(step="any"))
    bank_submit = SubmitField('submit')
示例#15
0
class AddTransForm(FlaskForm):
    destination = StringField('destination', validators=[DataRequired()])
    amount = FloatField('amount', validators=[DataRequired()])
    currency = StringField('currency', validators=[DataRequired()], default='MXN')
    submit = SubmitField('Agregar')
示例#16
0
文件: sgpa.py 项目: simpuid/cvbuilder
class CGPAForm(FlaskForm):
    sg_list = FieldList(FormField(SGPAForm))
    semester = IntegerField('Semester', validators=[Optional()])
    sgpa = FloatField('SGPA', validators=[Optional()])
    add = SubmitField('Add')
示例#17
0
class AttributeIntervalRatioForm(FlaskForm):
    mscale_choice = SelectField('Measurement Scale',
                                choices=[("interval", "interval"),
                                         ("ratio", "ratio")])
    attribute_name = StringField('Name', validators=[])
    attribute_label = StringField('Label (Optional)', validators=[])
    attribute_definition = StringField('Definition', validators=[])
    storage_type = StringField('Storage Type (Optional)', validators=[])
    storage_type_system = StringField('Storage Type System (Optional)',
                                      validators=[])
    standard_units = [
        '', 'acre', 'ampere', 'amperePerMeter', 'amperePerMeterSquared',
        'angstrom', 'are', 'atmosphere', 'bar', 'becquerel',
        'britishThermalUnit', 'bushel', 'bushelPerAcre', 'calorie', 'candela',
        'candelaPerMeterSquared', 'celsius', 'centigram', 'centimeter',
        'centimeterCubed', 'centimeterPerSecond', 'centimeterSquared',
        'centisecond', 'coulomb', 'decibar', 'decigram', 'decimeter',
        'decisecond', 'degree', 'dekagram', 'dekameter', 'dekasecond',
        'dimensionless', 'equivalentPerLiter', 'fahrenheit', 'farad', 'fathom',
        'foot', 'Foot_Gold_Coast', 'Foot_US', 'footCubedPerSecond',
        'footPerDay', 'footPerHour', 'footPerSecond', 'footPound',
        'footSquared', 'footSquaredPerDay', 'gallon', 'grad', 'gram',
        'gramPerCentimeterCubed', 'gramPercentimeterSquared',
        'gramPerCentimeterSquaredPerSecond', 'gramPerDayPerHectare',
        'gramPerDayPerLiter', 'gramPerGram', 'gramPerLiter',
        'gramPerMeterSquared', 'gramPerMeterSquaredPerDay',
        'gramPerMeterSquaredPerYear', 'gramPerMilliliter', 'gramPerYear',
        'gray', 'hectare', 'hectogram', 'hectometer', 'hectopascal',
        'hectosecond', 'henry', 'hertz', 'hour', 'inch', 'inchCubed',
        'inchPerHour', 'inverseCentimeter', 'inverseMeter', 'joule', 'katal',
        'kelvin', 'kilogram', 'kilogramPerHectare',
        'kilogramPerHectarePerYear', 'kilogramPerMeterCubed',
        'kilogramPerMeterSquared', 'kilogramPerMeterSquaredPerDay',
        'kilogramPerMeterSquaredPerSecond', 'kilogramPerMeterSquaredPerYear',
        'kilogramPerSecond', 'kilohertz', 'kiloliter', 'kilometer',
        'kilometerPerHour', 'kilometerSquared', 'kilopascal', 'kilosecond',
        'kilovolt', 'kilowatt', 'kilowattPerMeterSquared', 'knot', 'langley',
        'langleyPerDay', 'Link_Clarke', 'liter', 'literPerHectare',
        'literPerLiter', 'literPerMeterSquared', 'literPerSecond', 'lumen',
        'lux', 'megagram', 'megagramPerMeterCubed', 'megahertz',
        'megajoulePerMeterSquaredPerDay', 'megameter', 'megapascal',
        'megasecond', 'megavolt', 'megawatt', 'meter', 'meterCubed',
        'meterCubedPerHectare', 'meterCubedPerKilogram',
        'meterCubedPerMeterCubed', 'meterCubedPerMeterSquared',
        'meterCubedPerSecond', 'meterPerDay', 'meterPerGram', 'meterPerSecond',
        'meterPerSecondSquared', 'meterSquared', 'meterSquaredPerDay',
        'meterSquaredPerHectare', 'meterSquaredPerKilogram',
        'meterSquaredPerSecond', 'microequivalentPerLiter', 'microgram',
        'microgramPerGram', 'microgramPerGramPerDay',
        'microgramPerGramPerHour', 'microgramPerGramPerWeek',
        'microgramPerLiter', 'microliter', 'microliterPerLiter', 'micrometer',
        'micrometerCubedPerGram', 'micromolePerCentimeterSquaredPerSecond',
        'micromolePerGram', 'micromolePerGramPerDay',
        'micromolePerGramPerHour', 'micromolePerGramPerSecond',
        'micromolePerKilogram', 'micromolePerLiter',
        'micromolePerMeterSquaredPerSecond', 'micromolePerMole', 'microsecond',
        'microwattPerCentimeterSquaredPerNanometer',
        'microwattPerCentimeterSquaredPerNanometerPerSteradian',
        'microwattPerCentimeterSquaredPerSteradian', 'mile', 'milePerHour',
        'milePerMinute', 'milePerSecond', 'mileSquared', 'millibar',
        'milliequivalentPerLiter', 'milligram', 'milligramPerKilogram',
        'milligramPerLiter', 'milligramPerMeterCubed',
        'milligramPerMeterCubedPerDay', 'milligramPerMeterSquared',
        'milligramPerMeterSquaredPerDay', 'milligramPerMilliliter',
        'millihertz', 'milliliter', 'milliliterPerLiter', 'millimeter',
        'millimeterPerDay', 'millimeterPerSecond', 'millimeterSquared',
        'millimolePerGram', 'millimolePerKilogram', 'millimolePerLiter',
        'millimolePerMeterCubed', 'millimolePerMole', 'millisecond',
        'millivolt', 'milliwatt', 'minute', 'mole', 'molePerGram',
        'molePerKilogram', 'molePerKilogram', 'molePerKilogramPerSecond',
        'molePerLiter', 'molePerMeterCubed', 'molePerMeterSquaredPerSecond',
        'molePerMole', 'nanogram', 'nanogramPerGram', 'nanogramPerGramPerHour',
        'nanoliterPerLiter', 'nanometer', 'nanomolePerGramPerDay',
        'nanomolePerGramPerHour', 'nanomolePerGramPerSecond',
        'nanomolePerKilogram', 'nanomolePerLiter', 'nanomolePerMole',
        'nanosecond', 'nauticalMile', 'newton', 'nominalDay', 'nominalHour',
        'nominalLeapYear', 'nominalMinute', 'nominalWeek', 'nominalYear',
        'number', 'numberPerGram', 'numberPerHectare',
        'numberPerKilometerSquared', 'numberPerLiter', 'numberPerMeterCubed',
        'numberPerMeterSquared', 'numberPerMilliliter', 'ohm', 'ohmMeter',
        'pascal', 'percent', 'permil', 'pint', 'pound', 'poundPerAcre',
        'poundPerInchSquared', 'quart', 'radian', 'second', 'siemens',
        'siemensPerCentimeter', 'siemensPerMeter', 'sievert', 'steradian',
        'tesla', 'ton', 'tonne', 'tonnePerHectare', 'tonnePerYear', 'volt',
        'watt', 'wattPerMeterSquared', 'wattPerMeterSquaredPerNanometer',
        'wattPerMeterSquaredPerNanometerPerSteradian',
        'wattPerMeterSquaredPerSteradian', 'weber', 'yard', 'Yard_Indian',
        'yardPerSecond', 'yardSquared'
    ]
    standard_unit = SelectField('Standard Unit',
                                choices=[(unit, unit)
                                         for unit in standard_units])
    custom_unit = StringField('Custom Unit', validators=[])
    precision = FloatField('Precision (Optional)', validators=[Optional()])
    number_type = SelectField('Number Type',
                              choices=[("real", "real"),
                                       ("integer", "integer"),
                                       ("natural", "natural"),
                                       ("whole", "whole")])
    bounds_minimum = FloatField('Bounds Minimum', validators=[Optional()])
    bounds_minimum_exclusive = BooleanField('Bounds Minimum is Exclusive',
                                            validators=[])
    bounds_maximum = FloatField('Bounds Maximum', validators=[Optional()])
    bounds_maximum_exclusive = BooleanField('Bounds Maximum is Exclusive',
                                            validators=[])
    code_1 = StringField('Missing Value Code', validators=[])
    code_explanation_1 = StringField('Explanation', validators=[])
    code_2 = StringField('Missing Value Code', validators=[])
    code_explanation_2 = StringField('Explanation', validators=[])
    code_3 = StringField('Missing Value Code', validators=[])
    code_explanation_3 = StringField('Explanation', validators=[])
    md5 = HiddenField('')
    mscale = HiddenField('')

    def field_data(self) -> tuple:
        return (self.mscale_choice.data, self.attribute_name.data,
                self.attribute_label.data, self.attribute_definition.data,
                self.storage_type.data, self.storage_type_system.data,
                self.standard_unit.data, self.custom_unit.data,
                self.precision.data, self.number_type.data,
                self.bounds_minimum.data, self.bounds_minimum_exclusive.data,
                self.bounds_maximum.data, self.bounds_maximum_exclusive.data,
                self.code_1.data, self.code_explanation_1.data,
                self.code_2.data, self.code_explanation_2.data,
                self.code_3.data, self.code_explanation_3.data,
                self.mscale.data)
示例#18
0
文件: sgpa.py 项目: simpuid/cvbuilder
class SGPAForm(Form):
    semester = IntegerField('Semester', validators=[Optional()])
    sgpa = FloatField('SGPA', validators=[Optional()])
    save = SubmitField('Save')
    delete = SubmitField('Delete')
示例#19
0
class BasePaymentForm(FlaskForm):
    amount = FloatField('Amount', validators=[DataRequired()])
    currency = SelectField('Currency', validators=[DataRequired()],
                           choices=CURRENCY_CHOICES, coerce=int)
    description = TextAreaField('Description', validators=[DataRequired()])
    submit = SubmitField('Pay')
示例#20
0
class InputMicroNutrientsForm(Form):
    Betaine = FloatField()
    Calcium = FloatField()
    Choline = FloatField()
    Copper = FloatField()
    Fluoride = FloatField()
    Folate = FloatField()
    Folate_DFE = FloatField()
    Folate_food = FloatField()
    Folic_acid = FloatField()
    Iron = FloatField()
    Magnesium = FloatField()
    Manganese = FloatField()
    Niacin = FloatField()
    Fluoride = FloatField()
    Pantothenic_acid = FloatField()
    Phosphorus = FloatField()
    Potassium = FloatField()
    Retinol = FloatField()
    Riboflavin = FloatField()
    Selenium = FloatField()
    Sodium = FloatField()
    Fluoride = FloatField()
    Thiamin = FloatField()
    Vitamin_A = FloatField()
    Vitamin_B12 = FloatField()
    Vitamin_B12_added = FloatField()
    Vitamin_B6 = FloatField()
    Vitamin_C = FloatField()
    Vitamin_D = FloatField()
    Vitamin_D2 = FloatField()
    Vitamin_D3 = FloatField()
    Vitamin_E = FloatField()
    Vitamin_E_added = FloatField()
    Vitamin_K = FloatField()
    Zinc = FloatField()
示例#21
0
class OnePlant(FlaskForm):
    LocationName = StringField('Location Name')
    lat = FloatField('Latitude')
    lon = FloatField('Longitude')
    existing_location = BooleanField('Existing Location')
    existing_tech = SelectField('Technology at existing location')
示例#22
0
class PostForm(FlaskForm):
    title = StringField('Title', validators=[DataRequired()])
    # change
    score = FloatField('Score', validators=[DataRequired()])
    content = TextAreaField('Content', validators=[DataRequired()])
    submit = SubmitField('Post')
示例#23
0
class OneParam(FlaskForm):
    Label = StringField('Parameter')
    Unit = StringField('Unit')
    Value = FloatField('Value')
    Description = StringField('Description')
示例#24
0
class AddExpense(FlaskForm):
    name = StringField('Name of Expense', validators=[DataRequired()])
    price = FloatField('Price', validators=[DataRequired()])
    description = TextAreaField('Description', validators=[DataRequired()])
    submit = SubmitField('Submit')
示例#25
0
class PurchaseForm(FlaskForm):
    category = SelectField('Catégorie', coerce=int)
    price = FloatField('Prix', widget=NumberInput(step=0.01))
    label = StringField('Description')
示例#26
0
def generate_settings_form(settings):
    """Generates a settings form which includes field validation
    based on our Setting Schema."""
    class SettingsForm(FlaskForm):
        pass

    # now parse the settings in this group
    for setting in settings:
        field_validators = []

        if setting.value_type in {
                SettingValueType.integer, SettingValueType.float
        }:
            validator_class = NumberRange
        elif setting.value_type == SettingValueType.string:
            validator_class = Length

        # generate the validators
        if setting.extra:
            if "min" in setting.extra:
                # Min number validator
                field_validators.append(
                    validator_class(min=setting.extra["min"]))

            if "max" in setting.extra:
                # Max number validator
                field_validators.append(
                    validator_class(max=setting.extra["max"]))

        # Generate the fields based on value_type
        # IntegerField
        if setting.value_type == SettingValueType.integer:
            setattr(
                SettingsForm,
                setting.key,
                IntegerField(
                    setting.name,
                    validators=field_validators,
                    description=setting.description,
                ),
            )
        # FloatField
        elif setting.value_type == SettingValueType.float:
            setattr(
                SettingsForm,
                setting.key,
                FloatField(
                    setting.name,
                    validators=field_validators,
                    description=setting.description,
                ),
            )

        # TextField
        elif setting.value_type == SettingValueType.string:
            setattr(
                SettingsForm,
                setting.key,
                StringField(
                    setting.name,
                    validators=field_validators,
                    description=setting.description,
                ),
            )

        # SelectMultipleField
        elif setting.value_type == SettingValueType.selectmultiple:
            # if no coerce is found, it will fallback to unicode
            if "coerce" in setting.extra:
                coerce_to = setting.extra["coerce"]
            else:
                coerce_to = text_type

            setattr(
                SettingsForm,
                setting.key,
                SelectMultipleField(
                    setting.name,
                    choices=setting.extra["choices"](),
                    coerce=coerce_to,
                    description=setting.description,
                ),
            )

        # SelectField
        elif setting.value_type == SettingValueType.select:
            # if no coerce is found, it will fallback to unicode
            if "coerce" in setting.extra:
                coerce_to = setting.extra["coerce"]
            else:
                coerce_to = text_type

            setattr(
                SettingsForm,
                setting.key,
                SelectField(
                    setting.name,
                    coerce=coerce_to,
                    choices=setting.extra["choices"](),
                    description=setting.description,
                ),
            )

        # BooleanField
        elif setting.value_type == SettingValueType.boolean:
            setattr(
                SettingsForm,
                setting.key,
                BooleanField(setting.name, description=setting.description),
            )

    return SettingsForm
示例#27
0
class UserProductEditForm(FlaskForm):
    product_price = FloatField("  Price: ", [validators.regexp('\d{1,10}', message="Price must be real number not exceeding 10 characters")])
    product_count = IntegerField("  Count: ",)
    product_priority = SelectField("  Priority: ", choices=[('Low','Low'), ('Medium','Medium'), ('High','High')])
    edit = SubmitField('Edit')
示例#28
0
class PromocodeCreateForm(FlaskForm):
    promocode = StringField('Добавить промокод', validators=[DataRequired()])
    award = FloatField(validators=[DataRequired()])
    submit = SubmitField('Добавить')
示例#29
0
class PlanForm(ModelForm):
    class Meta:
        model = models.Plan
        exclude = ['plan_args']

    dateobs = DateTimeField()

    telescope = SelectField(default='ZTF')

    localization = SelectField()

    def _localization_query(self):
        return models.Localization.query.filter_by(dateobs=self.dateobs.data)

    validity_window_start = DateTimeField(
        format='%Y-%m-%d %H:%M:%S',
        default=lambda: datetime.datetime.utcnow(),
        validators=[validators.DataRequired()])

    validity_window_end = DateTimeField(
        format='%Y-%m-%d %H:%M:%S',
        default=lambda: datetime.datetime.utcnow() + datetime.timedelta(1),
        validators=[validators.DataRequired()])

    filters = TextField('filters', validators=[validators.DataRequired()])

    schedule = RadioField(choices=[('greedy', 'greedy'), ('sear', 'sear'),
                                   ('airmass_weighted', 'airmass_weighted'),
                                   ('greedy_slew', 'greedy_slew')],
                          default='greedy')

    dither = BooleanField(default=False)

    references = BooleanField(default=False)

    primary = BooleanField(default=False)

    balance = BooleanField(default=False)

    completed = BooleanField(default=False)

    completed_window_start = DateTimeField(
        format='%Y-%m-%d %H:%M:%S',
        default=lambda: datetime.datetime.utcnow() - datetime.timedelta(1),
        validators=[validators.DataRequired()])

    completed_window_end = DateTimeField(
        format='%Y-%m-%d %H:%M:%S',
        default=lambda: datetime.datetime.utcnow(),
        validators=[validators.DataRequired()])

    planned = BooleanField(default=False)

    maxtiles = BooleanField(default=False)

    filterschedule = RadioField(choices=[('block', 'block'),
                                         ('integrated', 'integrated')],
                                default='block')

    schedule_strategy = RadioField(choices=[('tiling', 'tiling'),
                                            ('catalog', 'catalog')],
                                   default='tiling')

    exposure_time = FloatField(
        default=300,
        validators=[validators.DataRequired(),
                    validators.NumberRange(min=0)])

    max_nb_tiles = DecimalSliderField(
        [validators.NumberRange(min=0, max=1000)], default=1000)

    probability = DecimalSliderField([validators.NumberRange(min=0, max=100)],
                                     default=90)

    airmass_limit = DecimalSliderField(
        [validators.NumberRange(min=1.0, max=5.0)], default=2.5)

    mindiff = DecimalSliderField([validators.NumberRange(min=0, max=180)],
                                 default=30)

    plan_name = TextField(validators=[validators.DataRequired()],
                          default='REPLACE ME')

    previous = BooleanField(default=False)

    previous_plan = SelectField()

    def _previous_plan_query(self):
        return models.Plan.query.filter_by(dateobs=self.dateobs.data)

    def validate_validity_window_end(self, field):
        other = self.validity_window_start
        if field.validate(self) and other.validate(self):
            if field.data <= self.validity_window_start.data:
                raise validators.ValidationError(
                    'End time must be after start time')

    def validate_filters(self, field):
        available_filters = set(
            models.Telescope.query.get(self.telescope.data).filters)
        filters = set(re.split(r'[\s,]+', self.filters.data))

        unavailable_filters = filters - available_filters
        if unavailable_filters:
            raise validators.ValidationError(
                'Some filters are not available for this telescope: ' +
                ', '.join(unavailable_filters))

    def validate_plan_name(self, field):
        nplans = models.Plan.query.filter_by(
            dateobs=self.dateobs.data,
            telescope=self.telescope.data,
            plan_name=self.plan_name.data).count()
        if nplans > 0:
            raise validators.ValidationError('That plan name already exists.')

    def populate_obj(self, obj):
        super().populate_obj(obj)

        start_mjd = time.Time(self.validity_window_start.data).mjd
        end_mjd = time.Time(self.validity_window_end.data).mjd
        event_mjd = time.Time(self.dateobs.data).mjd
        timediff1 = start_mjd - event_mjd
        timediff2 = end_mjd - event_mjd
        t_obs = [timediff1, timediff2]
        completed_start_mjd = time.Time(self.completed_window_start.data).mjd
        completed_end_mjd = time.Time(self.completed_window_end.data).mjd
        c_obs = [completed_start_mjd, completed_end_mjd]
        filters = re.split(r'[\s,]+', self.filters.data)

        obj.plan_args = dict(localization_name=self.localization.data,
                             tobs=t_obs,
                             filt=filters,
                             exposuretimes=[self.exposure_time.data] *
                             len(filters),
                             probability=0.01 * float(self.probability.data),
                             airmass=float(self.airmass_limit.data),
                             mindiff=float(self.mindiff.data),
                             schedule_type=self.schedule.data,
                             doDither=self.dither.data,
                             doReferences=self.references.data,
                             doUsePrimary=self.primary.data,
                             doBalanceExposure=self.balance.data,
                             filterScheduleType=self.filterschedule.data,
                             schedule_strategy=self.schedule_strategy.data,
                             usePrevious=self.previous.data,
                             previous_plan=self.previous_plan.data,
                             doCompletedObservations=self.completed.data,
                             cobs=c_obs,
                             doPlannedObservations=self.planned.data,
                             doMaxTiles=self.maxtiles.data,
                             max_nb_tiles=int(self.max_nb_tiles.data))
class addexistingform(FlaskForm):
    itemid = TextField('item ID: ', validators=[DataRequired()])
    quantity = FloatField('change quantity', validators=[DataRequired()])
    submit = SubmitField("change")