I find myself repeating a lot of this in sqlalchemy, I wonder what\'s the best way to handle it?
try:
#do some database query
db_session.commit()
exc
You could design a function to manage error handle and you should be evaluating them and consider if you need a performance optimization.
def commit_or_rollback(my_session, do_something, error_type):
try:
do_something(my_session)
my_session.commit()
return True
except error_type as err:
my_session.rollback()
print(err)
return False
def do_something(my_session):
# do something
commit_result = commit_or_rollback(my_session, do_something, NoResultFound)
Be careful session control and performance. This method could keep the code clearly.