Isvara
Isvara

Reputation: 3463

Hooking entity creation in SQLAlchemy

I want to write a SessionExtension that fires a 'Foo-created' event or 'Bar-created' event every time a new Foo or new Bar is committed to the database. However, once inside the after_commit method, I don't know where to find which entities have been committed. Where do I get this information?

Upvotes: 1

Views: 456

Answers (2)

Rick
Rick

Reputation: 16234

Look at the Mapper Extension bits. It provides you before/after insert/update/delete hooks that you can place your code for this kind of thing.

http://www.sqlalchemy.org/docs/mappers.html?highlight=mapper%20extension#extending-mapper

Upvotes: 0

Denis Otkidach
Denis Otkidach

Reputation: 33200

The Session instance has attribute new, dirty, deleted holding added, updated and deleted objects respectively. They will be already empty when after_commit is executed, but they are available in after_flush. You can extent your own list of added instances for each flush in after_flush hook and use them for events and clear in after_commit.

Upvotes: 2

Related Questions