Validation and json output

18 views
Skip to first unread message

Raphael Slinckx

unread,
Feb 19, 2009, 6:00:38 AM2/19/09
to TurboGears
I wanted to share the following decorator i wrote, maybe it's useful
to some

class validate_json(validate):
"""
Validates the params for a exposed controller much like
turbogears.validate.
If the validation succeeds, nothing particular happens
If the validation fails, we return a json blurb:
{"success": False, "errors": {key: message}}
Each failed field will add its key:value error message to the
errors dict.
"""
def __init__(self, validators):
super(validate_json, self).__init__(validators=validators,
error_handler=self.handle_json_error)

@expose('json')
def handle_json_error(self, *args, **kwargs):
return {"success": False, "errors": pylons.c.form_errors}

Can be used in a json api like this:

@validate_json(dict(
a=validators.Int(not_empty=True),
b=validators.Int(if_empty=3)
))
@expose('json')
def foo(self, a, b)
return {'success': True, 'a': a, 'b': b}

You can then call foo:

/foo -> {success: False, errors: {a: 'Please enter a value'}}
/foo?a=1&b=a -> {success: False, errors: {b: 'Not an integer value'}}
/foo?a=1&b=2 -> {success: True, a: 1, b: 2}

And handle the return response in javascript easily with validation
errors.

Florent Aide

unread,
Feb 19, 2009, 6:14:25 AM2/19/09
to turbo...@googlegroups.com
This would be a worthy addition to tgext.*

Diez B. Roggisch

unread,
Feb 19, 2009, 6:23:29 AM2/19/09
to turbo...@googlegroups.com
Florent Aide schrieb:

> This would be a worthy addition to tgext.*

I personally used this thing here, which I like better because it
doesn't introduce yet another decorator:


@expose("json")
def json_error_handler(self, *unused_args, **unused_kwargs):
"""
Error-handler to be used in json-methods.

This error-handler will set the respons-status to

412 (Precodition Failed)

and returns a mapping of parameter-names to their
error-messages.
"""
response.status = 412
return c.form_errors


You use it on a controller as error_handler in the @validate-decorator.

And I personally think that using HTTP-response-codes is better
protocol-wise, as you don't pollute your returned objects namespace, but
instead can use a simple error-handler on the AJAX-side.


Diez

Raphael Slinckx

unread,
Feb 19, 2009, 6:40:35 AM2/19/09
to TurboGears
> I personally used this thing here, which I like better because it
> doesn't introduce yet another decorator:

Both approaches work, and I was sure something so simple wouldn't be
THE solution, just wanted to share it.
Some JS frameworks make working with http status code easier than
others, so YMMV.

I don't think it's worth including something like that in a library,
because often it needs to be suited to your application JS stack

Maybe it could be used as example or in a snippet repository
Reply all
Reply to author
Forward
0 new messages