def getValidator(self, request): return { self.name: formencode.ForEach( BaseSchema(id=formencode.validators.String(if_missing=None)), not_empty=self.attrs.required) }
class ConfigForm(formencode.Schema): allow_extra_fields = True filter_extra_fields = True #pre_validators = [formencode.NestedVariables()] action = formencode.validators.String(not_empty=False, if_missing=None) cancel = formencode.validators.String(not_empty=False, if_missing=None) firsttime = formencode.validators.Int(not_empty=False, if_missing=0) server = formencode.validators.String( strip=True, not_empty=True, messages={'empty': 'please enter a server host name'}) port = formencode.validators.Int( strip=True, not_empty=True, messages={ 'empty': 'please enter a port, MPD default is 6600', 'integer': 'please enter an integer value for port, MPD default is 6600' }) password = formencode.validators.String(not_empty=False, if_missing=None) webpassword = formencode.validators.String(not_empty=False, if_missing=None) timeout = formencode.validators.Bool() default_search = formencode.validators.String(not_empty=True) awskey = formencode.validators.String(strip=True, not_empty=False, if_missing=None) aws_secret = formencode.validators.String(strip=True, not_empty=False, if_missing=None) outputs = formencode.ForEach(OutputSchema(), if_missing=[])
class UserAgentSchema(formencode.Schema): input_type = formencode.ForEach(formencode.validators.OneOf( ['mouse', 'touch', 'keyboard']), convert_to_list=True) screen_size = formencode.validators.UnicodeString(if_missing=None, if_empty=None)
def process_args(self): # noqa had_strict_arg_failure = False for argname, processor, required, takes_list, list_item_invalidates, \ strict, show_msg, custom_msg, pass_as in self._processors: is_invalid = False pass_as = pass_as or argname argval = self.calling_args.get(argname, None) try: if isinstance(argval, list): if takes_list is False: raise formencode.Invalid('multiple values not allowed', argval, None) if takes_list is None: self.calling_args[pass_as] = argval = argval[0] elif takes_list: self.calling_args[pass_as] = argval = tolist(argval) if pass_as != argname: # catches a couple cases where a replacement doesn't # already happen above self.calling_args[pass_as] = argval # delete the old value if it exists if argname in self.calling_args: del self.calling_args[argname] if processor: if takes_list: processor = formencode.ForEach(processor) try: if required: processor = formencode.All(formencode.validators.NotEmpty, processor) processed_val = processor.to_python(argval) except formencode.Invalid as e: """ do a second round of processing for list values """ if not takes_list or not e.error_list or list_item_invalidates: raise """ only remove the bad values, keep the good ones """ new_list = [] for index, error in enumerate(e.error_list): if error is None: new_list.append(argval[index]) # revalidate for conversion and required processed_val = processor.to_python(new_list) self.calling_args[pass_as] = processed_val except formencode.Invalid as e: is_invalid = True if self.strict_args or strict: had_strict_arg_failure = True self.invalid_arg_keys.append(argname) if show_msg: invalid_msg = '%s: %s' % (argname, custom_msg or str(e)) user.add_message('error', invalid_msg) try: if is_invalid or self.calling_args[pass_as] is None or \ self.calling_args[pass_as] == '': del self.calling_args[pass_as] except KeyError: pass if len(self.invalid_arg_keys) > 0: log.debug('%s had bad args: %s', self.__class__.__name__, self.invalid_arg_keys) if had_strict_arg_failure: raise BadRequest('strict arg failure w/ invalid keys: %s' % self.invalid_arg_keys)
class JournalEntrySchema(formencode.Schema): allow_extra_fields = True text = formencode.validators.UnicodeString(not_empty=True) indicators = formencode.ForEach(formencode.validators.String()) image = ImageUploadConverter(if_missing=None) image_action = formencode.validators.OneOf( (u'nochange', u'delete', u'replace'), hideList=True, if_missing=u'nochange')
class Test_and_Spec(formencode.Schema): reference = validators.UnicodeString(not_empty=True, strip=True, encoding='utf-8') name = validators.UnicodeString(encoding='utf-8') test_group = compound.Any(validators.OneOf(["none","new"]), TestGroupId()) new_group = validators.UnicodeString(encoding='utf-8') description = validators.UnicodeString(encoding='utf-8') expected_result = validators.UnicodeString(encoding='utf-8') code = validators.UnicodeString(encoding='utf-8') comment = validators.UnicodeString(encoding='utf-8') dependencies = formencode.ForEach(TestSpecId())
def getValidator(self, request): validators = {} for v in self.fields: if v.is_validated: validators.update(v.getValidator(request)) return { self.name: formencode.ForEach(BaseSchema(**validators), not_empty=self.attrs.required) }
class TemplateForm(formencode.Schema): """ Formencode Form validators for Email Template add/edit """ allow_extra_fields = True filter_exter_fields = True pre_validators = [formencode.variabledecode.NestedVariables()] _id = formencode.validators.String(not_empty=True, if_missing=None) name = formencode.validators.String(not_empty=True) class contents(formencode.Schema): lang = formencode.validators.String(not_empty=False) subject = formencode.validators.String(not_empty=False) body = formencode.validators.String(not_empty=False) contents = formencode.ForEach(contents)
class ActionSchema(CSRFSchema): """The :class:`~wte.views.user_role.ActionSchema` handles the validation of a actions applied in :func:`~wte.views.user_role.action` and :func:`~wte.views.user_role.update`. """ action = formencode.All(formencode.validators.UnicodeString(not_empty=True), formencode.validators.OneOf(['block', 'remove', 'change_role'])) """The action to apply""" role_id = formencode.ForEach(formencode.validators.Int(not_empty=True), convert_to_list=True, if_missing=formencode.api.NoDefault, not_empty=True) """The list of :class:`~wte.models.UserPartRole` to apply the action to""" allow_extra_fields = True
def getValidator(self, request): validators = {} pre_validators = [] chained_validators = [] for v in self.fields: if v and v.is_validated: val = v.getValidator(request) if isinstance(val, formencode.Schema): pre_validators += val.pre_validators chained_validators += val.chained_validators val = val.fields validators = dict_merge(validators, val) return {self.name : formencode.ForEach(BaseSchema(pre_validators=pre_validators, chained_validators=chained_validators, **validators), not_empty = self.attrs.required, convert_to_list = True, if_empty = None)}
class AddUserSchema(CSRFSchema): """The :class:`~wte.views.user_role.AddUserSchema` handles the validation of a adding a :class:`~wte.models.User` to a :class:`~wte.models.Part`.. """ user_id = formencode.ForEach(formencode.validators.Int(not_empty=True), convert_to_list=True) """The id of the :class:`~wte.models.User` to add""" role = formencode.All(formencode.validators.UnicodeString(not_empty=True), formencode.validators.OneOf(['owner', 'tutor', 'student'])) """The new role for the :class:`~wte.models.User`""" q = formencode.validators.UnicodeString(not_empty=False) """Save the query in case there are validation errors""" start = formencode.validators.Int(not_empty=False, if_missing=0) """Save the pagination in case there are validation errors"""
class GeneratorForm( formencode.Schema ): use_builtin_gettext = False allow_extra_fields = True filter_extra_fields = True ###todo: end=.cif/.pdb; data_cif = FileUploadValidator( not_empty=False, use_builtin_gettext=False ) data_pdb = FileUploadValidator( not_empty=False, use_builtin_gettext=False ) data_idpdb = validators.String( not_empty=False, min=4, max=4) ###todo:alle drei sind noch auszuwaehlen --> idpdb wird gestartet # a = validators.RequireIfMissing(required='data_idpdb', missing='data_pdb') or validators.RequireIfMissing(required='data_idpdb', missing='data_cif') # f = (validators.RequireIfPresent(required='data_cif', present='data_pdb') or validators.RequireIfMissing(required='data_cif', missing='data_idpdb') or validators.RequireIfMissing(required='data_pdb', missing='data_idpdb') or validators.RequireIfMissing(required='data_cif', missing='data_idpdb')) omit = validators.String( if_empty='False', if_missing='False' ) sfcheck = validators.String( if_empty='False', if_missing='False' ) mapext = validators.String() topic = validators.String() subtopics = formencode.ForEach(validators.String())
class ChangeRoleSchema(CSRFSchema): """The :class:`~wte.views.user_role.ChangeRoleSchema` handles the validation of a "change_role" action applied in :func:`~wte.views.user_role.update`. """ action = formencode.All(formencode.validators.UnicodeString(not_empty=True), formencode.validators.OneOf(['change_role'])) """The action to apply""" role_id = formencode.ForEach(formencode.validators.Int(not_empty=True), convert_to_list=True, if_missing=formencode.api.NoDefault, not_empty=True) """The list of :class:`~wte.models.UserPartRole` to apply the action to""" role = formencode.All(formencode.validators.UnicodeString(not_empty=True), formencode.validators.OneOf(['owner', 'tutor', 'student'])) """The new role""" q = formencode.validators.UnicodeString(if_empty=None, if_missing=None) """Optional query parameter for the redirect""" start = formencode.validators.UnicodeString(if_empty=None, if_missing=None) """Optional start parameter for the redirect"""
class HelloForm(formencode.Schema): hello = formencode.ForEach(formencode.validators.Int())
class ConceptAnswersSchema(formencode.Schema): concept = formencode.validators.Int() concept_answer = formencode.ForEach(formencode.validators.Int()) allow_extra_fields = True
class Campaign(formencode.Schema): reference = validators.UnicodeString(not_empty=True, strip=True, encoding='utf-8') name = validators.UnicodeString(not_empty=True, encoding='utf-8') description = validators.UnicodeString(encoding='utf-8') test_mean = TestMeanId() test_plans = formencode.ForEach(TestPlanId())
class Objective_Tests(formencode.Schema): tcodes = formencode.ForEach(TestId())
class FormConceptSchema(Schema): form = formencode.validators.Int() concepts = formencode.ForEach(formencode.validators.Int()) allow_extra_fields = True
def getValidator(self, request): return deep_dict(self.name, formencode.ForEach(name = formencode.validators.String(required=True)))
class ObjectiveSchema(formencode.Schema): allow_extra_fields = True title = formencode.validators.UnicodeString(not_empty=True, max=255) description = formencode.validators.UnicodeString(not_empty=True) competences = formencode.ForEach(formencode.validators.String())
def getValidator(self, request): validators = {} return {self.name : formencode.ForEach(BaseSchema(type = formencode.validators.String(), file = formencode.validators.String(), name=formencode.validators.String()), not_empty = self.attrs.required)}
def export_settings(request): dbsession = DBSession() experiment = dbsession.query(Experiment).filter( Experiment.id == request.matchdict['eid']).first() if experiment: if request.method == 'POST': try: schema = ExportSchema() questions = [ str(q.id) for p in experiment.pages for q in p.questions if q['frontend', 'generates_response'] ] schema.add_field( 'question', formencode.ForEach( formencode.validators.OneOf(questions, not_empty=True))) for data_set in experiment.data_sets: schema.add_field( 'data_set_identifier_%s' % data_set.id, formencode.validators.OneOf( ['_id'] + [str(c) for c in data_set['columns']])) params = schema.to_python(request.params, State(request=request)) def data_item_column_mapper(data_item): if params['data_set_identifier_%s' % data_item.dataset_id] == '_id': return data_item.id else: return data_item['values'][params[ 'data_set_identifier_%s' % data_item.dataset_id]] columns = set(['_participant']) if params['include_incomplete']: query = dbsession.query(Participant).filter( and_(Participant.experiment_id == experiment.id)) columns.add('_completed') else: query = dbsession.query(Participant).filter( and_(Participant.experiment_id == experiment.id, Participant.completed == True)) # noqa: 712 if params['include_useragent']: columns.add('_user_agent.screen_size') columns.add('_user_agent.string') for participant in query: if params['include_useragent']: if 'user_agent' in participant: if 'input_types' in participant['user_agent']: columns.update([ '_user_agent.input_type.%s' % input_type for input_type in participant['user_agent'] ['input_types'] ]) for answer in participant.answers: if str(answer.question.id) not in params['question']: continue if 'response' not in answer or answer[ 'response'] is None: continue column = '%s.%s' % (answer.question.page.name, answer.question['name']) new_columns = [] if answer.question[ 'frontend', 'display_as'] == 'select_simple_choice': if answer.question['frontend', 'allow_other']: if answer.question['frontend', 'allow_multiple']: if isinstance( answer['response']['response'], list): new_columns = [ '%s.%s' % (column, a) for a in answer['response']['response'] ] else: new_columns = [ '%s.%s' % (column, answer['response']['response']) ] new_columns.append('%s.other_response' % (column)) else: new_columns = [ column, '%s.other_response' % column ] else: if answer.question['frontend', 'allow_multiple']: if isinstance(answer['response'], list): new_columns = [ '%s.%s' % (column, a) for a in answer['response'] ] else: new_columns = [ '%s.%s' % (column, answer['response']) ] else: new_columns = [column] if answer.question['frontend', 'randomise_answers']: new_columns.append('%s.answer_order' % column) elif answer.question[ 'frontend', 'display_as'] == 'select_grid_choice': for key, value in answer['response'].items(): sub_column = '%s.%s' % (column, key) if answer.question['frontend', 'allow_multiple']: if isinstance(value, list): sub_column = [ '%s.%s' % (sub_column, a) for a in value ] else: sub_column = [ '%s.%s' % (sub_column, value) ] else: sub_column = [sub_column] new_columns.extend(sub_column) if answer.question['frontend', 'randomise_answers']: new_columns.append('%s.answer_order' % column) if answer.question['frontend', 'randomise_questions']: new_columns.append('%s.question_order' % column) elif answer.question['frontend', 'display_as'] == 'ranking': new_columns.extend([ '%s.%s' % (column, a['value']) for a in answer.question['frontend', 'answers'] ]) if answer.question['frontend', 'randomise_answers']: new_columns.append('%s.answer_order' % column) else: if answer.question['frontend', 'allow_multiple']: if isinstance(answer['response'], list): new_columns = [ '%s.%s' % (column, a) for a in answer['response'] ] else: new_columns = [ '%s.%s' % (column, answer['response']) ] else: new_columns = [column] if answer.question.page.dataset_id is not None: new_columns = [ '%s.%s' % (c, data_item_column_mapper(di)) for c in new_columns for di in answer.question.page.data_set.items ] columns.update(new_columns) columns = list(columns) columns.sort(key=lambda k: k.split('.')) io = StringIO() writer = DictWriter(io, fieldnames=columns, restval=params['na_value'], extrasaction='ignore') writer.writeheader() for participant in query.order_by(Participant.id): responses = {'_participant': participant.id} if params['include_incomplete']: responses['_completed'] = participant.completed if params['include_useragent']: if 'user_agent' in participant: if 'input_types' in participant['user_agent']: for column in columns: if column.startswith( '_user_agent.input_type.'): responses[column] = 0 for input_type in participant['user_agent'][ 'input_types']: responses['_user_agent.input_type.%s' % input_type] = 1 if 'screen_size' in participant['user_agent']: responses[ '_user_agent.screen_size'] = participant[ 'user_agent']['screen_size'] if 'user_agent' in participant['user_agent']: responses['_user_agent.string'] = participant[ 'user_agent']['user_agent'] for answer in participant.answers: if 'response' not in answer or answer[ 'response'] is None: continue column = '%s.%s' % (answer.question.page.name, answer.question['name']) if answer.question[ 'frontend', 'display_as'] == 'select_simple_choice': if answer.question['frontend', 'allow_other']: if answer.question['frontend', 'allow_multiple']: for c in columns: if c.startswith(column): responses[c] = 0 if isinstance( answer['response']['response'], list): for sub_answer in answer['response'][ 'response']: if answer.data_item_id is None: responses['%s.%s' % (column, sub_answer)] = 1 else: responses['%s.%s.%s' % ( column, sub_answer, data_item_column_mapper( answer.data_item))] = 1 else: if answer.data_item_id is None: responses['%s.%s' % (column, answer['response'] ['response'])] = 1 else: responses['%s.%s.%s' % ( column, answer['response']['response'], data_item_column_mapper( answer.data_item))] = 1 if answer['response']['other']: if answer.data_item_id is None: responses['%s.other_response' % column] = answer[ 'response']['other'] else: responses['%s.other_response.%s' % (column, data_item_column_mapper(answer.data_item))] = \ answer['response']['other'] else: if answer.data_item_id is None: if isinstance(answer['response'], dict): responses[column] = answer[ 'response']['response'] if answer['response']['other']: responses[ '%s.other_response' % column] = answer[ 'response']['other'] else: responses[column] = answer[ 'response'] else: responses['%s.%s' % (column, data_item_column_mapper(answer.data_item))] = \ answer['response']['response'] if answer['response']['other']: responses['%s.other_response.%s' % (column, data_item_column_mapper(answer.data_item))] = \ answer['response']['other'] else: if answer.question['frontend', 'allow_multiple']: for c in columns: if c.startswith(column): responses[c] = 0 if isinstance(answer['response'], list): for sub_answer in answer['response']: if answer.data_item_id is None: responses['%s.%s' % (column, sub_answer)] = 1 else: responses['%s.%s.%s' % ( column, sub_answer, data_item_column_mapper( answer.data_item))] = 1 else: if answer.data_item_id is None: responses['%s.%s' % (column, answer['response'])] = 1 else: responses[ '%s.%s.%s' % (column, answer['response'], data_item_column_mapper( answer.data_item))] = 1 else: if answer.data_item_id is None: responses[column] = answer['response'] else: responses['%s.%s' % (column, data_item_column_mapper(answer.data_item))] = \ answer['response'] if answer.question['frontend', 'randomise_answers']: responses['%s.answer_order' % column] = answer['answer_order'] elif answer.question[ 'frontend', 'display_as'] == 'select_grid_choice': for key, value in answer['response'].items(): sub_column = '%s.%s' % (column, key) if answer.question['frontend', 'allow_multiple']: for c in columns: if c.startswith(sub_column): responses[c] = 0 if isinstance(value, list): for sub_answer in value: if answer.data_item_id is None: responses['%s.%s' % (sub_column, sub_answer)] = 1 else: responses['%s.%s.%s' % ( sub_column, sub_answer, data_item_column_mapper( answer.data_item))] = 1 else: if answer.data_item_id is None: responses['%s.%s' % (sub_column, value)] = 1 else: responses[ '%s.%s.%s' % (sub_column, value, data_item_column_mapper( answer.data_item))] = 1 else: if answer.data_item_id is None: responses[sub_column] = value else: responses[ '%s.%s' % (sub_column, data_item_column_mapper( answer.data_item))] = value if answer.question['frontend', 'randomise_answers']: responses['%s.answer_order' % column] = answer['answer_order'] if answer.question['frontend', 'randomise_questions']: responses['%s.question_order' % column] = answer['question_order'] elif answer.question['frontend', 'display_as'] == 'ranking': for idx, sub_answer in enumerate( answer['response']): if answer.data_item_id is None: responses['%s.%s' % (column, sub_answer)] = idx else: responses['%s.%s.%s' % (column, sub_answer, data_item_column_mapper( answer.data_item))] = idx if answer.question['frontend', 'randomise_answers']: responses['%s.answer_order' % column] = answer['answer_order'] else: if answer.question['frontend', 'allow_multiple']: for c in columns: if c.startswith(column): responses[c] = 0 if isinstance(answer['response'], list): for sub_answer in answer['response']: if answer.data_item_id is None: responses['%s.%s' % (column, sub_answer)] = 1 else: responses[ '%s.%s.%s' % (column, sub_answer, data_item_column_mapper( answer.data_item))] = 1 else: if answer.data_item_id is None: responses['%s.%s' % (column, answer['response'])] = 1 else: responses['%s.%s.%s' % (column, answer['response'], data_item_column_mapper( answer.data_item))] = 1 else: if answer.data_item_id is None: responses[column] = answer['response'] else: responses['%s.%s' % (column, data_item_column_mapper(answer.data_item))] = \ answer['response'] writer.writerow(responses) return Response(body=io.getvalue().encode('utf8'), headers=[('Content-Type', 'text/csv'), ('Content-Disposition', 'attachment; filename="%s.csv"' % experiment.title)]) except formencode.Invalid as e: return { 'experiment': experiment, 'values': request.params, 'errors': e.error_dict, 'crumbs': [{ 'title': 'Experiments', 'url': request.route_url('dashboard') }, { 'title': experiment.title, 'url': request.route_url('experiment.view', eid=experiment.id) }, { 'title': 'Results', 'url': request.route_url('experiment.results', eid=experiment.id) }, { 'title': 'Export', 'url': request.route_url('experiment.results.export', eid=experiment.id) }] } return { 'experiment': experiment, 'crumbs': [{ 'title': 'Experiments', 'url': request.route_url('dashboard') }, { 'title': experiment.title, 'url': request.route_url('experiment.view', eid=experiment.id) }, { 'title': 'Results', 'url': request.route_url('experiment.results', eid=experiment.id) }, { 'title': 'Export', 'url': request.route_url('experiment.results.export', eid=experiment.id) }] } else: raise HTTPNotFound()
def getValidator(self, request): return { self.name: formencode.ForEach(name=formencode.validators.String( required=True)) }