Updating database after after_insert()

59 views
Skip to first unread message

grassoalvaro

unread,
Aug 10, 2009, 7:34:39 PM8/10/09
to sqlalchemy
Hi,

example from Pylons application, but i think that framework doesn't
matter here:

class DBAccountExtension(orm.interfaces.MapperExtension):
def after_insert(self, mapper, connection, instance):
response = hrd.user_create(instance.to_hrd())
if response['status'] == hrd.STATUS_OK:
instance.csa = response['resdata']['user']['id']
db.save_or_update(instance)
db.commit()
return orm.interfaces.EXT_CONTINUE

After saving model i'm making request to some API (to save data there
also). API return status information (response['resdata']['user']
['id']) which i want to update in database so i'm trying to do
db.save_or_update(instance) and then db.commit() but after this 2
lines application prints exception:

InvalidRequestError: The transaction is closed

Any solutions?

(sorry for my english).

grassoalvaro

unread,
Aug 11, 2009, 12:00:19 PM8/11/09
to sqlalchemy
I don't know why but now exception is:

InvalidRequestError: Instance '<DBAccount at 0x134360d0>' is not
persisted

Michael Bayer

unread,
Aug 11, 2009, 12:35:59 PM8/11/09
to sqlal...@googlegroups.com
you can't do Session operations and commits inside of after_insert().
you're already in the session.flush() operation. I guess I have to make
this clearer for every individual method in the docs.

grassoalvaro

unread,
Aug 11, 2009, 1:09:17 PM8/11/09
to sqlalchemy
Hmm, but after_insert() is the best place where i can put this king
logic (updating/inserting data in may places). So i can't use session
operations inside of after_insert() at all?

Michael Bayer

unread,
Aug 11, 2009, 1:36:27 PM8/11/09
to sqlal...@googlegroups.com
grassoalvaro wrote:
>
> Hmm, but after_insert() is the best place where i can put this king
> logic (updating/inserting data in may places). So i can't use session
> operations inside of after_insert() at all?

nope. use before_flush() or after_flush() on SessionExtension for that.

grassoalvaro

unread,
Aug 11, 2009, 1:59:24 PM8/11/09
to sqlalchemy
This is not exactly what i was looking for. I want to connect only one
model with some kind of operations, not all session...

Michael Bayer

unread,
Aug 11, 2009, 2:12:46 PM8/11/09
to sqlal...@googlegroups.com
grassoalvaro wrote:
>
> This is not exactly what i was looking for. I want to connect only one
> model with some kind of operations, not all session...

scan through Session.dirty etc. for the objects you want. if a new
extension "MapperExtension.before_flush()" were added it would be working
more or less the same way anyway.

grassoalvaro

unread,
Aug 11, 2009, 2:44:20 PM8/11/09
to sqlalchemy
Oh, that is a good idea and it's working.
Thanks ;-)
Reply all
Reply to author
Forward
0 new messages