Marco Sulla
Marco Sulla

Reputation: 15930

try-finally with SqlAlchemy: is this a good habit?

I'm used to do this:

from sqlalchemy.orm import sessionmaker
from sqlalchemy.engine import create_engine

Session = sessionmaker()
engine = create_engine("some connection db string", echo=False)
Session.configure(bind=engine)

db_con = Session()

try:
    # DB MANIPULATION
finally:
    db_con.close()

Is this a good habit? If so, why sqlalchemy does not permit you to do simply:

with Session() as db_con:
    # DB MANIPULATION

?

Upvotes: 0

Views: 1124

Answers (2)

Daenyth
Daenyth

Reputation: 37461

No, this isn't good practice. It's easy to forget, and will make the code more confusing.

Instead, you can use the contextlib.closing context manager, and make that the only way to get a session.

# Wrapped in a custom context manager for better readability
@contextlib.contextmanager
def get_session():
    with contextlib.closing(Session()) as session:
        yield session

with get_session() as session:
    session.add(...)

Upvotes: 1

aviator
aviator

Reputation: 523

Firstly if you are done with the session object you should close the session. session.close will return the connection back to engine pool and if you are exiting the program you should dispose the engine pool with engine.dispose.

Now to your question. In most cases sessions will be used on long running applications like web server. Where it makes sense to centralize the session management. For example in flask-sqlalchemy session is created with start of each web-request and closed when the request of over.

Upvotes: 0

Related Questions