21. Pattern¶
Overview¶
There are some common pattern that I often use when working with sqlalchemy since then.
Patterns¶
Using context manager with session¶
I usually have this kind of pattern when working with sqlalchemy:
session = get_the_session_one_way_or_another()
try: # do something with the session except: # * see comment below session.rollback() raise else: session.commit()
To make things easier to use, it is useful to have this as a context manager:
@contextmanager
def get_session():
session = get_the_session_one_way_or_another()
try:
yield session
except:
session.rollback()
raise
else:
session.commit()
This code snippset when I build ASGI application with focus on CRUD on databases tasks (insert, update, delete)
And then:
with get_session() as session: # do something with the session
https://stackoverflow.com/questions/52232979/sqlalchemy-rollback-when-exception