Tuesday, August 03, 2010

python decorator for input validation

I was reading how decorator in python can be used to state machine... And, wonder, can this also apply to input validation for web framework like web.py.

I tried the following:
def getInput():
    ''' simulate web.input() for web.py framework '''
    return {
        'x': 'banananaa',
        'y': None,
        'z': 'zz',

def validate_required(rules):
    ''' validation decorator '''
    def wrapper(method):
        ''' wrapping the actual handler '''
        def validate(*args, **kwargs):
            ''' validation take places according to rules '''
            inputs = getInput()
            for k in inputs.keys():
                if k in rules: f = rules[k]
                else: continue
                input = inputs[k]
                if not f(input):
                    out = 'Invalid input %s - %s' % (k, input)
                    print out # or raise Exception here to stop execution
            return method(*args, **kwargs)
        return validate
    return wrapper

class Handler:
    rules = {
        'x': lambda(x): len(x) > 0,
        'y': lambda(y): y is not None,
        'z': lambda(z): z is not None and len(z) > 3,

    def POST(self):
        print 'do something'

# simulate request handling
h = Handler()

No response to “python decorator for input validation”

© 2009 Emptiness Blogging. All Rights Reserved | Powered by Blogger
Design by psdvibe | Bloggerized By LawnyDesignz