Add to SQLAlchemy Session in before_flush event?

Issue #3637 resolved
Roman Dubina created an issue

Is there a proper way to add new object to Session while in before_flush event without infinite loop?

Example:

from sqlalchemy import event

@event.listens_for(SomeSessionOrFactory, 'before_flush')
def receive_before_flush(session, flush_context, instances):
    session.add(NEW_OBJECT)

I'm trying to make logging system for all models. Maybe there is a better way to do this? :)

Comments (3)

  1. Mike Bayer repo owner

    no infinite loop is implicit in this activity. Feel free to provide an actual demonstration of your issue per the guidelines at http://stackoverflow.com/help/mcve. Here's a demo, thanks!

    from sqlalchemy import Integer, Column, create_engine
    from sqlalchemy.orm import Session
    from sqlalchemy.ext.declarative import declarative_base
    
    Base = declarative_base()
    
    
    class A(Base):
        __tablename__ = 'a'
        id = Column(Integer, primary_key=True)
    
    
    e = create_engine("sqlite://", echo=True)
    Base.metadata.create_all(e)
    
    s = Session(e)
    
    from sqlalchemy import event
    
    
    @event.listens_for(s, 'before_flush')
    def receive_before_flush(session, flush_context, instances):
        session.add(A())
    
    s.add_all([A(), A(), A()])
    s.flush()
    
    assert s.query(A).count() == 4
    
  2. Log in to comment