def _to_python(self, value, state=None): project_name_re = re.compile(r'^[a-z0-9][a-z0-9-]{,61}$') if project_name_re.match(value): # just a name project_name = value else: # try as a URL project_name = None project_name_simple = None url = urlparse(value.strip()) if url.netloc.endswith('.googlecode.com'): project_name = url.netloc.split('.')[0] elif url.netloc == 'code.google.com': path_parts = url.path.lstrip('/').split('/') if len(path_parts) >= 2 and path_parts[0] == 'p': project_name = path_parts[1] elif len(path_parts) >= 4 and path_parts[ 0] == 'a' and path_parts[2] == 'p': project_name_simple = path_parts[3] project_name = '/'.join(path_parts[0:4]) if not project_name_simple: project_name_simple = project_name if not project_name or not project_name_re.match( project_name_simple): raise fev.Invalid(self.message('invalid', state), value, state) if not GoogleCodeProjectExtractor(project_name).check_readable(): raise fev.Invalid(self.message('unavailable', state), value, state) return project_name
def _to_python(self, value_dict, state): if value_dict: return value_dict sl = syslanguage active_cultures = sl.active_record_cultures( ) if self.record_cultures else sl.active_cultures() errors = {} for fieldname, validator in self.targetvalidator.fields.iteritems(): if not validator.not_empty: continue for culture in active_cultures: culture = culture.replace('-', '_') errors[culture + '.' + fieldname] = validators.Invalid( self.message('empty', state), value_dict, state) if errors: raise validators.Invalid(schema.format_compound_error(errors), value_dict, state, error_dict=errors) return value_dict
def validate_python(self, value, state): if isinstance(value, Exception): raise validators.Invalid(self.message("invalid", state), value, state) super(ThumbnailImage, self).validate_python(value, state) if value and not valid_md5_digest.match(value): raise validators.Invalid(self.message("invalid_digest", state), value, state)
def validate_python(self, field_dict, state): errors = {} for name in self._convert_to_list(self.field_names): if not field_dict.get(name): errors[name] = validators.Invalid(self.message('empty', state), field_dict, state) if errors: raise validators.Invalid(schema.format_compound_error(errors), field_dict, state, error_dict=errors) return field_dict
def model(self, id): model = self._raw['models'][id] if 'id' not in model: raise fev.Invalid('No id field for model {}'.format(id), model, None) if model['id'] != id: raise fev.Invalid('id mismatch: {} != {}'.format(id, model['id']), model, None) model.setdefault('type', 'object') model.setdefault('additionalProperties', False) return model
def _to_python(self, value, state=None): user_name = state.full_dict.get('user_name', '') user_name = state.full_dict.get('gh_user_name', user_name).strip() project_name = value.strip() full_project_name = '%s/%s' % (user_name, project_name) if not re.match(r'^[a-zA-Z0-9-_.]+$', project_name): raise fev.Invalid(self.message('invalid', state), value, state) if not GitHubProjectExtractor(full_project_name, user=c.user).check_readable(): raise fev.Invalid(self.message('unavailable', state), value, state) return project_name
def _to_python(self, value, state): # we don't support multiple values, so we run a quick check here (we got a webapp where this was a problem) if type(value) != type(u""): raise fv.Invalid('You must supply a valid email.', value, state) user = Session.query(users.User).filter( sa.func.lower(users.User.email) == value.lower()).first() # if this user is the same as the logged in one then don't throw the error - allows keeping old email address when editing contact info if user and user != self.user: raise fv.Invalid( 'That user already exists. Please choose another.', value, state) return value
def _to_python(self, value, state): if type(value) != type(u""): raise fv.Invalid('You must supply a valid subdomain.', value, state) subd = Session.query(users.Organization).filter( sa.func.lower(users.Organization.subdomain) == value.lower()).first() if subd: raise fv.Invalid('%s is already taken' % value, value, state) return value.lower()
def _to_python(self, value, state): try: hours, colon, minutes = value.partition(":") hours = int(hours) minutes = int(minutes) if minutes > 60 or minutes < 0: raise validators.Invalid( "Duration minutes should be in [0,60]", value, state) except ValueError: raise validators.Invalid("Duration format should be HH:MM", value, state) else: fraction = Decimal(minutes) / 60 return hours + fraction
def _to_python(self, value, state): try: return datetime.datetime.strptime(value, self.format).date() except ValueError as e: raise validators.Invalid( "%s does not match format %s" % (value, self.format), value, state)
def validate_python(self, value, state): super(UniqueEmail, self).validate_python(value, state) from .model import get_existing_email existing = get_existing_email(value) if existing and existing.is_confirmed: msg = self.message("taken", state) raise validators.Invalid(msg, value, state)
def to_python(self, value, state): result = M.Forum.query.get( shortname=value, app_config_id=c.app.config._id) if not result: raise fev.Invalid('Illegal forum shortname: %s' % value, value, state) return result
def _to_python(self, value_dict, state): val = value_dict.get("Parent") code = value_dict.get("Code") errors = {} if not val and code and len(str(code)) != NAICS_SECTOR: errors["Parent"] = validators.Invalid( self.message("notsector", state), value_dict, state ) raise validators.Invalid( schema.format_compound_error(errors), value_dict, state, error_dict=errors, ) return value_dict
def _to_python(self, value_dict, state): is_required = False if self.predicate(value_dict, state): is_required = True errors = {} if is_required: for name in self._convert_to_list(self.required): if not value_dict.get(name): errors[name] = validators.Invalid(self.message('empty', state), value_dict, state) if errors: raise validators.Invalid(schema.format_compound_error(errors), value_dict, state, error_dict=errors) return value_dict
def validate_python(self, value, state): super(RequestPath, self).validate_python(value, state) path = urlparse.urlparse(value).path if path == value and path.startswith('/'): pass else: raise validators.Invalid(self.message("invalid", state), value, state)
def from_python(self, value, state): if value is None: return None try: return cjson.encode(value) except Exception: raise validators.Invalid( "expected an encodable JSON object in the JSONCol '%s', got %s %r instead" % (self.name, type(value), value), value, state)
def _to_python(self, value, c): try: category = model.Category.by_slug(value).one() raise validators.Invalid( _('There is already a category with that name.'), value, c ) except NoResultFound: pass return validators.UnicodeString._to_python(self, value, c)
def _to_python(self, value, state): # we don't support multiple values, so we run a quick check here (we got a webapp where this was a problem) if not isinstance(value, unicode): raise fv.Invalid('You must supply a valid string.', value, state) project = Session.query(projects.Project ).filter(projects.Project.organization==self.organization ).filter(projects.Project.name==value ) if self.project: project = project.filter(projects.Project.id != self.project.id) project = project.first() if project: raise fv.Invalid('A project with this name already exists. Please choose another.', value, state) return value
def _to_python(self, value, state=None): url = urlparse(value.strip()) if url.netloc.endswith('.googlecode.com'): project_name = url.netloc.split('.')[0] else: project_name = os.path.basename(url.path.strip('/')) if not re.match(r'^[a-z0-9][a-z0-9-]{,61}$', project_name): raise fev.Invalid(self.message('invalid')) return project_name
def _to_python(self, value, state): # we don't support multiple values, so we run a quick check here (we got a webapp where this was a problem) if not isinstance(value, unicode): raise fv.Invalid('You must supply a valid string.', value, state) file = Session.query(projects.Entity).filter( projects.Entity.project == self.project).filter( projects.Entity.path == self.file.path).filter( projects.Entity.name == value) file = file.filter(projects.Entity.id != self.file.id) file = file.first() if file: raise fv.Invalid( 'A file with this name already exists. Please choose another.', value, state) return value
def _to_python(self, value, state): if not value: return u'' if isinstance(value, unicode): return value if not isinstance(value, unicode): if hasattr(value, '__unicode__'): value = unicode(value) return value else: value = str(value) try: return unicode(value, self.inputEncoding) except UnicodeDecodeError: raise validators.Invalid(self.message('badEncoding', state), value, state) except TypeError: raise validators.Invalid( self.message('badType', state, type=type(value), value=value), value, state)
def validate_python(self, value, state): super(UsernameAllowEmail, self).validate_python(value, state) email_validator = Email() is_valid_username = valid_username.match(value) if not is_valid_username: try: email = email_validator.to_python(value) return email except: msg = self.message("invalid", state) raise validators.Invalid(msg, value, state)
def to_python(self, value, state=None): value = super(ToolsValidator, self).to_python(value, state) valid = [] invalid = [] for name in value: importer = ToolImporter.by_name(name) if importer is not None and importer.source == self.source: valid.append(name) else: invalid.append(name) if invalid: pl = 's' if len(invalid) > 1 else '' raise fev.Invalid('Invalid tool%s selected: %s' % (pl, ', '.join(invalid)), value, state) return valid
def validate_python(self, field_dict, state): try: encrypted_password = field_dict[self.field_names[0]] except TypeError: # Generally because field_dict isn't a dict raise validators.Invalid(self.message('notDict', state), field_dict, state) except KeyError: encrypted_password = None if encrypted_password: errors = {} for name in self.field_names[1:]: raw_password = field_dict.get(name) # Values are validated both before and after conversion, so we check to # see if the raw values match or if the raw password can be verified against # encrypted one. ok = False if raw_password == encrypted_password: ok = True else: try: ok = pwd_context.verify(raw_password, encrypted_password) except ValueError: pass if not ok: errors[name] = self.message('invalidNoMatch', state) if errors: error_list = errors.items() error_list.sort() lines = [ '%s: %s' % (name, value) for name, value in error_list ] raise validators.Invalid('<br>\n'.join(lines), field_dict, state, error_dict=errors)
def _to_python(self, value, state=None): value = super(TracURLValidator, self)._to_python(value, state) # remove extraneous /wiki/[PageName] from the end of the URL url_parts = value.split('/') try: wiki_in_url = url_parts.index('wiki') except ValueError: wiki_in_url = -1 if wiki_in_url >= len(url_parts) - 2: value = '/'.join(url_parts[:wiki_in_url]) # normalize trailing slash value = value.rstrip('/') + '/' try: resp = requests.head(value, allow_redirects=True, timeout=10) except IOError: # fall through to 'raise' below pass else: if resp.status_code == 200: return value raise fev.Invalid(self.message('unavailable', state), value, state)
def _to_python(self, value, state): try: value = convert_date(value) except (ValueError, ), e: raise fv.Invalid(e.args[0], value, state)
def validate(self, value, state=None): tg.request.validation.intent = None raise validators.Invalid('Unknown Error', value, {'_the_form': 'Unknown Error'})
def validate(self, value, state=None): raise validators.Invalid('Unknown Error', value, {'_the_form': 'Unknown Error'})
def validate_python(self, value, state): raise validators.Invalid('ERROR: Description', value, state)
def validate_python(self, value, state): super(Username, self).validate_python(value, state) if not valid_username.match(value): raise validators.Invalid(self.message("invalid", state), value, state)