Python 为什么炼金术不';不要写这些变化

Python 为什么炼金术不';不要写这些变化,python,sqlalchemy,Python,Sqlalchemy,在某些情况下,对对象本身所做的更改不会更改数据库: 具有以下models.py代码: class Task(db.Model): __tablename__ = "task" __table_args__ = {'autoload': True, 'autoload_with': db.engine} [...] def action(self, action_type): if self.task_

在某些情况下,对对象本身所做的更改不会更改数据库: 具有以下models.py代码:

class Task(db.Model):
    __tablename__ = "task"
    __table_args__ = {'autoload': True,
                      'autoload_with': db.engine}

    [...]

    def action(self, action_type):
        if self.task_type == 1:
            if action_type == 1:
                try:
                    user = User.query.filter(User.n_login == self.requestor).first()
                    role_id = self.value
                    new_user_to_role = UserToRole(user.id, role_id)
                    db.session().add(new_user_to_role)
                    db.session().commit() # HERE WE FACE EXCEPTION INTEGRITYERROR IF ROLE IS ALREADY ASSIGNED
                    self.status = 1
                except IntegrityError as ex:
                    # Already assigned role
                    if "UNIQUE constraint" in ex.args[0]:
                        print("Role was already assigned.")
                        db.session().rollback()
                        self.status = 1
                    else:
                        raise IntegrityError(ex.statement, ex.params, ex.orig)

                except Exception as ex:
                    print(ex)
                    self.status = 999
                    db.session().rollback()
                finally:
                    self.update_timestamp = current_timestamp
当我面对用户试图分配已经分配的角色时,我得到IntegrityError异常,我正在处理它,我正在回滚更改,然后我将self.status设置为1,因为任务已经完成,即使之前分配了角色。但在刷新之前,状态仅在页面上可见

有时在调试模式下,我会收到以下错误:

sqlalchemy.exc.ProgrammingError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely) (sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 10720 and this is thread id 13540 (Background on this error at: http://sqlalche.me/e/f405)
但只有在调试模式下缓慢按F8时才会发生,如果按得很快,则不会发生


知道为什么不写更改吗

我猜这是调试模式所说的-sqlalchemy在进行新查询之前刷新您的更改,如所述:
跟踪会话维护的对象的所有更改-在再次查询数据库之前或提交当前事务之前,它会刷新对数据库的所有挂起更改。这称为工作单元模式。


您可以通过
db.session().commit()
在设置
self.status

后将更改保存到数据库。