views:

27

answers:

1

I'm working on a web app (using Python & Bottle) and building a decorator for validating HTTP parameters sent in GET or POST. The early version takes callables, so this:

@params(user_id=int, user_name=unicode)

... ensures that user_id is an int, user_name is a string, and both fields exist.

But that's not enough. I want to be able to specify that user_name is optional, or that it must be non-empty and within 40 characters. Implementing that is easy enough, but I'm struggling with what syntax would be most elegant. It seems like that might be a problem someone's solved before, but I'm not finding an answer. Specifically I'm wondering if there's an elegant way to take parseable strings that provide the syntax. Something like:

@params(user_id='int:min1', user_name='unicode:required:max40')

I just don't want to invent a syntax if there's a good one floating around somewhere.

Anyone seen something like this? In any language..but I'm specifically valuing terseness and readability.

+2  A: 

You could use lists.

@validate(user_id=[int, min(1)], user_name=[unicode,required,max(40)])

And each item could be a function (or class/object) that gets executed with the corresponding field as an argument. If it raises an error, it fails validation.

Mark
Thanks Mark! This occurred to us too, and it's a reasonable possibility.. but requires the caller to potentially `import` loads of callables, which seems a bit cumbersome.
royal
`import * from validationmethods`. Or use lists, but with strings, as you had it before.
Mark
yeah, lists of strings would probably work better. the problem other than having to import * is namespace issues. lots of these are fundamental concepts that collide with builtins. min() and max() are both examples of this.
royal