Writing a validator to look for cookie data
Matthew Wilson <[email protected]> Thu, 12 Mar 2009 13:39:40 -0400
| Newsgroups | gmane.comp.python.formencode |
|---|---|
| Message-ID | <[email protected]> |
I store fields from form submissions into a cookie, and then when a
user hits a form, I prepopulate the form with that data.
I want to write a validator that first tries to get values from the
query string, and if that is None, then the validator should check the
cookie.
Here is what I have:
class LookInCookie(FancyValidator):
"""
Retrieves something from the cookie. Depends on a state with an
attribute named 'simple_cookie'.
"""
def __init__(self, k, d=None):
"""
Return k from the cookie, or d if it isn't there.
"""
self.k, self.d = k, d
def to_python(self, value, state=None):
log.debug("Inside LookInCookie.to_python with locals: %s"
% locals())
if hasattr(state, 'simple_cookie') \
and state.simple_cookie.has_key(self.k):
return state.simple_cookie[self.k]
else:
return self.d
Then I tried to combine this validator with Any() like this:
>>> from turbogears.util import Bunch
>>> s = Bunch(simple_cookie={'city':1})
>>> v = Any(LookInCookie('city'), validators.Int())
>>> v.to_python('99', s)
99
>>> v.to_python('abc', s)
1
So far, so good! First, the Int validator runs, then when Int fails,
I get the value from the cookie s.
However, here's where things fall apart. When there is no value
passed in, nothing comes back out!
>>> v.to_python('', s)
>>> v.to_python(None, s)
How do I force validators to run even when the value is missing?
More generally, is there a better solution to what I'm trying to do?
--
Matthew Wilson
[email protected]
http://tplus1.com
------------------------------------------------------------------------------
Apps built with the Adobe(R) Flex(R) framework and Flex Builder(TM) are
powering Web 2.0 with engaging, cross-platform capabilities. Quickly and
easily build your RIAs with Flex Builder, the Eclipse(TM)based development
software that enables intelligent coding and step-through debugging.
Download the free 60 day trial. http://p.sf.net/sfu/www-adobe-com