新手学习时,遇到一个问题,GG查了下,看得不是很明白,因此这里请教一下。
要实现的:用户列表有一个「禁言」操作,点击后更新该用户的禁言字段的布尔值。
「禁言」操作是通过视图函数实现的:
@app.route('/member/status-false/<int:user_id>')
@login_required
def status_false(user_id):
from models import Member
user = Member.query.filter_by(id=user_id).first()
user.status = '0' #禁用用户
db.session.add(user)
db.session.commit()
return redirect(url_for('member'))
运行后,点击「禁言」Flask报错:
sqlalchemy.exc.InvalidRequestError: Object '' is already attached to session '1' (this is '2')
报错的问题大致理解是会话绑定对象乱掉了,但是不知道怎么修改上面的代码使得目的可以实现。
I continued to check some information last night, and the solution is as follows:
Once the manipulation of db.session is involved in the view function, perform from models import db
within the function.That’s normal.
1. Remove db.session.add(user) and try it
2. Place the import introduction at the head of the file
Conclusion:
Reason: