使用Werkzeug Security与Flask login_user实现用户登录时遭遇404及对象属性错误的求助
Hey there, let's break down what's going wrong here and get your login flow working smoothly!
The Root Cause
That error message tells us exactly the issue: you’re passing a database query result tuple (row) directly to login_user(), but Flask-Login’s login_user() expects an object that implements specific properties and methods (like is_active, is_authenticated, etc.). A tuple doesn’t have these attributes, so the method throws an exception.
You already built a valid User_obj class that meets Flask-Login’s requirements—great work! The problem is just that you aren’t converting your database row into an instance of this class before calling login_user().
Step-by-Step Fix
Let’s adjust your code to properly use your User_obj class:
Convert the database row to a User_obj instance
When your password check passes, pull theidandemailvalues from yourrowtuple and create aUser_objwith them. Make sure the order matches yourUser_obj.__init__method (id first, then email).Pass the User_obj instance to login_user()
Replacelogin_user(row)withlogin_user(user)whereuseris your newUser_objinstance.
Here’s the corrected code snippet:
if check_password_hash(stored_hash, request.form.get('password')): print('logging in') # Convert database row to User_obj instance # Adjust indices if your row's field order is different! user = User_obj(row[0], row[1]) # Now pass the valid User_obj to login_user login_user(user) return redirect(url_for('home', email=user_email, name=user_email)) else: return render_template('error.html') except Exception as e: print(e) return render_template('invalid_details.html')
Quick Checks to Ensure Success
- Double-check that your database
rowreturnsidandemailin the order you’re passing toUser_obj.__init__. If your query returns fields in a different order (e.g., email first), adjust the indices (likerow[1], row[0]). - Confirm your
homeroute accepts theemailandnameparameters you’re passing viaurl_for(you mentioned the redirect works whenlogin_useris commented out, so this is probably okay, but it’s good to verify).
Bonus: Simplify with UserMixin (Optional)
If you want to skip writing those four user methods (is_authenticated, is_active, etc.) manually, you can use Flask-Login’s UserMixin class. Update your User_obj like this:
from flask_login import UserMixin class User_obj(UserMixin): def __init__(self, id, email): self.id = id self.email = email
UserMixin provides default implementations for all required methods, so you don’t have to write them yourself.
内容的提问来源于stack exchange,提问作者Rolaxy

