简体   繁体   English

属性错误- current_user 在权限装饰器中是 NoneType

[英]attribute error- current_user is NoneType in persmissions decorator

I keep getting the error message below when I try to run my application.当我尝试运行我的应用程序时,我不断收到以下错误消息。

    if not current_user.can(permission):
AttributeError: 'NoneType' object has no attribute 'can'

Models.py模型.py

from datetime import datetime
import hashlib
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from markdown import markdown
import bleach
from flask import current_app, request, url_for
from flask_login import UserMixin, AnonymousUserMixin
from app.exceptions import ValidationError
from . import db, login_manager

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)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    password_hash = db.Column(db.String(128))
    confirmed = db.Column(db.Boolean, default=False)
    name = db.Column(db.String(64))
    location = db.Column(db.String(64))
    about_me = db.Column(db.Text())
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    avatar_hash = db.Column(db.String(32))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    followed = db.relationship('Follow',
                               foreign_keys=[Follow.follower_id],
                               backref=db.backref('follower', lazy='joined'),
                               lazy='dynamic',
                               cascade='all, delete-orphan')
    followers = db.relationship('Follow',
                                foreign_keys=[Follow.followed_id],
                                backref=db.backref('followed', lazy='joined'),
                                lazy='dynamic',
                                cascade='all, delete-orphan')
    comments = db.relationship('Comment', backref='author', lazy='dynamic')

    def can(self, perm):
        return self.role is not None and self.role.has_permission(perm)

    def is_administrator(self):
        return self.can(Permission.ADMIN)

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

    def is_administrator(self):
        return False

login_manager.anonymous_user = AnonymousUser


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

Decorators.py装饰器.py

...

from functools import wraps
from flask import abort
from flask_login import current_user
from .models import Permission


def permission_required(permission):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not current_user.can(permission):
                abort(403)
            return f(*args, **kwargs)
        return decorated_function
    return decorator


def admin_required(f):
    return permission_required(Permission.ADMIN)(f)
...

my view我的观点

@main.route('/admin_hub')
@login_required
@admin_required
def admin_hub():
    return render_template('admin_hub.html')

When I run attempt to run the code it throws up the attribute error, and I am at a loss why, it's as if current_user does not exist because there is no user logged in yet, the decorator gets executed at definition time causing this error and I really do not know how to deal with this, please assist if you are able to.当我尝试运行代码时,它会抛出属性错误,我不知道为什么,就好像 current_user 不存在,因为还没有用户登录,装饰器在定义时执行,导致这个错误和我真的不知道如何处理这个问题,如果你可以的话,请帮忙。 Kindly offer a suggestion if you are can.如果可以,请提供建议。 Without the permissions decorator the code executes perfectly.如果没有权限装饰器,代码可以完美执行。

Untested, but how about importing current_user from flask-login.utils .未经测试,但是如何从flask-login.utils导入current_user This is a proxy for the real current_user and is used by flask-login in its decorators, eg login_required .这是真正的current_user的代理,由 flask-login 在其装饰器中使用,例如login_required

Something like:就像是:

# Don't use current_user directly from flask_login
# from flask_login import current_user
from flask_login.utils import current_user


def permission_required(permission):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not current_user.can(permission):
                abort(403)
            return f(*args, **kwargs)
        return decorated_function
    return decorator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM