[storm] Fwd: question about valitation
Sean Upton
sdupton at gmail.com
Sat Mar 29 00:23:32 GMT 2008
Oops - forgot to reply-to-list... see below.
On Fri, Mar 28, 2008 at 10:15 AM, Massimo <max at studiomasson.it> wrote:
> Hi everybody,
> I have another newbie question, please beg my pardon...
>
> I'm wondering how to implement a "validation" function for a storm
> class/object.
I think you could subclass an existing property type (e.g. Int,
Unicode), or possibly storm.property.Property (requires a bit more
work). Your property class would implement __set__(), which might
look like (untested):
from storm.variable import IntVariable
class MyValidatingInt(Property):
def __init__(self, name, primary=False,
variable_class=IntVariable, **kwargs):
self._name = name
kwargs["value"] = kwargs.pop("default", Undef)
kwargs["value_factory"] = kwargs.pop("default_factory", Undef)
self._variable_kwargs = kwargs
self._variable_class = variable_class
self._primary = primary
def validate(self, obj, value):
if type(value) is not int or value < 42:
raise ValidationError, 'bad data'
if value > obj.maxfoo:
raise ValidationError, 'constraint is not met'
def __set__(self, obj, value):
if obj is not None:
self.validate(obj, value)
Property.__set__(self, obj, value)
On another note, have you looked at using zope.interface/zope.schema?
In addition to simple field validation, you can do multi-field
"invariant" validation using zope.schema, and it is not that difficult
to map many zope schema fields to storm properties in a way similar to
what I've documented above (I have similar code doing just that, using
zope.schema field validation).
Sean
More information about the storm
mailing list