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,
}
@validate_required(rules)
def POST(self):
print 'do something'
# simulate request handling
h = Handler()
h.POST()

No response to “python decorator for input validation”
Post a Comment