Python Input Validation: Documentation
Principle
- Create a Checker object with validators for the fields.
- Pass the fields to the checker object,
it will return the results.
Examples
Simple
from pyiv import * validator=Checker(a=Int())
Initializes a checker object with a field a, which will try to convert it's input to a int.
result=validator(a="5")
This passes the value "5" to the checker object, it will pass the value to the validator, and be converted.
print(result.values.a) #Will return an int of value 5) print(result["a"].values)
You can either access the values trough result.values or by getting the information by key.
Dependencies
PYIV doesn't really know about dependencies, (see FAQ why) instead it uses passes: multiple validators are ran in sequence.
Typical example is a password-match:
#Note all should be equivalent, but they are NOT checker=Checker( { 'pass_a':Len(min=4), 'pass_b':Pass() }, {'pass_b':EqualTo("pass_a")} ) #Currently doesn't work, this is a BUG. checker=Checker( pass_a=Len(min=4), passb=Len(min=0) ) checker.add_pass(passb=Match('pass_a')) result=checker({'pass_a':'test','pass_b':'test'}) result=checker(pass_a='test',pass_b='test')
Input mashing
Sometimes it can be desired to mash input together:
checker=Checker(a=Int()) checker({'a':0},{'a':1},a=2).values.a==2
In this case the 0 is overruled by the 1 witch is on it's turn overruled by 2. In other words: the first dict is updates with the following dicts, and finally merged with the kargs.
Class: Checker
__init__/add_pass(self,*validator_dicts,**validators)
Takes a list of dicts and kargs to be used as validators.
They are all added as a validation pass. (BUGGED)
Checker.raise_on_error
Should an error be raised if the input validation failed ?
Default is False
Will return a pyiv.ValidatorException
Checker.raise_on_extra_arguments
Should an error be raised if arguments not specified in the validators are passed ?
Default is True
__call__(*field_dicts,**kargs)
Will mash all input together, the first dict from field_dicts is updated with the second, and finally updated with the kargs.
It will return a CheckerResult.
Depending upon raise_on_error and raise_on_extra_arguments, it will or will not raise an Exception:
- AttributeError:Will be raised when extra arguments are passed, not defined in the validators.
- Exception:Should not be raised, examples are: not validator passes defined.
- KeyError/IndexError:Will be raised when an argument is missing, and no required validator was used.
- CheckerException:If a validator fails and raise_on_error is set, this will be raised.
- Hopefully the end of this list
Class: CheckerException
Identical to CheckerResult,but in the form of an Exception.
Class: CheckerResult
Contains the following atributes
- checker:The checker that was used to create the results.
- values:A dict of the values after the checker has ran. (You can also use a dot notation to access the values.)
- errors:A dict of the error, if the key is not present, no errors occured. (Can also be accessed using dot notation.)
- rawinput:Raw input given to the checker.
- ok:Will be True if there are no errors in the results. Will be False when there is an error.
[] operator
This will return a CheckerResultArgument
CheckerResultArgument
This is a collections.namedtuple with the arguments:
value,error,rawinput,name,checker,validator
- value:The value after it has been checked.
- error:The error that occured. (None if no occured.)
- rawinput:The raw value, pyiv.undefined if not provided.
- validator:The main validator for this item.
- name:The key/name of this field.
- checker:The checker class used
Class: Validator
The default validators have no default __init__, all arguments are specific to the validator
Pass
Do absolute nothing like pass
And
Takes multiple validators as arguments, and runs them one by one. Example:
And(Int(),Gt(5))
This would convert the input to an integer, and check if it's larger then 5
Optional
Will not run the test given as argument. Example:
Option(Int())
This will try to convert the input to Int IF present.
Required
Causes a specific check for the presence of an argument. Otherwise a IndexError or other might be raised during check.
Default
If the value is not present, it will assign the argument a default value for the checker-field. Example:
checker=Checker(a=Default(0)) result=checker() result.a.value==0
EqualTo
Checks if a field is equal to another
It takes 1 argument: a reference to another field.
checker=Checker(a=Pass(),b=EqualTo("a"))
Note that the above has a racing condition, there is no grantee, that a will be present when b is checked. You should use passes in this case !
Map
Remaps values to another value, or keeps it the same. In python: dict.get(value,value). Example:
checker=Checker(a=Map(0:1)) checker(a=0).values.a==1
Remove
Removes the field if contains a value given in the list.
checker=Checker(a=Remove([0])) checker(a=0).values.a==KeyError
In
Checks if the value is in a list or other container, aka the python in operator
checker=Checker(choice=In(["a","b","c"])) checker(choice="d") #Will list an error checker(choice="a") #Will succeed
Cmp
Compare validators compare if stuff, you can best use one of the subclasses:
- Gt
- Ge
- Eq
- Ne
- Lt
- Le
Example:
checker=Checker(And( Gt(-1), Ge(0 ), Eq(0 ), Ne(-1), Lt(1 ), Le(0 ), ))
Len
Checks the len() of the input. It takes to keyworded arguments: min and max, witch will not be checked if left out.
checker=Checker(password=Len(min=4)) checker(password="ab") #Check would fail.
Type
Takes a type as an argument.
checker=Checker(number=Type(int)) checker(number="0") #Would return a int of value 0
You can use one of the predefined type converters.
- Int
- Long
- Float
Bool
Tries to map pyiv.bool_trues to True and pyiv.falses to False.
bool_trues.append("jawoel") bool_falses.append("mondieu") checker=Checker(io=Bool()) checker(io="jawoel") #Would return True checker(io="no" ) #Would return False checker(io="mondieu" ) #Would return False
Class: HTMLValidator
The are stored in:
import pyiv.html
Example:
checker=Checker( password=html.Password(Len(min=4)), hidden =html.Hidden(Default(0)), text =html.Text(Default("")), select =html.Select( [ (0,"A"), (1,"B") ], pre =[Int()], #Validators to run before checking post=[], #Validators to run afterwards optional=False #Don't check if value not present. ) ) result=checker( password="Test", select=0) result.hidden.validator.type #Gives access to the type "hidden" result.select.validator.options #Gives access to the options