make Session a context manager

This commit is contained in:
andygoblins
2020-02-09 14:53:17 -06:00
parent 4502afad4f
commit f1f450cedc
2 changed files with 67 additions and 62 deletions

View File

@@ -7,7 +7,7 @@ from gnucash import Session, Account, Transaction, Split, GncNumeric
FILE_1 = "/tmp/example.gnucash"
session = Session("xml://%s" % FILE_1, is_new=True)
with Session("xml://%s" % FILE_1, is_new=True) as session:
book = session.book
root_acct = Account(book)
@@ -81,7 +81,3 @@ split4.SetValue(num2.neg())
trans1.CommitEdit()
trans2.CommitEdit()
session.save()
session.end()
session.destroy()

View File

@@ -117,6 +117,15 @@ class Session(GnuCashCoreClass):
self.destroy()
raise
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
# Roll back changes on exception by not calling save. Only works for XMl backend.
if not exc_type:
self.save()
self.end()
def raise_backend_errors(self, called_function="qof_session function"):
"""Raises a GnuCashBackendException if there are outstanding
QOF_BACKEND errors.