Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQLAlchemy, why can I still commit to the database after closing a session?

I'm using SQLAlchemy with Postgres, for the first time. After doing the dance of

engine = create_engine('postgresql://localhost/test', convert_unicode=True)
db_session = scoped_session(sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=engine
))

I ran code to add some stuff to the test database, and after that, I issued a db_session.remove() command (and .close() for good measure). Yet, I was still able to query and modify the tables in the test database. If removing the session doesn't affect its functionality, what's the purpose of removing it? Am I doing something wrong?

like image 833
jclancy Avatar asked Jan 02 '26 07:01

jclancy


1 Answers

scoped_session is a special factory object. Accessing methods such as query() creates a session. One session exists per scope, so the same session will be used each time query (for example) is accessed. Calling remove() will remove the session and the next attribute access will create a new session.

Calling close() on a session will release the connection resources associated with it. They will be re-acquired when the session is used again.

close() and remove() are "temporary", they don't make the session unusable in the future. Typically, you do not need to close or remove a scoped_session, it will be managed automatically.

like image 191
davidism Avatar answered Jan 03 '26 21:01

davidism



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!