sqlalchemy.exc.InvalidRequestError: Can't reconnect until invalid transaction is rolled back


原因是:连接断开后,事务没有回滚,残留的锁导致后续的查询报错.sqlalchemy对每一个查询和插入等操作都是一个事务。

解决:在所有的数据库操作的时候捕捉异常进行事务的回滚。

# main.py
from models import OrderInfo 
from sqlalchemy.exc import InvalidRequestError
try:
    order = OrderInfo.query.filter_by(task_id=user_dict.get('task_id')).first()
    order.status = 'COMPLETE'
    db.session.commit()
except InvalidRequestError:
    db.session.rollback()
except Exception as e:
    print(e)