首页 > 解决方案 > 如何使用 flask_sqlalchemy 信号将操作记录到数据库?

问题描述

我正在尝试使用 sqlalchemy 信号将数据库操作记录到 actions_log 表,但我收到了这个错误

sqlalchemy.exc.InvalidRequestError:此会话处于“已提交”状态;在此事务中不能发出更多 SQL。

#acionslog model

class ActionsLog(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    object = db.Column(db.String(50))
    action = db.Column(db.String(10), nullable=False)
    user_id =  db.Column(db.Integer, db.ForeignKey("user.id"))

 
#__init__.py

@models_committed.connect
def log_action(sender, changes):

   if current_user.is_authenticated:
      print(sender)
      print(changes)

      instance = changes[0][0]
      action = changes[0][1]
    
      from app.backend.user.models import ActionsLog

      log = ActionsLog()
      log.object =  str(instance)
      log.action = action
      log.user_id = current_user.id

      db.session.add(log)
      db.session.commit()

标签: flaskflask-sqlalchemy

解决方案


推荐阅读