Uncover HN: Valito-Progressive validation for Python in step with typehints & dataclass

45
Uncover HN: Valito-Progressive validation for Python in step with typehints & dataclass

Validation that goes in conjunction with dataclasses


Package version

Installation

$ pip set up valito
---> 100%
Successfully attach in valito

Example

bytes:
are trying:
password=password.encode(“utf-8”)
excluding (Exception,):
dart
return bcrypt.hashpw(password, bcrypt.gensalt())

@confirm_password_field.add_post_validator
def encrypt_confirm_password(self, confirm_password: str) -> bytes:
are trying:
confirm_password=confirm_password.encode(“utf-8″)
excluding (Exception,):
dart
return bcrypt.hashpw(confirm_password, self.password)

user: User=user_field.validator
password: str=password_field.validator
confirm_password: str=confirm_password_field.validator

user=User(title=”acoconutcup”, …)

# if user comprises invalid values and debug is Appropriate on any self-discipline, it throws an error for all these debugged fields.
“>

from dataclasses import dataclass
import bcrypt
import valito
from valito import (StringValidator,
                    AadhaarCardValidator, 
                    PhoneNumberValidator, 
                    EmailIDValidator, 
                    PaymentCardValidator, 
                    DateValidator, 
                    Validator,
                    PatternValidator)

# before the entirety we execute a User class for diverse self-discipline validations.

@dataclass
class User(object):
   title: str = StringValidator(logger=Wrong, debug=Appropriate, max_length=50, required=Appropriate)
   aadhaar: str = AadhaarCardValidator(logger=Wrong, debug=Appropriate)
   cellular phone: str = PhoneNumberValidator(logger=Wrong, debug=Appropriate)
   email: str = EmailIDValidator(logger=Wrong, debug=Appropriate, reassign=Wrong)
   credit_card: str = PaymentCardValidator(logger=Wrong, debug=Appropriate)
   date: datetime.datetime = DateValidator(logger=Wrong, debug=Appropriate, default=datetime.datetime.utcnow)
   gender: str = Validator(in_choice=["Male", "Female", "Trans"], default="Female")

# if logger=Appropriate, the self-discipline is logged in a separate file. if debug=Appropriate, any evil kind/valued entry 
# throws an error in console else it defaults to None.

# now we are able to execute the UserValidator itself that validates the User class.
valito.Validator.register(User)  # noqa

class UserValidator(valito.Validator):
    annotation = typing.Union[User, None]

# this UserValidator might more than likely possibly well be straight away outdated-fashioned or outdated-fashioned extra to execute a UserField

class UserField(valito.Area):
    validator = UserValidator
    
# now we are able to say pre and put up validation with this self-discipline.

@dataclass
class RegisterUser(object):
    user_field = UserField(logger=Wrong, debug=Appropriate)
    password_field = valito.StringField(
        min_length=6,
        max_length=30,
        debug=Appropriate,
        required=Appropriate
    )
    confirm_password_field = valito.StringField(
        min_length=6,
        max_length=30,
        debug=Appropriate,
        required=Appropriate
    )
    
    @user_field.add_pre_valiator
    def user_not_in_db(self, user: User):
        # common sense goes here....
        
    @user_field.add_post_validator
    async def email_user_activity(self, user: User):
        # async common sense to email that user has signed up...
        
    @password_field.add_validator
    def one_small_char(self, fee: str):
        are trying:
            PatternValidator(sample=Sample(r"[a-z]", count_min=1)).validate(fee=fee)
        excluding Exception:
            elevate ValueError(f"{self.password_field} must haven't any no longer as much as one microscopic personality")
        return fee

    @password_field.add_validator
    def one_capital_char(self, fee: str):
        are trying:
            PatternValidator(sample=Sample(r"[A-Z]", count_min=1)).validate(fee=fee)
        excluding Exception:
            elevate ValueError(f"{self.password_field} must haven't any no longer as much as one capital personality")
        return fee

    @password_field.add_validator
    def one_digit_char(self, fee: str):
        are trying:
            PatternValidator(sample=Sample(r"d", count_min=1)).validate(fee=fee)
        excluding Exception:
            elevate ValueError(f"{self.password_field} must haven't any no longer as much as one integer personality")
        return fee

    @password_field.add_post_validator
    def encrypt_password(self, password: str) -> bytes:
        are trying:
            password = password.encode("utf-8")
        excluding (Exception,):
            dart
        return bcrypt.hashpw(password, bcrypt.gensalt())

    @confirm_password_field.add_post_validator
    def encrypt_confirm_password(self, confirm_password: str) -> bytes:
        are trying:
            confirm_password = confirm_password.encode("utf-8")
        excluding (Exception,):
            dart
        return bcrypt.hashpw(confirm_password, self.password)
        
     user: User = user_field.validator
     password: str = password_field.validator
     confirm_password: str = confirm_password_field.validator
    
user = User(title="acoconutcup", ...) 

# if user comprises invalid values and debug is Appropriate on any self-discipline, it throws an error for all these debugged fields.

Regex

Valito supports regex too out of the field.

from valito import Sample, StartOfString, WordBoundary
from pyparsing import Regex

hyphen = Sample(r"-", alias="-")
colon = Sample(r":", alias=":")
backslash = Sample(r"/", alias="/")
home = Sample(r"s", count_min=0, greedy=Wrong, alias=" ")
four_digits = home & Sample(r"d", depend=4, alias="dddd") & home
two_digits = home & Sample(r"d", depend=2, alias="dd") & home

# European Date Layout
eu_date_with_hyphen = four_digits & hyphen & two_digits & hyphen & two_digits
eu_date_with_colon = four_digits & colon & two_digits & colon & two_digits
eu_d

Read More

Charlie Layers
WRITTEN BY

Charlie Layers

Fill your life with experiences so you always have a great story to tell