好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

登录接口

作业一:编写登陆接口

1.输入用户名和密码

2.认证成功后显示欢迎信息

3.输错三次后锁定

思路:

(1)用户输入用户名;

  (2)去锁定文件中验证用户名是否锁定;

  (3)去当前用户验证用户是否存在;

  (4)用户输入密码,三次输错后锁定

(5)锁定之后从当前文件中删除用户名,添加到锁定文件中。

注意文件的读取、修改、写入操作,这些操作是要借助列表来完成的,不然就会导致一些不必要的错误,最后定义一个函数来完成这些操作,使用的时候调用这些函数就可以了。

列表文件的操作一定要注意换行的处理,如何添加元素进去,这些方法最好借助于列表和字典来读取写入文件,这样能够保持格式的整齐。

代码如下:

import os,sys,getpass,collections
retry_limit = 3   #密码错误三次被锁定
retry_count = 0   #起始次数是0次

def locked_user(users,filename):
    #用于存放锁定用户的文件,当用户锁定的时候,要从原文件删除,添加到新的文件中
    with open(filename,"w+") as locked_f:for key,value in users.items():
            line = []
            line.append(key)
            line.append(value)
            file_line = " ".join(line) + "\n"locked_f.write(file_line)

active = Trueif __name__ == "__main__":while True:
        username = input("请输入用户名(输入quit退出):")
        with open("account_lock.txt","r") as f:
            user_lists = f.readlines()for user_list in user_lists:if user_list.strip() == username:
                    print("您好,你的用户已经被锁定,请联系管理员!")continue    #如果用户锁定,结束当前循环,执行下一次用户输入else:
                    passif username == "quit":
            sys.exit(0)

        with open("account.txt") as active_f:
            users_dict = collections.OrderedDict()for line in active_f:
                user,pwd = line.strip().split()
                users_dict[user] = pwdif username in users_dict.keys():while retry_count < retry_limit:
                passwd = getpass.getpass("请输入你的密码:")  # 隐藏式输入密码
                # 判断用户是否在用户列表中if users_dict[username] == passwd:
                    print("欢迎回来,认证成功!")breakelse:if retry_count != 2:
                        #提示用户注意,还有几次机会将被锁定
                        print("您输入的密码不对,您还有%d次机会,否则系统将被锁定!" % (2 - retry_count))
                    retry_count += 1else:
                print("您输入的次数过多,%s已被锁定,请联系管理员" %username)

                #用户锁定之后,要把锁定的用户从当前文件删除,移到锁定文件中
                users_dict.pop(username)
                locked_user(users_dict,"account.txt")
                with open("account_lock.txt","a+") as a_f:
                    a_f.write(username + "\n")else:
            print("对不起,您输入的用户不存在,请重新输入!!!") 

查看更多关于登录接口的详细内容...

  阅读:57次