Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python variable loses value when passed to a if statement

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading