empty_space empty_space - 1 year ago 140
Python Question

Flask-Login login_user() throws TypeError when passing a user object

I'm trying to use the Flask-Login extension to handle my user sessions but when I call the login_user(user) method it throws the following error

File "app.py", line 55, in login_user
TypeError: login_user() takes 0 positional arguments but 1 was given

But the Flask-Login documentation says it takes in a user object as a parameter and all of the implementations I've found online use the method in this manner so I can't understand where my error lies.

This is my User model:

class Users(db.Model):
__tablename__ = "users"
u_id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80))
passhash = db.Column(db.String(256))
fname = db.Column(db.String(80))
lname = db.Column(db.String(80))

def hash_password(self, password):
self.passhash = pwd_context.encrypt(password)

def verify_password(self, password):
return pwd_context.verify(password, self.passhash)

def is_active(self):
return True

def is_authenticated(self):
return True

def is_anonymous(self):
return False

def get_id(self):
return str(self.u_id)

and here is the login function:

app = Flask(__name__)
login_manager = LoginManager()

def load_user(user_id):
return models.Users.query.filter_by(u_id =int(user_id)).first()

db = SQLAlchemy(app)

@app.route('/login', methods=['POST'])
def login_user():
username = request.form['username']
password = request.form['password']
user = models.Users.query.filter_by(username = username).first()
if not user or not user.verify_password(password):
return jsonify({'success': False})

return jsonify({'success': True})

Can anyone help shed some light on where I'm going wrong?
Thanks in advance!

Answer Source

Your error derives from a name conflict. The Flask login_user is being shadowed by your view which shares the same name. Python rightly assumes you're trying to make a recursive call albeit with a wrong signature. Rename your view function login_user to something else.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download