Esempio n. 1
0
class MyFormFields(widgets.WidgetsList):
    #XXX: Since allow_extra_fields should be removed from validators.Schema,
    #     we need a validator for every input-expecting widget
    name = widgets.TextField(validator=validators.String())
    age = widgets.TextField(validator=validators.Int(), default=0)
    date = widgets.CalendarDatePicker(validator=validators.DateConverter(
        if_empty=datetime.now()))
Esempio n. 2
0
    def __add_specialized_hash(self, argument, argument_name):
        """
        Specialized option adder for hash, we need it to be diffferent
        because the hash and list objects uses an advanced type of widgets
        which make them to be able to add, remove fields during using the
        web UI. It uses the RepeatingFieldSet which is able to contain the
        other normal input widgets. It will have two fields (TextFields)
        one for key : keyfield and other for value : valuefield
        Also the validator addition is a little bit different and should 
        be done in that method also ...

        @param : argument : the argument options,
        @param : argument_name : the name of the argument also the name of the widget
        @return : Nothing
        """
        hash_repeat_data = {
            'template':
            "funcweb.templates.repeater_form",  #may change that if someone doesnt like my design :)
            'fields': [
                widgets.TextField(name="keyfield", label="Key Field"),
                widgets.TextField(name="valuefield", label="Value Field")
            ],
        }

        #create the RepeatingFieldSet object and add it to global list like you do for others
        temp_object = getattr(
            widgets,
            self.__convert_table[argument['type']]['type'])(**hash_repeat_data)
        #print temp_object.fields
        #add the common options
        self.__add_commons_to_object(temp_object, argument, argument_name)
        #add a new entry to final list
        self.__widget_list[argument_name] = temp_object
        del temp_object
Esempio n. 3
0
def test_rendering():
    """Forms can be rendered"""
    for Form in (widgets.TableForm, widgets.ListForm):
        form = Form(fields=[widgets.TextField("name", label="Your Name")])
        output = form.render(action="mylocation", format="xhtml")
        assert '<form ' in output and '</form>' in output
        assert 'action="mylocation"' in output
        assert 'method="post"' in output
        assert 'name="form"' in output
        assert 'id="form"' not in output
        assert "Your Name" in output
        assert 'name="name"' in output
        assert "submit" in output
        assert (Form is widgets.TableForm) == ('</table>' in output
                                               and '</td>' in output)
        assert (Form is widgets.ListForm) == ('</ul>' in output
                                              and '</li>' in output)
        form = Form(name="myform", fields=[widgets.TextField("myfield")])
        output = form.render(format="xhtml")
        assert 'name="myform"' in output
        assert 'id="myform"' not in output
        assert 'name="myfield"' in output
        form = Form(name="myform",
                    use_name=False,
                    fields=[widgets.TextField("myfield")])
        output = form.render(format="xhtml")
        assert 'name="myform"' not in output
        assert 'id="myform"' in output
        assert 'name="myfield"' in output
Esempio n. 4
0
def test_default_value():
    """Widgets can have a default value"""
    textfield = widgets.TextField("name")
    output = textfield.render(format='xhtml')
    assert 'value' not in output
    textfield = widgets.TextField("name", default="ed kowalczyk")
    output = textfield.render(format='xhtml')
    assert 'value="ed kowalczyk"' in output
Esempio n. 5
0
def test_disabled_widget():
    form = widgets.TableForm(fields=[
        widgets.TextField("name"),
        widgets.TextField("age", validator=validators.Int())
    ],
                             submit_text="Submit")
    output = form.render(disabled_fields=["age"])
    assert "age" not in output
Esempio n. 6
0
def test_input_errors():
    """Data is stored in the request object if there are errors"""
    form = widgets.TableForm(fields=[
        widgets.TextField("name"),
        widgets.TextField("age", validator=validators.Int())
    ])
    values = dict(name="ed", age="ed")
    values, errors = catch_validation_errors(form, values)
    assert "enter an integer" in str(errors["age"])
class TestNestedWidgetsWMixedValidation:

    form = widgets.TableForm(
        name="myform",
        validator=s_validator,
        fields=[
            widgets.TextField("name"),
            widgets.TextField("age"),
            widgets.TextField("number", validator=int_validator),
            widgets.FieldSet(
                name="sub",
                validator=s_validator,
                fields=[
                    widgets.TextField("name"),
                    widgets.TextField("age"),
                    widgets.TextField("number", validator=int_validator),
                    widgets.FieldSet(
                        name="sub2",
                        fields=[
                            widgets.TextField("name"),
                            widgets.TextField("age", validator=int_validator),
                            widgets.TextField("number",
                                              validator=int_validator),
                        ]),
                ]),
        ])

    def test_mixed_validators(self):
        """
        Tests that schema validators and single validators can be mixed
        safely.
        """
        values = dict(age="bad",
                      number="22",
                      sub=dict(age="bad",
                               number="bad",
                               sub2=dict(
                                   age="bad",
                                   number="bad",
                               )))

        values, errors = catch_validation_errors(self.form, values)
        print values, errors

        assert errors.pop('age', False)
        #assert values['number'] == 22

        # assert errors are not getting poluted errors from other levels of
        # the tree
        assert errors.keys() == ['sub']
        errors = errors['sub']
        assert errors.pop('age', False)
        assert errors.pop('number', False)

        assert errors.keys() == ['sub2']
        errors = errors['sub2']
        assert errors.pop('age', False)
        assert errors.pop('number', False)
        assert not errors
Esempio n. 8
0
def test_input_conversion():
    """Input for the whole form can be validated and converted"""
    form = widgets.TableForm(fields=[
        widgets.TextField("name"),
        widgets.TextField("age", validator=validators.Int())
    ],
                             submit_text="Submit")
    values = dict(name="ed", age="15")
    values = form.validate(values)
    assert values["name"] == "ed"
    assert values["age"] == 15
    assert not values.has_key("submit")
Esempio n. 9
0
def test_passing_instance():
    """You can pass an instance to a form for the value"""
    form = widgets.TableForm(fields=[
        widgets.TextField("name"),
        widgets.TextField("age", validator=validators.Int())
    ],
                             submit_text="Submit")

    class Person(object):
        name = "ed"
        age = 892

    output = form.render(Person(), format="xhtml")
    assert 'value="ed"' in output
    assert 'value="892"' in output
Esempio n. 10
0
class InputFields(widgets.WidgetsList):
    peptide = widgets.TextArea(label="Uniprot Accession or Seq")

    enzyme = widgets.SingleSelectField(label="Enzyme",
                                       options=[
                                           "Chymotrypsin",
                                           "Chymotrypsin Low Specificity",
                                           "Trypsin", "Pepsin (ph = 1.3)",
                                           "Pepsin (ph >= 2.0)"
                                       ],
                                       default="Trypsin")
    misses = widgets.TextField(label="Allowed Missed Cleavages")
    minlen = widgets.TextField(label="Minimum Peptide Length")
    maxlen = widgets.TextField(label="Maximum Peptide Length")
    minweight = widgets.TextField(label="Minimum Peptide Weight")
    maxweight = widgets.TextField(label="Maximum Peptide Weight")
Esempio n. 11
0
def test_simple_widget_attrs():
    """A simple widget supports attributes passed to the constructor or at
    display time."""
    w = widgets.TextField(name="foo",
                          attrs={
                              'onchange': 'python',
                              'size': '10'
                          })
    output = w.render(format='xhtml')
    assert 'onchange="python"' in output
    assert 'size="10"' in output
    output = w.render(attrs={'onclick': 'java'}, format='xhtml')
    assert 'onchange="python"' not in output
    assert 'size="10"' not in output
    assert 'onclick="java"' in output
    output = w.render(attrs={
        'onchange': 'java',
        'size': '50',
        'alt': None
    },
                      format='xhtml')
    assert 'onchange="java"' in output
    assert 'size="50"' in output
    assert 'alt' not in output
    assert 'onclick' not in output
Esempio n. 12
0
class PrivateTitleFields(widgets.WidgetsList):
    import operator
    preferred_distributor = widgets.TextField()
    title_id = widgets.HiddenField()
    all_sections = [(l.id, l.sectionName) for l in list(Section.select())]
    all_sections.sort(key=operator.itemgetter(1))
    sections = widgets.CheckBoxList(options=all_sections, field_class='inline')
Esempio n. 13
0
    def __add_specialized_list(self, argument, argument_name):
        """
        Very similar to __add_specialized_hash except it has one field
        that is repeated so that provides a dynamic numbers of fields into 
        the web UI.
        
        TODO : combine the 2 methods into a one generic they are very similar 
        @param : argument : the argument options,
        @param : argument_name : the name of the argument also the name of the widget
        @return : Nothing
        """
        list_repeat_data = {
            'template':
            "funcweb.templates.repeater_form",  #may change that if someone doesnt like my design :)
            'fields':
            [widgets.TextField(name="listfield", label="List Field")],
        }

        #create the RepeatingFieldSet object and add it to global list like you do for others
        temp_object = getattr(
            widgets,
            self.__convert_table[argument['type']]['type'])(**list_repeat_data)
        #add the commno options
        self.__add_commons_to_object(temp_object, argument, argument_name)
        #add a new entry to final list
        self.__widget_list[argument_name] = temp_object
        del temp_object
Esempio n. 14
0
def test_field_for():
    cherrypy.request.validation_errors = dict(foo=dict(foo='error'))
    template = """\
    <div xmlns:py="http://purl.org/kid/ns#">
        ${field_for('foo').fq_name}.appears
        ${field_for('foo').error}_appears
        ${field_for('foo').field_id}_appears
        ${field_for('foo').display(value_for('foo'), **params_for('foo'))}
    </div>
    """
    textfield = widgets.TextField("foo")
    fieldset = widgets.FieldSet("foo", fields=[textfield], template=template)
    form = widgets.Form("form", fields=[fieldset], template=template)
    # Good example below of how you can pass parameters and values to nested
    # widgets.
    value = dict(foo=dict(foo="HiYo!"))
    params = dict(attrs=dict(foo=dict(foo=dict(size=100))))
    params['format'] = 'xhtml'
    output = form.render(value, **params)
    assert "form_foo_appears" in output
    assert "form_foo_foo_appears" in output
    assert "foo.appears" in output
    assert "foo.foo.appears" in output
    assert "error_appears" in output
    assert "textfield" in output
    assert "HiYo!" in output
    assert "size=\"100\"" in output
Esempio n. 15
0
def test_table_widget_js():
    """
    The TableForm Widget can require JavaScript and CSS resources. Addresses
    ticket #425. Should be applicable to any widget.
    """
    class MyTableWithJS(widgets.TableForm):
        javascript = [
            widgets.JSLink(mod=widgets.static, name="foo.js"),
            widgets.JSSource("alert('hello');")
        ]
        css = [widgets.CSSLink(mod=widgets.static, name="foo.css")]

    form = MyTableWithJS(fields=[widgets.TextField(name='title')])

    class MyRoot(turbogears.controllers.RootController):
        def test(self):
            return dict(form=form)

        test = turbogears.expose(template=".form")(test)

    cherrypy.root = MyRoot()
    testutil.create_request("/test")
    output = cherrypy.response.body[0]
    assert 'foo.js' in output
    assert "alert('hello');" in output
    assert 'foo.css' in output
Esempio n. 16
0
def test_validation():
    """Values can be converted to/from Python values"""
    textfield = widgets.TextField("age", validator=validators.Int())
    output = textfield.render(2, format="xhtml")
    assert 'value="2"' in output
    value = "2"
    value = textfield.validator.to_python(value)
    assert value == 2
Esempio n. 17
0
class RatingFields(widgets.WidgetsList):
    rater = widgets.TextField(validators=validators.NotEmpty)
    score = widgets.RadioButtonList(options=[(1, "1"), (2, "2"), (3, "3"),
                                             (4, "4"), (5, "5")],
                                    default=5,
                                    attrs={'class': 'ratingsform'})
    comments = widgets.TextArea()
    title = widgets.HiddenField()
Esempio n. 18
0
def test_creation_overriding():
    class TestFormFields(widgets.WidgetsList):
        foo = widgets.TextField()
        bar = widgets.CheckBox()

    fields = TestFormFields()
    fields[1] = widgets.TextField('bar')
    t = widgets.TableForm(fields=fields)
    assert len(t.fields) == 2, '%s' % [x.name for x in t.fields]
Esempio n. 19
0
def test_threadsafety():
    """Widget attributes can't be changed after init, for threadsafety"""
    w = widgets.TextField("bar")
    w.display()
    try:
        w.name = "foo"
        assert False, "should have gotten an exception"
    except ValueError:
        pass
Esempio n. 20
0
def test_unicode_input():
    """Unicode values are rendered correctly"""
    tf = widgets.TextField("name", validator=validators.UnicodeString())
    output = tf.render(u'Pete \u011C', format='xhtml')
    assert 'value="Pete \xc4\x9c"' in output
    return  # XXX: the folowing causes OTHER(!) tests to fail!
    try:
        print tf.render('Pete \xfe\xcd')
    except ValueError, e:
        pass
Esempio n. 21
0
def test_creation():
    class TestFormFields(widgets.WidgetsList):
        foo = widgets.TextField()
        bar = widgets.CheckBox()

    t = widgets.TableForm(fields=TestFormFields() + [widgets.TextField('a')])
    wlist = t.fields
    assert len(wlist) == 3, '%s' % [x.name for x in wlist]
    assert wlist[0].name == 'foo'
    assert wlist[1].name == 'bar'
    assert wlist[2].name == 'a'
Esempio n. 22
0
def test_false_default_value():
    """Widgets can have a default value that evaluates to False"""
    textfield = widgets.TextField("name")
    assert textfield.default is None
    output = textfield.render(format='xhtml')
    assert 'value' not in output
    textfield = widgets.TextField("name", default=0)
    assert textfield.default == 0
    output = textfield.render(format='xhtml')
    assert 'value="0"' in output
    textfield = widgets.TextField("name", default="")
    assert textfield.default == ""
    output = textfield.render(format='xhtml')
    assert 'value=""' in output
    msfield = widgets.MultipleSelectField("name",
                                          default=[],
                                          options=(1, 2, 3))
    assert msfield.default == []
    output = msfield.render(format='xhtml')
    assert 'selected' not in output
Esempio n. 23
0
class GroupForm(HorizontalForm):
    fields = [
        widgets.HiddenField(name='group_id'),
        widgets.TextField(name='group_name', label=_(u'Group Name')),
        widgets.TextField(name='display_name', label=_(u'Display Name')),
        widgets.PasswordField(name='root_password',
                              label=_(u'Root Password'),
                              validator=StrongPassword()),
        widgets.CheckBox(name='ldap',
                         label=_(u'LDAP'),
                         help_text=_(u'Populate group membership from LDAP?')),
    ]
    name = 'Group'
    action = 'save_data'
    submit_text = _(u'Save')
    validator = GroupFormSchema()

    def update_params(self, d):
        if not identity.current.user.is_admin() or \
                not config.get('identity.ldap.enabled', False):
            d['disabled_fields'] = ['ldap']
        super(GroupForm, self).update_params(d)
Esempio n. 24
0
def test_css_classes():
    """A FormField supports css_classes, they are added after the original
    class. They can be provided at construction or at display time, the latter
    overrides the former but attrs overrides everything."""
    w = widgets.TextField(name="foo")
    output = w.render(format='xhtml')
    assert 'class="textfield"' in output
    w = widgets.TextField(name="foo", css_classes=["bar", "bye"])
    output = w.render(format='xhtml')
    assert 'class="textfield bar bye"' in output
    output = w.render(css_classes=["coke", "pepsi"], format='xhtml')
    assert 'class="textfield coke pepsi"' in output
    w = widgets.TextField(name="foo",
                          css_classes=["bar", "bye"],
                          attrs={'class': 'again'})
    output = w.render(format='xhtml')
    assert 'class="again"' in output
    output = w.render(css_classes=["coke", "pepsi"], format='xhtml')
    assert 'class="again"' in output
    output = w.render(css_classes=["coke", "pepsi"],
                      attrs={'class': 'funny'},
                      format='xhtml')
    assert 'class="funny"' in output
Esempio n. 25
0
def test_class_attributes_form():
    class TestForm(widgets.ListForm):
        fields = [widgets.TextField("name"), widgets.TextField("age")]
        validator = validators.Schema()
        submit_text = "gimme"

    form = TestForm()
    output = form.render()
    assert "name" in output
    assert "age" in output
    assert "gimme" in output

    form = TestForm(fields=TestForm.fields + [widgets.TextField("phone")],
                    submit_text="your number too")
    output = form.render()
    assert "phone" in output
    assert "your number too" in output
Esempio n. 26
0
class KeyTypes(AdminPage):
    # For XMLRPC methods in this class.
    exposed = False

    id         = widgets.HiddenField(name='id')
    key_name   = widgets.TextField(name='key_name', label=_(u'Name'))
    numeric    = widgets.CheckBox(name='numeric', label=_(u'Numeric'))

    form = HorizontalForm(
        'keytypes',
        fields = [id, key_name, numeric],
        action = 'save_data',
        submit_text = _(u'Submit Data'),
    )

    
    def __init__(self,*args,**kw):
        kw['search_url'] =  url("/keytypes/by_name?anywhere=1"),
        kw['search_name'] = 'key'
        super(KeyTypes,self).__init__(*args,**kw)

        self.search_col = Key.key_name
        self.search_mapper = Key
    
    @expose(template='bkr.server.templates.form')
    def new(self, **kw):
        return dict(
            title=_(u'New Key Type'),
            form = self.form,
            action = './save',
            options = {},
            value = kw,
        )

    @expose(template='bkr.server.templates.form')
    def edit(self,**kw):
        values = []
        if kw.get('id'):
            key = Key.by_id(kw['id'])
            values = dict(
                id         = key.id,
                key_name   = key.key_name,
                numeric    = key.numeric
            )
        
        return dict(
            form = self.form,
            action = './save',
            options = {},
            value = values,
        )
    
    @expose()
    @error_handler(edit)
    def save(self, **kw):
        if kw['id']:
            key = Key.by_id(kw['id'])
            key.key_name = kw['key_name']
        else:
            key = Key(key_name=kw['key_name'])
            session.add(key)
        if 'numeric' in kw:
            key.numeric = kw['numeric']
        flash( _(u"OK") )
        redirect(".")

    @expose(template="bkr.server.templates.admin_grid")
    @paginate('list')
    def index(self,*args,**kw):
        keytypes = session.query(Key) 
        list_by_letters = set([elem.key_name[0].capitalize() for elem in keytypes])
        results = self.process_search(**kw)
        if results:
            keytypes = results.order_by(Key.key_name)
        keytypes_grid = myPaginateDataGrid(fields=[
                                  ('Key', lambda x: make_edit_link(x.key_name, x.id)),
                                  ('Numeric', lambda x: x.numeric),
                                  (' ', lambda x: make_remove_link(x.id)),
                              ],
                              add_action='./new')
        return dict(title="Key Types", 
                    grid = keytypes_grid, 
                    search_widget = self.search_widget_form,
                    alpha_nav_bar = AlphaNavBar(list_by_letters,self.search_name),
                    list = keytypes)

    @expose()
    def remove(self, **kw):
        remove = Key.by_id(kw['id'])
        session.delete(remove)
        flash( _(u"%s Deleted") % remove.key_name )
        raise redirect(".")

    @expose(format='json')
    def by_name(self,input,*args,**kw):
        if 'anywhere' in kw:
            search = Key.list_by_name(input,find_anywhere=True)
        else:
            search = Key.list_by_name(input)

        keys = [elem.key_name for elem in search]
        return dict(matches=keys)
Esempio n. 27
0
class Users(AdminPage):
    # For XMLRPC methods in this class.
    exposed = True

    user_id = widgets.HiddenField(name='user_id')
    user_name = widgets.TextField(name='user_name', label=_(u'Login'))
    display_name = widgets.TextField(name='display_name',
                                     label=_(u'Display Name'))
    email_address = widgets.TextField(name='email_address',
                                      label=_(u'Email Address'))
    password = widgets.PasswordField(name='password', label=_(u'Password'))
    disabled = widgets.CheckBox(name='disabled', label=_(u'Disabled'))
    user_form = HorizontalForm(
        'User',
        fields=[
            user_id, user_name, display_name, email_address, password, disabled
        ],
        action='save_data',
        submit_text=_(u'Save'),
    )

    def __init__(self, *args, **kw):
        kw['search_url'] = url("/users/by_name?anywhere=1&ldap=0")
        kw['search_name'] = 'user'
        super(Users, self).__init__(*args, **kw)

        self.search_col = User.user_name
        self.search_mapper = User

    @identity.require(identity.in_group("admin"))
    @expose(template='bkr.server.templates.form')
    def new(self, **kw):
        return dict(
            form=self.user_form,
            action='./save',
            options={},
            value=kw,
        )

    @identity.require(identity.in_group("admin"))
    @expose(template='bkr.server.templates.user_edit_form')
    def edit(self, id=None, **kw):
        if id:
            user = User.by_id(id)
            title = _(u'User %s') % user.user_name
            value = user
        else:
            user = None
            title = _(u'New user')
            value = kw
        return_vals = dict(form=self.user_form,
                           action='./save',
                           title=title,
                           options={},
                           value=value)
        if id:
            return_vals['groupsgrid'] = self.show_groups()
        else:
            return_vals['groupsgrid'] = None
        return return_vals

    @identity.require(identity.in_group("admin"))
    @expose()
    @validate(user_form, validators=UserFormSchema())
    @error_handler(edit)
    def save(self, **kw):
        if kw.get('user_id'):
            user = User.by_id(kw['user_id'])
        else:
            user = User()
            session.add(user)
        user.display_name = kw['display_name']
        user.user_name = kw['user_name']
        user.email_address = kw['email_address']
        if kw.get('disabled') != user.disabled:
            user.disabled = kw.get('disabled')
            if user.disabled:
                self._disable(user, method="WEBUI")
        if kw['password'] != user.password:
            user.password = kw['password']

        flash(_(u"%s saved" % user.display_name))
        redirect(".")

    def make_remove_link(self, user):
        if user.removed is not None:
            return XML('<a class="btn" href="unremove?id=%s">'
                       '<i class="fa fa-plus"/> Re-Add</a>' % user.user_id)
        else:
            return XML('<a class="btn" href="remove?id=%s">'
                       '<i class="fa fa-times"/> Remove</a>' % user.user_id)

    @expose(template="bkr.server.templates.admin_grid")
    @paginate('list', default_order='user_name', limit=20)
    def index(self, *args, **kw):
        users = session.query(User)
        list_by_letters = set(
            [elem.user_name[0].capitalize() for elem in users])
        result = self.process_search(**kw)
        if result:
            users = result

        users_grid = myPaginateDataGrid(fields=[
            ('Login', lambda x: make_edit_link(x.user_name, x.user_id)),
            ('Display Name', lambda x: x.display_name),
            ('Disabled', lambda x: x.disabled),
            ('', lambda x: self.make_remove_link(x)),
        ],
                                        add_action='./new')
        return dict(title="Users",
                    grid=users_grid,
                    alpha_nav_bar=AlphaNavBar(list_by_letters, 'user'),
                    search_widget=self.search_widget_form,
                    list=users)

    @identity.require(identity.in_group("admin"))
    @expose()
    def remove(self, id, **kw):
        try:
            user = User.by_id(id)
        except InvalidRequestError:
            flash(_(u'Invalid user id %s' % id))
            raise redirect('.')
        try:
            self._remove(user=user, method='WEBUI')
        except BX, e:
            flash(
                _(u'Failed to remove User %s, due to %s' %
                  (user.user_name, e)))
            raise redirect('.')
        else:
Esempio n. 28
0
class OSVersions(AdminPage):
    # For XMLRPC methods in this class.
    exposed = False

    id      = widgets.HiddenField(name="id")
    alias   = widgets.TextField(name="alias",
                                validator=validators.UnicodeString(if_empty=None))
    arches  = CheckBoxList(name="arches", label="Arches",
                                      options=lambda: [(arch.id, arch.arch) for arch in Arch.query],
                                      validator=validators.Int())

    osmajor_form = HorizontalForm(
        fields      = [id, alias],
        submit_text = _(u"Edit OSMajor"),
    )

    osversion_form = HorizontalForm(
        fields      = [id, arches],
        action      = "edit osversion",
        submit_text = _(u"Edit OSVersion"),
    )
 
    def __init__(self,*args,**kw):
        kw['search_name'] = 'osversion' 
        kw['search_url'] = url("/osversions/by_name?anywhere=1")
        super(OSVersions,self).__init__(*args,**kw) 

        self.search_col = OSMajor.osmajor
        self.join = [OSVersion.osmajor]
        self.search_mapper = OSVersion
        self.add = False
     
    @identity.require(identity.in_group("admin"))
    @expose(template="bkr.server.templates.form")
    def edit(self, id=None, *args, **kw):
        try:
            osversion = OSVersion.by_id(id)
        except InvalidRequestError:
            flash(_(u"Invalid OSVersion ID %s" % id))
            redirect(".")
        return dict(title   = unicode(osversion),
                    value   = dict(id     = osversion.id,
                                   arches = [arch.id for arch in osversion.arches]),
                    form    = self.osversion_form,
                    action  = "./save",
                    options = None)

    @identity.require(identity.in_group("admin"))
    @expose(template="bkr.server.templates.osmajor")
    def edit_osmajor(self, id=None, *args, **kw):
        try:
            osmajor = OSMajor.by_id(id)
        except InvalidRequestError:
            flash(_(u"Invalid OSMajor ID %s" % id))
            redirect(".")
        return dict(title   = "OSMajor",
                    value   = osmajor,
                    form    = self.osmajor_form,
                    action  = "./save_osmajor",
                    options = None)

    @identity.require(identity.in_group("admin"))
    @expose()
    @validate(form=osmajor_form)
    def save_osmajor(self, id=None, alias=None, *args, **kw):
        try:
            osmajor = OSMajor.by_id(id)
        except InvalidRequestError:
            flash(_(u"Invalid OSMajor ID %s" % id))
            redirect(".")
        if osmajor.alias != alias:
            if alias:
                try:
                    existing = OSMajor.by_name_alias(alias)
                except NoResultFound:
                    pass
                else:
                    flash(_(u'Cannot save alias %s, it is already used by %s')
                            % (alias, existing))
                    redirect('.')
            osmajor.alias = alias
            flash(_(u"Changes saved for %s" % osmajor))
        else:
            flash(_(u"No changes for %s" % osmajor))
        redirect(".")

    @identity.require(identity.in_group('admin'))
    @expose()
    def save_osmajor_installopts(self, osmajor_id=None, installopts=None):
        try:
            osmajor = OSMajor.by_id(osmajor_id)
        except InvalidRequestError:
            flash(_(u"Invalid OSMajor ID %s" % id))
            redirect(".")
        for arch, options in installopts.iteritems():
            # arch=None means applied to all arches
            io = OSMajorInstallOptions.lazy_create(osmajor_id=osmajor.id,
                    arch_id=Arch.by_name(arch).id if arch else None)
            io.ks_meta = options['ks_meta']
            io.kernel_options = options['kernel_options']
            io.kernel_options_post = options['kernel_options_post']
        flash(_(u'Install options saved for %s') % osmajor)
        redirect('.')

    @identity.require(identity.in_group("admin"))
    @expose()
    @validate(form=osversion_form)
    def save(self, id=None, arches=None, *args, **kw):
        try:
            osversion = OSVersion.by_id(id)
        except InvalidRequestError:
            flash(_(u"Invalid OSVersion ID %s" % id))
            redirect(".")
        arch_objects = [Arch.by_id(arch) for arch in arches]
        if osversion.arches != arch_objects:
            osversion.arches = arch_objects
            flash(_(u"Changes Saved for %s" % osversion))
        else:
            flash(_(u"No Changes for %s" % osversion))
        redirect(".")

    
    @expose(format='json')
    def by_name(self, input,*args,**kw):
        input = input.lower()
        if 'anywhere' in kw:
            search = OSVersion.list_osmajor_by_name(input, find_anywhere=True)
        else:
            search = OSVersion.list_osmajor_by_name(input)

        osmajors =  ["%s" % (match.osmajor.osmajor) for match in search] 
        osmajors = list(set(osmajors))
        return dict(matches=osmajors)

    @expose(template="bkr.server.templates.admin_grid")
    @paginate('list',limit=50, default_order='osmajor.osmajor')
    def index(self,*args,**kw):
        osversions = self.process_search(*args,**kw) 
        list_by_letters = []
        for elem in osversions:
            osmajor_name = elem.osmajor.osmajor
            if osmajor_name:
                list_by_letters.append(osmajor_name[0].capitalize())
        alpha_nav_data = set(list_by_letters)
        template_data = self.osversions(osversions,*args, **kw)
        nav_bar = self._build_nav_bar(alpha_nav_data,self.search_name)
        template_data['alpha_nav_bar'] = nav_bar
        template_data['search_widget'] = self.search_widget_form
        return template_data
         

    def osversions(self, osversions=None, *args, **kw):
        q = session.query(self.search_mapper) # This line +3 dupes the start of process_search
        if osversions is None:
            for j in self.join:
                q = q.join(j)
            osversions = q
        osversions_grid = myPaginateDataGrid(fields=[
                                  myPaginateDataGrid.Column(name='osmajor.osmajor', getter=lambda x: make_link(url = './edit_osmajor?id=%s' % x.osmajor.id, text = x.osmajor), title='OS Major', options=dict(sortable=True)),
                                  myPaginateDataGrid.Column(name='osmajor.alias', getter=lambda x: x.osmajor.alias, title='Alias', options=dict(sortable=True)),
                                  myPaginateDataGrid.Column(name='osminor', getter=lambda x: make_link(url  = './edit?id=%s' % x.id, text = x.osminor), title='OS Minor', options=dict(sortable=True)),
                                  myPaginateDataGrid.Column(name='arches', getter=lambda x: " ".join([arch.arch for arch in x.arches]), title='Arches', options=dict(sortable=True)),
                              ])
 
        return dict(title="OS Versions", 
                    grid = osversions_grid, 
                    addable = False,              
                    list = osversions)

    default = index
Esempio n. 29
0
class Preferences(RPCRoot):

    exposed = True
    delete_link = DeleteLinkWidgetForm()
    beaker_password = widgets.PasswordField(name='password',
                                            label='Beaker Password')
    root_password = widgets.TextField(name='_root_password',
                                      label='Root Password')
    rootpw_expiry = widgets.TextField(name='rootpw_expiry',
                                      label='Root Password Expiry',
                                      attrs={'disabled': True})
    email = widgets.TextField(name='email_address',
                              label='Email Address',
                              validator=validators.Email())
    prefs_form = HorizontalForm(
        'UserPrefs',
        fields=[email, beaker_password, root_password, rootpw_expiry],
        action='save',
        submit_text=_(u'Change'),
    )

    sshkey = widgets.TextArea(
        name='ssh_pub_key',
        label='Public SSH Key',
        validator=beaker_validators.SSHPubKey(not_empty=True))
    ssh_key_add_form = InlineForm(
        'ssh_key_add',
        fields=[sshkey],
        action='ssh_key_add',
        submit_text=_(u'Add'),
    )

    rootpw_grid = BeakerDataGrid(fields=[
        BeakerDataGrid.Column('root_password',
                              title=_(u'Root Password'),
                              getter=lambda x: x.value),
        BeakerDataGrid.Column('effective_from',
                              title=_(u'Effective from'),
                              getter=lambda x: x.valid_from,
                              options=dict(datetime=True)),
    ])

    auto_users = AutoCompleteField(name='user',
                                   search_controller=url("../users/by_name"),
                                   search_param="input",
                                   result_name="matches")

    submission_delegate_form = InlineForm(
        'SubmissionDelegates',
        fields=[auto_users],
        action='save_data',
        submit_text=_(u'Add'),
    )
    remove_submission_delegate_link = DoAndConfirmForm()

    def show_submission_delegates(self, user):
        user_fields = [
            ('Submission Delegate', lambda x: x.display_name),
            ('Action', lambda x: self.remove_submission_delegate_link. \
                display({'delegate_id': x.user_id},
                action=url('remove_submission_delegate'), look='link',
                msg='Are you sure you want to remove %s as a submitter?' % x,
                action_text='Remove (-)')),]
        return BeakerDataGrid(fields=user_fields)

    @expose(template='bkr.server.templates.prefs')
    @identity.require(identity.not_anonymous())
    def index(self, *args, **kw):
        user = identity.current.user

        # Show all future root passwords, and the previous five
        rootpw = ConfigItem.by_name('root_password')
        rootpw_values = rootpw.values().filter(rootpw.value_class.valid_from > datetime.utcnow())\
                       .order_by(rootpw.value_class.valid_from.desc()).all()\
                      + rootpw.values().filter(rootpw.value_class.valid_from <= datetime.utcnow())\
                       .order_by(rootpw.value_class.valid_from.desc())[:5]

        return dict(
            title='User Prefs',
            delete_link=self.delete_link,
            prefs_form=self.prefs_form,
            ssh_key_form=self.ssh_key_add_form,
            widgets={},
            ssh_keys=user.sshpubkeys,
            value=user,
            rootpw=rootpw.current_value(),
            rootpw_grid=self.rootpw_grid,
            rootpw_values=rootpw_values,
            options=None,
            #Hack, to insert static content for submission_delegate
            remove_submission_delegate=self.remove_submission_delegate_link,
            submission_delegates_grid=self.show_submission_delegates(user),
            submission_delegate_form=self.submission_delegate_form)

    # XMLRPC interface
    @expose()
    @identity.require(identity.not_anonymous())
    def remove_submission_delegate_by_name(self,
                                           delegate_name,
                                           service=u'XMLRPC'):
        user = identity.current.user
        try:
            submission_delegate = User.by_user_name(delegate_name)
        except NoResultFound:
            raise BX(_(u'%s is not a valid user name' % delegate_name))
        try:
            user.remove_submission_delegate(submission_delegate,
                                            service=service)
        except ValueError:
            raise BX(_(u'%s is not a submission delegate of %s' % \
                (delegate_name, user)))
        return delegate_name

    # UI interface
    @expose()
    @identity.require(identity.not_anonymous())
    def remove_submission_delegate(self, delegate_id, service=u'WEBUI'):
        user = identity.current.user
        try:
            submission_delegate = User.by_id(delegate_id)
        except NoResultFound:
            flash(_(u'%s is not a valid user id' % delegate_id))
            redirect('.')
        user.remove_submission_delegate(submission_delegate, service=service)
        flash(_(u'%s removed as a submission delegate' % submission_delegate))
        redirect('.')

    # XMLRPC Interface
    @expose()
    @identity.require(identity.not_anonymous())
    def add_submission_delegate_by_name(self,
                                        new_delegate_name,
                                        service=u'XMLRPC'):
        user = identity.current.user
        new_delegate = User.by_user_name(new_delegate_name)
        if not new_delegate:
            raise BX(_(u'%s is not a valid user' % new_delegate_name))
        user.add_submission_delegate(new_delegate, service)
        return new_delegate_name

    # UI Interface
    @expose()
    @identity.require(identity.not_anonymous())
    def add_submission_delegate(self, **kwargs):
        user = identity.current.user
        new_delegate_name = kwargs['user']['text']
        new_delegate = User.by_user_name(new_delegate_name)
        if not new_delegate:
            flash(_(u'%s is not a valid user' % new_delegate_name))
            redirect('.')

        try:
            user.add_submission_delegate(new_delegate, u'WEBUI')
        except NoChangeException, e:
            flash(_(unicode(e)))
            redirect('.')

        flash(_(u'Added %s as a submission delegate' % new_delegate_name))
        redirect('.')
class SimpleFields(widgets.WidgetsList):
    age = widgets.TextField(validator=validators.Int())
    phone = widgets.TextField()