Yannick Gingras wrote:
> Greetings Alchemists,
> Is it possible to define a hook in a mapped class that will
> be called
> to test the sanity of an instance before it gets committed?
>
> As an example:
>
> class Item(object):
> def _pre_commit(self):
> assert (self.dry_weight + self.fluids) < 50
> mapper(Item, items_table)
>
> I don't want to put the test mutators of dry_weight or fluids since
> it's OK to have a temporary inconsistent state as long as the state is
> consistent at commit time.
>
> I see that some of this functionality if covered by MapperExtention
> but since the test is only related to Item I'd rather put the test in
> it.
>
The way I've done this in the past is to define a fairly generic
MapperExtension that calls hook methods on my classes. Here's an
example:
----------------------------------------------
import sqlalchemy as sa
class EventExtension(sa.orm.MapperExtension):
def handle_event(self, event, mapper, connection, instance):
name = '__%s__' % event
handler = getattr(instance, name, None)
if handler:
handler()
def _add_handler(event):
def handle_event(self, *args, **kwargs):
self.handle_event(event, *args, **kwargs)
return sa.orm.EXT_CONTINUE
setattr(EventExtension, event, handle_event)
for _name in ['before_insert',
'after_insert',
'before_update',
'after_update',
'before_delete',
'after_delete']:
_add_handler(_name)
event_extension = EventExtension()
-----------------------------------------------
Now if your mapped class has __before_insert__, __after_insert__ etc.
methods, they will be called at the appropriate point. (Remember to
include event_extension when you map the class)
Hope that helps,
Simon
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---