0

Following this amazing explenation: SQLAlchemy: Creating vs. Reusing a Session

I have this code:

session_factory = sessionmaker(bind=engine, autocommit=False, autoflush=False)
Session = scoped_session(session_factory)


@contextmanager
def db_session():
    """Provide a transactional scope around a series of operations."""
    session = Session()
    try:
        yield session
        session.commit()
    except Exception as e:
        session.rollback()
        raise
    finally:
        session.close()
        Session.remove()

I've noticed that it works for me when I do:

Session.query(...).all()
Session.flush()
Session.add(...)

So I see that

session_one = Session()
session_two = Session()
session_one == session_two # TRUE

Session() == Session # FALSE
type(Session()) # Session
type(Session) # scoped_session

Why does the scoped_session succeed to add and flush, while it's also a container for a session?

davidism
  • 121,510
  • 29
  • 395
  • 339
RoieL
  • 109
  • 7

0 Answers0