搜索

首页  >  问答  >  正文

python - 在 flask-login中使用login_user报错?

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

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

怪我咯怪我咯2727 天前937

全部回复(1)我来回复

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-12 09:27:19

    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) 
    

    回复
    0
  • 取消回复