alvy
  • 165

flask网站'AnonymousUser'对象没有'confirmed'属性

flask写的个人网站,前几天还运行正常,昨天运行python manage runserver后打开主页出现问题,百思不得其解,自身对用户登录注册这一块也一知半解,求达人解答,拜谢,问题如下:

Traceback (most recent call last):
  File "/home/alvy/myBlog-heroku/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/alvy/myBlog-heroku/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/alvy/myBlog-heroku/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/alvy/myBlog-heroku/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/alvy/myBlog-heroku/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/alvy/myBlog-heroku/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/alvy/myBlog-heroku/venv/lib/python2.7/site-packages/flask/app.py", line 1473, in full_dispatch_request
    rv = self.preprocess_request()
  File "/home/alvy/myBlog-heroku/venv/lib/python2.7/site-packages/flask/app.py", line 1666, in preprocess_request
    rv = func()
  File "/home/alvy/myBlog-heroku/app/auth/views.py", line 54, in before_request
    if current_user.is_authenticated and not current_user.confirmed and request.endpoint[:5] != 'auth.' and request.endpoint != 'static:':
  File "/home/alvy/myBlog-heroku/venv/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
    return getattr(self._get_current_object(), name)
AttributeError: 'AnonymousUser' object has no attribute 'confirmed'

我的model代码是:

class User(UserMixin,db.Model):
    __tablename__='users'
    id=db.Column(db.Integer,primary_key=True)
    email=db.Column(db.String(64),unique=True,index=True)
    username=db.Column(db.String(64),unique=True,index=True)
    password_hash=db.Column(db.String(128))
    role_id=db.Column(db.Integer,db.ForeignKey('roles.id'))
    confirmed=db.Column(db.Boolean,default=False)
    posts=db.relationship('Post',backref='author',lazy='dynamic')
    comments=db.relationship('Comment',backref='author',lazy='dynamic')
    messages=db.relationship('Message',backref='author',lazy='dynamic')
    
    def __repr__(self):
        return '<User %r>' % self.username

    @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) #返回True或者False

    def generate_confirmation_token(self,expiration=3600):
        s=Serializer(current_app.config['SECRET_KEY'],expiration)
        return s.dumps({'confirm':self.id})

    def confirm(self,token):
        s=Serializer(current_app.config['SECRET_KEY'])
        try:
            data=s.loads(token)
        except:
            return False
        if data.get('confirm') != self.id:
            return False
        self.confirmed=True
        db.session.add(self)
        return True

    def __init__(self,**kwargs):
        super(User,self).__init__(**kwargs)
        if self.role is None:
            if self.email==current_app.config['HULU_ADMIN']:
                self.role=Role.query.filter_by(permissions=0xff).first()
            if self.role is None:
                self.role=Role.query.filter_by(default=True).first() 
    def can(self,permissions):
        return self.role is not None and (self.role.permissions & permissions)==permissions
    def is_administrator(self):
        return self.can(Permission.ADMINISTER)

class AnonymousUser(AnonymousUserMixin):
    def can(self,permissions):
        return False
    def is_administrator(self):
        return False

login_manager.anonymous_user=AnonymousUser

view代码如下:

@auth.before_app_request
def before_request():
    if current_user.is_authenticated and not current_user.confirmed and request.endpoint[:5] != 'auth.' and request.endpoint != 'static:':
        return redirect(url_for('auth.unconfirmed'))

@auth.route('/unconfirmed')
def unconfirmed():
    if current_user.is_anonymous or current_user.confirmed:
        return redirect(url_for('main.homePage'))
    return render_template('auth/unconfirmed.html')

最后我发现是login版本问题,我安装的login是2.0版本,然后is_authenticated应该要加()

阅读 4.6k
评论 更新于 2015-11-30
    1 个回答

    你用的是@auth.before_app_request,而且是在未登录之前就请求了。按照flask-login文档,默认情况下,用户没有实际登录的话,current_user会被设置为AnonymousUserMixin对象的。而从你的模型定义中看到,你的AnonymousUser类里面并没有定义confirmed字段。具体怎么解决,估计你应该有个方向了吧。

    评论 赞赏 2015-11-25
      撰写回答

      登录后参与交流、获取后续更新提醒