[Solved] Can’t reconnect until invalid transaction is rolled back

The reason is that there is no call

session.rollback()

Solution:

@contextmanager
    def session_scope(self):
        self.db_engine = create_engine(self.db_config, pool_pre_ping=True) # echo=True if needed to see background SQL        
        Session = sessionmaker(bind=self.db_engine)
        session = Session()
        try:
            # this is where the "work" happens!
            yield session
            # always commit changes!
            session.commit()
        except:
            # if any kind of exception occurs, rollback transaction
            session.rollback()
            raise
        finally:
            session.close()

Another form:

        try:
        	......
            ......
            ......
            ......
        except Exception:
            import traceback
            traceback.print_exc()
            db.session.rollback()
            pass
        finally:
            db.session.close()
            pass

Read More: