Solved: (sqlalchemy.exc.InvalidRequestError) Can’t reconnect until invalid transaction is rolled back

Fairly such error came (sqlalchemy.exc.InvalidRequestError) Can’t reconnect until invalid transaction is rolled back, using python flask and sqlalchemy with MySQL or PostgreSQL.
So in my case i am using sqlalchemy with flask and flask-sqlalchemy.
{Read:- Solved: (psycopg2.OperationalError) SSL connection has been closed unexpectedly }
Reason of (sqlalchemy.exc.InvalidRequestError) Can’t reconnect until invalid transaction is rolled back Error:
While using the session, a sqlalchemy Error is raised (anything which would also throw an error when be used as pure SQL: syntax errors, unique constraints, key collisions etc.).
Solution of (sqlalchemy.exc.InvalidRequestError) Can’t reconnect until invalid transaction is rolled back Error:
You need to rollback your commit/whatever last happened with the session object. Wrap your code in a try/except clause. In the except part do session.rollback()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
@app.teardown_appcontext def shutdown_session(exception=None): '''Shut Down Session''' if exception: db.session.rollback() db.session.close() db.session.remove() @app.teardown_request def teardown_request(exception): '''Teardown Request''' if exception: db.session.rollback() db.session.remove() def session_commit(self): '''Session Commit ''' try: db.session.add(self) db.session.commit() except Exception as ex: db.session.rollback() db.session.close() db.session.remove() |
{Read:- How To Run Python 3 Flask App with Gunicorn - Step by Step Guide }