在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)發生錯誤
試著把這段
改成