如何修复Flask登录中TypeError: '>'不支持NoneType与int比较的问题
Hey there, let's work through this error together—it's a common gotcha with mysql.connector!
The Root Issue
The TypeError happens because cursor.execute() returns None for SELECT queries in mysql.connector, not the number of matching rows. When you try to compare result > 0, you're trying to pit None against an integer, which Python can't do.
The Fix
Instead of relying on the return value of execute(), fetch the user data directly and check if it exists. Here's the corrected login route with explanations:
# Login @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': # Get form input username = request.form['username'] password_candidate = request.form['password'] # Run the query to find the user cursor.execute("SELECT * FROM users WHERE username = %s", [username]) # Fetch the first matching user (returns None if no match exists) data = cursor.fetchone() if data is not None: # Retrieve the stored password hash password = data['password'] # Compare the submitted password with the stored hash if sha256_crypt.verify(password_candidate, password): # Login success: set session variables session['logged_in'] = True session['username'] = username flash('You are now logged in', 'success') return redirect(url_for('dashboard')) else: error = 'Invalid Login' return render_template('login.html', error=error) else: error = 'Username not found' return render_template('login.html', error=error) # Ensure cursor is closed after processing cursor.close() return render_template('login.html')
Key Improvements:
- Removed the
resultvariable entirely, sinceexecute()doesn't return useful data for SELECT queries. - Used
cursor.fetchone()to get the user data directly—this returns a dictionary (or tuple, based on your cursor config) if a user exists, otherwiseNone. - Replaced
if result > 0withif data is not Noneto properly check for a matching username. - Fixed the placement of
cursor.close()to ensure it runs after query processing (you could also use a context manager likewith cursor:to handle closure automatically).
Quick Extra Tip:
If you ever need the count of rows returned for a SELECT query, you can use cursor.rowcount after running execute()—but fetchone() is more efficient here since we only care about a single user match.
This should resolve the TypeError and get your login flow working as expected!
内容的提问来源于stack exchange,提问作者Lux Rodrz

