首先,Python 不是我的第一語言,但我正在學習的一門課程需要它,所以我在這里......我正在使用 python 和flask 制作一個帶有簡單登錄/注冊頁面的網站。制作頁面很簡單(我認為?)但是,在設定注冊條件時,我用來檢查用戶是否已經存在的 for 回圈一開始可以作業,但是沒有更改代碼,它不再有效。我輸入 'admin' 作為用戶名,但盡管存在于 txt 檔案中,但回圈無法找到它。我是瘋了還是我錯過了什么?
def info():
with open('passfile.txt', "r") as f:
lines = f.readlines()
for line in lines:
text = line.split()
username = text[0]
print(text[0])
password = text[1]
yield username, password
def add_info(username, password):
with open('passfile.txt', "a") as f:
f.write(username " " password "\n")
@week6.route("/registration", methods=["GET", "POST"])
def register():
"""
function to register a new user
"""
username, password = info()
if request.method == "POST":
un = request.form.get("username")
pw = request.form.get("password")
secure = sc.hash(str(pw))
register.secure = secure
print(un)
if un in username:
flash("That username is already taken")
return render_template("registration.html")
if pw_verify(pw) == True:
add_info(un, secure)
flash("Your officially registered!")
return render_template("registration.html")
uj5u.com熱心網友回復:
您的問題在于您如何使用生成器功能:
def info():
...
for line in lines:
...
yield username, password
然后后來:
username, password = info()
第一個函式的作用(一個生成器函式,因為它使用 yield 而不是 return)回傳一個迭代器,當你迭代它時,它會給你(username, password)元組。
當您將其稱為 like 時username, password = info(),您將對其進行兩次迭代并將這些元組分配給username和password。
所以,username可能是("user1", "secret_password"),password也可能是("admin", "admin_password"),這顯然不是你想要的。
看起來您想要info做的是回傳用戶名串列和密碼串列。像這樣更改它可以與您的代碼一起使用:
def info():
usernames = []
passwords = []
with open('passfile.txt', "r") as f:
for line in f.readlines():
username, password = line.split(maxsplit=1)
usernames.append(username)
passwords.append(password)
return usernames, passwords
盡管這是一個快速解決方案,但我認為這可能不是解決此問題的最佳方法。
uj5u.com熱心網友回復:
使用yield將函式變成生成器。這意味著info實際上回傳一個迭代器。第一步是將您的info呼叫更改為:
users = info()
迭代器in會即時計算它們的值,因此操作員不會使用它們。您需要使用迭代器來查看其內容。您可以修改您的if陳述句以使用any函式和推導式。
if any(u[0] == un for u in users):
推導式基于從 產生的元組的第一個元素產生一個布林值info。any如果任何元素為真,則該函式回傳 True。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/374243.html
