if request.method == "POST":
user = None
users = User.query.all()
for x in users:
if x.email == request.form["email"] and check_password_hash(x.password, request.form["password"]):
user = x
if not user:
return render_template("login.html",err = "Invalid Credentials")
else:
login_user(user)
return redirect(url_for("home"))
else:
if current_user.is_authenticated:
return redirect(url_for("home"))
我總是發現自己設定了一個變數 = None,然后再檢查變數是否仍然是 None ,就像上面的例子一樣。我覺得有更好的方法來寫這個,但我想不出任何方法。任何幫助表示贊賞
uj5u.com熱心網友回復:
與其在資料庫中查詢所有用戶,然后遍歷應用程式中的所有結果,不如讓資料庫來完成這項作業。
以下是我如何重寫你的代碼片段(我猜你正在使用 Flask-SQLAlchemy):
if request.method == "POST":
user = User.query.filter_by(email=request.form["email"]).first()
if not user or not check_password_hash(user.password, request.form["password"]):
return render_template("login.html", err="Invalid Credentials")
login_user(user)
return redirect(url_for("home"))
if current_user.is_authenticated:
return redirect(url_for("home"))
需要注意的一些事項:
- 簡化您的流程控制并避免不必要的嵌套
- 在您的代碼中,您正在回圈訪問資料庫中的所有用戶,即使您找到了有問題的用戶。確保使用
breakandcontinue陳述句避免不必要的作業 - 避免為構建資料庫的任務手動實作邏輯(例如查詢和過濾資料)
uj5u.com熱心網友回復:
您可以使用 atry/except并捕獲 a NameError。
try:
login_user(user)
return redirect(url_for("home"))
except NameError:
render_template("login.html",err = "Invalid Credentials")
這不需要您定義user=None,并且在可讀性方面更有意義,假設您希望更頻繁地獲得用戶。但是,我對您的代碼有點困惑,因為您正在遍歷一個串列但只分配一個變數。為什么不把所有的代碼都放在回圈if陳述句下面呢?我相信你有理由不這樣做,但從你的代碼中并不清楚。
uj5u.com熱心網友回復:
我發現問題中的代碼足夠好,邏輯也很清楚。
也就是說,下面是一個使用串列理解來展示另一種方法的示例。請注意,不會有效率提升。這是一個偏好和風格的問題。
if request.method == "POST":
def _validated(x):
return (x.email == request.form["email"] and
check_password_hash(x.password, request.form["password"])
users = [x for x in User.query.all() if _validated(x)]
if len(users) == 0:
return render_template("login.html",err = "Invalid Credentials")
else:
login_user(users[0])
return redirect(url_for("home"))
else:
if current_user.is_authenticated:
return redirect(url_for("home"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/447860.html
