原因是没有调用
session.rollback()
解决方法:
- @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()
另一种形式:
- try:
- ......
- ......
- ......
- ......
- except Exception:
- import traceback
- traceback.print_exc()
- db.session.rollback()
- pass
- finally:
- db.session.close()
- pass