簡體   English   中英

如何在python中創建“如果循環最后一次執行”條件

[英]How do I make "if the loop is executing for the last time" condition in python

所以,我正在通過python中的文件處理來制作登錄系統。 當我輸入正確的用戶名/密碼時,代碼工作正常,但當我使用“else”語句作為用戶輸入錯誤密碼時應執行的條件時,它不起作用。

for line in open('accounts.txt','r+').readlines():
    loginfo = line.split()
    if a==loginfo[0] and b==loginfo[1]:
        return render(request, 'login.html')
    else:
        return render(request, 'index.html')
  • 在這里,執行循環並檢查每一行以查看用戶輸入的用戶名、密碼是否在文件中。
  • 我正在使用 getlines() 函數通過行獲取用戶的用戶名和密碼,這意味着每一行都應該包含一個用空格分隔的用戶名和密碼。
  • 我正在使用 line.split 拆分文件中的用戶名和密碼。
  • 如果我刪除“else”然后輸入正確的密碼,那么代碼可以正常工作,但是當我輸入錯誤的密碼時它不能正常工作。
  • 如果我將“else”條件放在循環中,那么它會弄亂算法,並且在循環第一次執行時會呈現網頁。
  • 我想要的是“else”條件應該只執行,網頁“index.html”應該只在文件被完全檢查(這意味着最后一次執行 for 循環)和用戶名時顯示在文件中找不到用戶輸入的 /password。

這里不需要標志或獨特的功能:

# use a with block to ensure the file will be properly closed
with open("accounts.txt") as file:
    # files are their own iterators, no need to read the
    # whole file in memory
    for line in file:
        # get rid of newlines / trailing whitespaces etc
        loginfo = line.strip().split()
        if a==loginfo[0] and b==loginfo[1]:
            return render(request, 'login.html')

    # if a match has been found, we'll never get here,
    # so if we get here no match has been found...
    return render(request, 'index.html')

現在我不得不說將登錄數據存儲在文本文件中是有史以來最糟糕的想法,特別是當 Django 作為一個完整、安全、工作且非常易於使用的身份驗證/用戶系統時。

您的文本文件有很多行,每一行都匹配一個特定的帳戶。 您所做的錯誤是您在循環內返回False ,這是錯誤的,因為您必須遍歷所有行。 之后你可以只返回False因為沒有帳戶匹配登錄名和密碼

def check_login():
    for line in open('accounts.txt','r+').readlines():
        loginfo = line.split()
        if a==loginfo[0] and b==loginfo[1]:
            return True
    return False

def login_view(request):
    if check_login():
        return render(request, 'index.html')
    else:
        return render(request, 'login.html')
for line in file:  
    loginfo = line.strip().split()
    if a==loginfo[0] and b==loginfo[1]:
        return render(request, 'login.html')
return render(request, 'index.html')

注意:- 這應該應用於distinct usernames

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM