Home > Software design >  Python variable loses value when passed to a if statement
Python variable loses value when passed to a if statement

Time:05-26

I am trying to retrieve a password hash that i stored in my database. The problem is how i handle when the query is null.

In the case that I search for a user that exists the first print will print something but the in the second print that is inside the if statement it will output None

I don't understand what is happening. It seems to me that the variable is loosing it's value

            db_password = c.execute("SELECT hashed FROM contas WHERE username=?", [username])

            print(db_password.fetchone())

            if(db_password.fetchone() != None):
                print(db_password.fetchone())
                hashed, = db_password.fetchone()

                # Verify if passwords match
                if ((bcrypt.checkpw(password.encode('utf8'), hashed) == False)):
                    print("Wrong credentials")

                else:
                    print("User logged in successfully")


            else:
                print(db_password.fetchone())
                print("User doesn't exist")

CodePudding user response:

Each time you call db_password.fetchone() it fetches the next row of results. But your query only returns one row.

The call in the if statement fetches that row. Then the call in the print() call tries to fetch the next row, but there isn't another row, so it prints None. Then the third call in the variable assignment tries to fetch the next row, but there still isn't another row, so you get an error because you're trying to assign None in a tuple assignment.

You should fetch into a variable. Then you can test that and use it in the assignment.

row = db_password.fetchone()
if row:
    print(row)
    hashed = row[0]
    ...
else:
    print("user doesn't exist")

CodePudding user response:

Calling fetchone() will move the cursor to the next row each time and return None if there are no rows available (see documentation here). If you want to just check the one password, store the result of the fetchone call in a variable and use it for future comparisons/printing, i.e.

password = db_password.fetchone()
print(password)
if password is not None:
    print(password) # If password is not None, this will print the same thing as the previous print call
    ...
else:
    ...
  • Related