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()
def test_textarea(): w = widgets.TextArea(rows=20, cols=30) output = w.render(format='xhtml') assert 'rows="20"' in output assert 'cols="30"' in output output = w.render(rows=50, cols=50, format='xhtml') assert 'rows="50"' in output assert 'cols="50"' in output assert '> +++ </textarea>' in w.render(' +++ ', format='xhtml')
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")
class JobForm(widgets.Form): template = 'bkr.server.templates.job_form' name = 'job' submit_text = _(u'Queue') fields = [widgets.TextArea(name='textxml')] hidden_fields = [ widgets.HiddenField(name='confirmed', validator=validators.StringBool()) ] params = ['xsd_errors'] xsd_errors = None def update_params(self, d): super(JobForm, self).update_params(d) if 'xsd_errors' in d['options']: d['xsd_errors'] = d['options']['xsd_errors'] d['submit_text'] = _(u'Queue despite validation errors')
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 Jobs(RPCRoot): # For XMLRPC methods in this class. exposed = True job_list_action_widget = JobActionWidget() job_page_action_widget = JobPageActionWidget() recipeset_widget = RecipeSetWidget() recipe_widget = RecipeWidget() priority_widget = PriorityWidget( ) #FIXME I have a feeling we don't need this as the RecipeSet widget declares an instance of it product_widget = ProductWidget() retention_tag_widget = RetentionTagWidget() job_type = {'RS': RecipeSet, 'J': Job} whiteboard_widget = JobWhiteboard() hidden_id = widgets.HiddenField(name='id') confirm = widgets.Label(name='confirm', default="Are you sure you want to cancel?") message = widgets.TextArea(name='msg', label=_(u'Reason?'), help_text=_(u'Optional')) _upload = widgets.FileField(name='filexml', label='Job XML') form = HorizontalForm('jobs', fields=[_upload], action='save_data', submit_text=_(u'Submit Data')) del _upload cancel_form = widgets.TableForm('cancel_job', fields=[hidden_id, message, confirm], action='really_cancel', submit_text=_(u'Yes')) job_form = JobForm() job_schema_doc = lxml.etree.parse( pkg_resources.resource_stream('bkr.common', 'schema/beaker-job.rng')) @classmethod def success_redirect(cls, id, url='/jobs/mine', *args, **kw): flash(_(u'Success! job id: %s' % id)) redirect('%s' % url) @expose(template='bkr.server.templates.form-post') @identity.require(identity.not_anonymous()) def new(self, **kw): return dict( title='New Job', form=self.form, action='./clone', options={}, value=kw, ) def _check_job_deletability(self, t_id, job): if not isinstance(job, Job): raise TypeError('%s is not of type %s' % (t_id, Job.__name__)) if not job.can_delete(identity.current.user): raise BeakerException( _(u'You do not have permission to delete %s' % t_id)) def _delete_job(self, t_id): job = TaskBase.get_by_t_id(t_id) self._check_job_deletability(t_id, job) Job.delete_jobs([job]) return [t_id] @expose() @identity.require(identity.not_anonymous()) @restrict_http_method('post') def delete_job_page(self, t_id): try: self._delete_job(t_id) flash(_(u'Succesfully deleted %s' % t_id)) except (BeakerException, TypeError): flash(_(u'Unable to delete %s' % t_id)) redirect('.') redirect('./mine') @expose() @identity.require(identity.not_anonymous()) @restrict_http_method('post') def delete_job_row(self, t_id): try: self._delete_job(t_id) return [t_id] except (BeakerException, TypeError), e: log.debug(str(e)) response.status = 400 return ['Unable to delete %s' % t_id]
class RecipeSets(RPCRoot): # For XMLRPC methods in this class. exposed = True hidden_id = widgets.HiddenField(name='id') confirm = widgets.Label(name='confirm', default="Are you sure you want to cancel?") message = widgets.TextArea(name='msg', label=_(u'Reason?'), help_text=_(u'Optional')) cancel_form = widgets.TableForm('cancel_recipeset', fields=[hidden_id, message, confirm], action='really_cancel', submit_text=_(u'Yes')) @identity.require(identity.not_anonymous()) @expose(template="bkr.server.templates.form") def cancel(self, id): """ Confirm cancel recipeset """ try: recipeset = RecipeSet.by_id(id) except InvalidRequestError: flash(_(u"Invalid recipeset id %s" % id)) redirect("/jobs/%s" % recipeset.job.id) if not recipeset.can_cancel(identity.current.user): flash( _(u"You don't have permission to cancel recipeset id %s" % id)) redirect("/jobs/%s" % recipeset.job.id) return dict( title='Cancel RecipeSet %s' % id, form=self.cancel_form, action='./really_cancel', options={}, value=dict(id=recipeset.id, confirm='really cancel recipeset %s?' % id), ) @identity.require(identity.not_anonymous()) @expose() def really_cancel(self, id, msg=None): """ Confirm cancel recipeset """ try: recipeset = RecipeSet.by_id(id) except InvalidRequestError: flash(_(u"Invalid recipeset id %s" % id)) redirect("/jobs/%s" % recipeset.job.id) if not recipeset.can_cancel(identity.current.user): flash( _(u"You don't have permission to cancel recipeset id %s" % id)) redirect("/jobs/%s" % recipeset.job.id) recipeset.cancel(msg) recipeset.record_activity(user=identity.current.user, service=u'WEBUI', field=u'Status', action=u'Cancelled', old='', new='') flash(_(u"Successfully cancelled recipeset %s" % id)) redirect("/jobs/%s" % recipeset.job.id) @cherrypy.expose @identity.require(identity.not_anonymous()) def stop(self, recipeset_id, stop_type, msg=None): """ Set recipeset status to Completed """ try: recipeset = RecipeSet.by_id(recipeset_id) except InvalidRequestError: raise BX(_('Invalid recipeset ID: %s' % recipeset_id)) if stop_type not in recipeset.stop_types: raise BX( _('Invalid stop_type: %s, must be one of %s' % (stop_type, recipeset.stop_types))) kwargs = dict(msg=msg) return getattr(recipeset, stop_type)(**kwargs)
def default(self, menu=None, action=None): # is this a valid menu name? m = None try: m = self.app.menus[menu] except: m = self.app.currentMenu() if m == None: m = self.app.currentMenu() if action != None: try: if action == 'm': self.app.processTransition(m, 'm', self.app.webModeHandler) else: idx = int(action) self.app.processTransition(m, str(idx), self.app.webModeHandler) except: print formatExceptionInfo() # After transition, set up new page cmenu = self.app.currentMenu() menuname = cmenu.title tupleList = [("", "")] wlist = [] mitems = cmenu.menuitems for i in range(0, len(mitems)): tupleList.append( ('/menus/' + self.app.currentmenu + '?action=' + str(i + 1), mitems[i][0])) jump = widgets.JumpMenu("Options", options=tupleList) wlist.append(jump.js) wlist.append(jump) hc = self.app.hardcopyReady sr = self.app.shellResult if hc != None: self.app.hardcopyReady = None try: f = open(self.app.hardcopies[hc], 'r') txt = f.read() f.close() wlist.append( widgets.TextArea(default=txt, rows=24, cols=80, attrs={'READONLY': 'true'})) except: wlist.append( widgets.TextArea(default='No screen available.', rows=24, cols=80, attrs={'READONLY': 'true'})) if sr != None: self.app.shellResult = None wlist.append( widgets.TextArea(default=sr, rows=24, cols=80, attrs={'READONLY': 'true'})) return dict(title=cmenu.title, wlist=wlist)
class Configuration(AdminPage): exposed = False id = widgets.HiddenField(name='id') value_str = widgets.TextArea(name='value', label=_(u'Value')) value_int = widgets.TextField(name='value', label=_(u'Value'), validator=validators.Int()) valid_from = widgets.TextField( name='valid_from', label=_(u'Effective from date'), help_text= u"Enter date and time (YYYY-MM-DD HH:MM) in the future or leave blank for setting to take immediate effect" ) string_form = HorizontalForm( 'configitem', fields=[id, value_str, valid_from], action='save_data', submit_text=_(u'Save'), ) int_form = HorizontalForm( 'configitem', fields=[id, value_int, valid_from], action='save_data', submit_text=_(u'Save'), ) value_grid = BeakerDataGrid(fields=[ ('Value', lambda x: x.value), ('Effective from', lambda x: x.valid_from, {'datetime': True}), ('Set by', lambda x: x.user), ('Date set', lambda x: x.modified, {'datetime': True}), ('', lambda x: x.valid_from <= datetime.utcnow() and " " or \ make_link(url = 'delete?item=%s&id=%s' % (x.config_item.id, x.id), text = 'Delete')), ]) def __init__(self, *args, **kw): kw['search_url'] = url("/configuration/by_name?anywhere=1"), kw['search_name'] = 'name' super(Configuration, self).__init__(*args, **kw) self.search_col = ConfigItem.name self.search_mapper = ConfigItem @identity.require(identity.in_group("admin")) @expose(template='bkr.server.templates.config_edit') def edit(self, **kw): if kw.get('id'): item = ConfigItem.by_id(kw['id']) form_values = dict(id=item.id, numeric=item.numeric, value=item.current_value()) else: flash(_(u"Error: No item ID specified")) raise redirect(".") # Show all future values, and the previous five config_values = item.values().filter(item.value_class.valid_from > datetime.utcnow()).order_by(item.value_class.valid_from.desc()).all() \ + item.values().filter(item.value_class.valid_from <= datetime.utcnow()).order_by(item.value_class.valid_from.desc())[:5] if item.readonly: form = None elif item.numeric: form = self.int_form else: form = self.string_form return dict( title=item.name, subtitle=item.description, form=form, action='./save', options={}, value=form_values, list=config_values, grid=self.value_grid, warn_msg=item.readonly and "This item is read-only", ) @expose() @error_handler(edit) @identity.require(identity.in_group("admin")) def save(self, **kw): if 'id' in kw and kw['id']: item = ConfigItem.by_id(kw['id']) else: flash(_(u"Error: No item ID")) raise redirect(".") if kw['valid_from']: try: valid_from = datetime.strptime(kw['valid_from'], '%Y-%m-%d %H:%M') except ValueError: flash( _(u"Invalid date and time specification, use: YYYY-MM-DD HH:MM" )) raise redirect("/configuration/edit?id=%d" % item.id) else: valid_from = None try: item.set(kw['value'], valid_from, identity.current.user) except Exception, msg: flash(_(u"Failed to save setting: %s" % msg)) raise redirect("/configuration/edit?id=%d" % item.id) flash(_(u"%s saved" % item.name)) redirect(".")
class MyFields(widgets.WidgetsList): age = widgets.TextField(validator=validators.Int()) email = widgets.TextArea(validator=validators.Email())
class MyFields(widgets.WidgetsList): name = widgets.TextField(validator=validators.String()) comment = widgets.TextArea(validator=validators.String(not_empty=True))
class MyFields(widgets.WidgetsList): name = widgets.TextField() age = widgets.TextArea()