import re
from functools import wraps
from inspect import getcallargs
from .error import ValidateException
def boolean(value, field):
t=[True,"true",1]
f=[False,"false",0]
if value in t:
return True
elif value in f:
return False
else:
raise ValidateException(field=field, msg='%s is not boolean' % field)
def validateHash(value,field,minlength=None,maxlength=None):
if not re.match(r'^[a-f0-9]*$', value.lower()):
raise ValidateException(field=field)
if minlength and len(value)<minlength:
raise ValidateException(field=field)
if maxlength and len(value)>maxlength:
raise ValidateException(field=field)
return value
def vuserhash(value,field):
'''vailidate function for userhash'''
return validateHash(value,field,minlength=15,maxlength=15)
def validate(kwd,func, need=True,*args,**kargs):
'''validate decorator
use it like this:
@validate(kwd=userhash, func=vuserhash)
f(userhash)
that will validate usrhash with the function vuserhash.
Every validate function should raise an Exception, if the the value is not valid'''
def v(f):
@wraps(f)
def new_f(*a,**k):
kp=getcallargs(new_f.original,*a,**k)
try:
if need or kp[kwd] is not None:
kp[kwd] = func(kp[kwd],kwd,*args,**kargs)
else:
kp[kwd] = None
except KeyError:
if need:
raise ValidateException(field=kwd,msg="%s is nessasary"%kwd)
return f(**kp)
try:
new_f.original=f.original
except AttributeError:
new_f.original=f
return new_f
return v