1 import re |
1 import re |
|
2 from functools import wraps |
|
3 |
2 from inspect import getcallargs |
4 from inspect import getcallargs |
3 from .error import ValidateException |
5 from .error import ValidateException |
4 |
6 |
5 def vuserhash(hash,field): |
7 def boolean(value, field): |
|
8 t=[True,"true",1] |
|
9 f=[False,"false",0] |
|
10 if value in t: |
|
11 return True |
|
12 elif value in f: |
|
13 return False |
|
14 else: |
|
15 raise ValidateException(field=field, msg='%s is not boolean' % field) |
|
16 |
|
17 |
|
18 def validateHash(value,field,minlength=None,maxlength=None): |
|
19 if not re.match(r'^[a-f0-9]*$', value.lower()): |
|
20 raise ValidateException(field=field) |
|
21 if minlength and len(value)<minlength: |
|
22 raise ValidateException(field=field) |
|
23 if maxlength and len(value)>maxlength: |
|
24 raise ValidateException(field=field) |
|
25 return value |
|
26 |
|
27 def vuserhash(value,field): |
6 '''vailidate function for userhash''' |
28 '''vailidate function for userhash''' |
7 if not re.match(r'^[a-f0-9]{15,}$', hash.lower()): |
29 return validateHash(value,field,minlength=15,maxlength=15) |
8 raise ValidateException(field=field) |
|
9 return True |
|
10 |
30 |
11 def validate(**kargs): |
31 def validate(kwd,func, need=True,*args,**kargs): |
12 '''validate decorator |
32 '''validate decorator |
13 use it like this: |
33 use it like this: |
14 @validate(userhash=vuserhash) |
34 @validate(kwd=userhash, func=vuserhash) |
15 f(userhash) |
35 f(userhash) |
16 that will validate usrhah with the function vuserhash. |
36 that will validate usrhash with the function vuserhash. |
17 Every validate function should raise an Exception, if the the value is not valid''' |
37 Every validate function should raise an Exception, if the the value is not valid''' |
18 def v(f): |
38 def v(f): |
|
39 @wraps(f) |
19 def new_f(*a,**k): |
40 def new_f(*a,**k): |
20 kp=getcallargs(f,*a,**k) |
41 kp=getcallargs(new_f.original,*a,**k) |
21 for i in kargs: |
42 try: |
22 kargs[i](kp[i],i) |
43 if need or kp[kwd] is not None: |
23 return f(*a,**k) |
44 kp[kwd] = func(kp[kwd],kwd,*args,**kargs) |
24 new_f.__name__ = f.__name__ |
45 else: |
|
46 kp[kwd] = None |
|
47 except KeyError: |
|
48 if need: |
|
49 raise ValidateException(field=kwd,msg="%s is nessasary"%kwd) |
|
50 return f(**kp) |
|
51 try: |
|
52 new_f.original=f.original |
|
53 except AttributeError: |
|
54 new_f.original=f |
25 return new_f |
55 return new_f |
26 return v |
56 return v |
27 |
57 |