How to do a Django like post_save signal with Flask-SQLAlchemy?
<p>I'd like to notice whenever a model is saved and then do some processing and save another model. I need the model to already have an ID set by the database in the processing stage.</p>

<p>With Django one would override the <code>.save()</code> method of model or use signals like:</p>

<pre><code>from django.db.models.signals import post_save 
from django.dispatch import receiver

from .models import MyModel, OtherModel

@receiver(post_save, sender=MyModel)
def do_stuff(sender, instance, created, **kwargs):
    assert instance.id is not None
    ...
    OtherModel.create(related=instance, data=...)
</code></pre>

<p>How to do similar with <code>SQLAlchemy</code> and <code>Flask</code>? I looked up <a href="http://docs.sqlalchemy.org/en/latest/orm/events.html" rel="nofollow">ORM Events</a> and it seemed that <code>expire</code> IntanceEvent would fit the bill. It seems to fire whenever a model instance is saved but when I try to do the same kind of thing:</p>

<pre><code>from sqlalchemy import event

from . import db
from .models import MyModel, OtherModel

@event.listens_for(MyModel, "expire")
def do_stuff(target, attrs):
    assert target.id is not None
    ...
    db.session.add(OtherModel(related=target, data=...))
    db.session.commit()
</code></pre>

<p>It fails on <code>assert instance.id is not None</code> with:</p>

<pre><code>InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.
</code></pre>

<p>It might be that I'm just approaching this the wrong way or I'm missing something crucial but I cannot figure it out. The documentation is split among <code>Flask</code>, <code>Flask-SQLAlchemy</code> and <code>SQLAlchemy</code> and I have hard time piecing this together.</p>

<p>How should I make this kind of post save trigger with <code>SQLAlchemy</code>?</p>