SQLAlchemy 2.0 上下文管理
Session Context Managers
Now a session can be instantiated with a context manager, so there is a clear start and end. Here is an example:
with Session() as session:
session.add(user)
session.commit()
Here the session is closed when the context manager block ends. And if an error occurs inside it, the session is rolled back.
A variant of this pattern can be used to have a session that automatically commits at the end, while still rolling back on errors:
with Session() as session:
with session.begin():
session.add(user)