Hi,
I am trying to use validates() to dynamically add validation to my sqla classes, but i cannot figure out how to do this. I have read python decorator docs and docs n validates, but something escapes me (or it is just not possible).
A code snippet (this does not work):
def create_validators(self):
for cls in self.itervalues():
names = tuple([fld.key() for fld in cls._type_.fields()])
def validator(obj, name, value):
if not cls._type_[name].validate(value):
raise ValueError("incorrect value '%s' for '%s' in '%s'" % (str(value), name, cls.__name__))
return value
setattr(cls, 'validator', validates(*names)(validator)) #does NOT work
in which:
'self' is a dictionary of sqla classes,
'cls' is an sqla class (derived from declarative_base(...)),
'cls._type_' contains the information for (further) generation of 'cls' (e.g. cls._type_[name].validate(value) calls a validate method for value for a field (say String(50)) with name 'name')
The method above runs without problem, but the validator function is never called when setting field values. I have tried all alternatives i can think of, but maybe i am missing something basic.
Can anyone help?
Cheers, Lars