我将 Flask 与 SQLAlchemy 和 Flask-Login 一起使用。
我可以成功登录和注销注册用户。
我感到困惑的是,当我在登录页面上输入错误的密码时,我会返回登录页面并显示一条“欢迎用户@email.com”的闪烁消息,根据代码,我本以为会只有在我成功登录时才会出现。
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
user = User.query.filter_by(email=form.email.data).first()
if form.validate_on_submit():
if user and check_password_hash(user.password, form.password.data):
session['user_id'] = user.id
flash('Welcome %s' % user.email)
return redirect(url_for('dashboard'))
else:
flash('Wrong email or password')
return render_template("login.html", form=form)
flash('The email or password is wrong.')
return render_template("login.html", form=form)
编辑:感谢 Tigra,这就是我最终的结果。
在views.py
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
user = User.query.filter_by(email=form.email.data).first()
if request.method == "POST":
if form.validate():
# the session can't be modified as it's signed,
# so it's a safe place to store the user
session['user_id'] = user.id
flash('Welcome %s' % user.email)
return redirect(url_for('dashboard'))
else:
flash('Wrong email or password')
return render_template("login.html", form=form)
return render_template("login.html", form=form)
在forms.py
from models import User
from werkzeug import check_password_hash
class LoginForm(Form):
email = TextField('email', validators = [Required(), Email()])
password = PasswordField('password', validators = [Required()])
remember_me = BooleanField('remember_me', default = False)
def __init__(self, *args, **kwargs):
Form.__init__(self, *args, **kwargs)
self.user = None
def validate(self):
rv = Form.validate(self)
if not rv:
return False
user = User.query.filter_by(email=self.email.data).first()
if user is None:
self.email.errors.append('Unknown username')
return False
if not check_password_hash(user.password,self.password.data):
self.password.errors.append('Invalid password')
return False
self.user = user
return True