我正在嘗試檢索存盤在資料庫中的密碼哈希。問題是當查詢為空時我如何處理。
在我搜索存在的用戶的情況下,第一個 print將列印一些東西,但在 if 陳述句內的第二個 print中它將輸出None
我不明白發生了什么。在我看來,變數正在失去它的價值
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")
uj5u.com熱心網友回復:
每次呼叫db_password.fetchone()它都會獲取下一行結果。但是您的查詢只回傳一行。
if陳述句中的呼叫獲取該行。然后呼叫中的print()呼叫嘗試獲取下一行,但沒有另一行,所以它列印None. 然后變數賦值中的第三個呼叫嘗試獲取下一行,但仍然沒有另一行,所以你得到一個錯誤,因為你試圖None在一個元組賦值中進行賦值。
您應該獲取一個變數。然后你可以測驗它并在作業中使用它。
row = db_password.fetchone()
if row:
print(row)
hashed = row[0]
...
else:
print("user doesn't exist")
uj5u.com熱心網友回復:
每次呼叫 fetchone() 都會將游標移動到下一行,如果沒有可用的行則回傳 None(請參閱此處的檔案)。如果您只想檢查一個密碼,請將 fetchone 呼叫的結果存盤在一個變數中,并將其用于將來的比較/列印,即
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:
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/482618.html
上一篇:IF AND陳述句
