python-flask db.session.commit() 不工作

python-flask db.session.commit() is not working

问题出在用户尝试 'forgot password' 选项时。它创建新的 reset_key 用于验证,但新密钥没有更新到数据库中。

@app.route('/login/forgot/', methods=['GET', 'POST'])
def forgot():
   form = ResetLoginForm(request.form)
   #There's no session yet. User just pointing to /login/forgot url.

   if request.method == 'POST' and form.validate():
      user = User.query.filter_by(email=form.email.data).first()

   if not user:
     flash('The username or email incorrect')
     return render_template('forgot.html', form=form)

   reset_key = generate_key() ## this creates a new key, but how update  this key into db?
   #tried something like 
   user.reset_key = reset_key 
   db.session.add(user)
   db.session.commit()
   #this is not working. Is it due to session is not started or something?

感谢您的帮助或提示。

这是因为 User.query.filter_by(email=form.email.data).first() 将 return 一个 sqlalchemy.orm.query.Query 对象。正如其文档所说:

Query is the source of all SELECT statements generated by the ORM, both those formulated by end-user query operations as well as by high level internal operations such as related collection loading. It features a generative interface whereby successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.

所以你只是得到了一个复制的对象,所以你的改变不会起作用;

你可以这样使用: user = db.session.query(User).filter_by(email==form.email.data).first() 然后你可以改变 user attrs

user = db.session.query(User).first() 解决了问题。