iro/validate.py
author Sandro Knauß <knauss@netzguerilla.net>
Thu, 26 Jan 2012 01:20:03 +0100
branchdevel
changeset 111 8b493ab9c74f
parent 110 601fc908d9f1
child 114 1ed072cc6793
permissions -rw-r--r--
userhash -> apikey fpr better Exception description

import re
from inspect import getcallargs
from .error import ValidateException

def vuserhash(hash,field):
    '''vailidate function for userhash'''
    if not re.match(r'^[a-f0-9]{15,}$', hash.lower()):
        raise ValidateException(field=field)
    return True

def validate(**kargs):
    '''validate decorator
    use it like this:
        @validate(userhash=vuserhash)
        f(userhash)
    that will validate usrhah with the function vuserhash.
    Every validate function should raise an Exception, if the the value is not valid'''
    def v(f):
        def new_f(*a,**k):
            kp=getcallargs(f,*a,**k)
            for i in kargs:
                kargs[i](kp[i],i)
            return f(*a,**k)
        new_f.__name__ = f.__name__
        return new_f
    return v