我已经为我的烧瓶应用程序实现了登录,当我使用正确的凭据登录用户时,它可以正常工作,但是当我尝试使用不存在的用户登录时,我已经点击了这个错误讯息:
TypeError:' NoneType'对象不可订阅
# user login
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == 'POST':
# Get Fields Username & Password
# Client Side Login & Validation handled by wtforms in register class
username = request.form['username']
usr_entered = request.form['password']
#usr_entered = {k: (v).encode("utf-8") for k,v in usr_entered()}
cursor = cnx.cursor(dictionary=True,buffered=True)
# Need to check if the username exists in the db first
# Get User By Username
cursor.execute("SELECT * FROM users WHERE username =%s", [username])
if cursor is not None:
# Get Stored Hased and Salted password - Need to change fetch one to only return the one username
data =cursor.fetchone()
password = data['password']
# Compare Password with hashed password- Bcrypt
if bcrypt.checkpw(usr_entered.encode('utf-8'),password.encode('utf-8')):
#if (usr_entered==password):
app.logger.info('Password Matched')
session['logged_in'] = True
session['username'] = username
flash('You are now logged in','success')
return redirect(url_for('dashboard'))
# Close Connection
cursor.close()
else:
error = 'Invlaid Username or Password'
return render_template('login.html',error=error)
else:
error = 'Username not found'
return render_template('login.html', error=error)
return render_template('login.html')
答案 0 :(得分:1)
问题是你正试图获得密码'即使在数据库中找不到用户名。换句话说,如果找不到用户名,您将获得一个空的游标对象。 您可以将代码更改为:
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
usr_entered = request.form['password']
cursor = cnx.cursor(dictionary=True, buffered=True)
cursor.execute("SELECT * FROM users WHERE username =%s", [username])
if cursor is not None:
data = cursor.fetchone()
try:
password = data['password']
except Exception:
error = 'Invalid Username or Password'
return render_template('login.html', error=error)
if bcrypt.checkpw(usr_entered.encode('utf-8'), password.encode('utf-8')):
app.logger.info('Password Matched')
session['logged_in'] = True
session['username'] = username
flash('You are now logged in', 'success')
cursor.close()
return redirect(url_for('dashboard'))
else:
error = 'Invalid Username or Password'
return render_template('login.html', error=error)
else:
error = 'Invalid Username or Password'
return render_template('login.html', error=error)
return render_template('login.html')
这是解决问题的一种方法。如果句子你可以用它。我还在cursor.close()
之前移动了return redirect(url_for('dashboard'))
。在您的版本中,cursor.close()
无法访问。
另一项安全措施是永远不要告知此人他们错误的用户名/密码的哪一部分。
答案 1 :(得分:0)
从错误日志判断,如果找不到用户,则光标看起来不会返回None
。使用Flask的调试功能可以告诉用户找不到数据的值,然后更新if语句以获得正确的值。如果你想要懒惰,你可以输入if data['password']
。