Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close and re-connect SQLAlchemy session's database connection?

Tags:

sqlalchemy

Suppose we need to do some long-time computing after loading some objects from SQLAlchemy session, we want to close the database connection during the computing, then reconnect to the database. How to do it in SQLAlchemy?

Or, is it necessary to close the session and re-create one every time, and merge/reload all related objects? But I found session.close() doesn't close the connection, even session.connection().close() or close the connection bound to the session doesn't close it either. So how to close the connection, after I used a session and before I quit the application?

like image 718
Gary Shi Avatar asked Apr 05 '11 05:04

Gary Shi


People also ask

How do you close a SQLAlchemy session in python?

A SQLAlchemy Session generally represents the scope of one or more transactions, upon a particular database connection. Therefore, the answer to your question as literally asked, is to call session. close() , that is, "how to properly close a SQLAlchemy session".

What does SQLAlchemy refresh do?

refresh() to immediately get an up-to-date version of the object, even if the session already queried the object earlier.

Can't reconnect until invalid transaction is rolled back python?

To solve this problem, you should open a new db session at the beginning of the web request, and close the session at the end of the request.


1 Answers

Got the answer from the SQLAlchemy Google Group: use session.bind.dispose() after terminating the on-going transaction. It disposes the whole connection pool, so all database connections are closed.

And I can hold the session, e.g. commit or rollback the session instead of closing it. When I need to use it later, it'll automatically make necessary connections. This method saves me from recreating the session and merging objects.

like image 184
Gary Shi Avatar answered Sep 23 '22 04:09

Gary Shi