Welcome, guest | Sign In | My Account | Store | Cart

Validation decorator based on formencode package. It uses validation schemas.

Python, 26 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import formencode
from formencode import validators

def validate(schema):
    def fn(realfn):
        def wrapper(*args, **kws):
            field_names = schema.fields.keys()
            args_dict = dict(zip(realfn.func_code.co_varnames, args))
            args_dict.update(dict((field_name, kws.get(field_name)) for field_name in field_names if field_name in kws))
            schema().to_python(args_dict)
            return realfn(*args, **kws)
        return wrapper
    return fn


class GreetSchema(formencode.Schema):
    name = validators.String(not_empty=True)


@validate(GreetSchema)
def greet(name):
    print 'hello', name

greet('shon')
greet(name='shon')
greet('')

Excellent Formencode is used by pylons and TurboGears for validation. And these frameworks provide decorators to make using it easier. Now sometimes we need to use it outside these frameworks. Here is a small utility function for the same.