在 flask-login中使用login_user报错?

yzhengwei
  • 170

在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)

现在的情况是,当用户注册成功时会自动登录跳转到下面的页面,但是跳转后继续请求会出错,如果在注册中去掉登录,就没问题了,不知道为什么

clipboard.png

clipboard.png

回复
阅读 3.8k
1 个回答

user_id找不到時為None,執行int(user_id)發生錯誤

試著把這段

def load_user(user_id):
    return User.query.get(int(user_id))

改成

def load_user(user_id):
    try: 
        output = User.query.get(int(user_id))
        return(output)
    except:
        return(None) 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏