def validate_python(self, value, state): super(SubjectCodeDoesntExist, self).validate_python(value, state) session_id = value['id'] subject_id = int(value['subject']['id']) subject_code = value['subject']['code'] session = Session.query.filter_by(id=session_id).first() if not session: raise twc.ValidationError('parseerr', self) subject = Subject.query.filter_by(code=subject_code).filter_by( experiment=session.experiment).first() if subject and subject.id != subject_id: raise twc.ValidationError('exists', self)
def _validate_python(self, value, outer_call=None): if isinstance(value, cgi.FieldStorage): if self.required and not getattr(value, 'filename', None): raise twc.ValidationError('required', self) if (self.extension is not None and not value.filename.endswith(self.extension)): raise twc.ValidationError('badext', self) elif value: raise twc.ValidationError('corrupt', self) elif self.required: raise twc.ValidationError('required', self)
def _validate(self, value, state=None): self._validated = True value = value or {} if not isinstance(value, dict): raise vd.ValidationError('corrupt', self.validator) self.value = value any_errors = False data = {} show = set() for c in self.children: if c.id in self.hiding_ctrls and c.id not in show: data[c.id] = None else: try: if c._sub_compound: data.update(c._validate(value, data)) else: data[c.id] = c._validate(value.get(c.id), data) if isinstance(c, HidingComponentMixin): show.update(c.mapping.get(data[c.id], [])) except twc.ValidationError: data[c.id] = twc.Invalid any_errors = True if self.validator: data = self.validator.to_python(data, state) self.validator.validate_python(data, state) if any_errors: raise twc.ValidationError('childerror', self.validator) return data
def from_python(self, value, state=None): if not value: return value if not isinstance(value, self.entity): raise twc.ValidationError( 'from_python not passed instance of self.entity but ' + 'instead "%s" of type "%s".' % (str(value), str(type(value)))) return value and unicode( sa.orm.object_mapper(value).primary_key_from_instance(value)[0])
def validate_python(self, value, state): super(ExperimentDoesntExist, self).validate_python(value, state) if state[self.owner] == twc.validation.Invalid: state[self.owner] = None experiment_exists = (Experiment.query.join(ResearchGroup).filter( Experiment.name == value).filter( ResearchGroup.gid == state[self.owner]).first()) if experiment_exists: raise twc.ValidationError('exists', self)
def _validate_python(self, value, state=None): if value in self.allowed_values: return value try: self.entity.query.filter_by(**{self.key: value}).one() except NoResultFound: return value else: raise twc.ValidationError('notunique', self)
def _validate_python(self, data, state=None): controller = request.controller_state.controller submission = controller.submission language = data['language'] if language not in controller.assignment.allowed_languages: raise twc.ValidationError( 'The language %s is not allowed for this assignment' % (language)) source, filename = u'', u'' try: source = data['source'] filename = (data['filename'] or 'submission_%d.%s' % (submission.id, language.extension_src)) except KeyError: pass try: source = data['source_file'].value try: source = unicode(source, encoding='utf-8') except UnicodeDecodeError as e: log.info('Encoding errors in submission %d: %s', submission.id, e) try: det = detect(source) source = unicode(source, encoding=det['encoding']) if det['confidence'] < 0.66: flash( 'Your submission source code was automatically determined to be ' 'of encoding %s. Please check for wrongly converted characters!' % det['encoding'], 'info') except ( UnicodeDecodeError, TypeError ) as e: # TypeError occurs when det['encoding'] is None log.info( 'Encoding errors in submission %d with detected encoding %s: %s', submission.id, det['encoding'], e) source = unicode(source, errors='ignore') flash( 'Your submission source code failed to convert to proper Unicode. ' 'Please verify your source code for replaced or missing characters. ' '(You should not be using umlauts in source code anyway...) ' 'And even more should you not be submitting anything else but ' 'source code text files here!', 'warning') filename = data['source_file'].filename except (KeyError, AttributeError): pass # data['source_file'] = None del data['source_file'] data['source'] = source data['filename'] = filename return data
def to_python(self, value, state=None): if not value: if self.required: raise twc.ValidationError('required', self) return None # How could this happen (that we are already to_python'd)? if isinstance(value, self.entity): return value if isinstance(self.primary_key.type, sa.types.Integer): try: value = int(value) except ValueError: raise twc.ValidationError('norel', self) value = self.entity.query.filter( getattr(self.entity, self.primary_key.name) == value).first() if not value: raise twc.ValidationError('norel', self) return value
def to_python(self, value, state=None): """We just validate, there is at least one value """ def has_value(dic): """Returns bool Returns True if there is at least one value defined in the given dic """ for v in dic.values(): if type(v) == dict: if has_value(v): return True if v: return True return False if self.required: if not has_value(value): raise twc.ValidationError('required', self) elif self.required_children: if not has_value(value): # No problem, no value posted. # We return None to make sure we will delete the onetoone field # or not create it return None error_dict = {} for c in self.required_children: v = value.get(c.key) if v is twc.Invalid: continue if not v: error_dict[c.key] = self.msgs['required'] if error_dict: e = twc.ValidationError('required', self) e.error_dict = error_dict raise e return value
def _save_file(self, filename, value): if not self.png_dir: raise twc.ValidationError("Image saving is misconfigured.") filename = os.path.sep.join([self.png_dir, filename]) log.info("Writing image to %s" % filename) with open(filename, 'wb') as f: f.write(value) scale_to_standard_size(filename) return True
def validate_python(self, value, state): if self.other_field in state: if value != state[self.other_field]: raise twc.ValidationError('mismatch_param', self)
def test_ve_subst(self): try: vld = twc.IntValidator(max=10) raise twc.ValidationError('toobig', vld) except twc.ValidationError, e: assert (str(e) == 'Cannot be more than 10')
def test_ve_rewrite(self): try: raise twc.ValidationError('required') except twc.ValidationError, e: assert (str(e) == 'Enter a value')
def test_ve_string(self): try: raise twc.ValidationError('this is a test') except twc.ValidationError, e: assert (str(e) == 'this is a test')
def to_python(self, value, state=None): value = value or [] if not isinstance(value, list): raise twc.ValidationError('corrupt', self) return [v for v in value if self.any_content(v)]
def validate_python(self, value, state=None): super(UserExists, self).validate_python(value, state) matches = User.query.filter_by(uid=value).all() if len(matches) == 0: raise twc.ValidationError('doesntexist', self)
def to_python(self, value, state=None): value = [twc.safe_validate(self.item_validator, v) for v in value] value = [v for v in value if v is not twc.Invalid] if not value and self.required: raise twc.ValidationError('required', self) return value