【问题标题】:How do I make "if the loop is executing for the last time" condition in python如何在python中制作“如果循环最后一次执行”条件
【发布时间】:2019-06-19 08:15:59
【问题描述】:

所以,我正在通过 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循环最后一次执行)并且在文件中找不到用户输入的用户名/密码。

【问题讨论】:

  • 无论 for 循环的第一次迭代,你都会返回,所以它只会检查第一行
  • 在 Django 应用程序中使用纯文本文件登录 ???你是认真的???

标签: python django


【解决方案1】:

这里不需要标志或独特的功能:

# 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 作为一个完整、安全、工作且非常易于使用的身份验证/用户系统时。

【讨论】:

    【解决方案2】:

    您的文本文件有很多行,每行都匹配一个特定的帐户。您正在做的错误是您在循环内返回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')
    

    【讨论】:

      【解决方案3】:
      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

      【讨论】:

      • 你确定你的缩进是正确的吗?您仍然在循环的第一次迭代中无条件返回。
      • 感谢@rtoijala,我在格式化代码时把它推到了里面。
      • 我已经更新了代码,请再次检查@FahadAzeem
      • 您根本不需要标志 - 您可以从循环中的 if 块返回。
      • @Exprator 我完全理解这个问题,谢谢。我再说一遍:你根本不需要旗帜。
      猜你喜欢
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 2022-01-03
      相关资源
      最近更新 更多