I’m hoping somebody will read this and show me a better way.
In general, I like formencode. I like that I can do stuff like:
def m(self, a, b, c, d, e=None):
And then I know that all my parameters have been converted from their original string values into whatever I want.
But I also find that I spend a lot of time getting my complex schemas to work. Like right now, I have an optional parameter e. e should either be a string representing a date, or it can be None.
I’ve got a validator with this logic in it for e:
- First try to return a datetime.date object from parsing e.
- Otherwise, look in the cookie for a key “e” and try to return that after parsing it into a datetime.date.
- Finally, just return today’s date.
So, the idea is that some visitor can come to page /m and always see data for today. Or, they can use a calendar widget to choose a value. On subsequent visits back to /m, I’ll keep showing them that same date they chose because I saved in it a cookie.
Here’s the problem. I have to make e an optional parameter because I don’t want to require that people hit the site with a url that contains a value for e.
However, when e is None, then my validator for e is ignored! So, as far as I know, at this point, I need to use a validator that operates on the whole set of parameters.
Which is also possible, but in my brain, it seems wrong that I have to use a schema-level validator when I really am only validating one single field.
More generally, anybody that subscribes to the formencode mailing list sees first-hand just how confusing a lot of people find formencode. It is a very powerful library, but very tricky to get right.
Here’s my question — does validate really need to use formencode? Is there some better, simpler solution? I’ve read about how django tackles this problem, and their approach does seem simpler, but I can’t say for sure until I really build something with it.
If any readers can show how to make a form.clean method that does the 1-2-3 logic I described above, I’d be really grateful.
Maybe formencode just needs a fat cookbook of solutions.