1

I have a python code that needs to login the user and also do the validation of inputs like check if password is good or if user excists, but I keep getting this error TypeError: 'long' object is not subscriptable??

Here is my code:

@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)

It seems like the error occurs at the line when it checks for password and when session need to start. Any clues how I could fix this?

Srdan Ristic
  • 3,203
  • 5
  • 18
  • 23

1 Answers1

5

The result of calling cursor.execute is the number of rows affected, not the result of the query. To get that, you need to call cursor.fetchone() or cursor.fetchall() if you have several rows you want to iterate over.

Note that your code still won't work though, because the API does not return a dictionary, rather a tuple of values, so you can't do user['password']. If you want a dictionary, you need to use a DictCursor, as explained in this answer. Otherwise you'll simply need to refer to the columns by number: user[0] etc. That would be clearer if you specified which columns you wanted in the SELECT query in the first place.

Community
  • 1
  • 1
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895