python - How can I better handle this Flask-SQLAlchemy commit/rollback? -


i'm reviewing old code wrote , looking @ shared commit function had written handle responses user on failures when attempting commit changes database (such deletes):

def _commit_to_database():     """a shared function make commit database , handle exceptions     if encountered.     """     flask.current_app.logger.info('committing changes database...')     try:         db.session.commit()     except assertionerror err:         flask.abort(409, err)     except (exc.integrityerror, sqlite3.integrityerror) err:         flask.abort(409, err.orig)     except exception err:         flask.abort(500, err)     finally:         db.session.rollback() 

i think understand thought process: attempt commit, upon failures trigger flask.abort send response back, believe found database left open session requiring rollback when did , adding rollback finally statement resolved allowing me still use flask.abort.

the questions have around me code are:

1) bug: flask-sqlalchemy extension not close out session normal; calling rollback on finally triggering after abort going affect successful commits?

2) if bug: should doing differently in handling try-except-finally , db session?

you need rollback when exception occurs , close session:

def _commit_to_database():      """a shared function make           commit database ,        handle exceptions if encountered.     """     flask.current_app.logger.info(         'committing changes db...'     )     try:          db.session.commit()      except assertionerror err:         db.session.rollback()         flask.abort(409, err)      except (         exc.integrityerror,          sqlite3.integrityerror      ) err:         db.session.rollback()         flask.abort(409, err.orig)      except exception err:         db.session.rollback()         flask.abort(500, err)      finally:          db.session.close() 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -