Example #1
0
class DagRunForm(DynamicForm):
    dag_id = StringField(lazy_gettext('Dag Id'),
                         validators=[validators.DataRequired()],
                         widget=BS3TextFieldWidget())
    start_date = DateTimeField(lazy_gettext('Start Date'),
                               widget=AirflowDateTimePickerWidget())
    end_date = DateTimeField(lazy_gettext('End Date'),
                             widget=AirflowDateTimePickerWidget())
    run_id = StringField(lazy_gettext('Run Id'),
                         validators=[validators.DataRequired()],
                         widget=BS3TextFieldWidget())
    state = SelectField(lazy_gettext('State'),
                        choices=(
                            ('success', 'success'),
                            ('running', 'running'),
                            ('failed', 'failed'),
                        ),
                        widget=Select2Widget())
    execution_date = DateTimeField(lazy_gettext('Execution Date'),
                                   widget=AirflowDateTimePickerWidget())
    external_trigger = BooleanField(lazy_gettext('External Trigger'))
    conf = TextAreaField(lazy_gettext('Conf'),
                         validators=[ValidJson(),
                                     validators.Optional()],
                         widget=BS3TextAreaFieldWidget())

    def populate_obj(self, item):
        # TODO: This is probably better done as a custom field type so we can
        # set TZ at parse time
        super().populate_obj(item)
        item.execution_date = timezone.make_aware(item.execution_date)
        if item.conf:
            item.conf = json.loads(item.conf)
Example #2
0
class DagRunForm(DynamicForm):
    dag_id = StringField(lazy_gettext('Dag Id'),
                         validators=[validators.DataRequired()],
                         widget=BS3TextFieldWidget())
    start_date = DateTimeWithTimezoneField(
        lazy_gettext('Start Date'), widget=AirflowDateTimePickerWidget())
    end_date = DateTimeWithTimezoneField(lazy_gettext('End Date'),
                                         widget=AirflowDateTimePickerWidget())
    run_id = StringField(lazy_gettext('Run Id'),
                         validators=[validators.DataRequired()],
                         widget=BS3TextFieldWidget())
    state = SelectField(lazy_gettext('State'),
                        choices=(
                            ('success', 'success'),
                            ('running', 'running'),
                            ('failed', 'failed'),
                        ),
                        widget=Select2Widget())
    execution_date = DateTimeWithTimezoneField(
        lazy_gettext('Execution Date'), widget=AirflowDateTimePickerWidget())
    external_trigger = BooleanField(lazy_gettext('External Trigger'))
    conf = TextAreaField(lazy_gettext('Conf'),
                         validators=[ValidJson(),
                                     validators.Optional()],
                         widget=BS3TextAreaFieldWidget())

    def populate_obj(self, item):
        super(DagRunForm, self).populate_obj(item)
        if item.conf:
            item.conf = json.loads(item.conf)
Example #3
0
    def get_connection_form_widgets() -> Dict[str, Any]:
        """Returns connection widgets to add to connection form"""
        from flask_appbuilder.fieldwidgets import BS3TextAreaFieldWidget, BS3TextFieldWidget
        from flask_babel import lazy_gettext
        from wtforms import BooleanField, StringField

        return {
            "extra__snowflake__account":
            StringField(lazy_gettext('Account'), widget=BS3TextFieldWidget()),
            "extra__snowflake__warehouse":
            StringField(lazy_gettext('Warehouse'),
                        widget=BS3TextFieldWidget()),
            "extra__snowflake__database":
            StringField(lazy_gettext('Database'), widget=BS3TextFieldWidget()),
            "extra__snowflake__region":
            StringField(lazy_gettext('Region'), widget=BS3TextFieldWidget()),
            "extra__snowflake__role":
            StringField(lazy_gettext('Role'), widget=BS3TextFieldWidget()),
            "extra__snowflake__private_key_file":
            StringField(lazy_gettext('Private key (Path)'),
                        widget=BS3TextFieldWidget()),
            "extra__snowflake__private_key_content":
            StringField(lazy_gettext('Private key (Text)'),
                        widget=BS3TextAreaFieldWidget()),
            "extra__snowflake__insecure_mode":
            BooleanField(label=lazy_gettext('Insecure mode'),
                         description="Turns off OCSP certificate checks"),
        }
Example #4
0
class DagRunForm(DynamicForm):
    """Form for editing and adding DAG Run"""

    dag_id = StringField(lazy_gettext('Dag Id'),
                         validators=[DataRequired()],
                         widget=BS3TextFieldWidget())
    start_date = DateTimeWithTimezoneField(
        lazy_gettext('Start Date'), widget=AirflowDateTimePickerWidget())
    end_date = DateTimeWithTimezoneField(lazy_gettext('End Date'),
                                         widget=AirflowDateTimePickerWidget())
    run_id = StringField(lazy_gettext('Run Id'),
                         validators=[DataRequired()],
                         widget=BS3TextFieldWidget())
    state = SelectField(
        lazy_gettext('State'),
        choices=(
            ('success', 'success'),
            ('running', 'running'),
            ('failed', 'failed'),
        ),
        widget=Select2Widget(),
    )
    execution_date = DateTimeWithTimezoneField(
        lazy_gettext('Execution Date'), widget=AirflowDateTimePickerWidget())
    external_trigger = BooleanField(lazy_gettext('External Trigger'))
    conf = TextAreaField(lazy_gettext('Conf'),
                         validators=[ValidJson(), Optional()],
                         widget=BS3TextAreaFieldWidget())

    def populate_obj(self, item):
        """Populates the attributes of the passed obj with data from the form’s fields."""
        super().populate_obj(item)  # pylint: disable=no-member
        item.run_type = DagRunType.from_run_id(item.run_id)
        if item.conf:
            item.conf = json.loads(item.conf)
Example #5
0
class ConnectionForm(DynamicForm):
    conn_id = StringField(lazy_gettext('Conn Id'), widget=BS3TextFieldWidget())
    conn_type = SelectField(lazy_gettext('Conn Type'),
                            choices=models.Connection._types,
                            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=[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())
Example #6
0
class ConnectionForm(DynamicForm):
    """Form for editing and adding Connection"""

    conn_id = StringField(lazy_gettext('Conn Id'),
                          validators=[InputRequired()],
                          widget=BS3TextFieldWidget())
    description = StringField(lazy_gettext('Description'),
                              widget=BS3TextAreaFieldWidget())
    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())
Example #7
0
class SMSForm(DynamicForm):
    DIRECTION_INCOMING = 'I'
    DIRECTION_OUTGOING = 'O'

    DIRECTION_CHOICES = [(DIRECTION_INCOMING, "Incoming"),
                         (DIRECTION_OUTGOING, "Outgoing")]

    STATUS_SUCCESS = 'success'
    '''Outgoing STATUS types'''
    STATUS_WARNING = 'warning'
    STATUS_ERROR = 'error'
    STATUS_INFO = 'info'
    STATUS_ALERT = 'alert'
    STATUS_REMINDER = 'reminder'
    STATUS_LOGGER_RESPONSE = 'from_logger'
    STATUS_SYSTEM_ERROR = 'system_error'
    STATUS_PENDING = 'pending'
    '''Incoming STATUS types'''
    STATUS_MIXED = 'mixed'
    STATUS_PARSE_ERRROR = 'parse_error'
    STATUS_BAD_VALUE = 'bad_value'
    STATUS_INAPPLICABLE = 'inapplicable'
    STATUS_NOT_ALLOWED = 'not_allowed'

    STATUS_CHOICES = [(STATUS_SUCCESS, "Success"), (STATUS_PENDING, "Pending"),
                      (STATUS_WARNING, "Warning"), (STATUS_ERROR, "Error"),
                      (STATUS_INFO, "Info"), (STATUS_ALERT, "Alert"),
                      (STATUS_REMINDER, "Reminder"),
                      (STATUS_LOGGER_RESPONSE, "Response from logger"),
                      (STATUS_SYSTEM_ERROR, "System error"),
                      (STATUS_MIXED, "Mixed"),
                      (STATUS_PARSE_ERRROR, "Parse Error"),
                      (STATUS_BAD_VALUE, "Bad Value"),
                      (STATUS_INAPPLICABLE, "Inapplicable"),
                      (STATUS_NOT_ALLOWED, "Not Allowed")]

    date = DateField(('Date'),
                     description=('Date'),
                     validators=[DataRequired()],
                     widget=DatePickerWidget())
    direction = SelectField(('Direction'),
                            choices=DIRECTION_CHOICES,
                            validators=[],
                            widget=Select2Widget())
    text = StringField(('Text'),
                       description=('Text'),
                       validators=[DataRequired()],
                       widget=BS3TextAreaFieldWidget())
    status = SelectField(('Status'),
                         choices=STATUS_CHOICES,
                         validators=[DataRequired()],
                         widget=Select2Widget())
    identity = IntegerField(('Identity'),
                            validators=[validate_telephone,
                                        optional()],
                            widget=BS3TextFieldWidget())
    response_to = StringField(('Response To'), widget=BS3TextFieldWidget())
Example #8
0
class ContactForm(DynamicForm):
    email = StringField(('Email'),
                        validators=[DataRequired(), Email()],
                        description=('Email we can use to contact you'),
                        widget=BS3TextFieldWidget())
    name = StringField(('Name'),
                       validators=[DataRequired()],
                       widget=BS3TextFieldWidget())
    message = StringField(('Message'),
                          validators=[DataRequired()],
                          widget=BS3TextAreaFieldWidget())
Example #9
0
class LoadUserForm(DynamicForm):
    emails = StringField(
        'Emails',
        description=_(
            'Enter comma separated list of partial emails/usernames'),
        validators=[validators.DataRequired()],
        widget=BS3TextAreaFieldWidget())

    role = StringField(
        'Role',
        description=_('Select role users will belong to'),
        validators=[validators.DataRequired()],
        widget=Select2AJAXWidget(endpoint='/roles/api/readvalues'))
Example #10
0
class SubmissionForm(DynamicForm):
    field1 = StringField(('Field1'),
                         description=('Description'),
                         validators=[DataRequired()],
                         widget=BS3TextFieldWidget())
    select1 = SelectField(('Selector1'),
                          description=('Description'),
                          validators=[DataRequired()],
                          widget=Select2Widget(),
                          choices=selector_choices)
    field2 = StringField(('Field2'),
                         description=('Description'),
                         validators=[DataRequired()],
                         widget=BS3TextFieldWidget())
    field3 = TextAreaField(('Field3'),
                           description=('Description'),
                           validators=[DataRequired()],
                           widget=BS3TextAreaFieldWidget())
Example #11
0
class ReverseTableForm(DynamicForm):

    table_schema = StringField(label='数据库',
                               validators=[DataRequired()],
                               widget=Select2AJAXWidget(
                                   endpoint='/apimpsview/api/query_schema',
                                   extra_classes="readonly"))
    table_name = StringField(
        label='表名',
        validators=[DataRequired()],
        widget=Select2SlaveAJAXWidget(
            master_id='table_schema',
            extra_classes="readonly",
            endpoint='/apimpsview/api/query_table/{{ID}}'))
    code_type = SelectField('类型',
                            coerce=str,
                            choices=[('All', 'All'), ('Model', 'Model'),
                                     ('Controller', 'Controller')],
                            validators=[DataRequired()],
                            widget=Select2Widget())

    code = StringField('代码', widget=BS3TextAreaFieldWidget())
Example #12
0
class ConnectionForm(DynamicForm):
    conn_id = StringField(lazy_gettext('Conn Id'), widget=BS3TextFieldWidget())
    conn_type = SelectField(lazy_gettext('Conn Type'),
                            choices=sorted(Connection._types,
                                           key=itemgetter(1)),
                            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=[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=[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 = StringField(
        lazy_gettext('Kube config (JSON format)'), widget=BS3TextFieldWidget())
    extra__kubernetes__namespace = StringField(lazy_gettext('Namespace'),
                                               widget=BS3TextFieldWidget())
Example #13
0
class PandasDatasourceModelView(DatasourceModelView, DeleteMixin):  # noqa
    datamodel = SQLAInterface(PandasDatasource)

    list_title = _('List File Datasources')
    show_title = _('Show File Datasource')
    add_title = _('Add File Datasource')
    edit_title = _('Edit File Datasource')

    list_columns = ['link', 'changed_by_', 'modified']
    order_columns = ['link', 'changed_on_']
    add_columns = [
        'name', 'source_url', 'source_auth', 'source_parameters', 'format',
        'additional_parameters'
    ]
    add_form_extra_fields = {
        'source_auth':
        JSONField(
            _('Source Credentials'),
            [validators.optional(),
             validators.length(max=100)],
            widget=BS3TextFieldWidget(),
            description=(
                'Credentials required to access the raw data, if required. '
                'Can be either a username and password in the form '
                "'[\"username\", \"password\"]' which will be authenticated "
                'using HTTP Basic Auth, or a string which will be used as '
                'an Authorization header')),
        'source_parameters':
        JSONField(_('Additional Query Parameters'),
                  [validators.optional(),
                   validators.length(max=500)],
                  widget=BS3TextAreaFieldWidget(),
                  description=(
                      'A JSON-formatted dictionary of additional parameters '
                      'used to request the remote file')),
        'format':
        ChoiceTypeSelectField(_('Format'), choices=FORMATS),
        'additional_parameters':
        JSONField(_('Additional Read Parameters'),
                  [validators.optional(),
                   validators.length(max=500)],
                  widget=BS3TextAreaFieldWidget(),
                  description=(
                      'A JSON-formatted dictionary of additional parameters '
                      'passed to the Pandas read function')),
    }
    edit_columns = [
        'name', 'source_url', 'source_auth', 'source_parameters', 'format',
        'additional_parameters', 'filter_select_enabled', 'slices',
        'fetch_values_predicate', 'description', 'owner', 'main_dttm_col',
        'default_endpoint', 'offset', 'cache_timeout'
    ]
    edit_form_extra_fields = add_form_extra_fields
    show_columns = edit_columns + ['perm']
    related_views = [PandasColumnInlineView, PandasMetricInlineView]
    base_order = ('changed_on', 'desc')
    search_columns = (
        'owner',
        'name',
        'source_url',
    )
    description_columns = {
        'slices':
        _('The list of slices associated with this datasource. By '
          'altering this datasource, you may change how these associated '
          'slices behave. '
          'Also note that slices need to point to a datasource, so '
          'this form will fail at saving if removing slices from a '
          'datasource. If you want to change the datasource for a slice, '
          "overwrite the slice from the 'explore view'"),
        'offset':
        _('Timezone offset (in hours) for this datasource'),
        'name':
        _('The name of this datasource'),
        'source_url':
        _('The URL used to access the raw data'),
        'format':
        _('The format of the raw data, e.g. csv'),
        'description':
        Markup(
            "Supports <a href='https://daringfireball.net/projects/markdown/'>"
            'markdown</a>'),
        'fetch_values_predicate':
        _('Predicate applied when fetching distinct value to '
          'populate the filter control component. Supports '
          'jinja template syntax. Applies only when '
          '`Enable Filter Select` is on.'),
        'default_endpoint':
        _('Redirects to this endpoint when clicking on the datasource '
          'from the datasource list'),
        'filter_select_enabled':
        _("Whether to populate the filter's dropdown in the explore "
          "view's filter section with a list of distinct values fetched "
          'from the backend on the fly'),
    }
    base_filters = [['id', DatasourceFilter, lambda: []]]
    label_columns = {
        'slices': _('Associated Slices'),
        'link': _('Datasource'),
        'changed_by_': _('Changed By'),
        'changed_on_': _('Last Changed'),
        'filter_select_enabled': _('Enable Filter Select'),
        'default_endpoint': _('Default Endpoint'),
        'offset': _('Offset'),
        'cache_timeout': _('Cache Timeout'),
        'name': _('Name'),
        'source_url': _('Source URL'),
        'format': _('Format'),
        'fetch_values_predicate': _('Fetch Values Predicate'),
        'owner': _('Owner'),
        'main_dttm_col': _('Main Datetime Column'),
        'description': _('Description'),
    }

    def pre_add(self, datasource):
        number_of_existing_datasources = (db.session.query(
            sa.func.count('*')).filter(
                PandasDatasource.source_url == datasource.source_url).scalar())
        # datasource object is already added to the session
        if number_of_existing_datasources > 1:
            raise Exception(
                get_datasource_exist_error_msg(datasource.full_name))

        # Fail before adding if the datasource can't be found
        try:
            datasource.get_dataframe()
        except Exception as e:
            logging.exception(e)
            raise Exception(
                _('File [{}] could not be read, '
                  'please double check the '
                  'Source URL and Read Method').format(datasource.name))

    def post_add(self, datasource, flash_message=True):
        datasource.get_metadata()
        security.merge_perm(security_manager, 'datasource_access',
                            datasource.get_perm())

        if flash_message:
            flash(
                _('The datasource was created. '
                  'As part of this two phase configuration '
                  'process, you should now click the edit button by '
                  'the new datasource to configure it.'), 'info')

    def post_update(self, datasource):
        self.post_add(datasource, flash_message=False)

    def _delete(self, pk):
        DeleteMixin._delete(self, pk)

    @expose('/edit/<pk>', methods=['GET', 'POST'])
    @has_access
    def edit(self, pk):
        """Simple hack to redirect to explore view after saving"""
        resp = super(PandasDatasourceModelView, self).edit(pk)
        if isinstance(resp, basestring):
            return resp
        return redirect(url_for('Superset.explore') + 'pandas/{}/'.format(pk))
Example #14
0
class ReportForm(DynamicForm):
    report_id = HiddenField()
    schedule_timezone = HiddenField()
    report_title = StringField(
        ("Title"),
        description="Title will be used as the report's name",
        widget=BS3TextFieldWidget(),
        validators=[DataRequired()],
    )
    description = TextAreaField(("Description"),
                                widget=BS3TextAreaFieldWidget(),
                                validators=[DataRequired()])
    owner_name = StringField(("Owner Name"),
                             widget=BS3TextFieldWidget(),
                             validators=[DataRequired()])
    owner_email = StringField(
        ("Owner Email"),
        description="Owner email will be added to the subscribers list",
        widget=BS3TextFieldWidget(),
        validators=[DataRequired(), Email()],
    )
    subscribers = StringField(
        ("Subscribers"),
        description=("List of comma separeted emails that should receive email\
             notifications. Automatically adds owner email to this list."),
        widget=BS3TextFieldWidget(),
    )
    tests = SelectMultipleField(
        ("Tests"),
        description=(
            "List of the tests to include in the report. Only includes\
         tasks that have ran in airflow."),
        choices=None,
        widget=Select2ManyWidget(),
        validators=[DataRequired()],
    )
    schedule_type = SelectField(
        ("Schedule"),
        description=("Select how you want to schedule the report"),
        choices=[
            ("manual", "None (Manual triggering)"),
            ("daily", "Daily"),
            ("weekly", "Weekly"),
            ("custom", "Custom (Cron)"),
        ],
        widget=Select2Widget(),
        validators=[DataRequired()],
    )
    schedule_time = TimeField(
        "Time",
        description=("Note that time zone being used is the "
                     "selected timezone in your clock interface."),
        render_kw={"class": "form-control"},
        validators=[DataRequired()],
    )
    schedule_week_day = SelectField(
        ("Day of week"),
        description=("Select day of a week you want to schedule the report"),
        choices=[
            ("0", "Sunday"),
            ("1", "Monday"),
            ("2", "Tuesday"),
            ("3", "Wednesday"),
            ("4", "Thursday"),
            ("5", "Friday"),
            ("6", "Saturday"),
        ],
        widget=Select2Widget(),
        validators=[DataRequired()],
    )
    schedule_custom = StringField(
        ("Cron schedule"),
        description=('Enter cron schedule (e.g. "0 0 * * *").\
         Note that time zone being used is UTC.'),
        widget=BS3TextFieldWidget(),
        validators=[DataRequired()],
    )
Example #15
0
class ItemModelView(ModelView):
    datamodel = SQLAInterface(Item)

    label_columns = {'category': 'Category'}
    list_columns = ['title', 'description', 'category']
    visible_columns = ['title', 'description', 'category']

    add_columns = visible_columns
    edit_columns = visible_columns
    show_columns = visible_columns

    show_fieldsets = [
        ('Summary', {
            'fields': ['title', 'description', 'category']
        }),
    ]

    edit_form_extra_fields = {
        'description':
        TextField('Provide a description',
                  description='Item description',
                  widget=BS3TextAreaFieldWidget())
    }

    add_form_extra_fields = {
        'description':
        TextField('Provide a description',
                  description='Item description',
                  widget=BS3TextAreaFieldWidget())
    }

    # adds custom endpoint to query items by name
    @expose('/<name>')
    def detail(self, name):
        item = self.appbuilder\
            .get_session.query(Item)\
            .filter(Item.title == name)\
            .one_or_none()
        return render_template('item.html',
                               appbuilder=self.appbuilder,
                               item=item)

    @expose('/<filter_id>')
    def as_json(self, filter_id):
        item = self.appbuilder\
            .get_session.query(Item)\
            .filter(Item.id == filter_id) \
            .one_or_none()
        if item is None:
            item_json = json.dumps({})
        else:
            item_json = json.dumps(item.to_json())
        response = make_response(item_json, 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    def pre_add(self, item):
        user_id = session['user_id']
        item.user_id = user_id

    def pre_update(self, item):
        check_logged_user(item)

    def prefill_form(self, form, pk):
        # checks if the logged in user is the author,
        # if it's not, shows data readonly
        category = self.datamodel.get(pk)
        user_id = session['user_id']
        if category.user_id != int(user_id):
            form.title.widget = BS3TextFieldROWidget()
            form.description.widget = BS3TextAreaFieldROWidget()
            # TODO create a readonly widget that works correctly
            # form.category.widget = Select2ROWWidget()

    def pre_delete(self, item):
        check_logged_user(item)
Example #16
0
class NotepadForm(DynamicForm):
    context = TextAreaField('内容', widget=BS3TextAreaFieldWidget())