Flask-Login raises TypeError: 'int' object is not callable

Question:

I just write a flask login demo.

@app.route('/reg/', methods=['GET', 'POST'])
def reg():
    username = request.form.get('username').strip()
    password = request.form.get('password').strip()
    if (username == '' or password == ''):
        return redirect_with_msg('/regloginpage/', u'用户名或密码不能为空', category='reglogin')

    user = User.query.filter_by(username=username).first()
    if (user != None):
        return redirect_with_msg('/regloginpage/', u'用户名已存在', category='reglogin')

    salt = '.'.join(random.sample('0123456789abcdfeghijklmnABCDEFG', 10))
    m = hashlib.md5()
    str1 = (password + salt).encode('utf-8')
    m.update(str1)
    password = m.hexdigest()
    user = User(username, password, salt)
    db.session.add(user)
    db.session.commit()
    login_user(user)
    return redirect('/')

And Traceback like this:

TypeError: 'int' object is not callable
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/apple/PycharmProjects/pinstagram/pinstagram/views.py", line 94, in login
login_user(user)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask_login/utils.py", line 140, in login_user
user_id = getattr(user, current_app.login_manager.id_attribute)()
TypeError: 'int' object is not callable

It makes me upset, someone can save me ?

Asked By: vainman

||

Answers:

Reading the error message shows that the error is occurring on line 140 of utils.py. This is probably because you have

user_id = getattr(user, current_app.login_manager.id_attribute)()

The () on the end is making your program try to call the return value of getattr as a function, when it is an int. Remove the () and it should work.

I just ran into this same issue with flask-login and landed on this question. While @Sweater-Baron’s answer hints at the issue, here’s the direct fix in your User class since it doesn’t make sense to edit Flask-Login. The method get_id() should not be declared as a property:

@property
def get_id(self):
    return self.uid

unlike is_authenticated(), is_active() and is_anonymous().

def get_id(self):
    return self.uid

From the Flask-Login documentation:

get_id()

This method must return a unicode that uniquely identifies this user, and
can be used to load the user from the user_loader callback.

[emphasis is mine]

Answered By: dlasalle
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.