2017-09-13 55 views
0

我回顧了一些舊的代碼我寫的,並期待在我寫嘗試提交到數據庫的更改(如刪除)時,處理對某些故障的用戶響應共享提交功能:如何更好地處理此Flask-SQLAlchemy提交/回滾?

def _commit_to_database(): 
    """A shared function to make a commit to the database and handle exceptions 
    if encountered. 
    """ 
    flask.current_app.logger.info('Committing changes to database...') 
    try: 
     db.session.commit() 
    except AssertionError as err: 
     flask.abort(409, err) 
    except (exc.IntegrityError, sqlite3.IntegrityError) as err: 
     flask.abort(409, err.orig) 
    except Exception as err: 
     flask.abort(500, err) 
    finally: 
     db.session.rollback() 

我想我理解我的思考過程:嘗試commit,在發生某些故障時觸發flask.abort發回響應,但我相信我發現數據庫留下了一個打開的會話,需要回滾時,我這樣做並添加rollback轉化爲finally聲明解決了這個問題,讓我仍然使用flask.abort

我有我身邊的代碼的問題是:

1)這是一個錯誤:將燒瓶SQLAlchemy的擴展未平倉的會話爲正常;在finally上撥打rollback這將在abort影響成功commit後觸發嗎?

2)如果這是一個錯誤:在處理try-except-finallydb會話時,我應該做些什麼不同?

回答

0

你需要的時候出現異常時回滾最後關閉會話:

def _commit_to_database(): 
    """A shared function to make a 
     commit to the database and 
     handle exceptions if encountered. 
    """ 
    flask.current_app.logger.info(
     'Committing changes to db...' 
    ) 
    try: 
     db.session.commit() 
    except AssertionError as err: 
     db.session.rollback() 
     flask.abort(409, err) 
    except (
     exc.IntegrityError, 
     sqlite3.IntegrityError 
    ) as err: 
     db.session.rollback() 
     flask.abort(409, err.orig) 
    except Exception as err: 
     db.session.rollback() 
     flask.abort(500, err) 
    finally: 
     db.session.close()