SQLAlchemy
Session
Framing out a begin
/ commit
/ rollback
block
The code below:
# verbose version of what a context manager will do
with Session(engine) as session:
session.begin()
try:
session.add(some_object)
session.add(some_other_object)
except:
session.rollback()
raise
else:
session.commit()
# create session and add objects
with Session(engine) as session, session.begin():
session.add(some_object)
session.add(some_other_object)
# inner context calls session.commit(), if there were no exceptions outer context
# calls session.close()
Using a sessionmaker
When you write your application, the sessionmaker
factory should be scoped the same as the Engine
object created
by create_engine()
, which is typically at module-level or global scope. As these objects are both factories, they
can be used by any number of functions and threads simultaneously.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# an Engine, which the Session will use for connection
# resources
engine = create_engine("postgresql://username:password@localhost/")
# a sessionmaker(), also in the same scope as the engine
Session = sessionmaker(engine, future=True)
# we can now construct a Session() and include begin()/commit()/rollback() at once
with Session.begin() as session:
session.add(some_object)
session.add(some_other_object)
# commits the transaction, closes the session