Home > front end >  flask-login using UserMixin - no 'id' attribute error despite being implemented
flask-login using UserMixin - no 'id' attribute error despite being implemented

Time:10-07

I have been trying to use flask-login for authentication in my flask app. While trying to implement the user_loader like this:

@login_manager.user_loader
def load_user(id):
    return User.get_id(id)

i get the error

NotImplementedError: No id attribute - override get_id

My User class is defined like this:

class User(Base, UserMixin):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    email = Column(String(70), unique=True)
    userName = Column(String(40), unique=True)
    password = Column(String(150))

    #def get_id(self):
    #    return (self.id)

i tried overriding the get_id method, as you can see in the User class. It just got me the error

AttributeError: 'str' object has no attribute 'id'

What am i missing? Why is the id attribute not found?

CodePudding user response:

You are correctly implementing a getter for the id variable in your override, but I think that you are misinterpreting how to use the function in the code to load a user by id. In your overridden function, get_id takes in no parameters besides self, because the function simply returns the id of a user. However you are trying to use this as a function to load a user from their id. The reason we are getting this specific error is because by calling User.get_id(id), you are calling get_id with self=id and since id is a str, we get the AttributeError from trying to get the id property of id, which doesn't exist.

CodePudding user response:

Try using get instead of get_id (as shown in this tutorial). This way the returned value is an instance of User with the desired id

@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id))
  • Related