Python类型错误:‘long’对象不可下标访问
我有一段Python代码,它需要让用户登录,并且还要验证输入,比如检查密码是否合格或者用户是否存在。但是我一直收到这个错误TypeError: 'long' object is not subscriptable??
这是我的代码:
@app.route('/login', methods=['GET', 'POST'])
def login():
if g.user:
return redirect(url_for('hello'))
error = None
if request.method == 'POST':
db = MySQLdb.connect(user="root", passwd="", db="cs324", host="127.0.0.1")
c=db.cursor()
user = c.execute('''select * from user where
username = %s''', [request.form['username']])
if user is None:
error = ('Wrong username!')
elif not check_password_hash(user['password'],
request.form['password']):
error = ('Wrong password!')
else:
session['user_id'] = user['user_id']
return redirect(url_for('hello'))
return render_template('login.html', error=error)
看起来这个错误发生在检查密码和开始会话的那一行。有没有什么线索可以帮我解决这个问题?
1 个回答
5
调用 cursor.execute
的结果是受影响的行数,而不是查询的结果。要获取查询结果,你需要调用 cursor.fetchone()
,如果你想处理多行数据,可以用 cursor.fetchall()
。
不过要注意,你的代码还是不能正常工作,因为这个接口返回的不是字典,而是一个值的元组,所以你不能用 user['password']
这种方式来访问。如果你想要字典格式的数据,你需要使用 DictCursor,具体可以参考 这个回答。否则,你只能通过数字来访问列,比如 user[0]
等等。如果你在最开始的 SELECT 查询中就指定了想要的列,那样会更清晰。