Repository navigation
SessionEvent listener not called if registered before sessionmaker
#8466
|
I was looking at: sqlalchemy-continuum/sqlalchemy-continuum#275 If I am listening to Is this the expected behavior ? Here is a working example: from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.event import listen
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, mapper
from sqlalchemy.orm.session import Session
engine = create_engine('sqlite:////tmp/db.sqlite3')
session_1 = lambda session, flush_context, instances: print("IN session_1")
session_2 = lambda session, flush_context, instances: print("IN session_2")
factory = sessionmaker(bind=engine, autocommit=False) # <--- Here both listeners are called
listen(Session, 'before_flush', session_1)
# <--- Moving the line here calls only session_2
listen(factory, 'before_flush', session_2)
Base = declarative_base()
class Article(Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(255))
Base.metadata.create_all(engine)
session = factory()
article = Article(name='Some article')
session.add(article)
session.commit() |
Replies: 1 comment 2 replies
|
I was digging a bit deeper and found this calls both the listeners: listen(Session, 'before_flush', session_1)
factory = sessionmaker(bind=engine, autocommit=False)
listen(Session, 'before_flush', session_2) # NOTE that this is on Session and not on factorThe issue seems to be very specific only when I have a listener on both: I tried (naively) to change it to I also tried changing how I create the session:
|
I was digging a bit deeper and found this calls both the listeners:
The issue seems to be very specific only when I have a listener on both:
SessionandfactoryThe listener on
Sessionis ignoredI tried (naively) to change it to
listen(Session, 'before_flush', session_1, propagate=True)but that didn't work either(I has used propagate when listening to a Model 'before_insert' for something else)
I also tried changing how I create the session:
session = Session(bind=engine)- Calls session_1 onlyse…