I've only found partial answers to this problem so far, so I'd like to
expand on it here.

I have a site in which users post stories, and their friends are
notified. In order to decouple different parts of the business logic,
I would like to use a publish/subscribe mechanism that raises an event
for any new model instance, so that a news feed item referring to that
story can be created for each of the author's friends. I believe that
I want to create the news feed item only when the story has been
successfully committed, so that failure in creating the news feed item
doesn't cause the story to be rolled back too.

My current code looks like this:

class EventExtension(SessionExtension):
    def __init__(self):
        self.new = []

    def after_flush(self, session, flush_context):
        self.new = session.new
        return EXT_CONTINUE

    def after_commit(self, session):
        for instance in self.new:
            fire_event('model/create/%s' %
instance.__class__.__name__, instance)
        self.new = []
        return EXT_CONTINUE

The reason for the __init__ method is that after_commit was being
called without after_flush having been called, because I was calling
session.commit() after processing every request, or session.rollback()
if an exception was thrown. Perhaps autocommit would suit me better.

The problem I have is that the newly created Story doesn't have its
relationship attributes populated. For example, author_id==1, but
author==None. This particularly confuses me because the docs say that
relations are lazily loaded by default.

Can someone explain to me what is going on, and clue me in to the
correct way to do this? Thank you.

-- 
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.

Reply via email to