title: event listener on scoped session
body: <p>I am trying to add an event listener to the <code>before_commit</code> event of an SQLAlchemy Session inside of a Flask application. When doing the following</p>
  
  <pre><code>def before_commit(session):
      for item in session:
          if hasattr(item, 'on_save'):
              item.on_save(session)
  
  event.listen(db.session, 'before_commit', before_commit)
  </code></pre>
  
  <p>I get </p>
  
  <pre><code>Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "app.py", line 60, in &lt;module&gt;
      event.listen(db.session, 'before_commit', before_commit)
    File "C:\Python27\lib\site-packages\sqlalchemy\event\api.py", line 49, in listen
      _event_key(target, identifier, fn).listen(*args, **kw)
    File "C:\Python27\lib\site-packages\sqlalchemy\event\api.py", line 22, in _event_key
      tgt = evt_cls._accept_with(target)
    File "C:\Python27\lib\site-packages\sqlalchemy\orm\events.py", line 1142, in _accept_with
      "Session event listen on a scoped_session "
  sqlalchemy.exc.ArgumentError: Session event listen on a scoped_session requires that its creation callable is associated with the Session class.
  </code></pre>
  
  <p>I can't find the correct way to register the event listener. The documentation actually states that <code>event.listen()</code> also accepts a <code>scoped_session</code>, but it seems like it does not?!</p>
  
  <hr>
  
  <p><a href="http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.SessionEvents">http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.SessionEvents</a></p>
  
  <blockquote>
    <p>The  listen() function will accept Session objects as well as the return result of
    sessionmaker() and scoped_session().</p>
    
    <p>Additionally, it accepts the Session class which will apply listeners to all Session
    instances globally.</p>
  </blockquote>