1、编写用户登录接口
需求点:(1)输入账号密码完成验证,验证通过后输出"登录成功"
(2)可以登录不同的用户
(3)同一账号输错三次锁定
import os from prettytable import PrettyTable path_of_user = os.path.dirname(os.path.abspath(__file__)) + '/user/user.db' # 用户登录模块 class Login: def __init__(self): self.count = 0 self.run() def run(self): self.username = input('请输入用户名:').strip() self.passwd = input('请输入密码:').strip() self.passwd = base64.b64encode(self.passwd.encode('utf-8')).decode('utf-8') self.match() def match(self): if os.path.exists(path_of_user): f = open(path_of_user,encoding='utf-8',mode='r') self.user_dict = {item.strip(' ').split('--')[0]:item.strip(' ').split('--')[1::1] for item in f.readlines()} f.close() if self.username in self.user_dict.keys(): if self.passwd == self.user_dict.get(self.username)[0]: tb = PrettyTable(['用户','登录地址','用户状态']) tb.add_row([self.username,socket.gethostbyname(socket.gethostname()),'success']) print('登录成功! {}'.format(tb)) else: self.user_dict[self.username][1] = str(int(self.user_dict[self.username][1])+1) print('密码错误,请重新输入,剩余{}次机会!'.format(3-int(self.user_dict[self.username][1]))) f = open(path_of_user,encoding='utf-8',mode='w') for k,v in self.user_dict.items(): pwd,err_count,state = v f.write(k+'--'+pwd+'--'+err_count+'--'+state+' ') f.close() if int(self.user_dict[self.username][1]) < 3:self.run() else: self.user_dict[self.username][1] = '0' self.user_dict[self.username][2] = 'lock' f = open(path_of_user,encoding='utf-8',mode='w') for k,v in self.user_dict.items(): pwd,err_count,state = v f.write(k+'--'+pwd+'--'+err_count+'--'+state+' ') f.close() else: print('用户{}不存在,请重新输入!'.format(self.username)) self.run() else: raise FileNotFoundError("data file does not exsist:'{}'".format(path_of_user)) def main(): Login() if __name__ == '__main__': main()
2、编写用户程序实现注册
flag=True #是否退出 count=0 #计算用户输错次数 name_existed=False # 判断用户是否 while flag: msg = """ 0 退出 1 登录 2 注册 """ print(msg) cmd = input('请输入命令编号>>: ').strip() if cmd.isdigit(): if cmd == '0': break elif cmd == '1': # 登录功能代码(附加:可以把之前的循环嵌套,三次输错退出引入过来) while flag: inp_name = input("请输入账号:>>>").strip() inp_pwd = input("请输入密码:>>>").strip() if count == 2: print("已经输错三次,退出程序。") flag=False break with open("info_db.txt", "r", encoding="utf-8") as f: for line in f: user_name, passwd = line.strip(" ").split(":") if inp_name == user_name and inp_pwd == passwd: print("登录成功。") flag=False break else: print("账号或密码错误。") count+=1 elif cmd == '2': add_name=input("请输入账号:>>>").strip() add_pwd=input("请输入密码:>>>").strip() # 判断用户是否已经存在 with open("info_db.txt", "r", encoding="utf-8") as f: for line in f: if add_name in line: name_existed=True if name_existed == False: #注册 with open("info_db.txt","a",encoding="utf-8") as f: f.write(" {}:{}".format(add_name,add_pwd)) print("用户{}注册成功。".format(add_name)) else: print("用户{}已经存在".format(add_name)) else: print('输入的命令不存在') else: print('必须输入命令编号的数字,傻叉')