我正在用Python开发一个应用程序,其中包括记录用户。我正在使用烧瓶。 SQLAlchemy,flask-login和flask形式。这些是我用于注册和记录的代码(在route.py模块中):
@app.route('/register', methods=['GET', 'POST'])
def register():
register_form = RegistrationForm(request.form)
if request.method == 'POST':
if register_form.validate():
email = request.form.get('email')
password = request.form.get('password')
username = request.form.get('username')
existing_user = User.query.filter_by(email=email).first()
if existing_user is None:
user = User(username=username, email=email,
password=bcrypt.generate_password_hash(password))
db.session.add(user)
db.session.commit()
login_user(user)
return redirect(url_for('home'))
flash('A user already exists with that email address.')
return redirect(url_for('register'))
return render_template('/register.html',
title='Create an Account',
form=RegistrationForm())
@app.route('/login', methods=['GET', 'POST'])
def login():
login_form = LoginForm(request.form)
if request.method == 'POST':
if login_form.validate():
email = request.form.get('email')
password = request.form.get('password')
user = User.query.filter_by(email=email).first()
if user:
if user.check_password(password=password):
login_user(user)
next = request.args.get('next')
return redirect(next or url_for('home'))
flash('Invalid username/password combination')
return redirect(url_for('login'))
return render_template('login.html',
form=LoginForm())
可以看出,它们是以类似的方式编写的。这是我的记录器功能(在models.py模块中):
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
注册可以按预期进行,但是登录时不能说相同。当我使用有效的电子邮件和密码(在sql中保存可以正常工作)时,我的Web应用程序始终闪烁“无效的用户名/密码组合”。
有人可以帮忙吗?
答案 0 :(得分:0)
我找到了解决方案。我的登录表单如下:
class LoginForm(FlaskForm):
email = StringField('Email',
validators=[DataRequired(), Email()])
password = PasswordField('Password',
validators=[DataRequired()])
confirm_password = PasswordField(' Confirm Password',
validators=[DataRequired(), EqualTo('password')])
remember = BooleanField('Remember Me')
submit = SubmitField('Log In')
我复制了我的注册表,却忘记了删除Confirm_Password字段。登录时尚未确认,因此不满足字段条件-> form.validate_on_submit为false。