コード例 #1
0
ファイル: ui.py プロジェクト: joshalbrecht/memdam
    def __call__(self, **kwargs):
        result = DateTimeField.__call__(self, **kwargs)
        result += '''
<input type="button" id="'''+self.id+'''_clear" value="Clear"/>
<script>
    $("#'''+self.id+'''").AnyTime_picker( {
      format: "%Y-%m-%d %H:%i:%s %:",
      formatUtcOffset: "%: (%@)" } );
    $("#'''+self.id+'''_clear").click( function(e) {
      $("#'''+self.id+'''").val("").change(); }
    );
</script>
        '''
        return result
コード例 #2
0
ファイル: forms.py プロジェクト: plumdog/datasheet
 def __init__(self, *args, **kwargs):
     kwargs["format"] = kwargs.get("format", "%d/%m/%Y %H:%M")
     kwargs["description"] = kwargs.get("description", "dd/mm/yyyy hh:mm")
     DateTimeField.__init__(self, *args, **kwargs)
コード例 #3
0
ファイル: forms.py プロジェクト: sbajandoh/FSND
class ShowForm(Form):
    artist_id = StringField('artist_id')
    venue_id = StringField('venue_id')
    start_time = DateTimeField('start_time',
                               validators=[DataRequired()],
                               default=datetime.today())
コード例 #4
0
ファイル: clients.py プロジェクト: anuraagkapoor/domogik
def client_devices_new_wiz(client_id, device_type_id, product):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('device.params')
    msg.set_data({'device_type': device_type_id})
    res = cli.request('dbmgr', msg.get(), timeout=10)
    if res is not None:
        detaila = res.get_data()
        params = detaila['result']
    else:
        flash(gettext("Device creation failed"), "warning")
        flash(gettext("DbMGR is not answering with device_type parameters"),
              "danger")
        return redirect("/client/{0}/dmg_devices/known".format(client_id))

    # dynamically generate the wtfform
    class F(Form):
        name = TextField(
            "Device", [Required()],
            description=gettext("the display name for this device"))
        description = TextField(
            "Description",
            description=gettext("A description for this device"))
        reference = TextField(
            "Reference", description=gettext("A reference for this device"))
        pass

    # add the global params
    for item in params["global"]:
        # build the field
        name = "Parameter - {0}".format(item["key"])
        if item["type"] == "boolean":
            if default == 'Y' or default == 1 or default == True:
                default = True
            else:
                default = False
            field = BooleanField(name, [Required()],
                                 description=item["description"])
        elif item["type"] == "integer":
            field = IntegerField(name, [Required()],
                                 description=item["description"])
        elif item["type"] == "date":
            field = DateField(name, [Required()],
                              description=item["description"])
        elif item["type"] == "datetime":
            field = DateTimeField(name, [Required()],
                                  description=item["description"])
        elif item["type"] == "float":
            field = DateTimeField(name, [Required()],
                                  description=item["description"])
        elif item["type"] == "choice":
            choices = []
            for key in sorted(item["choices"]):
                choices.append((key, item["choices"][key]))
            field = SelectField(name, [Required()],
                                description=item["description"],
                                choices=choices)
        elif item["type"] == "password":
            field = PasswordField(name, [Required()],
                                  description=item["description"])
        else:
            # time, email, ipv4, ipv6, url
            field = TextField(name, [Required()],
                              description=item["description"])
        setattr(F, "glob|{0}".format(item["key"]), field)
    # add the xpl params
    for item in params["xpl"]:
        # build the field
        name = "xPL Parameter - '{0}".format(item["key"])
        if item["type"] == "boolean":
            if default == 'Y' or default == 1 or default == True:
                default = True
            else:
                default = False
            field = BooleanField(name, [Required()],
                                 description=item["description"])
        elif item["type"] == "integer":
            field = IntegerField(name, [Required()],
                                 description=item["description"])
        elif item["type"] == "date":
            field = DateField(name, [Required()],
                              description=item["description"])
        elif item["type"] == "datetime":
            field = DateTimeField(name, [Required()],
                                  description=item["description"])
        elif item["type"] == "float":
            field = DateTimeField(name, [Required()],
                                  description=item["description"])
        elif item["type"] == "choice":
            choices = []
            for key in sorted(item["choices"]):
                choices.append((key, item["choices"][key]))
            field = SelectField(name, [Required()],
                                description=item["description"],
                                choices=choices)
        elif item["type"] == "password":
            field = PasswordField(name, [Required()],
                                  description=item["description"])
        else:
            # time, email, ipv4, ipv6, url
            field = TextField(name, [Required()],
                              description=item["description"])
        setattr(F, "xpl|{0}".format(item["key"]), field)
    for cmd in params["xpl_commands"]:
        for item in params["xpl_commands"][cmd]:
            # build the fiel
            name = "Xpl-Command '{0}' Parameter '{1}'".format(cmd, item["key"])
            if item["type"] == "boolean":
                if default == 'Y' or default == 1 or default == True:
                    default = True
                else:
                    default = False
                field = BooleanField(name, [Required()],
                                     description=item["description"])
            elif item["type"] == "integer":
                field = IntegerField(name, [Required()],
                                     description=item["description"])
            elif item["type"] == "date":
                field = DateField(name, [Required()],
                                  description=item["description"])
            elif item["type"] == "datetime":
                field = DateTimeField(name, [Required()],
                                      description=item["description"])
            elif item["type"] == "float":
                field = DateTimeField(name, [Required()],
                                      description=item["description"])
            elif item["type"] == "choice":
                choices = []
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
                field = SelectField(name, [Required()],
                                    description=item["description"],
                                    choices=choices)
            elif item["type"] == "password":
                field = PasswordField(name, [Required()],
                                      description=item["description"])
            else:
                # time, email, ipv4, ipv6, url
                field = TextField(name, [Required()],
                                  description=item["description"])
            setattr(F, "cmd|{0}|{1}".format(cmd, item["key"]), field)
    for cmd in params["xpl_stats"]:
        for item in params["xpl_stats"][cmd]:
            # build the fiel
            name = "Xpl-Stat '{0}' Parameter '{1}'".format(cmd, item["key"])
            if item["type"] == "boolean":
                if default == 'Y' or default == 1 or default == True:
                    default = True
                else:
                    default = False
                field = BooleanField(name, [Required()],
                                     description=item["description"])
            elif item["type"] == "integer":
                field = IntegerField(name, [Required()],
                                     description=item["description"])
            elif item["type"] == "date":
                field = DateField(name, [Required()],
                                  description=item["description"])
            elif item["type"] == "datetime":
                field = DateTimeField(name, [Required()],
                                      description=item["description"])
            elif item["type"] == "float":
                field = DateTimeField(name, [Required()],
                                      description=item["description"])
            elif item["type"] == "choice":
                choices = []
                for key in sorted(item["choices"]):
                    choices.append((key, item["choices"][key]))
                field = SelectField(name, [Required()],
                                    description=item["description"],
                                    choices=choices)
            elif item["type"] == "password":
                field = PasswordField(name, [Required()],
                                      description=item["description"])
            else:
                # time, email, ipv4, ipv6, url
                field = TextField(name, [Required()],
                                  description=item["description"])
            setattr(F, "stat|{0}|{1}".format(cmd, item["key"]), field)
    form = F()

    if request.method == 'POST' and form.validate():
        # aprams hold the stucture,
        # append a vlaue key everywhere with the value submitted
        # or fill in the key
        params['client_id'] = client_id
        for item in request.form:
            if item in ["name", "reference", "description"]:
                # handle the global things
                params[item] = request.form.get(item)
            elif item.startswith('xpl') or item.startswith('glob'):
                # handle the global params
                if item.startswith('xpl'):
                    key = 'xpl'
                else:
                    key = 'global'
                par = item.split('|')[1]
                i = 0
                while i < len(params[key]):
                    param = params[key][i]
                    if par == param['key']:
                        params[key][i]['value'] = request.form.get(item)
                    i = i + 1
            elif item.startswith('stat') or item.startswith('cmd'):
                if item.startswith('stat'):
                    key = "xpl_stats"
                else:
                    key = "xpl_commands"
                name = item.split('|')[1]
                par = item.split('|')[2]
                i = 0
                while i < len(params[key][name]):
                    param = params[key][name][i]
                    if par == param['key']:
                        params[key][name][i]['value'] = request.form.get(item)
                    i = i + 1
        # we now have the json to return
        msg = MQMessage()
        msg.set_action('device.create')
        msg.set_data({'data': params})
        res = cli.request('dbmgr', msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
            if data["status"]:
                # reload stats
                req = MQSyncReq(app.zmq_context)
                msg = MQMessage()
                msg.set_action('reload')
                resp = req.request('xplgw', msg.get(), 100)
                flash(gettext("Device cerated succesfully"), 'success')
            else:
                flash(gettext("Device creation failed"), 'warning')
                flash(data["reason"], 'danger')
        else:
            flash(
                gettext(
                    "DbMgr did not respond on the device.create, check the logs"
                ), 'danger')
        return redirect("/client/{0}/dmg_devices/known".format(client_id))

    return render_template('client_device_new_wiz.html',
                           form=form,
                           params=params,
                           dtype=device_type_id,
                           clientid=client_id,
                           mactive="clients",
                           active='devices')
コード例 #5
0
ファイル: clients.py プロジェクト: anuraagkapoor/domogik
def client_config(client_id):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('client.detail.get')
    res = cli.request('manager', msg.get(), timeout=10)
    if res is not None:
        detaila = res.get_data()
        config = detaila[client_id]['data']['configuration']
    else:
        config = {}
    known_items = []

    # dynamically generate the wtfform
    class F(Form):
        submit = SubmitField("Send")
        pass

    for item in config:
        # keep track of the known fields
        known_items.append(item["key"])
        # handle required
        if item["required"] == "yes":
            arguments = [Required()]
        else:
            arguments = []
        # fill in the field
        if 'value' in item:
            default = item["value"]
        else:
            default = item["default"]
        # build the field
        if item["type"] == "boolean":
            if default == 'Y' or default == 1 or default == True:
                default = True
            else:
                default = False
            field = BooleanField(item["name"],
                                 arguments,
                                 description=item["description"],
                                 default=default)
        elif item["type"] == "integer":
            field = IntegerField(item["name"],
                                 arguments,
                                 description=item["description"],
                                 default=default)
        elif item["type"] == "date":
            field = DateField(item["name"],
                              arguments,
                              description=item["description"],
                              default=default)
        elif item["type"] == "datetime":
            field = DateTimeField(item["name"],
                                  arguments,
                                  description=item["description"],
                                  default=default)
        elif item["type"] == "float":
            field = DateTimeField(item["name"],
                                  arguments,
                                  description=item["description"],
                                  default=default)
        elif item["type"] == "choice":
            choices = []
            for choice in sorted(item["choices"]):
                choices.append((choice, choice))
            field = SelectField(item["name"],
                                arguments,
                                description=item["description"],
                                choices=choices,
                                default=default)
        elif item["type"] == "password":
            field = PasswordField(item["name"], [Required()],
                                  description=item["description"])
        else:
            # time, email, ipv4, ipv6, url
            field = TextField(item["name"],
                              arguments,
                              description=item["description"],
                              default=default)
        # add the field
        setattr(F, item["key"], field)
    # add the submit button
    field = submit = SubmitField("Save configuration")
    setattr(F, "submit", field)

    form = F()

    if request.method == 'POST' and form.validate():
        # build the requested config set
        data = {}
        for arg, value in list(request.form.items()):
            if arg in known_items:
                data[arg] = getattr(form, arg).data
        if 'auto_startup' in data.keys():
            data['auto_startup'] = 'Y'
        else:
            data['auto_startup'] = 'N'
        print data
        # build the message
        msg = MQMessage()
        msg.set_action('config.set')
        tmp = client_id.split('-')
        msg.add_data('type', tmp[0])
        tmp = tmp[1].split('.')
        msg.add_data('host', tmp[1])
        msg.add_data('name', tmp[0])
        msg.add_data('data', data)
        res = cli.request('dbmgr', msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
            if data["status"]:
                flash(gettext("Config saved successfull"), 'success')
            else:
                flash(gettext("Config saved failed"), 'warning')
                flash(data["reason"], 'danger')
        else:
            flash(
                gettext(
                    "DbMgr did not respond on the config.set, check the logs"),
                'danger')

    return render_template('client_config.html',
                           form=form,
                           clientid=client_id,
                           mactive="clients",
                           active='config')
コード例 #6
0
ファイル: forms.py プロジェクト: makai281/pysymo
class RequestForm(Form):
    # HOST
    host_ie = RadioField('HostIE', choices=ie_list, default=0, coerce=int)
    host = SelectMultipleField(lazy_gettext('Host'))
    # PROGRAM
    application_ie = RadioField('ApplicationIE',
                                choices=ie_list,
                                default=0,
                                coerce=int)
    application = SelectMultipleField(lazy_gettext('Application'))
    # FACILITY
    facility_ie = RadioField('FacilityIE',
                             choices=ie_list,
                             default=0,
                             coerce=int)
    facility = SelectMultipleField(lazy_gettext('Facility'))
    # PRIORITY
    priority_ie = RadioField('PriorityIE',
                             choices=ie_list,
                             default=0,
                             coerce=int)
    priority = SelectMultipleField(lazy_gettext('Priority'),
                                   choices=priority_list,
                                   coerce=int)
    # DATETIME (%Y-%m-%d %H:%M:%S)
    date_from = DateTimeField(lazy_gettext('From'), [validators.optional()],
                              format=DATETIME_FORMAT)
    date_to = DateTimeField(lazy_gettext('To'), [validators.optional()],
                            format=DATETIME_FORMAT)

    # RECORDS PER PAGE
    records_per_page = SelectField(lazy_gettext('Records per page'),
                                   choices=[(i, i)
                                            for i in (10, 25, 50, 100, 500)],
                                   coerce=int,
                                   default=25)

    # SORT DIRECTION - index - MongoDB sort style
    sort_direction = SelectField(lazy_gettext('Sort'),
                                 choices=sort_list,
                                 coerce=int,
                                 default=-1)

    # SEARCH STRING (regexp)
    search_str = StringField(lazy_gettext('Msg'))

    # PAGE NUMBER
    # hidden field has coerce=string - this cannot be changed
    # use int() in views to work with
    current_page = HiddenField('CurrentPage', default=1)

    # WATCH (auto refresh page)
    watch = HiddenField('Watch', default=0)

    # select fields with dynamic lists
    @classmethod
    def new(cls):
        form = cls()
        form.host.choices = sorted([(j, j) for j in db_get_hosts()])
        form.application.choices = sorted([(j, j)
                                           for j in db_get_applications()])
        form.facility.choices = sorted([(j, j) for j in db_get_facility()])
        return form
コード例 #7
0
class AppointmentsForm(FlaskForm):
    name = StringField('Customer Name', validators=[DataRequired()])
    start = DateTimeField('Start Date/Time', validators=[DataRequired()])
    end = DateTimeField('End Date/Time', validators=[DataRequired()])
    location = StringField('Location')
    submit = SubmitField('Add Appointment')
コード例 #8
0
ファイル: forms.py プロジェクト: kvakil/ok
class AssignmentForm(BaseForm):
    def __init__(self, course, obj=None, **kwargs):
        self.course = course
        self.obj = obj
        super(AssignmentForm, self).__init__(obj=obj, **kwargs)
        if obj:
            if obj.due_date == self.due_date.data:
                self.due_date.data = utils.local_time_obj(obj.due_date, course)
            if obj.lock_date == self.lock_date.data:
                self.lock_date.data = utils.local_time_obj(
                    obj.lock_date, course)

    display_name = StringField('Display Name',
                               validators=[validators.required()])
    name = StringField('Offering (example: cal/cs61a/fa16/proj01)',
                       validators=[validators.required()])
    due_date = DateTimeField('Due Date (Course Time)',
                             validators=[validators.required()])
    lock_date = DateTimeField('Lock Date (Course Time)',
                              validators=[validators.required()])
    max_group_size = IntegerField('Max Group Size',
                                  default=1,
                                  validators=[
                                      validators.InputRequired(),
                                      validators.number_range(min=1)
                                  ])
    url = StringField('URL',
                      validators=[validators.optional(),
                                  validators.url()])
    revisions_allowed = BooleanField('Enable Revisions',
                                     default=False,
                                     validators=[validators.optional()])
    autograding_key = StringField('Autograder Key', [validators.optional()])
    uploads_enabled = BooleanField('Enable Web Uploads',
                                   default=False,
                                   validators=[validators.optional()])
    upload_info = StringField('Upload Instructions',
                              validators=[validators.optional()])
    visible = BooleanField('Visible On Student Dashboard', default=True)
    autograding_key = StringField('Autograder Key',
                                  validators=[validators.optional()])

    def populate_obj(self, obj):
        """ Updates obj attributes based on form contents. """

        super(AssignmentForm, self).populate_obj(obj)
        obj.due_date = utils.server_time_obj(self.due_date.data, self.course)
        obj.lock_date = utils.server_time_obj(self.lock_date.data, self.course)

    def validate(self):
        check_validate = super(AssignmentForm, self).validate()

        # if our validators do not pass
        if not check_validate:
            return False

        # Ensure the name has the right format:
        is_valid_endpoint = utils.is_valid_endpoint(
            self.name.data, ASSIGNMENT_ENDPOINT_FORMAT)
        has_course_endpoint = self.name.data.startswith(self.course.offering)

        if not has_course_endpoint or not is_valid_endpoint:
            self.name.errors.append(
                'The name should be of the form {0}/<name>'.format(
                    self.course.offering))
            return False

        # If the name is changed, ensure assignment offering is unique
        assgn = Assignment.query.filter_by(name=self.name.data).first()
        if assgn:
            self.name.errors.append('That offering already exists')
            return False
        return True