def to_python(self, value): if self.strict and value in accepted_resolutions: raise ValidationError() try: return str(value) except: ValidationError()
def to_python(self, value: str) -> str: if len(value) < 2: raise ValidationError('Entity ID must have ≥2 characters') if value[0] not in {'Q', 'P', 'L', 'M'}: raise ValidationError('Entity ID must start with Q, P, L, or M') if value[1] == '0': raise ValidationError('Entity ID must not be zero-padded') if value[0] == 'L': lexeme_id, _, subentity_id = value.partition('-') if len(lexeme_id) < 2: raise ValidationError('Lexeme ID must have ≥2 characters') lexeme_numeric_part = lexeme_id[1:] if not lexeme_numeric_part.isascii() \ and lexeme_numeric_part.isnumeric(): raise ValidationError('Lexeme ID must be (ASCII) numeric') if subentity_id: if len(subentity_id) < 2: raise ValidationError('Lexeme sub-entity ID must ' 'have ≥2 characters') if subentity_id[0] not in {'S', 'F'}: raise ValidationError('Lexeme sub-entity ID must ' 'start with S or F') if subentity_id[1] == '0': raise ValidationError('Lexeme sub-entity ID must ' 'not be zero-padded') subentity_numeric_part = subentity_id[1:] if not subentity_numeric_part.isascii() \ and subentity_numeric_part.isnumeric(): raise ValidationError('Lexeme sub-entity ID must ' 'be (ASCII) numeric') else: numeric_part = value[1:] if not numeric_part.isascii() and numeric_part.isnumeric(): raise ValidationError('Property ID must be (ASCII) numeric') return value
def register(): form = UserRegitrationForm() try: if form.validate_on_submit(): if Accounts.query.filter_by(email=form.email.data).first(): raise ValidationError("your email has already been registered") if Accounts.query.filter_by(username=form.username.data).first(): raise ValidationError( "The User Name has already been taken Please Choose another name" ) if len(form.password.data) < 8: raise ValidationError( "Password must be at least 8 characters long") if not re.search(r"[\d]+", form.password.data): raise ValidationError( "This password must contain at least 1 digit") if not re.search(r"[A-Z]+", form.password.data): print(form.password.data) raise ValidationError( "This password must contain at least 1 uppercase character" ) new_user = Accounts(username=form.username.data, email=form.email.data, password=form.password.data) db.session.add(new_user) db.session.commit() flash("Registered successfully ") return redirect(url_for("users.login")) return render_template("register.html", form=form) except Exception as e: return render_template("register.html", error=e, form=form)
def on_model_change(self, form, model: AdminCommand, is_created): logging.info(f"form = {form}, model = {model}, is_created = {is_created}") model.status = AdminCommand.Status.success.value if model.command == AdminCommand.Command.sync_item.value: try: extra_json = json.loads(model.extra) tag_ids = extra_json['tag_ids'] except Exception: valid_extra_format = { "tag_ids": [1, 2] } raise ValidationError('参数不合法,合法参数格式如下:' + json.dumps(valid_extra_format)) if not tag_ids: raise ValidationError('参数不允许为空') nums_deleted = Commodity.query.delete() logging.info(f"item deleted, nums_deleted = {nums_deleted}") sync_items_by_tag_ids(tag_ids) db.session.commit() return if model.command == AdminCommand.Command.sync_tag.value: nums_deleted = Tag.query.delete() logging.info(f"tag deleted, nums_deleted = {nums_deleted}") sync_tags() db.session.commit() return return
def register(body): user_name = body['user_name'] password = body['password'] name = body['name'] email = body['email'] user = User.query.filter(User.email == email).first() if user is not None: raise ValidationError("Mail already exsists", 401) if not user_name: raise ValidationError("User name missing", 401) if not password: raise ValidationError("Password is missing", 401) if not name: raise ValidationError("Name is missing", 401) if not email: raise ValidationError("Email is missing", 401) new_user = User(name=name, user_name=user_name, password_hash=pbkdf2_sha256.hash(password), email=email) db.session.add(new_user) db.session.commit() db.session.flush() return {"status": True}
def get_messages_by_user_id(args): user_id = args.get('user_id') if user_id is None: raise ValidationError("Invalid User id", 401) current_user = User.query.filter(User.id == user_id).first() if current_user is None: raise ValidationError("User is not exists", 401) messages = Message.query.filter( or_(Message.receiver == current_user.email, Message.sender == current_user.email)).all() messages_response = [] for m in messages: if m.deleted_by_receiver == False and m.receiver == current_user.email \ or m.deleted_by_sender == False and m.sender == current_user.email: message = { 'subject': m.subject, 'id': m.id, 'sender': m.sender, 'receiver': m.receiver, 'message': m.message, 'creation_date': m.creation_date } messages_response.append(message) return {'messages': messages_response}
def add_message(body): subject = body['subject'] sender = body['sender'] receiver_name = body['receiver'] message = body['message'] if subject is None: raise ValidationError("Subject is missing", 401) if sender is None: raise ValidationError("Sender is missing", 401) if receiver_name is None: raise ValidationError("Receiver is missing", 401) if message is None: raise ValidationError("Message is missing", 401) current_user = User.query.filter(User.email == sender).first() if current_user is None: raise ValidationError("Invalid sender", 401) new_message = Message(sender=sender, receiver=receiver_name, subject=subject, message=message) db.session.add(new_message) db.session.commit() db.session.flush() return {'status': True}
def delete_messages_by_id(body): messages_ids = body['messages_ids'] user_id = body['user_id'] if messages_ids is None: raise ValidationError("Invalid request", 401) if len(messages_ids) == 0: raise ValidationError("No messages was selected", 401) current_user = User.query.filter(User.id == user_id).first() for message_id in messages_ids: current_message = Message.query.filter( Message.id == message_id).first() if current_message is not None: if current_message.receiver == current_user.email: current_message.deleted_by_receiver = True else: current_message.deleted_by_sender = True if current_message.deleted_by_receiver and current_message.deleted_by_sender: db.session.delete(current_message) db.session.commit() db.session.flush() return {'status': True}
def login(body): user_name = body['user_name'] password = body['password'] if not user_name: raise ValidationError("User name missing", 401) if not password: raise ValidationError("Password is missing", 401) current_user = User.query.filter(User.user_name == user_name).first() if current_user is None: raise ValidationError('User or password are incorrect') if not pbkdf2_sha256.verify(password, current_user.password_hash): raise ValueError('Password is incorrect') response = { "token": create_access_token(identity=user_name), "name": current_user.name, "id": current_user.id, "user_name": current_user.user_name, "email": current_user.email } return response
def to_python(self, value): if self.strict and not UUID_RE.match(value): raise ValidationError() try: return uuid.UUID(value) except ValueError: raise ValidationError()
def to_python(self, value): if self.strict and not YT_RE.match(value): raise ValidationError() try: return str(value) except: ValidationError()
def to_python(self, value): if not validation.check_board_name_validity(value): raise ValidationError() model = board_service.find_board(value) if not model: raise ValidationError() return model
def decode_value(self, value): if self.uselist: value = value.encode("utf-8") val = [ self.model.decode_id(value[i:i + 12]) for i in range(0, len(value), 12) ] attr = 'id' query = getattr(self.model, self.query_arg_name) return query.filter(self.model.id.in_(val)).all() elif self.attr == "encoded_id": attr, val = ("id", self.model.decode_id(value.encode("utf-8"))) else: attr, val = (self.attr, value) if val is None: raise ValidationError() if self.value_only: return val try: obj = getattr(self.model, self.query_arg_name).filter_by(**{ attr: val }).one() except orm_exc.NoResultFound, e: raise ValidationError()
def to_python(self, value): match = re.search(r'(\d+)\.(\d+)\.(\d+)\.(\d+)$', value) if not match: raise ValidationError() for i in [1, 2, 3, 4]: if not 0 <= int(match.group(i)) <= 255: raise ValidationError() return value
def to_python(self, value): intval = int(value) if not 0 < intval <= 2**32: raise ValidationError() model = self.resolve_id(intval) if not model: raise ValidationError() return model
def to_python(self, value: str) -> UUID: """to_python override, which handles conversion from an incoming capture to the view-function parameter.""" if not self.UUID_RE.match(value): raise ValidationError() try: return UUID(value) except ValueError: raise ValidationError()
def to_python(self, value): """Validate entity id.""" if self._exist and hass.states.get(value) is None: raise ValidationError() if self._domain is not None and \ split_entity_id(value)[0] != self._domain: raise ValidationError() return value
def url(full_url): """Return full_url if valid, raise an exception in other case.""" if not validators.url(full_url): raise ValidationError('{} is not a valid url'.format(full_url)) if UrlRepository.get_exist_url(full_url): raise ValidationError('{} is already exists'.format(full_url)) return full_url
def check_password(self, field): if len(field.password < 8): raise ValidationError( "Password must be at least 8 characters long") if not re.search(r"[\d]+", field.password): raise ValidationError( "This password must contain at least 1 digit") if re.search(r"[A-Z]+", field.password.data): raise ValidationError( "This password must contain at least 1 uppercase characte")
def from_json(json_post, user_id): title = json_post.get('title') text = json_post.get('text') if title is None or title == '': raise ValidationError('Post has no title.') if text is None or text == '': raise ValidationError('Post has no text.') return BlogPost(title=title, text=text, user_id=user_id)
def to_python(self, value): tmp = [None, None, None] for k, v in enumerate(value.split('-')): if k == 3: raise ValidationError() tmp[k] = v try: tmp[1] = int(tmp[1]) except: raise ValidationError() return tmp
def to_python(self, value): pth = PurePath(value) if not pth.parts: raise ValidationError("All path parts squashed out") for part in pth.parts: if self._disallowed_path_part_re.match(part): raise ValidationError(f"Disallowed path part {part!r}") return pth
def validate_source(self, field): response = requests.get(field.data) if not response.ok: raise ValidationError('{} responded with status: {}.'.format( response.url, response.status_code)) try: swagger_def = response.json() except ValueError: raise ValidationError('Response did not return valid JSON.')
def to_python(self, value: str) -> str: if len(value) < 2: raise ValidationError('Property ID must have ≥2 characters') if value[0] != 'P': raise ValidationError('Property ID must start with P') if value[1] == '0': raise ValidationError('Property ID must not be zero-padded') numeric_part = value[1:] if not numeric_part.isascii() and numeric_part.isnumeric(): raise ValidationError('Property ID must be (ASCII) numeric') return value
def to_python(self, value): try: u = UUID(value) except ValueError: raise ValidationError() if str(u) == value: # the uuid is already canonical return u else: raise ValidationError()
def to_python(self, token): if not '~' in token: raise ValidationError() value, signature = token.rsplit('~', 1) try: valid_sig = base64.urlsafe_b64encode( HMAC(self.key, str(value)).digest())[:self.size] except Exception: raise ValidationError() if valid_sig != signature: raise ValidationError() return value
def to_python(self, value): if value[:2] != '0x': raise ValidationError() try: value = unhexlify(value[2:]) except TypeError: raise ValidationError() if len(value) != 20: raise ValidationError() return value
def decode_keccak(value: str) -> bytes: if value[:2] != '0x': raise ValidationError("Channel Id is missing the '0x' prefix") try: value = decode_hex(value) except DecodeError: raise ValidationError('Channel Id is not a valid hexadecimal value') if len(value) != 32: raise ValidationError('Channel Id is not valid') return value
def to_python(self, value): if not value.startswith(';'): raise ValidationError() value = value[1:] parts = value.split(';') result = self.defaults.copy() for part in parts: try: key, value = part.split('=') except ValueError: raise ValidationError() result[key.strip()] = value.strip() return result
def to_python(self, value): if value[:2] != '0x': raise ValidationError() try: value = value[2:].decode('hex') except TypeError: raise ValidationError() if len(value) != 20: raise ValidationError() return value