How to manage this commit/rollback pattern in sqlalchemy

前端 未结 2 1092
自闭症患者
自闭症患者 2020-12-20 01:29

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         


        
2条回答
  •  醉梦人生
    2020-12-20 01:59

    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.

提交回复
热议问题