sprinkle
sprinkle

Reputation: 21

AttributeError: 'AnonymousUserMixin' object has no attribute 'can'

flask learning problem

In order to custom requirements for anonymous users,I set a class in models:

    class MyAnonymousUser(AnonymousUserMixin):    
        def can(self, permissions):
            return False
        def is_administrator(self):
            return False
    login_manager.anonymous_user = MyAnonymousUser

Flask run met error: 'AnonymousUserMixin' object has no attribute 'can',in the views:

@main.route('/', methods=['GET', 'POST'])
    def index():
        form = PostForm()
        if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
            post = Post(body=form.body.data,
                        author=current_user._get_current_object())
            db.session.add(post)
            db.session.commit()
            return redirect(url_for('.index'))

I do not understand why is current_user not attributed by MyAnonymousUser.

Here is my origin code

Thanks for your help

Upvotes: 2

Views: 3934

Answers (1)

ElectroMotiveHorse
ElectroMotiveHorse

Reputation: 456

It seems that you assumed that by assigning the login manager to your class, you would be inheriting the methods you created. This is not what is happening in the code. What you are actually doing is overwriting the functionality of login_manager.anonymous_user that is already provided.

Check the documentation here

Your function should actually be defined within your model that contains your users. It seems as if you are trying to check whether the user is anonymous or not. So below is my recommendation of coding.

UserModel(db.Model, UserMixin):

    def can(self, permissions):
        return False

    def is_administrator(self):
        return False

@main.route('/', methods=['GET', 'POST'])
def index():
    form = PostForm()
    if current_user.is_active and form.validate_on_submit():

        if current_user.can(Permission.WRITE_ARTICLES):
            post = Post(body=form.body.data,
                        author=current_user._get_current_object())
            db.session.add(post)
            db.session.commit()
            return redirect(url_for('.index'))

Upvotes: 1

Related Questions