Ejemplo n.º 1
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._instances = Instances(self._supervisor.get_db())

        hosts_names = [host.get_name() for host in self._supervisor.get_hosts()]
        apps_images = [app.get_image() for app in self._supervisor.get_apps()]

        self.host.validators = [validators.input_required(),
                                validators.any_of(hosts_names)]
        self.image.validators = [validators.input_required(),
                                 validators.any_of(apps_images)]
Ejemplo n.º 2
0
class NewEmployeeForm(Form):
    """
    Handle backend communications for the button associated with generating predictions on a hypothetical employee
    """
    satisfaction_level = FloatField(
        'Satisfaction Level, ranging from 0 to 1',
        [
            validators.DataRequired()  #,
            # validators.number_range(0, 1)
        ])
    last_evaluation = FloatField(
        'Last Evaluation, ranging from 0 to 1',
        [
            validators.DataRequired()  #,
            #validators.number_range(0, 1)
        ])
    number_project = IntegerField(
        'Number of Projects, at least zero',
        [
            validators.DataRequired()  #,
            #validators.number_range(min=0)
        ])
    average_montly_hours = IntegerField(
        'Average Monthly Hours, at least zero',
        [
            validators.DataRequired()  #,
            #validators.number_range(min=0)
        ])
    time_spend_company = IntegerField(
        'Time Spent at Company, at least zero',
        [
            validators.DataRequired()  #,
            #validators.number_range(min=0)
        ])
    Work_accident = StringField(
        'Work Accident, True or False',
        [
            validators.DataRequired(),
            validators.any_of(["True", "False", "true", "false", "0", "1"])
            # ideally, this is a BooleanField
        ])
    promotion_last_5years = StringField(
        'Promotion Within Last 5 Years, True or False',
        [
            validators.DataRequired(),
            validators.any_of(["True", "False", "true", "false", "0", "1"])
            # ideally, this is a BooleanField
        ])
    department = StringField('Depatrment', [validators.DataRequired()])
    salary = StringField('Salary Band', [validators.DataRequired()])
Ejemplo n.º 3
0
class formReg(Form):
    first_name = StringField('First Name', [validators.length(min=1, max=50)])
    last_name = StringField('Last Name', [validators.length(min=1, max=50)])
    address1 = StringField('Address 1', [validators.length(min=1, max=95)])
    address2 = StringField('Address 2')
    city = StringField('City', [validators.length(min=1, max=35)])
    state = StringField(
        'State (2 Digit Code)',
        [validators.any_of(states),
         validators.length(min=1, max=2)])
    zipCode = StringField('Zip Code', [validators.length(min=5, max=9)])
    country = StringField(
        'Country (US Only)',
        [validators.any_of(countries),
         validators.length(min=1, max=2)])
Ejemplo n.º 4
0
Archivo: app.py Proyecto: svwk/tutor
class BookingForm(FlaskForm):
    clientName = wtforms.StringField(
        "Вас зовут",
        [validators.InputRequired(message="Необходимо ввести имя")])
    clientPhone = wtforms.StringField("Ваш телефон", [
        validators.InputRequired(message="Необходимо ввести телефон"),
        validators.regexp(TEL_REG,
                          message="Телефон должен содержать от 6 до 11 цифр")
    ])
    clientTeacher = wtforms.HiddenField()
    clientWeekday = wtforms.HiddenField("", [
        validators.any_of(DAY_VALUES,
                          "К сожалению, вы ввели неверный день недели")
    ])
    clientTime = wtforms.HiddenField("", [
        validators.any_of(TIME_VALUES, "К сожалению, вы ввели неверное время")
    ])
Ejemplo n.º 5
0
class SearchForm(Form):
    flag = HiddenField('flag',
                       validators=[
                           validators.any_of(
                               message="invalid search option/form",
                               values=c.form_flags.values(),
                               values_formatter=str),
                       ])
Ejemplo n.º 6
0
class GetOssStsToken(CMForm):
    pic_type = StringField(u'pic_type',
                           validators=[
                               validators.data_required(message=u'u缺少图片分类'),
                               validators.any_of([
                                   'index', 'team', 'investment', 'news',
                                   'addr', 'about'
                               ])
                           ])
Ejemplo n.º 7
0
class LockinForm(ValidatingForm):
    fuel_type = StringField("fuel_type",
                            validators=[
                                validators.input_required(),
                                validators.any_of(fuel_types.keys())
                            ])
    expected_price = FloatField("expected_price",
                                validators=[validators.input_required()])
    lat = FloatField("lat", validators=[validators.input_required()])
    lng = FloatField("lng", validators=[validators.input_required()])
Ejemplo n.º 8
0
class UserInput(FlaskForm):
    address = StringField('Address')
    zip_code = StringField(
        'Zip Code',
        validators=[
            any_of(list(zip_populations.keys()),
                   message='Please Enter a Milwaukee Zip Code.')
        ])
    time = SelectField('Time', choices=[*time_slots])
    submit = SubmitField('Submit')
Ejemplo n.º 9
0
class CountryForm(Form):

    name = StringField(
        "Country name: ",
        [validators.data_required("Please, enter a country name.")])
    population = IntegerField("Population: ", [validators.number_range(0, )])
    gov = StringField("Government type (унітарна, парламентська): ",
                      [validators.any_of('унітарна', 'парламентська')])
    year_creation = IntegerField("Year of creation: ")

    submit = SubmitField("Enter")
Ejemplo n.º 10
0
class MainSearch(SearchForm):
    # _attributes = {
    #     "placeholder": gettext('Entre o nome cientifico de seguida <ENTER>'),
    # }
    name_field = StringField(
        label=gettext('Nome Científico'),
        name=b_c.name_full_scientific_name_string,
        validators=[
            validators.DataRequired(
                message=gettext("Por favor submeta um nome científico"))
        ],
        render_kw=None)

    flag = HiddenField('flag',
                       validators=[
                           validators.any_of(
                               message="invalid search option/form",
                               values=c.form_flags.values(),
                               values_formatter=str),
                       ],
                       render_kw={'value': c.form_flags['simple_search']})

    def __init__(self, *args, **kwargs):
        # creates an attribute for the form with the name.
        # now have to delete the previous name_attr

        setattr(self, b_c.name_full_scientific_name_string, self.name_field)
        self._to_remove_from = ['name_field']
        _new_unbound_fields = []

        for unbound_field in self._unbound_fields:
            if unbound_field[0][0] not in self._to_remove_from:
                _new_unbound_fields.append(unbound_field)

        _new_unbound_fields.append(
            (b_c.name_full_scientific_name_string, self.name_field))

        self._unbound_fields = _new_unbound_fields
        # self._unbound_fields = self._unbound_fields + [[b_c.name_full_scientific_name_string, self.name_field]]
        super(SearchForm, self).__init__(*args, **kwargs)

    def field_name(self):
        return self.name_field

    def get_errors(self):
        if self.errors:
            # the most anti-pythonic line of code ever!
            return {
                self._fields.get(key).label.text: error_list
                for key, error_list in self.errors.items()
                if key not in self._to_remove_from
            }
Ejemplo n.º 11
0
class CountryForm(FlaskForm):

    country_name = StringField("Country name: ", [
        validators.DataRequired("Please enter a country name."),
        validators.Length(3, 20, "Value should be from 3 to 20 symbols")
    ])

    country_population = IntegerField("Population: ",
                                      [validators.number_range(2)])

    country_goverment = StringField(
        "Type of goverment: ", [validators.any_of("унітарне", "демократичне")])

    country_location = StringField(
        "Location: ",
        [validators.Length(5, 20, "Value should be from 5 to 20 symbols")])

    submit = SubmitField("Save")
Ejemplo n.º 12
0
class UserForm(Form):
    """
    The form for update the user.
    """
    name = StringField(
        validators=[validators.data_required()],
        filters=[lambda x: x.strip() if isinstance(x, basestring) else None],
    )
    email = StringField(
        validators=[validators.email()],
        filters=[
            lambda x: x.strip().lower() if isinstance(x, basestring) else None
        ],
    )
    permission = IntegerField(
        default=UserPermission.normal,
        validators=[
            validators.any_of([UserPermission.root, UserPermission.normal])
        ],
        filters=[utils.int_filter],
    )
Ejemplo n.º 13
0
class WishForm(FlaskForm):
    id = HiddenField()

    student_id = SelectField(
        "Оберіть ID студента: ",
        [validators.DataRequired("Це поле є обов'язковим")],
        choices=ch,
        coerce=int)

    wish_date = DateField(
        "Дата побажання: ",
        [validators.data_required("Це поле є обов'язковим.")],
        format='%Y-%m-%d')

    wish_performer = StringField(
        "Оберіть виконавця: ",
        [validators.any_of(pers, "Перевірте, чи такий виконавець існує")])

    wish_melody = SelectField("Код мелодії: ", None, choices=ch2, coerce=int)

    wish_genre = SelectField("Код жанру: ", None, choices=ch1, coerce=int)

    submit = SubmitField("Зберегти")
Ejemplo n.º 14
0
Archivo: app.py Proyecto: andyzt/tceh
from flask import Flask, request, render_template
from flask.ext.wtf import Form
from wtforms import StringField, IntegerField, validators, ValidationError
import wtforms_json

import config

import os


app = Flask(__name__, template_folder='templates')
app.config.from_object(config)

API_validators = [{'client.name': [validators.Length(min=1),],
                  'order.count': [validators.number_range(min=1,max=5),],
                  'order.product_name': [validators.any_of(['potatoes','apples','cherries']),],
                  'client.full_address': [validators.Length(min=1),],
                   },
                  {'client.name': [validators.Length(min=1),],
                  'order.count': [validators.number_range(min=1,max=10),],
                  'order.product_name': [validators.any_of(['potatoes','apples','cherries']),],
                  'client.address.full_address': [validators.Length(min=1),],
                  'client.email': [validators.Length(min=1),validators.Email(),]
                   }
                  ]


def flatten_dict(dd, separator='.', prefix=''):
        return { prefix + separator + k if prefix else k : v
                 for kk, vv in dd.items()
                 for k, v in flatten_dict(vv, separator, kk).items()
Ejemplo n.º 15
0
class AdvancedSearch(MainSearch):
    flag = HiddenField('flag',
                       validators=[
                           validators.any_of(
                               message="invalid search option/form",
                               values=c.form_flags.values(),
                               values_formatter=str),
                       ],
                       render_kw={'value': c.form_flags['advanced_search']})

    # validators.Optional()
    name_field = StringField(label=gettext('Nome Científico'),
                             name=b_c.name_full_scientific_name_string,
                             validators=[validators.Optional()],
                             render_kw=None)

    province_field = ThisSelectField(
        label=gettext("Província"),
        choices=[(province, province) for province in service.get_provinces()],
        render_kw={
            'multiple': '',
            'size': len(service.get_provinces())
        },
        validators=[
            validators.Optional(),
        ])

    start_date_field = DateField(label=(gettext("Data") + ' ' +
                                        gettext("(inicio)")),
                                 format=c.date_format,
                                 render_kw={
                                     'data-language': gettext("lang"),
                                 },
                                 validators=[
                                     LessThan(b_c.name_last_date_end),
                                     validators.Optional(),
                                 ])

    end_date_field = DateField(label=(gettext("Data") + ' ' +
                                      gettext("(fim)")),
                               format=c.date_format,
                               validators=[
                                   GreaterThan(b_c.name_last_date_start),
                                   validators.Optional(),
                               ])

    start_latitude_field = DecimalField(
        label=(gettext("Latitude") + ' (' + gettext("início") + ')'),
        validators=[
            LessThan(b_c.name_latitude_decimal_end),
            validators.NumberRange(
                min=-180,
                max=180,
                message=gettext(
                    "permitido valores no intervalo de -180 a 180")),
            validators.Optional(),
        ])

    end_latitude_field = DecimalField(
        label=(gettext("Latitude") + ' (' + gettext("fim") + ')'),
        validators=[
            GreaterThan(b_c.name_latitude_decimal_start),
            validators.NumberRange(
                min=-180,
                max=180,
                message=gettext(
                    "permitido valores no intervalo de -180 a 180")),
            validators.Optional(),
        ])

    start_longitude_field = DecimalField(
        label=(gettext("Longitude") + ' (' + gettext("início") + ')'),
        validators=[
            LessThan(b_c.name_longitude_decimal_end),
            validators.Optional(),
            validators.NumberRange(
                min=-180,
                max=180,
                message=gettext(
                    "permitido valores no intervalo de -180 a 180")),
            validators.Optional(),
        ])

    end_longitude_field = DecimalField(
        label=(gettext("Longitude") + ' (' + gettext("fim") + ')'),
        validators=[
            GreaterThan(b_c.name_longitude_decimal_start),
            validators.Optional(),
            validators.NumberRange(
                min=-180,
                max=180,
                message=gettext(
                    "permitido valores no intervalo de -180 a 180")),
            validators.Optional(),
        ])

    def __init__(self, *args, **kwargs):

        setattr(self, b_c.name_full_scientific_name_string, self.name_field)
        setattr(self, b_c.name_province, self.province_field)
        setattr(self, b_c.name_last_date_start, self.start_date_field)
        setattr(self, b_c.name_last_date_end, self.end_date_field)
        setattr(self, b_c.name_latitude_decimal_start,
                self.start_latitude_field)
        setattr(self, b_c.name_latitude_decimal_end, self.end_latitude_field)
        setattr(self, b_c.name_longitude_decimal_start,
                self.start_longitude_field)
        setattr(self, b_c.name_longitude_decimal_end, self.end_longitude_field)

        # add here to remove original, keep mines... HAH!
        self._to_remove_from = [
            'name_field', 'province_field', 'start_date_field',
            'end_date_field', 'start_latitude_field', 'start_longitude_field',
            'end_latitude_field', 'end_longitude_field'
        ]
        _new_unbound_fields = []

        for unbound_field in self._unbound_fields:
            if unbound_field[0] not in self._to_remove_from:
                _new_unbound_fields.append(unbound_field)

        # add here. to the new unbound_fields
        _new_unbound_fields.append(
            (b_c.name_full_scientific_name_string, self.name_field))
        _new_unbound_fields.append((b_c.name_province, self.province_field))
        _new_unbound_fields.append(
            (b_c.name_last_date_start, self.start_date_field))
        _new_unbound_fields.append(
            (b_c.name_last_date_end, self.end_date_field))
        _new_unbound_fields.append(
            (b_c.name_latitude_decimal_start, self.start_latitude_field))
        _new_unbound_fields.append(
            (b_c.name_latitude_decimal_end, self.end_latitude_field))
        _new_unbound_fields.append(
            (b_c.name_longitude_decimal_start, self.start_longitude_field))
        _new_unbound_fields.append(
            (b_c.name_longitude_decimal_end, self.end_longitude_field))

        self._unbound_fields = _new_unbound_fields
        super(MainSearch, self).__init__(*args, **kwargs)
Ejemplo n.º 16
0
class UpdateSettingForm(Form):

    nameString = ["departments", "positions", "shieldTypes", "spliceTypes", "interfaceProtocol"]
    name = StringField(validators=[validators.any_of(nameString)])
    value = StringField(validators=[validators.length(max=125)])
Ejemplo n.º 17
0
class ActionForm(Form):
    type = SelectField('Which type?', choices=[
        ('none', ''), ('randplaylist', 'Random from playlist')],
        validators=[any_of(('randplaylist',))])
    randplaylist = FormField(RandomPlaylistForm, 'Random from playlist')
Ejemplo n.º 18
0
 def AnyOf(cls, values, message=None, values_formatter=None):
     ''' Compares the incoming data to a sequence of valid inputs. '''
     return validators.any_of(values, message, values_formatter)
Ejemplo n.º 19
0
class FilterSearch(AdvancedSearch):
    flag = HiddenField('flag',
                       validators=[
                           validators.any_of(
                               message="invalid search option/form",
                               values=c.form_flags.values(),
                               values_formatter=str),
                       ],
                       render_kw={'value': c.form_flags['side_filter']})

    provider_field = None
    province_field = None

    start_latitude_field = None
    end_latitude_field = None
    start_longitude_field = None
    end_longitude_field = None

    start_date_field = None
    end_date_field = None

    def __init__(self, *args, **kwargs):
        # setattr(self, b_c.name_province, self.province_field)

        _provider_choices = []
        _province_choices = []

        _latitude_start = None
        _latitude_end = None
        _longitude_start = None
        _longitude_end = None

        _date_start = None
        _date_end = None

        _results_dict = kwargs.pop('_results_dict', None)
        if _results_dict:
            _provider_choices = [
                (provider.id, provider.full_name)
                for provider in _results_dict['data_providers']
            ]

            _province_choices = [(province, province)
                                 for province in _results_dict['provinces']]

            if _results_dict.get('filter_form_values', None):

                if _results_dict['filter_form_values'].get(
                        b_c.name_latitude_decimal_start, None):
                    _latitude_start = _results_dict['filter_form_values'][
                        b_c.name_latitude_decimal_start]

                if _results_dict['filter_form_values'].get(
                        b_c.name_latitude_decimal_end, None):
                    _latitude_end = _results_dict['filter_form_values'][
                        b_c.name_latitude_decimal_end]

                if _results_dict['filter_form_values'].get(
                        b_c.name_latitude_decimal_start, None):
                    _longitude_start = _results_dict['filter_form_values'][
                        b_c.name_longitude_decimal_start]

                if _results_dict['filter_form_values'].get(
                        b_c.name_latitude_decimal_start, None):
                    _longitude_end = _results_dict['filter_form_values'][
                        b_c.name_longitude_decimal_end]

                if _results_dict['filter_form_values'].get(
                        b_c.name_last_date_start, None):
                    _date_start = _results_dict['filter_form_values'][
                        b_c.name_last_date_start]

                if _results_dict['filter_form_values'].get(
                        b_c.name_last_date_end, None):
                    _date_end = _results_dict['filter_form_values'][
                        b_c.name_last_date_end]
        else:
            if args and args[0]:
                if args[0].getlist(b_c.name_province):
                    _province_choices = [
                        (province, province)
                        for province in args[0].getlist(b_c.name_province)
                    ]

                if args[0].getlist(b_c.name_provider):
                    provider_id_list = args[0].getlist(b_c.name_provider)
                    providers = service.get_providers_with_ids(
                        provider_id_list)
                    _provider_choices = [(provider.id, provider.full_name)
                                         for provider in providers]
                else:
                    providers = service.get_providers()
                    _provider_choices = [(provider.id, provider.full_name)
                                         for provider in providers]

        self.provider_field = ThisSelectField(
            label=gettext("Instituição"),
            choices=_provider_choices,
            coerce=int,
            default=_provider_choices[0][0] if _provider_choices else None,
            render_kw={
                'multiple': 'multiple',
                'size': len(_provider_choices)
            },
            validators=[validators.Optional()])  #validators.DataRequired()

        self.province_field = ThisSelectField(
            label=gettext("Província"),
            choices=_province_choices,
            render_kw={
                'multiple': 'multiple',
                'size': len(_province_choices)
            },
            default=_province_choices[0][0] if _province_choices else None,
            coerce=str,
            validators=[])  #validators.Optional(),

        self.start_latitude_field = DecimalField(
            label=(gettext("Latitude") + ' (' + gettext("início") + ')'),
            render_kw={"value": _latitude_start if _latitude_start else ''},
            validators=[
                LessThan(b_c.name_latitude_decimal_end),
                validators.NumberRange(
                    min=-180,
                    max=180,
                    message=gettext(
                        "permitido valores no intervalo de -180 a 180")),
                validators.Optional(),
            ])

        self.end_latitude_field = DecimalField(
            label=(gettext("Latitude") + ' (' + gettext("fim") + ')'),
            render_kw={"value": _latitude_end if _latitude_end else ''},
            validators=[
                GreaterThan(b_c.name_latitude_decimal_start),
                validators.NumberRange(
                    min=-180,
                    max=180,
                    message=gettext(
                        "permitido valores no intervalo de -180 a 180")),
                validators.Optional(),
            ])

        self.start_longitude_field = DecimalField(
            label=(gettext("Longitude") + ' (' + gettext("início") + ')'),
            render_kw={"value": _longitude_start if _longitude_start else ''},
            validators=[
                LessThan(b_c.name_longitude_decimal_end),
                validators.Optional(),
                validators.NumberRange(
                    min=-180,
                    max=180,
                    message=gettext(
                        "permitido valores no intervalo de -180 a 180")),
                validators.Optional(),
            ])

        self.end_longitude_field = DecimalField(
            label=(gettext("Longitude") + ' (' + gettext("fim") + ')'),
            render_kw={"value": _longitude_end if _longitude_end else ''},
            validators=[
                GreaterThan(b_c.name_longitude_decimal_start),
                validators.Optional(),
                validators.NumberRange(
                    min=-180,
                    max=180,
                    message=gettext(
                        "permitido valores no intervalo de -180 a 180")),
                validators.Optional(),
            ])

        self.start_date_field = DateField(
            label=(gettext("Data") + ' ' + gettext("(inicio)")),
            render_kw={"value": _date_start if _date_start else ''},
            format=c.date_format,
            validators=[
                LessThan(b_c.name_last_date_end),
                validators.Optional(),
            ])

        self.end_date_field = DateField(
            label=(gettext("Data") + ' ' + gettext("(fim)")),
            render_kw={"value": _date_end if _date_end else ''},
            format=c.date_format,
            validators=[
                GreaterThan(b_c.name_last_date_start),
                validators.Optional(),
            ])

        setattr(self, b_c.name_full_scientific_name_string, self.name_field)
        setattr(self, b_c.name_provider, self.provider_field)
        setattr(self, b_c.name_province, self.province_field)
        setattr(self, b_c.name_last_date_start, self.start_date_field)
        setattr(self, b_c.name_last_date_end, self.end_date_field)
        setattr(self, b_c.name_latitude_decimal_start,
                self.start_latitude_field)
        setattr(self, b_c.name_latitude_decimal_end, self.end_latitude_field)
        setattr(self, b_c.name_longitude_decimal_start,
                self.start_longitude_field)
        setattr(self, b_c.name_longitude_decimal_end, self.end_longitude_field)

        self._to_remove_from = [
            'name_field', 'province_field', 'provider_field',
            'start_date_field', 'end_date_field', 'start_latitude_field',
            'start_longitude_field', 'end_latitude_field',
            'end_longitude_field'
        ]
        _new_unbound_fields = []

        for unbound_field in self._unbound_fields:
            if unbound_field[0] not in self._to_remove_from:
                _new_unbound_fields.append(unbound_field)

        # add here. to the new unbound_fields
        _new_unbound_fields.append(
            (b_c.name_full_scientific_name_string, self.name_field))
        _new_unbound_fields.append((b_c.name_province, self.province_field))
        _new_unbound_fields.append((b_c.name_provider, self.provider_field))
        _new_unbound_fields.append(
            (b_c.name_last_date_start, self.start_date_field))
        _new_unbound_fields.append(
            (b_c.name_last_date_end, self.end_date_field))
        _new_unbound_fields.append(
            (b_c.name_latitude_decimal_start, self.start_latitude_field))
        _new_unbound_fields.append(
            (b_c.name_latitude_decimal_end, self.end_latitude_field))
        _new_unbound_fields.append(
            (b_c.name_longitude_decimal_start, self.start_longitude_field))
        _new_unbound_fields.append(
            (b_c.name_longitude_decimal_end, self.end_longitude_field))

        self._unbound_fields = _new_unbound_fields
        super(AdvancedSearch, self).__init__(*args, **kwargs)
Ejemplo n.º 20
0
def construct_colum_for_column_type(type_name,
                                    column_name,
                                    required=False,
                                    column_default=None,
                                    column_min=None,
                                    column_max=None,
                                    widget=None,
                                    filter_=None,
                                    primary=False,
                                    rel_class=None):

    validators_ = []

    if required and not primary:
        validators_.append(
            validators.any_of([True, False]) if type_name ==
            'boolean' else validators.data_required())
    else:
        validators_.append(validators.optional())

    if not type_name == 'date' and not type_name == 'datetime':
        if column_min or column_max:
            if column_min and column_max:
                lenght_validator = validators.length(min=column_min,
                                                     max=column_max)
            elif column_min and not column_max:
                lenght_validator = validators.length(min=column_min)
            else:
                lenght_validator = validators.length(max=column_max)
            validators_.append(lenght_validator)
    else:
        if column_min or column_max:
            if column_min and column_max:
                lenght_validator = validators.number_range(
                    min=date(column_min, 1, 1) if type_name == "date" else
                    datetime.datetime(column_min, 1, 1, 1, 1, 1),
                    max=date(column_max, 12, 31) if type_name == "date" else
                    datetime.datetime(column_min, 12, 31, 23, 59, 59))
            elif column_min and not column_max:
                lenght_validator = validators.number_range(
                    min=date(column_min, 1, 1) if type_name ==
                    "date" else datetime.datetime(column_min, 1, 1, 1, 1, 1))
            else:
                lenght_validator = validators.number_range(
                    max=date(column_max, 12, 31) if type_name == "date" else
                    datetime.datetime(column_min, 12, 31, 23, 59, 59))
            validators_.append(lenght_validator)
        else:
            lenght_validator = validators.number_range(
                min=date(1920, 1, 1) if type_name ==
                "date" else datetime.datetime(1920, 1, 1, 1, 1, 1))
            validators_.append(lenght_validator)

    choices = []
    if rel_class:
        choices = [(g.id, g.name)
                   for g in session_db.query(rel_class).order_by('id')]

    data = {
        'integer':
        IntegerField(column_name, validators_, default=column_default),
        'unicode_text':
        StringField(column_name, validators_, default=column_default),
        'text':
        StringField(column_name, validators_, default=column_default),
        'string':
        StringField(column_name, validators_, default=column_default),
        'decimal':
        IntegerField(column_name, validators_, default=column_default),
        'boolean':
        BooleanField(column_name, validators_, default=column_default),
        'datetime':
        DateTimeField(column_name, validators_, default=column_default),
        'date':
        DateField(column_name, validators_, default=column_default),
        'select':
        SelectField(column_name, validators_, coerce=int, choices=choices)
    }

    if type_name in data:
        if rel_class:
            current_column = data['select']
        else:
            current_column = data[type_name]
        if widget:
            current_column.field_class.widget = widget
        if filter_:
            current_column.filters = [filter_]
        if primary:
            current_column.field_class.widget = widgets.HiddenInput()
        # if rel_class:
        #     current_column.choices = [(g.id, g.name) for g in session_db.query(rel_class).order_by('id')]
        # if required:
        #     current_column.render_kw = current_column.render_kw + {"class": 'req-field'}
    else:
        current_column = None

    return current_column
Ejemplo n.º 21
0
class AlarmForm(Form):
    type = SelectField('Which type?', choices=[
        ('none', ''), ('frequency', 'Frequency'), ('single', 'Single')],
        validators=[any_of(('frequency', 'single'))])
    single = FormField(SingleAlarmForm, 'Single')
    freq = FormField(FreqAlarmForm, 'Frequency')