在flask中使用了flask-login作登录验证,下面这个是User模型:
class User(db.Model, UserMixin):
id = db.Column(db.INTEGER, primary_key=True)
name = db.Column(db.String(64))
email = db.Column(db.String(64))
password_hash = db.Column(db.String(128))
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return '<User %r>' % self.name
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
这是form:
class RegisterForm(FlaskForm):
email = StringField('Email', validators=[Required(), Length(1, 64), Email()])
username = StringField('Username', validators=[Required(), Length(1, 16), Regexp('^[A-Za-z][1-9]*$',
message='first is a string and the second must be a int')])
password = PasswordField('Password', validators=[Required(), Length(1, 64)])
password2 = PasswordField('Config Password', validators=[Required(), Length(1, 64)])
submit = SubmitField('Register')
def validata_email(self, field):
if User.query.filter_by(email=field.data).first():
raise ValidationError('Email is already register')
def validata_username(self, field):
if User.query_by(username=field.data).first():
raise ValidationError('User is already in use')
这个是视图函数:
@auth.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
user = User(name=form.username.data, email=form.email.data, password=form.password.data)
db.session.add(user)
login_user(user, True)
flash('Register successful!!')
return render_template('user.html')
return render_template('register.html', form=form)
现在的情况是,当用户注册成功时会自动登录跳转到下面的页面,但是跳转后继续请求会出错,如果在注册中去掉登录,就没问题了,不知道为什么
user_id找不到时为None,执行int(user_id)发生错误
试着把这段
改成